sentence1
stringlengths
52
3.87M
sentence2
stringlengths
1
47.2k
label
stringclasses
1 value
protected function dereferenceProperty(...$properties) { foreach ((array)$properties as $property) { if (!property_exists($this, $property)) { continue; // @codeCoverageIgnore } $value = $this->$property; unset($this->$property); $this->$property = $value; } }
Remove referencing from properties @param string[] $properties
entailment
public function withGlobalEnvironment($bind = false) { if ($this->isStale) { throw new \BadMethodCallException("Unable to use a stale server request. Did you mean to rivive it?"); } if ($this->isStale === false) { return $this->copy(); } $request = $this->buildGlobalEnvironment(); if (!$bind) { $request->copy(); $request->isStale = null; } return $request; }
Use superglobals $_SERVER, $_COOKIE, $_GET, $_POST and $_FILES and the php://input stream. Note: this method is not part of the PSR-7 specs. @param boolean $bind Bind server request to global environment @return ServerRequest @throws RuntimeException if isn't not possible to open the 'php://input' stream
entailment
protected function buildGlobalEnvironment() { $request = clone $this; $request->serverParams =& $_SERVER; $request->cookies =& $_COOKIE; $request->queryParams =& $_GET; $request->setPostData($_POST); $request->setUploadedFiles($_FILES); $request->body = Stream::open('php://input', 'r'); $request->reset(); $request->isStale = false; return $request; }
Build the global environment
entailment
public function withoutGlobalEnvironment() { if ($this->isStale !== false) { return $this; } $request = clone $this; $request->copy(); $request->isStale = null; return $request; }
Return object that is disconnected from superglobals @return ServerRequest
entailment
protected function copy() { if ($this->isStale) { throw new \BadMethodCallException("Unable to modify a stale server request object"); } $request = clone $this; if ($this->isStale === false) { $this->dereferenceProperty('serverParams', 'cookies', 'queryParams', 'postData', 'uploadedFiles'); $this->isStale = true; } return $request; }
Clone the server request. Turn stale if the request is bound to the global environment. @return ServerRequest A non-stale request @throws \BadMethodCallException when the request is stale
entailment
public function revive() { if ($this->isStale !== true) { return $this; } $request = $this->buildGlobalEnvironment(); return $request ->withServerParams($this->getServerParams()) ->withCookieParams($this->getCookieParams()) ->withQueryParams($this->getQueryParams()) ->withParsedBody($this->getParsedBody()) ->withBody(clone $this->getBody()) ->withUploadedFiles($this->getUploadedFiles()); }
Revive a stale server request @return ServerRequest
entailment
public function invoke(ServerRequestInterface $request, RouteParams $params) { $callable = $this->callable; // Controller Actions are lazy loaded so we need to call the factory to get the callable if ($this->isControllerAction()) { $callable = call_user_func($this->callable); } // Call the target action with any provided params if ($this->invoker) { return $this->invoker->setRequest($request)->call($callable, $params->toArray()); } else { return call_user_func($callable, $params); } }
Invoke the action @param ServerRequestInterface $request @param RouteParams $params @return mixed
entailment
private function createCallableFromAction($action) : callable { // Check if this looks like it could be a class/method string if (!is_callable($action) && is_string($action)) { return $this->convertClassStringToFactory($action); } return $action; }
If the action is a Controller string, a factory callable is returned to allow for lazy loading @param mixed $action @return callable
entailment
private function getController() { if (empty($this->controllerName)) { return null; } if (isset($this->controller)) { return $this->controller; } $this->controller = $this->createControllerFromClassName($this->controllerName); return $this->controller; }
Get the Controller for this action. The Controller will only be created once @return mixed Returns null if this is not a Controller based action
entailment
private function createControllerFromClassName($className) { // If we can, use the container to build the Controller so that Constructor params can // be injected where possible if ($this->invoker) { return $this->invoker->getContainer()->get($className); } return new $className; }
Instantiate a Controller object from the provided class name @param string $className @return mixed
entailment
private function providesMiddleware() : bool { $controller = $this->getController(); if ($controller && ($controller instanceof ProvidesControllerMiddleware)) { return true; } return false; }
Can this action provide Middleware @return bool
entailment
public function getMiddleware() : array { if (!$this->providesMiddleware()) { return []; } $allControllerMiddleware = array_filter( $this->getController()->getControllerMiddleware(), function (ControllerMiddleware $middleware) { return !$middleware->excludedForMethod($this->controllerMethod); } ); return array_map( function ($controllerMiddleware) { return $controllerMiddleware->middleware(); }, $allControllerMiddleware ); }
Get an array of Middleware @return array
entailment
private function convertClassStringToFactory($string) : Closure { $this->controllerName = null; $this->controllerMethod = null; @list($className, $method) = explode('@', $string); if (!isset($className) || !isset($method)) { throw new RouteClassStringParseException('Could not parse route controller from string: `' . $string . '`'); } if (!class_exists($className)) { throw new RouteClassStringControllerNotFoundException( 'Could not find route controller class: `' . $className . '`' ); } if (!method_exists($className, $method)) { throw new RouteClassStringMethodNotFoundException( 'Route controller class: `' . $className . '` does not have a `' . $method . '` method' ); } $this->controllerName = $className; $this->controllerMethod = $method; return function () { $controller = $this->getController(); $method = $this->controllerMethod; if ($this->invoker) { return [$controller, $method]; } return function ($params = null) use ($controller, $method) { return $controller->$method($params); }; }; }
Create a factory Closure for the given Controller string @param string $string e.g. `MyController@myMethod` @return Closure
entailment
public function getActionName() { $callableName = null; if ($this->isControllerAction()) { return $this->controllerName . '@' . $this->controllerMethod; } if (is_callable($this->callable, false, $callableName)) { list($controller, $method) = explode('::', $callableName); if ($controller === 'Closure') { return $controller; } return $controller . '@' . $method; } }
Get the human readable name of this action @return string
entailment
protected function assertTmpFile() { if (empty($this->tmpName)) { throw new \RuntimeException("There is no tmp_file for " . $this->getDesc() . ": " . $this->getErrorDescription()); } if (!file_exists($this->tmpName)) { throw new \RuntimeException("The " . $this->getDesc() . " no longer exists or is already moved"); } if ($this->assertIsUploadedFile && !$this->isUploadedFile($this->tmpName)) { throw new \RuntimeException("The specified tmp_name for " . $this->getDesc() . " doesn't appear" . " to be uploaded via HTTP POST"); } }
Assert that the temp file exists and is an uploaded file @throws \RuntimeException if the file doesn't exist or is not an uploaded file.
entailment
public function moveTo($targetPath) { $this->assertTmpFile(); if (!$this->isValidPath($targetPath)) { throw new \InvalidArgumentException("Unable to move " . $this->getDesc() . ": " . "'$targetPath' is not a valid path"); } $fn = [$this, $this->assertIsUploadedFile ? 'moveUploadedFile' : 'rename']; $ret = @call_user_func($fn, $this->tmpName, $targetPath); if (!$ret) { $err = error_get_last(); throw new \RuntimeException("Failed to move " . $this->getDesc() . " to '$targetPath'" . ($err ? ': ' . $err['message'] : null)); } }
Move the uploaded file to a new location. Use this method as an alternative to move_uploaded_file(). This method is guaranteed to work in both SAPI and non-SAPI environments. Implementations must determine which environment they are in, and use the appropriate method (move_uploaded_file(), rename(), or a stream operation) to perform the operation. $targetPath may be an absolute path, or a relative path. If it is a relative path, resolution should be the same as used by PHP's rename() function. The original file or stream is removed on completion. When used in an SAPI environment where $_FILES is populated, when writing files via moveTo(), is_uploaded_file() and move_uploaded_file() is used to ensure permissions and upload status are verified correctly. If you wish to move to a stream, use getStream(), as SAPI operations cannot guarantee writing to stream destinations. @see http://php.net/is_uploaded_file @see http://php.net/move_uploaded_file @param string $targetPath Path to which to move the uploaded file. @throws \InvalidArgumentException if the $targetPath specified is invalid. @throws \RuntimeException on any error during the move operation, or on the second or subsequent call to the method.
entailment
public function getErrorDescription() { if ($this->error === UPLOAD_ERR_OK) { return null; } $descs = static::ERROR_DESCRIPTIONS; return isset($descs[$this->error]) ? $descs[$this->error] : $descs[-1]; }
Retrieve the description of the error associated with the uploaded file. If the file was uploaded successfully, this method returns null. This method is not part of PSR-7. @return string|null
entailment
public function decorate() { foreach ($this->log as &$entries) { array_walk($entries, array($this, 'injectLinks')); } return $this->log; }
Decorates the output (e.g. adds linkgs to the issue tracker) @return self
entailment
public function generate() { if (true === empty($this->log)) { return array(); } $log = array(); // Iterate over grouped entries foreach ($this->log as $header => &$entries) { // Add a group header (e.g. Bugfixes) $log[] = sprintf("\n#### %s", $header); // Iterate over entries foreach ($entries as &$line) { $message = explode(VCS::MSG_SEPARATOR, $line); $log[] = sprintf("* %s", trim($message[0])); // Include multi-line entries if (true === isset($message[1])) { $log[] = sprintf("\n %s", trim($message[1])); } } } // Return a write-ready log return array_merge(array("## {$this->release}", "*({$this->date->format('Y-m-d')})*"), $log, array("\n---\n")); }
Returns a write-ready log. @return array
entailment
protected function serverParamKeyToHeaderName($key) { $name = null; if (\Jasny\str_starts_with($key, 'HTTP_')) { $name = $this->headerCase(substr($key, 5)); } elseif (in_array($key, ['CONTENT_TYPE', 'CONTENT_LENGTH'])) { $name = $this->headerCase($key); } return $name; }
Turn a server parameter key to a header name @param string $key @return string|null
entailment
protected function determineHeaders() { $params = $this->getServerParams(); $headers = []; foreach ($params as $key => $value) { $name = $this->serverParamKeyToHeaderName($key); if (isset($name) && is_string($value)) { $headers[$name] = [$value]; } } return $headers; }
Determine the headers based on the server parameters @return array headers array with structure $key => [$value]
entailment
public function deserialize($json) { $data = json_decode($json, true); //catch JSON parsing error $error = RESTfulAPIError::get_json_error(); if ($error !== false) { return new RESTfulAPIError(400, $error); } if ($data) { $data = $this->unformatPayloadData($data); } else { return new RESTfulAPIError(400, "No data received." ); } return $data; }
Convert client JSON data to an array of data ready to be consumed by SilverStripe Expects payload to be formatted: { "FieldName": "Field value", "Relations": [1] } @param string $data JSON to be converted to data ready to be consumed by SilverStripe @return array|false Formatted array representation of the JSON data or false if failed
entailment
protected function unformatPayloadData(array $data) { $unformattedData = array(); foreach ($data as $key => $value) { $newKey = $this->deserializeColumnName($key); if (is_array($value)) { $newValue = $this->unformatPayloadData($value); } else { $newValue = $value; } $unformattedData[$newKey] = $newValue; } return $unformattedData; }
Process payload data from client and unformats columns/values recursively @param array $data Payload data (decoded JSON) @return array Paylaod data with all keys/values unformatted
entailment
public function parse($arrAttributes = null) { // Messages (passed on to fineuploader JS) $basicTextOptions = array( 'text' => array( 'formatProgress', 'failUpload', 'waitingForResponse', 'paused', ), 'messages' => array( 'typeError', 'sizeError', 'minSizeError', 'emptyError', 'noFilesError', 'tooManyItemsError', 'maxHeightImageError', 'maxWidthImageError', 'minHeightImageError', 'minWidthImageError', 'retryFailTooManyItems', 'onLeave', 'unsupportedBrowserIos8Safari', ), 'retry' => array( 'autoRetryNote', ), 'deleteFile' => array( 'confirmMessage', 'deletingStatusText', 'deletingFailedText', ), 'paste' => array( 'namePromptMessage', ) ); $config = array(); foreach ($basicTextOptions as $category => $messages) { foreach ($messages as $message) { // Only translate if available, otherwise fall back to default (EN) if (isset($GLOBALS['TL_LANG']['MSC']['fineuploader_trans'][$category][$message])) { $config[$category][$message] = $GLOBALS['TL_LANG']['MSC']['fineuploader_trans'][$category][$message]; } } } // BC (used to be a JSON string) if (isset($this->arrConfiguration['uploaderConfig']) && $this->arrConfiguration['uploaderConfig'] !== '' ) { $this->arrConfiguration['uploaderConfig'] = json_decode('{' . $this->arrConfiguration['uploaderConfig'] . '}', true); } // Merge with custom options $this->config = json_encode(array_merge($config, (array) $this->arrConfiguration['uploaderConfig'])); // Labels (in HTML) $labels = array( 'drop', 'upload', 'processing', 'cancel', 'retry', 'delete', 'close', 'yes', 'no', ); $preparedLabels = array(); foreach ($labels as $label) { $preparedLabels[$label] = $GLOBALS['TL_LANG']['MSC']['fineuploader_' . $label]; } // Set the upload button label if ($this->uploadButtonLabel) { $preparedLabels['upload'] = $this->uploadButtonLabel; } $this->labels = $preparedLabels; return parent::parse($arrAttributes); }
Add the labels and messages. @param null $arrAttributes
entailment
public function validateUpload() { \Message::reset(); $strTempName = $this->strName . '_fineuploader'; $objUploader = new \Haste\Util\FileUpload($this->strName); $blnIsChunk = isset($_POST['qqpartindex']); // Convert the $_FILES array to Contao format if (!empty($_FILES[$strTempName])) { $arrFile = array ( 'name' => array($_FILES[$strTempName]['name']), 'type' => array($_FILES[$strTempName]['type']), 'tmp_name' => array($_FILES[$strTempName]['tmp_name']), 'error' => array($_FILES[$strTempName]['error']), 'size' => array($_FILES[$strTempName]['size']), ); // Replace the comma character (#22) $arrFile['name'] = str_replace(',', '_', $arrFile['name']); // Set the UUID as the filename if ($blnIsChunk) { $arrFile['name'][0] = \Input::post('qquuid') . '.chunk'; } // Check if the file exists if (file_exists(TL_ROOT . '/' . $this->strTemporaryPath . '/' . $arrFile['name'][0])) { $arrFile['name'][0] = $this->getFileName($arrFile['name'][0], $this->strTemporaryPath); } $_FILES[$this->strName] = $arrFile; unset($_FILES[$strTempName]); // Unset the temporary file } $varInput = ''; // Add the "chunk" extension to upload types if ($blnIsChunk) { $extensions = trimsplit(',', $GLOBALS['TL_CONFIG']['uploadTypes']); $extensions[] = 'chunk'; $objUploader->setExtensions($extensions); } // Validate the minlength if ($this->arrConfiguration['minlength'] > 0 && !$blnIsChunk) { $objUploader->setMinFileSize($this->arrConfiguration['minlength']); } // Validate the maxlength if ($this->arrConfiguration['maxlength'] > 0 || $blnIsChunk) { $objUploader->setMaxFileSize($blnIsChunk ? $this->arrConfiguration['chunkSize'] : $this->arrConfiguration['maxlength']); } // Set the maximum width if ($this->arrConfiguration['maxWidth']) { $objUploader->setImageWidth($this->arrConfiguration['maxWidth']); } // Set the maximum height if ($this->arrConfiguration['maxHeight']) { $objUploader->setImageHeight($this->arrConfiguration['maxHeight']); } try { $varInput = $objUploader->uploadTo($this->strTemporaryPath); if ($objUploader->hasError()) { if (version_compare(VERSION, '4.2', '>=')) { $session = \System::getContainer()->get('session'); foreach ($session->getFlashBag()->peek('contao.'.TL_MODE.'.error') as $strError) { $this->addError($strError); } } else { foreach ((array) $_SESSION['TL_ERROR'] as $strError) { $this->addError($strError); } } } \Message::reset(); } catch (\Exception $e) { $this->addError($e->getMessage()); } if (!is_array($varInput) || empty($varInput)) { $this->addError($GLOBALS['TL_LANG']['MSC']['fineuploader_error']); } $varInput = $varInput[0]; // Store the chunk in the session for further merge if ($blnIsChunk) { $_SESSION[$this->strName . '_FINEUPLOADER_CHUNKS'][\Input::post('qqfilename')][] = $varInput; // This is the last chunking request, merge the chunks and create the final file if (\Input::post('qqpartindex') == \Input::post('qqtotalparts') - 1) { $strFileName = \Input::post('qqfilename'); // Get the new file name if (file_exists(TL_ROOT . '/' . $this->strTemporaryPath . '/' . $strFileName)) { $strFileName = $this->getFileName($strFileName, $this->strTemporaryPath); } $objFile = new \File($this->strTemporaryPath . '/' . $strFileName); // Merge the chunks foreach ($_SESSION[$this->strName . '_FINEUPLOADER_CHUNKS'][\Input::post('qqfilename')] as $strChunk) { $objFile->append(file_get_contents(TL_ROOT . '/' . $strChunk), ''); // Delete the file \Files::getInstance()->delete($strChunk); } $objFile->close(); $varInput = $objFile->path; // Validate the minlength if ($this->arrConfiguration['minlength'] > 0 && $objFile->size < $this->arrConfiguration['minlength']) { $readableSize = \System::getReadableSize($this->arrConfiguration['minlength']); $this->addError(sprintf($GLOBALS['TL_LANG']['ERR']['minFileSize'], $readableSize)); \System::log('File "'.$objFile->name.'" is smaller than the minimum file size of '.$readableSize, __METHOD__, TL_ERROR); } // Validate the maxlength if ($this->arrConfiguration['maxlength'] > 0 && $objFile->size > $this->arrConfiguration['maxlength']) { $readableSize = \System::getReadableSize($this->arrConfiguration['maxlength']); $this->addError(sprintf($GLOBALS['TL_LANG']['ERR']['maxFileSize'], $readableSize)); \System::log('File "'.$objFile->name.'" exceeds the maximum file size of '.$readableSize, __METHOD__, TL_ERROR); } // Reset the chunk flag $blnIsChunk = false; // Unset the file session after merging the chunks unset($_SESSION[$this->strName . '_FINEUPLOADER_CHUNKS'][\Input::post('qqfilename')]); } } // Validate and move the file immediately if ($this->arrConfiguration['directUpload'] && !$blnIsChunk) { $varInput = $this->validatorSingle($varInput, $this->getDestinationFolder()); } return $varInput; }
Validate the upload @return string
entailment
protected function validator($varInput) { $varReturn = $this->blnIsMultiple ? array() : ''; $strDestination = $this->getDestinationFolder(); // Check if mandatory if ($varInput == '' && $this->mandatory) { $this->addError(sprintf($GLOBALS['TL_LANG']['ERR']['mandatory'], $this->strLabel)); } // Single file elseif (strpos($varInput, ',') === false) { $varInput = $this->validatorSingle($varInput, $strDestination); $varReturn = $this->blnIsMultiple ? array($varInput) : $varInput; } // Multiple files else { $arrValues = array_filter(explode(',', $varInput)); // Limit the number of uploads if ($this->arrConfiguration['uploaderLimit'] > 0) { $arrValues = array_slice($arrValues, 0, $this->arrConfiguration['uploaderLimit']); } foreach ($arrValues as $k => $v) { $arrValues[$k] = $this->validatorSingle($v, $strDestination); } $varReturn = $this->blnIsMultiple ? $arrValues : $arrValues[0]; } return $varReturn; }
Return an array if the "multiple" attribute is set @param mixed @return mixed
entailment
protected function getDestinationFolder() { $destination = \Config::get('uploadPath'); $folder = null; // Specify the target folder in the DCA (eval) if (isset($this->arrConfiguration['uploadFolder'])) { $folder = $this->arrConfiguration['uploadFolder']; } // Use the user's home directory if ($this->arrConfiguration['useHomeDir'] && FE_USER_LOGGED_IN) { $user = FrontendUser::getInstance(); if ($user->assignDir && $user->homeDir) { $folder = $user->homeDir; } } if ($folder !== null && \Validator::isUuid($folder)) { $folderModel = \FilesModel::findByUuid($folder); if ($folderModel !== null) { $destination = $folderModel->path; } } else { $destination = $folder; } return $destination; }
Get the destination folder @return mixed
entailment
protected function validatorSingle($varFile, $strDestination) { // Move the temporary file if (!\Validator::isStringUuid($varFile) && is_file(TL_ROOT . '/' . $varFile)) { $varFile = $this->moveTemporaryFile($varFile, $strDestination); } // Convert uuid to binary format if (\Validator::isStringUuid($varFile)) { $varFile = \StringUtil::uuidToBin($varFile); } return $varFile; }
Validate a single file. @param mixed @param string @return mixed
entailment
protected function moveTemporaryFile($strFile, $strDestination) { if (!is_file(TL_ROOT . '/' . $strFile)) { return ''; } // Do not store the file if (!$this->arrConfiguration['storeFile']) { return $strFile; } // The file is not temporary if (stripos($strFile, $this->strTemporaryPath) === false) { return $strFile; } $strNew = $strDestination . '/' . basename($strFile); // Do not overwrite existing files if ($this->arrConfiguration['doNotOverwrite']) { $strNew = $strDestination . '/' . $this->getFileName(basename($strFile), $strDestination); } $blnRename = \Files::getInstance()->rename($strFile, $strNew); \Files::getInstance()->chmod($strNew, \Config::get('defaultFileChmod')); // Add the file to Dbafs if ($this->arrConfiguration['addToDbafs'] && $blnRename) { $objModel = \Dbafs::addResource($strNew); if ($objModel !== null) { $strNew = $objModel->uuid; } } return $strNew; }
Move the temporary file to its destination @param string @param string @return string
entailment
protected function getFileName($strFile, $strFolder) { if (!file_exists(TL_ROOT . '/' . $strFolder . '/' . $strFile)) { return $strFile; } $offset = 1; $pathinfo = pathinfo($strFile); $name = $pathinfo['filename']; $arrAll = scan(TL_ROOT . '/' . $strFolder); $arrFiles = preg_grep('/^' . preg_quote($name, '/') . '.*\.' . preg_quote($pathinfo['extension'], '/') . '/', $arrAll); foreach ($arrFiles as $file) { if (preg_match('/__[0-9]+\.' . preg_quote($pathinfo['extension'], '/') . '$/', $file)) { $file = str_replace('.' . $pathinfo['extension'], '', $file); $intValue = intval(substr($file, (strrpos($file, '_') + 1))); $offset = max($offset, $intValue); } } return str_replace($name, $name . '__' . ++$offset, $strFile); }
Get the new file name if it already exists in the folder @param string @param string @return string
entailment
protected function generateFileItem($strPath) { if (!is_file(TL_ROOT . '/' . $strPath)) { return ''; } $imageSize = $this->getImageSize(); $objFile = new \File($strPath, true); $strInfo = $strPath . ' <span class="tl_gray">(' . \System::getReadableSize($objFile->size) . ($objFile->isGdImage ? ', ' . $objFile->width . 'x' . $objFile->height . ' px' : '') . ')</span>'; $allowedDownload = trimsplit(',', strtolower($GLOBALS['TL_CONFIG']['allowedDownload'])); $strReturn = ''; // Show files and folders if (!$this->blnIsGallery && !$this->blnIsDownloads) { if ($objFile->isGdImage) { $strReturn = \Image::getHtml(\Image::get($strPath, $imageSize[0], $imageSize[1], $imageSize[2]), '', 'class="gimage" title="' . specialchars($strInfo) . '"'); } else { $strReturn = \Image::getHtml($objFile->icon) . ' ' . $strInfo; } } // Show a sortable list of files only else { if ($this->blnIsGallery) { // Only show images if ($objFile->isGdImage) { $strReturn = \Image::getHtml(\Image::get($strPath, $imageSize[0], $imageSize[1], $imageSize[2]), '', 'class="gimage" title="' . specialchars($strInfo) . '"'); } } else { // Only show allowed download types if (in_array($objFile->extension, $allowedDownload) && !preg_match('/^meta(_[a-z]{2})?\.txt$/', $objFile->basename)) { $strReturn = \Image::getHtml($objFile->icon) . ' ' . $strPath; } } } return $strReturn; }
Generate a file item and return it as HTML string @param string @return string
entailment
public static function get_json_error() { $error = 'JSON - '; switch (json_last_error()) { case JSON_ERROR_NONE: $error = false; break; case JSON_ERROR_DEPTH: $error .= 'The maximum stack depth has been exceeded.'; break; case JSON_ERROR_STATE_MISMATCH: $error .= 'Invalid or malformed JSON.'; break; case JSON_ERROR_CTRL_CHAR: $error .= 'Control character error, possibly incorrectly encoded.'; break; case JSON_ERROR_SYNTAX: $error .= 'Syntax error.'; break; default: $error .= 'Unknown error (' . json_last_error() . ').'; break; } return $error; }
Check for the latest JSON parsing error and return the message if any More available for PHP >= 5.3.3 http://www.php.net/manual/en/function.json-last-error.php @return false|string Returns false if no error or a string with the error detail.
entailment
protected function setScheme($scheme) { $scheme = strtolower($scheme); if ($scheme !== '' && !$this->isSupportedScheme($scheme)) { throw new \InvalidArgumentException("Invalid or unsupported scheme '$scheme'"); } $this->scheme = $scheme; }
Set the scheme @param string $scheme @throws \InvalidArgumentException for invalid or unsupported schemes.
entailment
protected function setFragment($fragment) { if (!$this->isValidFragment($fragment)) { throw new \InvalidArgumentException("Invalid fragment '$fragment'"); } $this->fragment = (string)$fragment; }
Set the fragment @param string $fragment
entailment
public function useGlobally() { if (!isset($this->handle)) { throw new \RuntimeException("The stream is closed"); } if ($this->isGlobal()) { return $this; } $this->assertOutputBuffering(); $output = $this->createOutputStream(); if ($output === false) { throw new \RuntimeException("Failed to create temp stream"); } $this->obClean(); $this->rewind(); stream_copy_to_stream($this->handle, $output); parent::close(); $this->handle = $output; return $this; }
After change Response body work with global enviroment this function are copy all content from previous Stream body (like php://temp) and copy it into current php://output stream. @return $this @throws \RuntimeException
entailment
public function withLocalScope() { if ($this->isClosed()) { throw new \RuntimeException("The stream is closed"); } if (!$this->isGlobal()) { return $this; } $stream = clone $this; fwrite($stream->handle, (string)$this); return $stream; }
Get this stream in a local scope. If the stream is global, it will create a temp stream and copy the contents. @return OutputBufferStream @throws \RuntimeException
entailment
public function seek($offset, $whence = SEEK_SET) { if (!$this->isGlobal()) { return parent::seek($offset, $whence); } throw new \RuntimeException("Stream isn't seekable"); }
Seek to a position in the stream. @see http://www.php.net/manual/en/function.fseek.php @param int $offset Stream offset @param int $whence Specifies how the cursor position will be calculated based on the seek offset. Valid values are identical to the built-in PHP $whence values for `fseek()`. SEEK_SET: Set position equal to offset bytes SEEK_CUR: Set position to current location plus offset SEEK_END: Set position to end-of-stream plus offset. @throws \RuntimeException on failure.
entailment
public function getBody() { if (!isset($this->body)) { $this->body = $this->createDefaultBody(); } return $this->body; }
Gets the body of the message. @return StreamInterface Returns the body as a stream.
entailment
public function withBody(StreamInterface $body) { $request = $this->copy(); $request->setBody($body); return $request; }
Return an instance with the specified message body. @param StreamInterface $body @return static
entailment
public function login(HTTPRequest $request) { $response = array(); if ($this->tokenConfig['owner'] === Member::class) { $email = $request->requestVar('email'); $pwd = $request->requestVar('pwd'); $member = false; if ($email && $pwd) { $member = Injector::inst()->get(MemberAuthenticator::class)->authenticate( array( 'Email' => $email, 'Password' => $pwd, ), $request ); if ($member) { $tokenData = $this->generateToken(); $tokenDBColumn = $this->tokenConfig['DBColumn']; $expireDBColumn = $this->tokenConfig['expireDBColumn']; $member->{$tokenDBColumn} = $tokenData['token']; $member->{$expireDBColumn} = $tokenData['expire']; $member->write(); $member->login(); } } if (!$member) { $response['result'] = false; $response['message'] = 'Authentication fail.'; $response['code'] = self::AUTH_CODE_LOGIN_FAIL; } else { $response['result'] = true; $response['message'] = 'Logged in.'; $response['code'] = self::AUTH_CODE_LOGGED_IN; $response['token'] = $tokenData['token']; $response['expire'] = $tokenData['expire']; $response['userID'] = $member->ID; } } return $response; }
Login a user into the Framework and generates API token Only works if the token owner is a Member @param HTTPRequest $request HTTP request containing 'email' & 'pwd' vars @return array login result with token
entailment
public function logout(HTTPRequest $request) { $email = $request->requestVar('email'); $member = Member::get()->filter(array('Email' => $email))->first(); if ($member) { //logout $member->logout(); if ($this->tokenConfig['owner'] === Member::class) { //generate expired token $tokenData = $this->generateToken(true); //write $tokenDBColumn = $this->tokenConfig['DBColumn']; $expireDBColumn = $this->tokenConfig['expireDBColumn']; $member->{$tokenDBColumn} = $tokenData['token']; $member->{$expireDBColumn} = $tokenData['expire']; $member->write(); } } }
Logout a user from framework and update token with an expired one if token owner class is a Member @param HTTPRequest $request HTTP request containing 'email' var
entailment
public function lostPassword(HTTPRequest $request) { $email = Convert::raw2sql($request->requestVar('email')); $member = DataObject::get_one(Member::class, "\"Email\" = '{$email}'"); if ($member) { $token = $member->generateAutologinTokenAndStoreHash(); $link = Security::lost_password_url(); $lostPasswordHandler = new LostPasswordHandler($link); $lostPasswordHandler->sendEmail($member, $token); } return array('done' => true); }
Sends password recovery email @param HTTPRequest $request HTTP request containing 'email' vars @return array 'email' => false if email fails (Member doesn't exist will not be reported)
entailment
public function getToken($id) { if ($id) { $ownerClass = $this->tokenConfig['owner']; $owner = DataObject::get_by_id($ownerClass, $id); if ($owner) { $tokenDBColumn = $this->tokenConfig['DBColumn']; return $owner->{$tokenDBColumn}; } else { user_error("API Token owner '$ownerClass' not found with ID = $id", E_USER_WARNING); } } else { user_error("TokenAuthenticator::getToken() requires an ID as argument.", E_USER_WARNING); } }
Return the stored API token for a specific owner @param integer $id ID of the token owner @return string API token for the owner
entailment
public function resetToken($id, $expired = false) { if ($id) { $ownerClass = $this->tokenConfig['owner']; $owner = DataObject::get_by_id($ownerClass, $id); if ($owner) { //generate token $tokenData = $this->generateToken($expired); //write $tokenDBColumn = $this->tokenConfig['DBColumn']; $expireDBColumn = $this->tokenConfig['expireDBColumn']; $owner->{$tokenDBColumn} = $tokenData['token']; $owner->{$expireDBColumn} = $tokenData['expire']; $owner->write(); } else { user_error("API Token owner '$ownerClass' not found with ID = $id", E_USER_WARNING); } } else { user_error("TokenAuthenticator::resetToken() requires an ID as argument.", E_USER_WARNING); } }
Reset an owner's token if $expired is set to true the owner's will have a new invalidated/expired token @param integer $id ID of the token owner @param boolean $expired if true the token will be invalidated
entailment
private function generateToken($expired = false) { $life = $this->tokenConfig['life']; if (!$expired) { $expire = time() + $life; } else { $expire = time() - ($life * 2); } $generator = new RandomGenerator(); $tokenString = $generator->randomToken(); $e = PasswordEncryptor::create_for_algorithm('blowfish'); //blowfish isn't URL safe and maybe too long? $salt = $e->salt($tokenString); $token = $e->encrypt($tokenString, $salt); return array( 'token' => substr($token, 7), 'expire' => $expire, ); }
Generates an encrypted random token and an expiry date @param boolean $expired Set to true to generate an outdated token @return array token data array('token' => HASH, 'expire' => EXPIRY_DATE)
entailment
public function getOwner(HTTPRequest $request) { $owner = null; //get the token $token = $request->getHeader($this->tokenConfig['header']); if (!$token) { $token = $request->requestVar($this->tokenConfig['queryVar']); } if ($token) { $SQLToken = Convert::raw2sql($token); $owner = DataObject::get_one( $this->tokenConfig['owner'], "\"" . $this->tokenConfig['DBColumn'] . "\"='" . $SQLToken . "'", false ); if (!$owner) { $owner = null; } } return $owner; }
Returns the DataObject related to the token that sent the authenticated request @param HTTPRequest $request HTTP API request @return null|DataObject null if failed or the DataObject token owner related to the request
entailment
public function authenticate(HTTPRequest $request) { //get the token $token = $request->getHeader($this->tokenConfig['header']); if (!$token) { $token = $request->requestVar($this->tokenConfig['queryVar']); } if ($token) { //check token validity return $this->validateAPIToken($token, $request); } else { //no token, bad news return new RESTfulAPIError(403, 'Token invalid.', array( 'message' => 'Token invalid.', 'code' => self::AUTH_CODE_TOKEN_INVALID, ) ); } }
Checks if a request to the API is authenticated Gets API Token from HTTP Request and return Auth result @param HTTPRequest $request HTTP API request @return true|RESTfulAPIError True if token is valid OR RESTfulAPIError with details
entailment
private function validateAPIToken($token, $request) { //get owner with that token $SQL_token = Convert::raw2sql($token); $tokenColumn = $this->tokenConfig['DBColumn']; $tokenOwner = DataObject::get_one( $this->tokenConfig['owner'], "\"" . $this->tokenConfig['DBColumn'] . "\"='" . $SQL_token . "'", false ); if ($tokenOwner) { //check token expiry $tokenExpire = $tokenOwner->{$this->tokenConfig['expireDBColumn']}; $now = time(); $life = $this->tokenConfig['life']; if ($tokenExpire > ($now - $life)) { // check if token should automatically be updated if ($this->tokenConfig['autoRefresh']) { $tokenOwner->setField($this->tokenConfig['expireDBColumn'], $now + $life); $tokenOwner->write(); } //all good, log Member in if (is_a($tokenOwner, Member::class)) { # this is a login without the logging Config::nest(); Config::modify()->set(Member::class, 'session_regenerate_id', true); $identityStore = Injector::inst()->get(IdentityStore::class); $identityStore->logIn($tokenOwner, false, $request); Config::unnest(); } return true; } else { //too old return new RESTfulAPIError(403, 'Token expired.', array( 'message' => 'Token expired.', 'code' => self::AUTH_CODE_TOKEN_EXPIRED, ) ); } } else { //token not found //not sure it's wise to say it doesn't exist. Let's be shady here return new RESTfulAPIError(403, 'Token invalid.', array( 'message' => 'Token invalid.', 'code' => self::AUTH_CODE_TOKEN_INVALID, ) ); } }
Validate the API token @param string $token Authentication token @param HTTPRequest $request HTTP API request @return true|RESTfulAPIError True if token is valid OR RESTfulAPIError with details
entailment
protected function jsonify($data) { // JSON_NUMERIC_CHECK removes leading zeros // which is an issue in cases like postcode e.g. 00160 // see https://bugs.php.net/bug.php?id=64695 $json = json_encode($data); //catch JSON parsing error $error = RESTfulAPIError::get_json_error(); if ($error !== false) { return new RESTfulAPIError(400, $error); } return $json; }
Convert data into a JSON string @param mixed $data Data to convert @return string JSON data
entailment
public function serialize($data) { $json = ''; $formattedData = null; if ($data instanceof DataObject) { $formattedData = $this->formatDataObject($data); } elseif ($data instanceof DataList) { $formattedData = $this->formatDataList($data); } if ($formattedData !== null) { $json = $this->jsonify($formattedData); } else { //fallback: convert non array to object then encode if (!is_array($data)) { $data = (object) $data; } $json = $this->jsonify($data); } return $json; }
Convert raw data (DataObject or DataList) to JSON ready to be consumed by the client API @param mixed $data Data to serialize @return string JSON representation of data
entailment
protected function formatDataObject(DataObject $dataObject) { // api access control if (!RESTfulAPI::api_access_control($dataObject, 'GET')) { return null; } if (method_exists($dataObject, 'onBeforeSerialize')) { $dataObject->onBeforeSerialize(); } $dataObject->extend('onBeforeSerialize'); // setup $formattedDataObjectMap = array(); // get DataObject config $class = get_class($dataObject); $db = Config::inst()->get($class, 'db'); $has_one = Config::inst()->get($class, 'has_one'); $has_many = Config::inst()->get($class, 'has_many'); $many_many = Config::inst()->get($class, 'many_many'); $belongs_many_many = Config::inst()->get($class, 'belongs_many_many'); // Get a possibly defined list of "api_fields" for this DataObject. If defined, they will be the only fields // for this DataObject that will be returned, including related models. $apiFields = (array) Config::inst()->get($class, 'api_fields'); //$many_many_extraFields = $dataObject->many_many_extraFields(); $many_many_extraFields = $dataObject->stat('many_many_extraFields'); // setup ID (not included in $db!!) $serializedColumnName = $this->serializeColumnName('ID'); $formattedDataObjectMap[$serializedColumnName] = $dataObject->getField('ID'); // iterate over simple DB fields if (!$db) { $db = array(); } foreach ($db as $columnName => $fieldClassName) { // Check whether this field has been specified as allowed via api_fields if (!empty($apiFields) && !in_array($columnName, $apiFields)) { continue; } $serializedColumnName = $this->serializeColumnName($columnName); $formattedDataObjectMap[$serializedColumnName] = $dataObject->getField($columnName); } // iterate over has_one relations if (!$has_one) { $has_one = array(); } foreach ($has_one as $columnName => $fieldClassName) { // Skip if api_fields is set for the parent, and this column is not in it if (!empty($apiFields) && !in_array($columnName, $apiFields)) { continue; } $serializedColumnName = $this->serializeColumnName($columnName); // convert foreign ID to integer $relationID = intVal($dataObject->{$columnName . 'ID'}); // skip empty relations if ($relationID === 0) { continue; } // check if this should be embedded if ($this->isEmbeddable($dataObject->ClassName, $columnName)) { // get the relation's record ready to embed $embedData = $this->getEmbedData($dataObject, $columnName); // embed the data if any if ($embedData !== null) { $formattedDataObjectMap[$serializedColumnName] = $embedData; } } else { // save foreign ID $formattedDataObjectMap[$serializedColumnName] = $relationID; } } // combine defined '_many' relations into 1 array $many_relations = array(); if (is_array($has_many)) { $many_relations = array_merge($many_relations, $has_many); } if (is_array($many_many)) { $many_relations = array_merge($many_relations, $many_many); } if (is_array($belongs_many_many)) { $many_relations = array_merge($many_relations, $belongs_many_many); } // iterate '_many' relations foreach ($many_relations as $relationName => $relationClassname) { // Skip if api_fields is set for the parent, and this column is not in it if (!empty($apiFields) && !in_array($relationName, $apiFields)) { continue; } //get the DataList for this realtion's name $dataList = $dataObject->{$relationName}(); //if there actually are objects in the relation if ($dataList->count()) { // check if this relation should be embedded if ($this->isEmbeddable($dataObject->ClassName, $relationName)) { // get the relation's record(s) ready to embed $embedData = $this->getEmbedData($dataObject, $relationName); // embed the data if any if ($embedData !== null) { $serializedColumnName = $this->serializeColumnName($relationName); $formattedDataObjectMap[$serializedColumnName] = $embedData; } } else { // set column value to ID list $idList = $dataList->map('ID', 'ID')->keys(); $serializedColumnName = $this->serializeColumnName($relationName); $formattedDataObjectMap[$serializedColumnName] = $idList; } } } if ($many_many_extraFields) { $extraFieldsData = array(); // loop through extra fields config foreach ($many_many_extraFields as $relation => $fields) { $manyManyDataObjects = $dataObject->$relation(); $relationData = array(); // get the extra data for each object in the relation foreach ($manyManyDataObjects as $manyManyDataObject) { $data = $manyManyDataObjects->getExtraData($relation, $manyManyDataObject->ID); // format data foreach ($data as $key => $value) { // clear empty data if (!$value) { unset($data[$key]); continue; } $newKey = $this->serializeColumnName($key); if ($newKey != $key) { unset($data[$key]); $data[$newKey] = $value; } } // store if there is any real data if ($data) { $relationData[$manyManyDataObject->ID] = $data; } } // add individual DO extra data to the relation's extra data if ($relationData) { $key = $this->serializeColumnName($relation); $extraFieldsData[$key] = $relationData; } } // save the extrafields data if ($extraFieldsData) { $key = $this->serializeColumnName('ManyManyExtraFields'); $formattedDataObjectMap[$key] = $extraFieldsData; } } if (method_exists($dataObject, 'onAfterSerialize')) { $dataObject->onAfterSerialize($formattedDataObjectMap); } $dataObject->extend('onAfterSerialize', $formattedDataObjectMap); return $formattedDataObjectMap; }
Format a DataObject keys and values ready to be turned into JSON @param DataObject $dataObject The data object to format @return array|null The formatted array map representation of the DataObject or null is permission denied
entailment
protected function formatDataList(DataList $dataList) { $formattedDataListMap = array(); foreach ($dataList as $dataObject) { $formattedDataObjectMap = $this->formatDataObject($dataObject); if ($formattedDataObjectMap) { array_push($formattedDataListMap, $formattedDataObjectMap); } } return $formattedDataListMap; }
Format a DataList into a formatted array ready to be turned into JSON @param DataList $dataList The DataList to format @return array The formatted array representation of the DataList
entailment
protected function getEmbedData(DataObject $record, $relationName) { if ($record->hasMethod($relationName)) { $relationData = $record->$relationName(); if ($relationData instanceof RelationList) { return $this->formatDataList($relationData); } else { return $this->formatDataObject($relationData); } } return null; }
Returns a DataObject relation's data formatted and ready to embed. @param DataObject $record The DataObject to get the data from @param string $relationName The name of the relation @return array|null Formatted DataObject or RelationList ready to embed or null if nothing to embed
entailment
protected function isEmbeddable($model, $relation) { if (array_key_exists($model, $this->embeddedRecords)) { return is_array($this->embeddedRecords[$model]) && in_array($relation, $this->embeddedRecords[$model]); } return false; }
Checks if a speicific model's relation should have its records embedded. @param string $model Model's classname @param string $relation Relation name @return boolean Trus if the relation should be embedded
entailment
protected function setQuery($query) { if (is_array($query)) { $query = http_build_query($query); } if (!$this->isValidQuery($query)) { throw new \InvalidArgumentException("Invalid query '$query'"); } $this->query = (string)$query; }
Set the query @param string|array $query
entailment
public function register() { /** @noinspection PhpUndefinedFieldInspection */ $this->app->singleton('onesignal', function ($app) { /** @noinspection PhpUndefinedFunctionInspection */ /** @noinspection PhpUndefinedFunctionInspection */ /** @noinspection PhpUndefinedFunctionInspection */ $config = [ "app_id" => $app['config']['onesignal']['onesignal_app_id'], "rest_api_key" => $app['config']['onesignal']['onesignal_rest_api_key'], "user_auth_key" => $app['config']['onesignal']['onesignal_user_auth_key'], ]; $client = new OneSignalClient($config[ 'app_id' ], $config[ 'rest_api_key' ], $config[ 'user_auth_key' ]); return $client; }); }
Register the application services. @return void
entailment
public function getMethod() { if (!isset($this->method)) { $this->method = $this->determineMethod(); } return $this->method; }
Retrieves the HTTP method of the request. @return string Returns the request method.
entailment
protected function assertMethod($method) { if (!is_string($method)) { $type = (is_object($method) ? get_class($method) . ' ' : '') . gettype($method); throw new \InvalidArgumentException("Method should be a string, not a $type"); } if (preg_match('/[^a-z\-]/i', $method)) { $type = (is_object($method) ? get_class($method) . ' ' : '') . gettype($method); throw new \InvalidArgumentException("Invalid method '$method': " . "Method may only contain letters and dashes"); } }
Assert method is valid @param string $method @throws \InvalidArgumentException
entailment
public function withMethod($method) { $this->assertMethod($method); $request = $this->copy(); $request->method = $method; return $request; }
Return an instance with the provided HTTP method. @param string $method Case-sensitive method. @return static @throws \InvalidArgumentException for invalid HTTP methods.
entailment
protected function header($string, $replace = true, $http_response_code = null) { header($string, $replace, $http_response_code); }
Wrapper for `header` function @link http://php.net/manual/en/function.header.php @codeCoverageIgnore @param string $string @param boolean $replace @param int $http_response_code
entailment
protected function assertStatusCode($code) { if (!is_int($code) && !(is_string($code) && ctype_digit($code))) { throw new \InvalidArgumentException("Response code must be integer"); } if ($code < 100 || $code > 999) { throw new \InvalidArgumentException("Response code must be in range 100...999"); } }
Assert that the status code is valid (100..999) @param string $code @throws \InvalidArgumentException
entailment
protected function setStatus($code, $reasonPhrase) { $this->assertStatusCode($code); $this->assertReasonPhrase($reasonPhrase); if (empty($reasonPhrase) && array_key_exists($code, $this->defaultStatuses)) { $reasonPhrase = $this->defaultStatuses[$code]; } $this->code = (int)$code; $this->phrase = (string)$reasonPhrase; }
Set the specified status code and reason phrase. @param int $code @param string $reasonPhrase
entailment
public function withStatus($code, $reasonPhrase = '') { $status = clone $this; $status->setStatus($code, $reasonPhrase); return $status; }
Create a new response status object with the specified code and phrase. @param int $code @param string $reasonPhrase @return ResponseStatus
entailment
public function requireDefaultRecords() { // Readers $readersGroup = DataObject::get(Group::class)->filter(array( 'Code' => 'restfulapi-readers', )); if (!$readersGroup->count()) { $readerGroup = new Group(); $readerGroup->Code = 'restfulapi-readers'; $readerGroup->Title = 'RESTful API Readers'; $readerGroup->Sort = 0; $readerGroup->write(); Permission::grant($readerGroup->ID, 'RESTfulAPI_VIEW'); } // Editors $editorsGroup = DataObject::get(Group::class)->filter(array( 'Code' => 'restfulapi-editors', )); if (!$editorsGroup->count()) { $editorGroup = new Group(); $editorGroup->Code = 'restfulapi-editors'; $editorGroup->Title = 'RESTful API Editors'; $editorGroup->Sort = 0; $editorGroup->write(); Permission::grant($editorGroup->ID, 'RESTfulAPI_VIEW'); Permission::grant($editorGroup->ID, 'RESTfulAPI_EDIT'); Permission::grant($editorGroup->ID, 'RESTfulAPI_CREATE'); } // Admins $adminsGroup = DataObject::get(Group::class)->filter(array( 'Code' => 'restfulapi-administrators', )); if (!$adminsGroup->count()) { $adminGroup = new Group(); $adminGroup->Code = 'restfulapi-administrators'; $adminGroup->Title = 'RESTful API Administrators'; $adminGroup->Sort = 0; $adminGroup->write(); Permission::grant($adminGroup->ID, 'RESTfulAPI_VIEW'); Permission::grant($adminGroup->ID, 'RESTfulAPI_EDIT'); Permission::grant($adminGroup->ID, 'RESTfulAPI_CREATE'); Permission::grant($adminGroup->ID, 'RESTfulAPI_DELETE'); } }
Create the default Groups and add default admin to admin group
entailment
public function loadAssets($table) { if (TL_MODE !== 'BE' || !is_array($GLOBALS['TL_DCA'][$table]['fields'])) { return; } foreach ($GLOBALS['TL_DCA'][$table]['fields'] as $field) { if ($field['inputType'] === 'fineUploader') { FineUploaderWidget::includeAssets(); break; } } }
Load the widget assets if they are needed. Load them here so the widget in subpalette can work as well. @param string $table
entailment
public function validateUpload() { $varInput = parent::validateUpload(); // Check image size if (($arrImageSize = @getimagesize(TL_ROOT . '/' . $varInput)) !== false) { // Image exceeds maximum image width if ($arrImageSize[0] > $GLOBALS['TL_CONFIG']['imageWidth']) { $this->addError(sprintf($GLOBALS['TL_LANG']['ERR']['filewidth'], '', $GLOBALS['TL_CONFIG']['imageWidth'])); } // Image exceeds maximum image height if ($arrImageSize[1] > $GLOBALS['TL_CONFIG']['imageHeight']) { $this->addError(sprintf($GLOBALS['TL_LANG']['ERR']['fileheight'], '', $GLOBALS['TL_CONFIG']['imageHeight'])); } } return $varInput; }
Validate the upload @return string
entailment
protected function validator($varInput) { $varReturn = parent::validator($varInput); $arrReturn = array_filter((array) $varReturn); $intCount = 0; foreach ($arrReturn as $varFile) { // Get the file model if (\Validator::isUuid($varFile)) { $objModel = \FilesModel::findByUuid($varFile); if ($objModel === null) { continue; } $varFile = $objModel->path; } $objFile = new \File($varFile, true); $_SESSION['FILES'][$this->strName . '_' . $intCount++] = array ( 'name' => $objFile->name, 'type' => $objFile->mime, 'tmp_name' => TL_ROOT . '/' . $objFile->path, 'error' => 0, 'size' => $objFile->size, 'uploaded' => true, 'uuid' => ($objModel !== null) ? \StringUtil::binToUuid($objModel->uuid) : '' ); } return $varReturn; }
Store the file information in the session @param mixed @return mixed
entailment
public function parse($arrAttributes=null) { if (!$this->blnValuesPrepared) { $arrSet = array(); $arrValues = array(); $arrUuids = array(); $arrTemp = array(); if (!empty($this->varValue)) { // Can be an array $this->varValue = (array) $this->varValue; foreach ($this->varValue as $varFile) { if (\Validator::isUuid($varFile)) { $arrUuids[] = $varFile; } else { $arrTemp[] = $varFile; } } $objFiles = \FilesModel::findMultipleByUuids($arrUuids); // Get the database files if ($objFiles !== null) { while ($objFiles->next()) { $chunk = $this->generateFileItem($objFiles->path); if (strlen($chunk)) { $arrValues[$objFiles->uuid] = array ( 'id' => (in_array($objFiles->uuid, $arrTemp) ? $objFiles->uuid : \StringUtil::binToUuid($objFiles->uuid)), 'value' => $chunk ); $arrSet[] = $objFiles->uuid; } } } // Get the temporary files foreach ($arrTemp as $varFile) { $chunk = $this->generateFileItem($varFile); if (strlen($chunk)) { $arrValues[$varFile] = array ( 'id' => (in_array($varFile, $arrTemp) ? $varFile : \StringUtil::binToUuid($varFile)), 'value' => $chunk ); $arrSet[] = $varFile; } } } // Parse the set array foreach ($arrSet as $k=>$v) { if (in_array($v, $arrTemp)) { $strSet[$k] = $v; } else { $arrSet[$k] = \StringUtil::binToUuid($v); } } $this->set = implode(',', $arrSet); $this->values = $arrValues; $this->deleteTitle = specialchars($GLOBALS['TL_LANG']['MSC']['delete']); $this->extensions = json_encode(trimsplit(',', $this->arrConfiguration['extensions'])); $this->limit = $this->arrConfiguration['uploaderLimit'] ? $this->arrConfiguration['uploaderLimit'] : 0; $this->minSizeLimit = $this->arrConfiguration['minlength'] ? $this->arrConfiguration['minlength'] : 0; $this->sizeLimit = $this->arrConfiguration['maxlength'] ? $this->arrConfiguration['maxlength'] : 0; $this->chunkSize = $this->arrConfiguration['chunkSize'] ? $this->arrConfiguration['chunkSize'] : 0; $this->concurrent = $this->arrConfiguration['concurrent'] ? true : false; $this->maxConnections = $this->arrConfiguration['maxConnections'] ? $this->arrConfiguration['maxConnections'] : 3; $this->blnValuesPrepared = true; } return parent::parse($arrAttributes); }
Generate the widget and return it as string @param array @return string
entailment
protected function mapUriPartsFromServerParams(array $params) { $parts = []; $map = [ 'PHP_AUTH_USER' => 'user', 'PHP_AUTH_PWD' => 'password', 'HTTP_HOST' => 'host', 'SERVER_PORT' => 'port', 'REQUEST_URI' => 'path', 'QUERY_STRING' => 'query' ]; foreach ($map as $param => $key) { if (isset($params[$param])) { $parts[$key] = $params[$param]; } } return $parts; }
Map server params for URI @param array $params @return array
entailment
protected function determineUri() { $params = $this->getServerParams(); $parts = $this->mapUriPartsFromServerParams($params); if ( isset($params['SERVER_PROTOCOL']) && \Jasny\str_starts_with(strtoupper($params['SERVER_PROTOCOL']), 'HTTP/') ) { $parts['scheme'] = !empty($params['HTTPS']) && $params['HTTPS'] !== 'off' ? 'https' : 'http'; } if (isset($parts['host'])) { list($parts['host']) = explode(':', $parts['host'], 2); // May include the port } if (isset($parts['path'])) { $parts['path'] = parse_url($parts['path'], PHP_URL_PATH); // Includes the query string } return new UriObject($parts); }
Determine the URI base on the server parameters @return string
entailment
public function getUri() { if (!isset($this->uri)) { $this->uri = $this->determineUri(); } return $this->uri; }
Retrieves the URI instance. This method MUST return a UriInterface instance. @see http://tools.ietf.org/html/rfc3986#section-4.3 @return UriInterface Returns a UriInterface instance representing the URI of the request.
entailment
public function withUri(UriInterface $uri, $preserveHost = false) { $request = $this->copy(); $request->uri = $uri; if (!$preserveHost) { $request = $request->withHeader('Host', $request->uri->getHost()); } return $request; }
Returns an instance with the provided URI. @see http://tools.ietf.org/html/rfc3986#section-4.3 @param UriInterface $uri New request URI to use. @param boolean $preserveHost Preserve the original state of the Host header. @return static
entailment
public function getParser() { if (true === empty($this->parser)) { $typeParserClassName = sprintf('\ReadmeGen\Vcs\Type\%s', ucfirst($this->config['vcs'])); if (false === class_exists($typeParserClassName)) { throw new \InvalidArgumentException(sprintf('Class "%s" does not exist', $typeParserClassName)); } $this->parser = new Parser(new $typeParserClassName()); } return $this->parser; }
Returns the parser. @return Parser @throws \InvalidArgumentException When the VCS parser class does not exist.
entailment
public function extractMessages(array $log = null) { if (true === empty($log)) { return array(); } $this->extractor->setMessageGroups($this->config['message_groups']); return $this->extractor->setLog($log) ->extract(); }
Returns messages extracted from the log. @param array $log @return array
entailment
public function getDecoratedMessages(array $log = null) { if (true === empty($log)) { return array(); } return $this->decorator->setLog($log) ->setIssueTrackerUrlPattern($this->config['issue_tracker_pattern']) ->decorate(); }
Returns decorated log messages. @param array $log @return array|Output\Format\FormatInterface
entailment
public function get($path, array $sourceConfig = null) { $config = Yaml::parse($this->getFileContent($path)); if (false === empty($sourceConfig)) { return array_replace_recursive($sourceConfig, $config); } return $config; }
Returns the config as an array. @param string $path Path to the file. @param array $sourceConfig Config array the result should be merged with. @return array @throws \Symfony\Component\Yaml\Exception\ParseException When a parse error occurs.
entailment
protected function getFileContent($path) { if (false === file_exists($path)) { throw new \InvalidArgumentException(sprintf('File "%s" does not exist.', $path)); } return file_get_contents($path); }
Returns the file's contents. @param string $path Path to file. @return string @throws \InvalidArgumentException When the file does not exist.
entailment
protected function setUriParts(array $parts) { foreach ($parts as $key => $value) { if (!method_exists($this, "set$key")) { continue; } $this->{"set$key"}($value); } }
Set the URI parts @param array $parts
entailment
protected function buildUri(array $parts) { $uri = ($parts['scheme'] ? "{$parts['scheme']}:" : '') . ($parts['user'] || $parts['host'] ? '//' : '') . ($parts['user'] ? "{$parts['user']}" : '') . ($parts['user'] && $parts['pass'] ? ":{$parts['pass']}" : '') . ($parts['user'] ? '@' : '') . ($parts['host'] ? "{$parts['host']}" : '') . ($parts['port'] ? ":{$parts['port']}" : ''); $uri .= ($uri && $parts['path'] && $parts['path'][0] !== '/' ? '/' : '') . ($parts['path'] ? "{$parts['path']}" : '') . ($parts['query'] ? "?{$parts['query']}" : '') . ($parts['fragment'] ? "#{$parts['fragment']}" : ''); return $uri; }
Build a uri from all the parts @param array $parts @return type
entailment
protected function determineRequestTarget() { $params = $this->getServerParams(); return isset($params['REQUEST_URI']) ? $params['REQUEST_URI'] : (isset($params['REQUEST_METHOD']) && $params['REQUEST_METHOD'] === 'OPTIONS' ? '*' : '/'); }
Determine the request target based on the server params @return string
entailment
public function getRequestTarget() { if (!isset($this->requestTarget)) { $this->requestTarget = $this->determineRequestTarget(); } return $this->requestTarget; }
Retrieves the message's request target. Retrieves the message's request-target either as it will appear (for clients), as it appeared at request (for servers), or as it was specified for the instance (see withRequestTarget()). In most cases, this will be the origin-form of the composed URI, unless a value was provided to the concrete implementation (see withRequestTarget() below). If no URI is available, and no request-target has been specifically provided, this method returns the string "/". @return string
entailment
protected function assertRequestTarget($requestTarget) { if (!is_string($requestTarget)) { $type = (is_object($requestTarget) ? get_class($requestTarget) . ' ' : '') . gettype($requestTarget); throw new \InvalidArgumentException("Request target should be a string, not a $type"); } }
Assert that the request target is a string @param string $requestTarget @throws \InvalidArgumentException
entailment
public function withRequestTarget($requestTarget) { $this->assertRequestTarget($requestTarget); $request = $this->copy(); $request->requestTarget = $requestTarget; return $request; }
Return an instance with the specific request-target. @see http://tools.ietf.org/html/rfc7230#section-5.3 (for the various request-target forms allowed in request messages) @param string $requestTarget @return static @throws \InvalidArgumentException if $requestTarget is not a string
entailment
protected function extractForFromForwardedHeader($forwarded) { $ips = []; $parts = array_map('trim', explode(',', $forwarded)); foreach ($parts as $part) { list($key, $value) = explode('=', $part, 2) + [1 => null]; if ($key === 'for') { $ips[] = trim($value, '[]'); } } return $ips; }
Extract the `for` part from the Forwarded header @param string $forwarded @return string
entailment
protected function getForwardedIp(ServerRequestInterface $request, $ip) { $ips = [$ip]; $forwardedFor = $this->splitIps($request->getHeaderLine('X-Forwarded-For')); $forwarded = $this->extractForFromForwardedHeader($request->getHeaderLine('Forwarded')); $clientIp = $this->splitIps($request->getHeaderLine('Client-Ip')); if (!$this->areAllTheSame($forwardedFor, $forwarded, $clientIp)) { $msg = 'Only one of `X-Forwarded-For`, `Forwarded` or `Client-Ip` headers should be set'; throw new \RuntimeException($msg); } $fwd = $forwardedFor ?: $forwarded ?: $clientIp; if ($fwd) { $ips = array_merge($ips, $fwd); } return $this->getTrustedForwardedIp($ips); }
Get the forwarded ip @param ServerRequestInterface $request @param string $ip Connected IP @return string|null
entailment
protected function getTrustedForwardedIp(array $ips) { if (is_string($this->trustedProxy)) { foreach ($ips as $ip) { if (\Jasny\ip_in_cidr($ip, $this->trustedProxy)) { continue; } return $ip; } } return end($ips); }
Select an IP which is within the list of trusted ips @param array $ips @return string
entailment
protected static function _cache($type, $key, $value = false) { $key = '_' . $key; $type = '_' . $type; if ($value !== false) { self::$_cache[$type][$key] = $value; return $value; } if (!isset(self::$_cache[$type][$key])) { return false; } return self::$_cache[$type][$key]; }
Cache inflected values, and return if already available @param string $type Inflection type @param string $key Original value @param string $value Inflected value @return string Inflected value, from cache
entailment
public static function rules($type, $rules, $reset = false) { $var = '_' . $type; switch ($type) { case 'transliteration': if ($reset) { self::$_transliteration = $rules; } else { self::$_transliteration = $rules + self::$_transliteration; } break; default: foreach ($rules as $rule => $pattern) { if (is_array($pattern)) { if ($reset) { self::${$var}[$rule] = $pattern; } else { if ($rule === 'uninflected') { self::${$var}[$rule] = array_merge($pattern, self::${$var}[$rule]); } else { self::${$var}[$rule] = $pattern + self::${$var}[$rule]; } } unset($rules[$rule], self::${$var}['cache' . ucfirst($rule)]); if (isset(self::${$var}['merged'][$rule])) { unset(self::${$var}['merged'][$rule]); } if ($type === 'plural') { self::$_cache['pluralize'] = self::$_cache['tableize'] = array(); } elseif ($type === 'singular') { self::$_cache['singularize'] = array(); } } } self::${$var}['rules'] = $rules + self::${$var}['rules']; break; } }
Adds custom inflection $rules, of either 'plural', 'singular' or 'transliteration' $type. ### Usage: {{{ Inflector::rules('plural', array('/^(inflect)or$/i' => '\1ables')); Inflector::rules('plural', array( 'rules' => array('/^(inflect)ors$/i' => '\1ables'), 'uninflected' => array('dontinflectme'), 'irregular' => array('red' => 'redlings') )); Inflector::rules('transliteration', array('/å/' => 'aa')); }}} @param string $type The type of inflection, either 'plural', 'singular' or 'transliteration' @param array $rules Array of rules to be added. @param boolean $reset If true, will unset default inflections for all new rules that are being defined in $rules. @return void
entailment
public static function pluralize($word) { if (isset(self::$_cache['pluralize'][$word])) { return self::$_cache['pluralize'][$word]; } if (!isset(self::$_plural['merged']['irregular'])) { self::$_plural['merged']['irregular'] = self::$_plural['irregular']; } if (!isset(self::$_plural['merged']['uninflected'])) { self::$_plural['merged']['uninflected'] = array_merge(self::$_plural['uninflected'], self::$_uninflected); } if (!isset(self::$_plural['cacheUninflected']) || !isset(self::$_plural['cacheIrregular'])) { self::$_plural['cacheUninflected'] = '(?:' . implode('|', self::$_plural['merged']['uninflected']) . ')'; self::$_plural['cacheIrregular'] = '(?:' . implode('|', array_keys(self::$_plural['merged']['irregular'])) . ')'; } if (preg_match('/(.*)\\b(' . self::$_plural['cacheIrregular'] . ')$/i', $word, $regs)) { self::$_cache['pluralize'][$word] = $regs[1] . substr($word, 0, 1) . substr(self::$_plural['merged']['irregular'][strtolower($regs[2])], 1); return self::$_cache['pluralize'][$word]; } if (preg_match('/^(' . self::$_plural['cacheUninflected'] . ')$/i', $word, $regs)) { self::$_cache['pluralize'][$word] = $word; return $word; } foreach (self::$_plural['rules'] as $rule => $replacement) { if (preg_match($rule, $word)) { self::$_cache['pluralize'][$word] = preg_replace($rule, $replacement, $word); return self::$_cache['pluralize'][$word]; } } }
Return $word in plural form. @param string $word Word in singular @return string Word in plural @link http://book.cakephp.org/2.0/en/core-utility-libraries/inflector.html#Inflector::pluralize
entailment
public static function camelize($lowerCaseAndUnderscoredWord) { if (!($result = self::_cache(__FUNCTION__, $lowerCaseAndUnderscoredWord))) { $result = str_replace(' ', '', Inflector::humanize($lowerCaseAndUnderscoredWord)); self::_cache(__FUNCTION__, $lowerCaseAndUnderscoredWord, $result); } return $result; }
Returns the given lower_case_and_underscored_word as a CamelCased word. @param string $lowerCaseAndUnderscoredWord Word to camelize @return string Camelized word. LikeThis. @link http://book.cakephp.org/2.0/en/core-utility-libraries/inflector.html#Inflector::camelize
entailment
public static function underscore($camelCasedWord) { if (!($result = self::_cache(__FUNCTION__, $camelCasedWord))) { $result = strtolower(preg_replace('/(?<=\\w)([A-Z])/', '_\\1', $camelCasedWord)); self::_cache(__FUNCTION__, $camelCasedWord, $result); } return $result; }
Returns the given camelCasedWord as an underscored_word. @param string $camelCasedWord Camel-cased word to be "underscorized" @return string Underscore-syntaxed version of the $camelCasedWord @link http://book.cakephp.org/2.0/en/core-utility-libraries/inflector.html#Inflector::underscore
entailment
public static function humanize($lowerCaseAndUnderscoredWord) { if (!($result = self::_cache(__FUNCTION__, $lowerCaseAndUnderscoredWord))) { $result = ucwords(str_replace('_', ' ', $lowerCaseAndUnderscoredWord)); self::_cache(__FUNCTION__, $lowerCaseAndUnderscoredWord, $result); } return $result; }
Returns the given underscored_word_group as a Human Readable Word Group. (Underscores are replaced by spaces and capitalized following words.) @param string $lowerCaseAndUnderscoredWord String to be made more readable @return string Human-readable string @link http://book.cakephp.org/2.0/en/core-utility-libraries/inflector.html#Inflector::humanize
entailment
public static function tableize($className) { if (!($result = self::_cache(__FUNCTION__, $className))) { $result = Inflector::pluralize(Inflector::underscore($className)); self::_cache(__FUNCTION__, $className, $result); } return $result; }
Returns corresponding table name for given model $className. ("people" for the model class "Person"). @param string $className Name of class to get database table name for @return string Name of the database table for given class @link http://book.cakephp.org/2.0/en/core-utility-libraries/inflector.html#Inflector::tableize
entailment
public static function classify($tableName) { if (!($result = self::_cache(__FUNCTION__, $tableName))) { $result = Inflector::camelize(Inflector::singularize($tableName)); self::_cache(__FUNCTION__, $tableName, $result); } return $result; }
Returns Cake model class name ("Person" for the database table "people".) for given database table. @param string $tableName Name of database table to get class name for @return string Class name @link http://book.cakephp.org/2.0/en/core-utility-libraries/inflector.html#Inflector::classify
entailment
public static function variable($string) { if (!($result = self::_cache(__FUNCTION__, $string))) { $camelized = Inflector::camelize(Inflector::underscore($string)); $replace = strtolower(substr($camelized, 0, 1)); $result = preg_replace('/\\w/', $replace, $camelized, 1); self::_cache(__FUNCTION__, $string, $result); } return $result; }
Returns camelBacked version of an underscored string. @param string $string @return string in variable form @link http://book.cakephp.org/2.0/en/core-utility-libraries/inflector.html#Inflector::variable
entailment
public static function slug($string, $replacement = '_') { $quotedReplacement = preg_quote($replacement, '/'); $merge = array( '/[^\s\p{Ll}\p{Lm}\p{Lo}\p{Lt}\p{Lu}\p{Nd}]/mu' => ' ', '/\\s+/' => $replacement, sprintf('/^[%s]+|[%s]+$/', $quotedReplacement, $quotedReplacement) => '', ); $map = self::$_transliteration + $merge; return preg_replace(array_keys($map), array_values($map), $string); }
Returns a string with all spaces converted to underscores (by default), accented characters converted to non-accented characters, and non word characters removed. @param string $string the string you want to slug @param string $replacement will replace keys in map @return string @link http://book.cakephp.org/2.0/en/core-utility-libraries/inflector.html#Inflector::slug
entailment
protected function isValidDomain($hostname) { return preg_match("/^([a-z\d](-*[a-z\d])*)(\.([a-z\d](-*[a-z\d])*))*$/i", $hostname) && preg_match("/^.{1,253}$/", $hostname) && preg_match("/^[^\.]{1,63}(\.[^\.]{1,63})*$/", $hostname) && !preg_match("/^\d{0,3}\.\d{0,3}\.\d{0,3}\.\d{0,3}$/", $hostname); }
Check if the hostname is valid a valid domain name according to RFC 3986 and RFC 1123 @param string $hostname @return boolean
entailment
protected function setHost($host) { $host = strtolower($host); if ($host !== '' && !$this->isValidDomain($host) && !$this->isValidIpv4($host) && !$this->isValidIpv6($host)) { throw new \InvalidArgumentException("Invalid hostname '$host'"); } $this->host = $host; }
Set the host @param string $host
entailment
public function dispatchAjaxRequest($strAction, \DataContainer $dc) { switch ($strAction) { // Upload the file /** @noinspection PhpMissingBreakStatementInspection */ case 'fineuploader_upload': $arrData['strTable'] = $dc->table; $arrData['id'] = $dc->id; // @todo what was $this->strAjaxName for? $arrData['name'] = \Input::post('name'); /** @var FineUploaderWidget $objWidget */ $objWidget = new $GLOBALS['BE_FFL']['fineUploader']($arrData, $dc); $strFile = $objWidget->validateUpload(); if ($objWidget->hasErrors()) { $arrResponse = array('success' => false, 'error' => $objWidget->getErrorAsString(), 'preventRetry' => true); } else { $arrResponse = array('success' => true, 'file' => $strFile); } $response = new \Haste\Http\Response\JsonResponse($arrResponse); $response->send(); // no break, response exits script // Reload the widget case 'fineuploader_reload': $intId = \Input::get('id'); $strField = $dc->field = \Input::post('name'); // Handle the keys in "edit multiple" mode if (\Input::get('act') == 'editAll') { $intId = preg_replace('/.*_([0-9a-zA-Z]+)$/', '$1', $strField); $strField = preg_replace('/(.*)_[0-9a-zA-Z]+$/', '$1', $strField); } // The field does not exist if (!isset($GLOBALS['TL_DCA'][$dc->table]['fields'][$strField])) { System::log('Field "' . $strField . '" does not exist in DCA "' . $dc->table . '"', __METHOD__, TL_ERROR); header('HTTP/1.1 400 Bad Request'); die('Bad Request'); } $objRow = null; $varValue = null; // Load the value if ($GLOBALS['TL_DCA'][$dc->table]['config']['dataContainer'] == 'File') { $varValue = $GLOBALS['TL_CONFIG'][$strField]; } elseif ($intId > 0 && Database::getInstance()->tableExists($dc->table)) { $objRow = Database::getInstance()->prepare("SELECT * FROM " . $dc->table . " WHERE id=?") ->execute($intId); // The record does not exist if ($objRow->numRows < 1) { System::log('A record with the ID "' . $intId . '" does not exist in table "' . $dc->table . '"', __METHOD__, TL_ERROR); header('HTTP/1.1 400 Bad Request'); die('Bad Request'); } $varValue = $objRow->$strField; $dc->activeRecord = $objRow; } // Call the load_callback if (is_array($GLOBALS['TL_DCA'][$dc->table]['fields'][$strField]['load_callback'])) { foreach ($GLOBALS['TL_DCA'][$dc->table]['fields'][$strField]['load_callback'] as $callback) { if (is_array($callback)) { $varValue = System::importStatic($callback[0])->{$callback[1]}($varValue, $dc); } elseif (is_callable($callback)) { $varValue = $callback($varValue, $dc); } } } $varValue = \Input::post('value', true); // Convert the selected values if ($varValue != '') { $varValue = trimsplit(',', $varValue); foreach ($varValue as $k => $v) { if (\Validator::isUuid($v) && !is_file(TL_ROOT . '/' . $v)) { $varValue[$k] = \StringUtil::uuidToBin($v); } } $varValue = serialize($varValue); } // Build the attributes based on the "eval" array $arrAttribs = $GLOBALS['TL_DCA'][$dc->table]['fields'][$strField]['eval']; $arrAttribs['id'] = $dc->field; $arrAttribs['name'] = $dc->field; $arrAttribs['value'] = $varValue; $arrAttribs['strTable'] = $dc->table; $arrAttribs['strField'] = $strField; $arrAttribs['activeRecord'] = $dc->activeRecord; $objWidget = new $GLOBALS['BE_FFL']['fineUploader']($arrAttribs); $response = new \Haste\Http\Response\HtmlResponse($objWidget->parse()); $response->send(); } }
Dispatch an AJAX request @param string @param \DataContainer
entailment
public function executeAjaxActions($arrData) { \Input::setGet('no_ajax', 1); // Avoid circular reference switch (\Input::post('action')) { // Upload the file case 'fineuploader_upload': $arrData['name'] = \Input::post('name'); /** @var FormFineUploader $objWidget */ $objWidget = new $GLOBALS['TL_FFL']['fineUploader']($arrData); $strFile = $objWidget->validateUpload(); if ($objWidget->hasErrors()) { $arrResponse = array('success' => false, 'error' => $objWidget->getErrorAsString(), 'preventRetry' => true); } else { $arrResponse = array('success' => true, 'file' => $strFile); } $response = new \Haste\Http\Response\JsonResponse($arrResponse); $response->send(false); exit; break; } }
Execute AJAX actions in front end @param array
entailment