sentence1
stringlengths
52
3.87M
sentence2
stringlengths
1
47.2k
label
stringclasses
1 value
public function establish(array $config = [], $assign = false) { $client = new Client($config + $this->config + $this->defaults()); if ($assign) { $this->client = $client; } return $client; }
Establishes the ES client using the provided config. Provided config values will take place over the object's config attribute. Finally, the defaults() result will be used as a final config source. @param array $config Config value to override the general config params @return Client
entailment
protected function _find($type, $id) { if (is_array($id)) { return $this->__mfind($this->index(), $type, $id); } else { return $this->__find($this->index(), $type, $id); } }
A decorator method to get specific document by its id. If the id is and array of strings or integers, then multiple documents will be retreived by id. @param string $type @param mixed|string|integer|mixed[]|int[]|string[] $id @return Model
entailment
protected function _create(array $data, $type, $id = null, array $parameters = []) { return $this->__create($data, $this->index(), $type, $id, $parameters); }
Index a new document @param array $data the document data @param string $type @param string|number $id @param array $parameters @return array
entailment
protected function __create(array $data, $index, $type, $id = null, array $parameters = []) { $parameters+=["api" => "create"]; $api = strtolower($parameters["api"]) == "index" ? "index" : "create"; unset($parameters["api"]); $result = $this->client->$api([ 'index' => $index, 'type' => $type, 'body' => $data] + ($id ? ['id' => $id] : []) + $parameters); if (array_key_exists('_shards', $result) && array_key_exists('failed', $result['_shards']) && $result['_shards']['failed'] > 0) { throw new Exception('Failed to create the document. Serialized results: ' + json_encode($result)); } else { $result = $this->__find($result['_index'], $result['_type'], $result['_id']); } return $result; }
Index a new document @param array $data the document data @param string $index @param string $type @param string|number $id @param array $parameters @return array
entailment
protected function _delete($type, $id = null, array $parameters = []) { return $this->__delete($this->index(), $type, $id, $parameters); }
Deletes a document @param string $type @param string|number $id @param array $parameters @return array
entailment
protected function __delete($index, $type, $id, array $parameters = []) { $result = $this->client->delete([ 'index' => $index, 'type' => $type, 'id' => $id] + $parameters); return $result; }
Deletes a document @param string $index @param string $type @param string|number $id @param array $parameters @return array
entailment
protected function __query($index, $type = null, array $query = []) { $result = $this->client->search([ 'index' => $index, 'body' => array_merge_recursive($query, $this->additionalQuery()) ] + ($type ? ['type' => $type] : [])); return $this->_makeResult($result); }
The actual method to call client's search method. Returns Result object @param string $index @param string $type if null, then all types will be searched @param array $query @return Result|Model[]
entailment
protected function __find($index, $type, $id) { try { $result = $this->client->get([ 'index' => $index, 'type' => $type, 'id' => $id ]); if ($result['found']) { return $this->_makeModel($result); } else { return null; } } catch (\Exception $e) { trigger_error($e->getMessage(), E_USER_WARNING); return null; } }
The actual method to call client's get method. Returns either a Model object or null on failure. @param string $index @param string $type @param sring|int $id @return null|Model
entailment
protected function __mfind($index, $type, $ids) { try { $docs = $this->client->mget([ 'index' => $index, 'type' => $type, 'body' => [ "ids" => $ids ] ]); $result = ['ids' => $ids, 'found' => [], 'missed' => [], 'docs' => []]; $missed = [] + $ids; foreach ($docs['docs'] as $doc) { if ($doc['found']) { $result['docs'][] = $doc; $result['found'][] = $doc['_id']; unset($missed[array_search($doc['_id'], $missed)]); } } $result['missed'] = $missed; return $this->_makeMultiGetResult($result); } catch (\Exception $e) { trigger_error($e->getMessage(), E_USER_WARNING); return null; } }
The actual method to call client's mget method. Returns either a result of Model objects or null on failure. @param string $index @param string $type @param sring[]|int[] $ids @return null|Model
entailment
protected function _makeResult(array $result) { return Result::make($result, $this->getClient())->setModelClass($this->_fullModelClassNamePattern()); }
Creates a results set for ES query hits @param array $result @return Result
entailment
protected function _makeMultiGetResult(array $result) { return MultiGetResult::make($result, $this->getClient())->setModelClass($this->_fullModelClassNamePattern()); }
Creates a results set for ES query hits @param array $result @return Result
entailment
protected function _meta($features = null, array $options = []) { if ($features) { $features = join(',', array_map(function($item) { return '_' . strtolower(trim($item, '_')); }, is_scalar($features) ? explode(",", $features) : $features)); } $options = ['index' => $this->index()] + $options + ($features ? ['feature' => $features] : []); $result = $this->client->indices()->get($options); $result = array_pop($result); return $result; }
Retreives the meta data of an index @param string|array $features a list of meta objects to fetch. null means everything. Can be * 1 string (i.e. '_settings'), * csv (i.e. '_settings,_aliases'), * array (i.e. ['_settings','_aliases'] @param array $options can contain: ['ignore_unavailable'] (bool) Whether specified concrete indices should be ignored when unavailable (missing or closed) ['allow_no_indices'] (bool) Whether to ignore if a wildcard indices expression resolves into no concrete indices. (This includes `_all` string or when no indices have been specified) ['expand_wildcards'] (enum) Whether to expand wildcard expression to concrete indices that are open, closed or both. ['local'] (bool) Return local information, do not retrieve the state from master node (default: false) @return array
entailment
public function setAuth($username, $password) { if (strlen($username) > 255 || strlen($password) > 255) { throw new InvalidArgumentException('Both username and password MUST NOT exceed a length of 255 bytes each'); } if ($this->protocolVersion !== null && $this->protocolVersion !== '5') { throw new UnexpectedValueException('Authentication requires SOCKS5. Consider using protocol version 5 or waive authentication'); } $this->auth = pack('C2', 0x01, strlen($username)) . $username . pack('C', strlen($password)) . $password; }
set login data for username/password authentication method (RFC1929) @param string $username @param string $password @link http://tools.ietf.org/html/rfc1929
entailment
public static function discoverAll() { $components = []; // Run through all extensions foreach (ExtensionManagementUtility::getLoadedExtensionListArray() as $extensionKey) { $components = array_merge($components, self::discoverExtensionComponents($extensionKey)); } return $components; }
Discover all components @return array Components
entailment
protected static function discoverExtensionComponents($extensionKey) { // Test if the extension contains a component directory $extCompRootDirectory = ExtensionManagementUtility::extPath($extensionKey, 'Components'); return is_dir($extCompRootDirectory) ? self::discoverExtensionComponentDirectory($extCompRootDirectory) : []; }
Discover the components of a single extension @param $extensionKey
entailment
protected static function discoverExtensionComponentDirectory($directory) { $components = []; $directoryIterator = new \RecursiveDirectoryIterator($directory); $recursiveIterator = new \RecursiveIteratorIterator($directoryIterator); $regexIterator = new \RegexIterator( $recursiveIterator, PATH_SEPARATOR.'^'.preg_quote($directory.DIRECTORY_SEPARATOR).'.+Component\.php$'.PATH_SEPARATOR, \RecursiveRegexIterator::GET_MATCH ); // Run through all potential component files foreach ($regexIterator as $component) { // Run through all classes declared in the file foreach (self::discoverClassesInFile(file_get_contents($component[0])) as $className) { // Test if this is a component class $classReflection = new \ReflectionClass($className); if ($classReflection->implementsInterface(ComponentInterface::class)) { $components[] = self::addLocalConfiguration($component[0], self::discoverComponent($className)); } } } return $components; }
Recursively scan a directory for components and return a component list @param string $directory Directory path @return array Components
entailment
protected static function discoverClassesInFile($phpCode) { $classes = array(); $tokens = token_get_all($phpCode); $gettingClassname = $gettingNamespace = false; $namespace = ''; $lastToken = null; // Run through all tokens for ($t = 0, $tokenCount = count($tokens); $t < $tokenCount; ++$t) { $token = $tokens[$t]; // If this is a namespace token if (is_array($token) && ($token[0] == T_NAMESPACE)) { $namespace = ''; $gettingNamespace = true; continue; } // If this is a class name token if (is_array($token) && ($token[0] == T_CLASS) && (!is_array( $lastToken ) || ($lastToken[0] !== T_PAAMAYIM_NEKUDOTAYIM))) { $gettingClassname = true; } // If we're getting a namespace if ($gettingNamespace === true) { if (is_array($token) && in_array($token[0], [T_STRING, T_NS_SEPARATOR])) { $namespace .= $token[1]; } elseif ($token === ';') { $gettingNamespace = false; } // Else if we're getting the class name } elseif ($gettingClassname === true) { if (is_array($token) && ($token[0] == T_STRING)) { $classes[] = ($namespace ? $namespace.'\\' : '').$token[1]; $gettingClassname = false; } } $lastToken = $token; } return $classes; }
Discover the classes declared in a file @param string $phpCode PHP code @return array Class names
entailment
protected static function addLocalConfiguration($componentDirectory, array $component) { $component['local'] = []; $componentDirectories = []; for ($dir = 0; $dir < count($component['path']); ++$dir) { $componentDirectory = $componentDirectories[] = dirname($componentDirectory); } foreach (array_reverse($componentDirectories) as $componentDirectory) { $component['local'][] = self::getLocalConfiguration($componentDirectory); } return $component; }
Amend the directory specific local configuration @param string $componentDirectory Component directory @param array $component Component @return array Amended component
entailment
protected static function getLocalConfiguration($dirname) { if (is_dir($dirname) && empty(self::$localConfigurations[$dirname])) { $localConfig = $dirname.DIRECTORY_SEPARATOR.'local.json'; self::$localConfigurations[$dirname] = file_exists($localConfig) ? (array)@\json_decode(file_get_contents($localConfig)) : []; } return self::$localConfigurations[$dirname]; }
Read, cache and return a directory specific local configuration @param string $dirname Directory name @return array Directory specific local configuration
entailment
public function writeTypeMarker(&$data, $markerType = null, $dataByVal = false) { // Workaround for PHP5 with E_STRICT enabled complaining about "Only // variables should be passed by reference" if ((null === $data) && ($dataByVal !== false)) { $data = &$dataByVal; } if (null !== $markerType) { //try to reference the given object if (!$this->writeObjectReference($data, $markerType)) { // Write the Type Marker to denote the following action script data type $this->_stream->writeByte($markerType); switch($markerType) { case Zend_Amf_Constants::AMF0_NUMBER: $this->_stream->writeDouble($data); break; case Zend_Amf_Constants::AMF0_BOOLEAN: $this->_stream->writeByte($data); break; case Zend_Amf_Constants::AMF0_STRING: $this->_stream->writeUTF($data); break; case Zend_Amf_Constants::AMF0_OBJECT: $this->writeObject($data); break; case Zend_Amf_Constants::AMF0_NULL: break; case Zend_Amf_Constants::AMF0_REFERENCE: $this->_stream->writeInt($data); break; case Zend_Amf_Constants::AMF0_MIXEDARRAY: // Write length of numeric keys as zero. $this->_stream->writeLong(0); $this->writeObject($data); break; case Zend_Amf_Constants::AMF0_ARRAY: $this->writeArray($data); break; case Zend_Amf_Constants::AMF0_DATE: $this->writeDate($data); break; case Zend_Amf_Constants::AMF0_LONGSTRING: $this->_stream->writeLongUTF($data); break; case Zend_Amf_Constants::AMF0_TYPEDOBJECT: $this->writeTypedObject($data); break; case Zend_Amf_Constants::AMF0_AMF3: $this->writeAmf3TypeMarker($data); break; default: require_once 'Zend/Amf/Exception.php'; throw new Zend_Amf_Exception("Unknown Type Marker: " . $markerType); } } } else { if (is_resource($data)) { $data = Zend_Amf_Parse_TypeLoader::handleResource($data); } switch (true) { case (is_int($data) || is_float($data)): $markerType = Zend_Amf_Constants::AMF0_NUMBER; break; case (is_bool($data)): $markerType = Zend_Amf_Constants::AMF0_BOOLEAN; break; case (is_string($data) && (strlen($data) > 65536)): $markerType = Zend_Amf_Constants::AMF0_LONGSTRING; break; case (is_string($data)): $markerType = Zend_Amf_Constants::AMF0_STRING; break; case (is_object($data)): if (($data instanceof DateTime) || ($data instanceof Zend_Date)) { $markerType = Zend_Amf_Constants::AMF0_DATE; } else { if($className = $this->getClassName($data)){ //Object is a Typed object set classname $markerType = Zend_Amf_Constants::AMF0_TYPEDOBJECT; $this->_className = $className; } else { // Object is a generic classname $markerType = Zend_Amf_Constants::AMF0_OBJECT; } break; } break; case (null === $data): $markerType = Zend_Amf_Constants::AMF0_NULL; break; case (is_array($data)): // check if it is an associative array $i = 0; foreach (array_keys($data) as $key) { // check if it contains non-integer keys if (!is_numeric($key) || intval($key) != $key) { $markerType = Zend_Amf_Constants::AMF0_OBJECT; break; // check if it is a sparse indexed array } else if ($key != $i) { $markerType = Zend_Amf_Constants::AMF0_MIXEDARRAY; break; } $i++; } // Dealing with a standard numeric array if(!$markerType){ $markerType = Zend_Amf_Constants::AMF0_ARRAY; break; } break; default: require_once 'Zend/Amf/Exception.php'; throw new Zend_Amf_Exception('Unsupported data type: ' . gettype($data)); } $this->writeTypeMarker($data, $markerType); } return $this; }
Determine type and serialize accordingly Checks to see if the type was declared and then either auto negotiates the type or relies on the user defined markerType to serialize the data into amf @param mixed $data @param mixed $markerType @param mixed $dataByVal @return Zend_Amf_Parse_Amf0_Serializer @throws Zend_Amf_Exception for unrecognized types or data
entailment
protected function writeObjectReference(&$object, $markerType, $objectByVal = false) { // Workaround for PHP5 with E_STRICT enabled complaining about "Only // variables should be passed by reference" if ((null === $object) && ($objectByVal !== false)) { $object = &$objectByVal; } if ($markerType == Zend_Amf_Constants::AMF0_OBJECT || $markerType == Zend_Amf_Constants::AMF0_MIXEDARRAY || $markerType == Zend_Amf_Constants::AMF0_ARRAY || $markerType == Zend_Amf_Constants::AMF0_TYPEDOBJECT ) { $ref = array_search($object, $this->_referenceObjects, true); //handle object reference if($ref !== false){ $this->writeTypeMarker($ref,Zend_Amf_Constants::AMF0_REFERENCE); return true; } $this->_referenceObjects[] = $object; } return false; }
Check if the given object is in the reference table, write the reference if it exists, otherwise add the object to the reference table @param mixed $object object reference to check for reference @param string $markerType AMF type of the object to write @param mixed $objectByVal object to check for reference @return Boolean true, if the reference was written, false otherwise
entailment
public function writeObject($object) { // Loop each element and write the name of the property. foreach ($object as $key => &$value) { // skip variables starting with an _ private transient if( $key[0] == "_") continue; $this->_stream->writeUTF($key); $this->writeTypeMarker($value); } // Write the end object flag $this->_stream->writeInt(0); $this->_stream->writeByte(Zend_Amf_Constants::AMF0_OBJECTTERM); return $this; }
Write a PHP array with string or mixed keys. @param object $data @return Zend_Amf_Parse_Amf0_Serializer
entailment
public function writeArray(&$array) { $length = count($array); if (!$length < 0) { // write the length of the array $this->_stream->writeLong(0); } else { // Write the length of the numeric array $this->_stream->writeLong($length); for ($i=0; $i<$length; $i++) { $value = isset($array[$i]) ? $array[$i] : null; $this->writeTypeMarker($value); } } return $this; }
Write a standard numeric array to the output stream. If a mixed array is encountered call writeTypeMarker with mixed array. @param array $array @return Zend_Amf_Parse_Amf0_Serializer
entailment
public function writeDate($data) { if ($data instanceof DateTime) { $dateString = $data->format('U'); } elseif ($data instanceof Zend_Date) { $dateString = $data->toString('U'); } else { require_once 'Zend/Amf/Exception.php'; throw new Zend_Amf_Exception('Invalid date specified; must be a DateTime or Zend_Date object'); } $dateString *= 1000; // Make the conversion and remove milliseconds. $this->_stream->writeDouble($dateString); // Flash does not respect timezone but requires it. $this->_stream->writeInt(0); return $this; }
Convert the DateTime into an AMF Date @param DateTime|Zend_Date $data @return Zend_Amf_Parse_Amf0_Serializer
entailment
public function writeTypedObject($data) { $this->_stream->writeUTF($this->_className); $this->writeObject($data); return $this; }
Write a class mapped object to the output stream. @param object $data @return Zend_Amf_Parse_Amf0_Serializer
entailment
public function writeAmf3TypeMarker(&$data) { require_once 'Zend/Amf/Parse/Amf3/Serializer.php'; $serializer = new Zend_Amf_Parse_Amf3_Serializer($this->_stream); $serializer->writeTypeMarker($data); return $this; }
Encountered and AMF3 Type Marker use AMF3 serializer. Once AMF3 is encountered it will not return to AMf0. @param string $data @return Zend_Amf_Parse_Amf0_Serializer
entailment
protected function getClassName($object) { require_once 'Zend/Amf/Parse/TypeLoader.php'; //Check to see if the object is a typed object and we need to change $className = ''; switch (true) { // the return class mapped name back to actionscript class name. case Zend_Amf_Parse_TypeLoader::getMappedClassName(get_class($object)): $className = Zend_Amf_Parse_TypeLoader::getMappedClassName(get_class($object)); break; // Check to see if the user has defined an explicit Action Script type. case isset($object->_explicitType): $className = $object->_explicitType; break; // Check if user has defined a method for accessing the Action Script type case method_exists($object, 'getASClassName'): $className = $object->getASClassName(); break; // No return class name is set make it a generic object case ($object instanceof stdClass): $className = ''; break; // By default, use object's class name default: $className = get_class($object); break; } if(!$className == '') { return $className; } else { return false; } }
Find if the class name is a class mapped name and return the respective classname if it is. @param object $object @return false|string $className
entailment
public static function extractTypoScriptKeyForPidAndType($id, $typeNum, $key) { $key = trim($key); if (!strlen($key)) { throw new \RuntimeException(sprintf('Invalid TypoScript key "%s"', $key), 1481365294); } // Get a frontend controller for the page id and type $TSFE = self::getTSFE($id, $typeNum); list($name, $conf) = GeneralUtility::makeInstance(TypoScriptParser::class)->getVal($key, $TSFE->tmpl->setup); $lastKey = explode('.', $key); $lastKey = array_pop($lastKey); return [$lastKey => $name, $lastKey.'.' => $conf]; }
Extract and return a TypoScript key for a particular page and type @param int $id Page ID @param int $typeNum Page type @param string $key TypoScript key @return array TypoScript values @throws \TYPO3\CMS\Core\Error\Http\ServiceUnavailableException @throws \Exception If the TypoScript key is invalid
entailment
public static function getTSFE($id, $typeNum) { // Initialize the tracker if necessary if (!is_object($GLOBALS['TT'])) { $GLOBALS['TT'] = new TimeTracker(false); $GLOBALS['TT']->start(); } if (!array_key_exists("$id/$typeNum", self::$frontendControllers)) { $tsfeBackup = empty($GLOBALS['TSFE']) ? null : $GLOBALS['TSFE']; $GLOBALS['TSFE'] = GeneralUtility::makeInstance( TypoScriptFrontendController::class, $GLOBALS['TYPO3_CONF_VARS'], $id, $typeNum ); $GLOBALS['TSFE']->sys_page = GeneralUtility::makeInstance(PageRepository::class); $GLOBALS['TSFE']->sys_page->init(true); $GLOBALS['TSFE']->connectToDB(); $GLOBALS['TSFE']->initFEuser(); $GLOBALS['TSFE']->determineId(); $GLOBALS['TSFE']->initTemplate(); $GLOBALS['TSFE']->rootLine = $GLOBALS['TSFE']->sys_page->getRootLine($id, ''); try { $GLOBALS['TSFE']->getConfigArray(); } catch (ServiceUnavailableException $e) { // Skip unconfigured page type } // Calculate the absolute path prefix if (!empty($GLOBALS['TSFE']->config['config']['absRefPrefix'])) { $absRefPrefix = trim($GLOBALS['TSFE']->config['config']['absRefPrefix']); $GLOBALS['TSFE']->absRefPrefix = ($absRefPrefix === 'auto') ? GeneralUtility::getIndpEnv( 'TYPO3_SITE_PATH' ) : $absRefPrefix; } else { $GLOBALS['TSFE']->absRefPrefix = ''; } self::$frontendControllers["$id/$typeNum"] = $GLOBALS['TSFE']; if ($tsfeBackup) { $GLOBALS['TSFE'] = $tsfeBackup; } else { unset($GLOBALS['TSFE']); } } return self::$frontendControllers["$id/$typeNum"]; }
Instantiate a Frontend controller for the given configuration @param int $id Page ID @param int $typeNum Page Type @return TypoScriptFrontendController Frontend controller @throws \Exception @throws \TYPO3\CMS\Core\Error\Http\ServiceUnavailableException
entailment
public static function serialize($prefix, array $typoscript, $indent = 0) { $serialized = []; // Sort the TypoScript fragment ksort($typoscript, SORT_NATURAL); // Run through the TypoScript fragment foreach ($typoscript as $key => $value) { $line = str_repeat(' ', $indent * 4); $line .= trim(strlen($prefix) ? "$prefix.$key" : $key, '.'); // If the value is a list of values if (is_array($value)) { // If the list has only one element if (count($value) === 1) { $line .= '.'.self::serialize('', $value, 0); } else { $line .= ' {'.PHP_EOL.self::serialize('', $value, $indent + 1).PHP_EOL.'}'; } // Else if it's a multiline value } elseif (preg_match('/\R/', $value)) { $line .= ' ('.PHP_EOL.$value.PHP_EOL.')'; // Else: Simple assignment } else { $line .= ' = '.$value; } $serialized[] = $line; } return implode(PHP_EOL, $serialized); }
Serialize a TypoScript fragment @param string $prefix Key prefix @param array $typoscript TypoScript fragment @param int $indent Indentation level @return string Serialized TypoScript
entailment
public function getSteam2RenderedID($newerFormat = false) { if ($this->type != self::TYPE_INDIVIDUAL) { throw new Exception("Can't get Steam2 rendered ID for non-individual ID"); } else { $universe = $this->universe; if ($universe == 1 && !$newerFormat) { $universe = 0; } return 'STEAM_' . $universe . ':' . ($this->accountid & 1) . ':' . floor($this->accountid / 2); } }
Gets the rendered STEAM_X:Y:Z format. @param bool $newerFormat If the universe is public, should X be 1 instead of 0? @return string @throws Exception If this isn't an individual account SteamID
entailment
public function getSteam3RenderedID() { $type_char = self::$typeChars[$this->type] ? self::$typeChars[$this->type] : 'i'; if ($this->instance & self::CHAT_INSTANCE_FLAG_CLAN) { $type_char = 'c'; } elseif ($this->instance & self::CHAT_INSTANCE_FLAG_LOBBY) { $type_char = 'L'; } $render_instance = ($this->type == self::TYPE_ANON_GAMESERVER || $this->type == self::TYPE_MULTISEAT || ($this->type == self::TYPE_INDIVIDUAL && $this->instance != self::INSTANCE_DESKTOP)); return '[' . $type_char . ':' . $this->universe . ':' . $this->accountid . ($render_instance ? ':' . $this->instance : '') . ']'; }
Gets the rendered [T:U:A(:I)] format (T = type, U = universe, A = accountid, I = instance) @return string
entailment
public function getSteamID64() { if (PHP_INT_SIZE == 4) { $ret = new Math_BigInteger(); $ret = $ret->add((new Math_BigInteger($this->universe))->bitwise_leftShift(56)); $ret = $ret->add((new Math_BigInteger($this->type))->bitwise_leftShift(52)); $ret = $ret->add((new Math_BigInteger($this->instance))->bitwise_leftShift(32)); $ret = $ret->add(new Math_BigInteger($this->accountid)); return $ret->toString(); } return (string) (($this->universe << 56) | ($this->type << 52) | ($this->instance << 32) | ($this->accountid)); }
Gets the SteamID as a 64-bit integer @return string
entailment
public static function makeForQueryInstance(Query $instance, array $query = []) { $query = static::make($query); return $query->setQueryInstance($instance); }
Initiates a new query builder for a specific Query instance This helps in fluiding the query stream. i.e. SomeTypeQuery::make($config)->builder()->where("id",8)->where("age",">=",19)->execute(); @param Query $instance @param array $query @return AutoQueryBuilder
entailment
public function init() { LeftAndMain::init(); Requirements::css(CB_DIR.'/css/CodeBank.css'); Requirements::customScript("var CB_DIR='".CB_DIR."';", 'cb_dir'); if(empty(CodeBankConfig::CurrentConfig()->IPMessage) || Session::get('CodeBankIPAgreed')===true) { $this->redirect('admin/codeBank'); } }
Initializes the code bank admin
entailment
public function getEditForm($id=null, $fields=null) { $defaultPanel=Config::inst()->get('AdminRootController', 'default_panel'); if($defaultPanel=='CodeBank') { $defaultPanel='SecurityAdmin'; $sng=singleton($defaultPanel); } $fields=new FieldList( new TabSet('Root', new Tab('Main', new HeaderField('IPMessageTitle', _t('CodeBank.IP_MESSAGE_TITLE', '_You must agree to the following terms before using Code Bank'), 2), new LiteralField('IPMessage', '<div class="ipMessage"><div class="middleColumn">'.CodeBankConfig::CurrentConfig()->dbObject('IPMessage')->forTemplate().'</div></div>'), new HiddenField('RedirectLink', 'RedirectLink', $sng->Link()) ) ) ); if(Session::get('CodeBankIPAgreed')===true) { $fields->addFieldToTab('Root.Main', new HiddenField('AgreementAgreed', 'AgreementAgreed', Session::get('CodeBankIPAgreed'))); } $actions=new FieldList( FormAction::create('doDisagree', _t('CodeBankIPAgreement.DISAGREE', '_Disagree'))->addExtraClass('ss-ui-action-destructive'), FormAction::create('doAgree', _t('CodeBankIPAgreement.AGREE', '_Agree'))->addExtraClass('ss-ui-action-constructive') ); $form=CMSForm::create($this, 'EditForm', $fields, $actions)->setHTMLID('Form_EditForm'); $form->disableDefaultAction(); $form->addExtraClass('cms-edit-form'); $form->setTemplate($this->getTemplatesWithSuffix('_EditForm')); $form->addExtraClass('center '.$this->BaseCSSClasses()); $form->setAttribute('data-pjax-fragment', 'CurrentForm'); //Display message telling user to run dev/build because the version numbers are out of sync if(CB_VERSION!='@@VERSION@@' && CodeBankConfig::CurrentConfig()->Version!=CB_VERSION.' '.CB_BUILD_DATE) { $form->setMessage(_t('CodeBank.UPDATE_NEEDED', '_A database upgrade is required please run {startlink}dev/build{endlink}.', array('startlink'=>'<a href="dev/build?flush=all">', 'endlink'=>'</a>')), 'error'); }else if($this->hasOldTables()) { $form->setMessage(_t('CodeBank.MIGRATION_AVAILABLE', '_It appears you are upgrading from Code Bank 2.2.x, your old data can be migrated {startlink}click here to begin{endlink}, though it is recommended you backup your database first.', array('startlink'=>'<a href="dev/tasks/CodeBankLegacyMigrate">', 'endlink'=>'</a>')), 'warning'); } $form->Actions()->push(new LiteralField('CodeBankVersion', '<p class="codeBankVersion">Code Bank: '.$this->getVersion().'</p>')); Requirements::javascript(CB_DIR.'/javascript/CodeBank.IPMessage.js'); return $form; }
Gets the form used for agreeing or disagreeing to the ip agreement @param {int} $id ID of the record to fetch @param {FieldList} $fields Fields to use @return {Form} Form to be used
entailment
public function render() { // Set the request arguments as GET parameters $_GET = $this->getRequestArguments(); try { $rendererClassName = $this->element->getRendererClassName(); /** @var FluidFormRenderer $renderer */ $renderer = $this->objectManager->get($rendererClassName); if (!($renderer instanceof RendererInterface)) { throw new RenderingException( sprintf('The renderer "%s" des not implement RendererInterface', $rendererClassName), 1326096024 ); } $renderer->setControllerContext($this->controllerContext); $this->controllerContext->getRequest()->setOriginalRequestMappingResults($this->validationErrors); $response = $this->objectManager->get(Response::class, $this->controllerContext->getResponse()); /** @var FormRuntime $form */ $form = $this->form->bind($this->controllerContext->getRequest(), $response); $renderer->setFormRuntime($form); $result = $this->beautify($renderer->render()); // In case of an error } catch (\Exception $e) { $result = '<pre class="error"><strong>'.$e->getMessage().'</strong>'.PHP_EOL .$e->getTraceAsString().'</pre>'; } return $result; }
Render this component @return string Rendered component (HTML)
entailment
protected function initialize() { parent::initialize(); // Use the standard language file as fallback if ($this->translationFile === null) { $this->translationFile = 'EXT:'.$this->extensionKey.'/Resources/Private/Language/locallang.xlf'; } $configurationService = $this->objectManager->get(ConfigurationService::class); $prototypeConfiguration = $configurationService->getPrototypeConfiguration('standard'); $this->form = $this->objectManager->get( FormDefinition::class, 'form', $prototypeConfiguration ); $this->form->setRenderingOption('translation', ['translationFile' => $this->translationFile]); $this->form->setRenderingOption('honeypot', ['enable' => false]); $this->page = $this->form->createPage('page'); $this->preview->setTemplateName('Form'); }
Initialize the component Gets called immediately after construction. Override this method in components to initialize the component. @return void @throws \TYPO3\CMS\Form\Domain\Configuration\Exception\PrototypeNotFoundException @throws \TYPO3\CMS\Form\Domain\Exception\TypeDefinitionNotFoundException
entailment
protected function createElement($typeName, $identifier = null) { $identifier = trim($identifier) ?: strtr(GeneralUtility::camelCaseToLowerCaseUnderscored($typeName), '_', '-').'-1'; $this->element = $this->page->createElement($identifier, $typeName); $this->element->setProperty('fluidAdditionalAttributes', []); return $this->element; }
Create a form element @param string $typeName Type of the new form element @param string $identifier Form element identifier @return AbstractRenderable Renderable form element @throws \TYPO3\CMS\Form\Domain\Exception\TypeDefinitionNotFoundException @throws \TYPO3\CMS\Form\Domain\Exception\TypeDefinitionNotValidException
entailment
protected function addElementError($message) { if ($this->element === null) { throw new \RuntimeException('Create a form element prior to adding a validation error', 1519731421); } $this->addError($this->element->getIdentifier(), $message); }
Register a validation error for the form element @param string $message Validation error message @throws \RuntimeException If no element has been created prior to adding an error message
entailment
protected function exportInternal() { // Read the linked TypoScript if ($this->config !== null) { $templateFile = GeneralUtility::getFileAbsFileName($this->config); if (!strlen($templateFile) || !is_file($templateFile)) { throw new \RuntimeException(sprintf('Invalid template file "%s"', $templateFile), 1481552328); } $this->template = file_get_contents($templateFile); } return parent::exportInternal(); }
Return component specific properties @return array Component specific properties
entailment
public function AddForm() { $sng=singleton('Snippet'); $fields=$sng->getCMSFields(); $validator=$sng->getCMSValidator(); $actions=new FieldList( FormAction::create('doAdd', _t('CodeBank.CREATE', '_Create'))->addExtraClass('ss-ui-action-constructive')->setAttribute('data-icon', 'accept')->setUseButtonTag(true) ); $form=CMSForm::create($this, 'AddForm', $fields, $actions)->setHTMLID('Form_AddForm'); $form->setValidator($validator); $form->disableDefaultAction(); $form->addExtraClass('cms-add-form cms-edit-form'); $form->setResponseNegotiator($this->getResponseNegotiator()); $form->setTemplate($this->getTemplatesWithSuffix('_EditForm')); $form->addExtraClass('center '.$this->BaseCSSClasses()); $form->setAttribute('data-pjax-fragment', 'CurrentForm'); //Handle Language id in url if($this->request->getVar('LanguageID')) { $langField=$form->Fields()->dataFieldByName('LanguageID'); if($langField && $langField->Value()=='') { $langField->setValue(intval(str_replace('language-', '', $this->request->getVar('LanguageID')))); } } //Handle folder id in url (or post) if($this->request->getVar('FolderID')) { $folder=SnippetFolder::get()->byID(intval($this->request->getVar('FolderID'))); if(!empty($folder) && $folder!==false && $folder->ID!=0) { $langField=$form->Fields()->dataFieldByName('LanguageID')->setValue($folder->ParentID); $form->Fields()->replaceField('LanguageID', $langField->performReadonlyTransformation()); $form->Fields()->push(new HiddenField('FolderID', 'FolderID', $folder->ID)); } }else if($this->request->postVar('FolderID')) { $folder=SnippetFolder::get()->byID(intval($this->request->postVar('FolderID'))); if(!empty($folder) && $folder!==false && $folder->ID!=0) { $langField=$form->Fields()->dataFieldByName('LanguageID')->setValue($folder->ParentID); $form->Fields()->replaceField('LanguageID', $langField->performReadonlyTransformation()); $form->Fields()->push(new HiddenField('FolderID', 'FolderID', $folder->ID)); } } $this->extend('updateAddForm', $form); //Display message telling user to run dev/build because the version numbers are out of sync if(CB_VERSION!='@@VERSION@@' && CodeBankConfig::CurrentConfig()->Version!=CB_VERSION.' '.CB_BUILD_DATE) { $form->insertBefore(new LiteralField('<p class="message error">'._t('CodeBank.UPDATE_NEEDED', '_A database upgrade is required please run {startlink}dev/build{endlink}.', array('startlink'=>'<a href="dev/build?flush=all">', 'endlink'=>'</a>')).'</p>'), 'LanguageID'); }else if($this->hasOldTables()) { $form->insertBefore(new LiteralField('<p class="message warning">'._t('CodeBank.MIGRATION_AVAILABLE', '_It appears you are upgrading from Code Bank 2.2.x, your old data can be migrated {startlink}click here to begin{endlink}, though it is recommended you backup your database first.', array('startlink'=>'<a href="dev/tasks/CodeBankLegacyMigrate">', 'endlink'=>'</a>')).'</p>'), 'LanguageID'); } $form->Actions()->push(new LiteralField('CodeBankVersion', '<p class="codeBankVersion">Code Bank: '.$this->getVersion().'</p>')); Requirements::javascript(CB_DIR.'/javascript/CodeBank.EditForm.js'); return $form; }
Generates the form used for adding snippets @return {Form} Form used to add snippets
entailment
public function doAdd($data, Form $form) { $record=$this->getRecord(null); $form->saveInto($record); $record->write(); $editController=singleton('CodeBank'); $editController->setCurrentPageID($record->ID); return $this->redirect(Controller::join_links(singleton('CodeBank')->Link('show'), $record->ID)); }
Handles adding the snippet to the database @param {array} $data Data submitted by the user @param {Form} $form Form submitted
entailment
public function doSnippetSearch($keywords, $languageID=false, $folderID=false) { $list=Snippet::get(); if(isset($languageID) && !empty($languageID)) { $list=$list->filter('LanguageID', intval($languageID)); } if(isset($folderID) && !empty($folderID)) { $list=$list->filter('FolderID', intval($folderID)); } if(isset($keywords) && !empty($keywords)) { $SQL_val=Convert::raw2sql($keywords); if(DB::getConn() instanceof MySQLDatabase) { $list=$list->where("MATCH(\"Title\", \"Description\", \"Tags\") AGAINST('".$SQL_val."' IN BOOLEAN MODE)"); }else { $list=$list->filterAny(array( 'Title:PartialMatch'=>$SQL_val, 'Description:PartialMatch'=>$SQL_val, 'Tags:PartialMatch'=>$SQL_val )); } } return $list; }
Performs the search against the snippets in the system @param {string} $keywords Keywords to search for @param {int} $languageID Language to filter to @param {int} $folderID Folder to filter to @return {DataList} Data list pointing to the snippets in the results
entailment
public function open() { if (!$this->isRemoteFile($this->path) && !is_readable($this->path)) { throw new BoxClientException('Failed to create BoxFile instance. Unable to read resource: ' . $this->path . '.'); } $this->stream = \GuzzleHttp\Psr7\stream_for(fopen($this->path, 'r')); if (!$this->stream) { throw new BoxClientException('Failed to create BoxFile instance. Unable to open resource: ' . $this->path . '.'); } }
Opens the File Stream @throws BoxClientException @return void
entailment
public function getContents() { // If an offset is provided if ($this->offset !== -1) { // Seek to the offset $this->stream->seek($this->offset); } // If a max length is provided if ($this->maxLength !== -1) { // Read from the offset till the maxLength return $this->stream->read($this->maxLength); } return $this->stream->getContents(); }
Return the contents of the file @return string
entailment
public function FieldHolder($properties=array()) { $obj=($properties ? $this->customise($properties):$this); Requirements::css(CB_DIR.'/css/PackageViewField.css'); Requirements::javascript(CB_DIR.'/javascript/PackageViewField.js'); return $obj->renderWith($this->getFieldHolderTemplates()); }
Returns a "field holder" for this field - used by templates. @param {array} $properties key value pairs of template variables @return {string} HTML to be used
entailment
public function load(array $configs, ContainerBuilder $container) { $loader = new XmlFileLoader($container, new FileLocator(__DIR__.'/../Resources/config')); $loader->load('services.xml'); if (!method_exists(AbstractType::class, 'getBlockPrefix')) { $container->getDefinition('ivory_ordered_form.form_extension') ->clearTag($tag = 'form.type_extension') ->addTag($tag, ['alias' => 'form']); $container->getDefinition('ivory_ordered_form.button_extension') ->clearTag($tag) ->addTag($tag, ['alias' => 'button']); } }
{@inheritdoc}
entailment
public function getServices() { $this->_zendAmfServer = ZendAmfServiceBrowser::$ZEND_AMF_SERVER; $methods = $this->_zendAmfServer->getFunctions(); $methodsTable = '<methods>'; foreach ($methods as $method => $value) { $functionReflection = $methods[ $method ]; $parameters = $functionReflection->getParameters(); $methodsTable = $methodsTable . "<method name='$method'>"; foreach ($parameters as $param) { $methodsTable = $methodsTable . "<param name='$param->name'/>"; } $methodsTable = $methodsTable . "</method>"; } $methodsTable = $methodsTable . '</methods>'; unset( $methods ); return $methodsTable; }
The getServices() method returns all of the available services for the Zend_Amf_Server object. @return array Table of parameters for each method key ("Class.method").
entailment
public function addListener(Listener $listener) : void { $this->listeners = $this->listeners->add($listener); }
add an event listener to the dispatcher @param Listener $listener
entailment
public function dispatch(DomainEvents $events) : void { $events->each(function (DomainEvent $event) { $this->listeners->each(function (Listener $listener) use ($event) { $listener->handle($event); }); }); }
dispatch domain events to listeners @param DomainEvents $events
entailment
public function toChunks(Csv $csv, $size=1000) { return Writer\ChunksWriter::write($this, $csv, $size); }
/* Special writers
entailment
public function initialize($request) { $this->_inputStream = new Zend_Amf_Parse_InputStream($request); $this->_deserializer = new Zend_Amf_Parse_Amf0_Deserializer($this->_inputStream); $this->readMessage($this->_inputStream); return $this; }
Prepare the AMF InputStream for parsing. @param string $request @return Zend_Amf_Request
entailment
public function readMessage(Zend_Amf_Parse_InputStream $stream) { $clientVersion = $stream->readUnsignedShort(); if (($clientVersion != Zend_Amf_Constants::AMF0_OBJECT_ENCODING) && ($clientVersion != Zend_Amf_Constants::AMF3_OBJECT_ENCODING) && ($clientVersion != Zend_Amf_Constants::FMS_OBJECT_ENCODING) ) { require_once 'Zend/Amf/Exception.php'; throw new Zend_Amf_Exception('Unknown Player Version ' . $clientVersion); } $this->_bodies = array(); $this->_headers = array(); $headerCount = $stream->readInt(); // Iterate through the AMF envelope header while ($headerCount--) { $this->_headers[] = $this->readHeader(); } // Iterate through the AMF envelope body $bodyCount = $stream->readInt(); while ($bodyCount--) { $this->_bodies[] = $this->readBody(); } return $this; }
Takes the raw AMF input stream and converts it into valid PHP objects @param Zend_Amf_Parse_InputStream @return Zend_Amf_Request
entailment
public function readHeader() { $name = $this->_inputStream->readUTF(); $mustRead = (bool)$this->_inputStream->readByte(); $length = $this->_inputStream->readLong(); try { $data = $this->_deserializer->readTypeMarker(); } catch (Exception $e) { require_once 'Zend/Amf/Exception.php'; throw new Zend_Amf_Exception('Unable to parse ' . $name . ' header data: ' . $e->getMessage() . ' '. $e->getLine(), 0, $e); } $header = new Zend_Amf_Value_MessageHeader($name, $mustRead, $data, $length); return $header; }
Deserialize a message header from the input stream. A message header is structured as: - NAME String - MUST UNDERSTAND Boolean - LENGTH Int - DATA Object @return Zend_Amf_Value_MessageHeader
entailment
public function readBody() { $targetURI = $this->_inputStream->readUTF(); $responseURI = $this->_inputStream->readUTF(); $length = $this->_inputStream->readLong(); try { $data = $this->_deserializer->readTypeMarker(); } catch (Exception $e) { require_once 'Zend/Amf/Exception.php'; throw new Zend_Amf_Exception('Unable to parse ' . $targetURI . ' body data ' . $e->getMessage(), 0, $e); } // Check for AMF3 objectEncoding if ($this->_deserializer->getObjectEncoding() == Zend_Amf_Constants::AMF3_OBJECT_ENCODING) { /* * When and AMF3 message is sent to the server it is nested inside * an AMF0 array called Content. The following code gets the object * out of the content array and sets it as the message data. */ if(is_array($data) && $data[0] instanceof Zend_Amf_Value_Messaging_AbstractMessage){ $data = $data[0]; } // set the encoding so we return our message in AMF3 $this->_objectEncoding = Zend_Amf_Constants::AMF3_OBJECT_ENCODING; } $body = new Zend_Amf_Value_MessageBody($targetURI, $responseURI, $data); return $body; }
Deserialize a message body from the input stream @return Zend_Amf_Value_MessageBody
entailment
public function onAuthenticationSuccess(Request $request, TokenInterface $token, $providerKey) { // if the user hit a secure page and start() was called, this was // the URL they were on, and probably where you want to redirect to $targetPath = $request->getSession()->get('_security.'.$providerKey.'.target_path'); if (!$targetPath) { $targetPath = $this->getDefaultSuccessRedirectUrl(); } return new RedirectResponse($targetPath); }
Override to change what happens after successful authentication @param Request $request @param TokenInterface $token @param string $providerKey @return RedirectResponse
entailment
protected function addRelation() { if ($this->relationType == 'hasAndBelongsToMany') { $junction = $this->getJunction(); try { Validate::table($junction)->exists(); } catch (dbException $e) { Database::create($junction, [ $this->tables['local'] . '_id' => 'integer', $this->tables['foreign'] . '_id' => 'integer', ]); $this->insertRelationData($junction, $this->tables['local'], 'hasMany', [ 'local' => $this->tables['local'] . '_id', 'foreign' => $this->keys['local'] ]); $this->insertRelationData($junction, $this->tables['foreign'], 'hasMany', [ 'local' => $this->tables['foreign'] . '_id', 'foreign' => $this->keys['foreign'] ]); } } $this->insertRelationData($this->tables['local'], $this->tables['foreign'], $this->relationType, $this->keys); }
Add data to configs and create all necessary files
entailment
protected function insertRelationData($from, $to, $type, array $keys) { $config = Config::table($from); $content = $config->get(); $content->relations->{$to} = [ 'type' => $type, 'keys' => $keys, ]; $config->put($content); }
Inserts relation data to config file @param string $from Local table @param string $to Related table @param string $type Relation type @param array $keys Relationed keys
entailment
protected function join($row) { $keys['local'] = $this->keys['local']; $keys['foreign'] = $this->keys['foreign']; if ($this->relationType == 'hasAndBelongsToMany') { $join = Database::table($this->getJunction()) ->groupBy($this->tables['local'] . '_id') ->where($this->tables['local'] . '_id', '=', $row->{$keys['local']}) ->findAll() ->asArray(null, $this->tables['foreign'] . '_id'); if (empty($join)) return []; return Database::table($this->tables['foreign']) ->where($keys['foreign'], 'IN', $join[$row->{$keys['local']}]); } return Database::table($this->tables['foreign']) ->where($keys['foreign'], '=', $row->{$keys['local']}); }
Process query with joined data @param object $row One row of data @return Database
entailment
protected function buildUrl($endpoint = '', $type = 'api') { //Get the base path $base = $this->getBasePath(); //If the endpoint type is 'upload' if ($type === 'upload') { //Get the Content Path $base = $this->getUploadPath(); } //Join and return the base and api path/endpoint return $base . $endpoint; }
Build URL for the Request @param string $endpoint Relative API endpoint @param string $type Endpoint Type @return string The Full URL to the API Endpoints
entailment
public function sendRequest(BoxRequest $request) { //Method $method = $request->getMethod(); //Prepare Request list($url, $headers, $requestBody, $options) = $this->prepareRequest($request); //Send the Request to the Server through the HTTP Client //and fetch the raw response as BoxRawResponse $rawResponse = $this->getHttpClient()->send($url, $method, $requestBody, $headers, $options); //Create BoxResponse from BoxRawResponse $boxResponse = new BoxResponse( $request, $rawResponse->getBody(), $rawResponse->getHttpResponseCode(), $rawResponse->getHeaders() ); //Return the BoxResponse return $boxResponse; }
Send the Request to the Server and return the Response @param BoxRequest $request @return BoxResponse @throws Exceptions\BoxClientException
entailment
protected function prepareRequest(BoxRequest $request) { $options = array(); $contentType = true; //Build URL $url = $this->buildUrl($request->getEndpoint(), $request->getEndpointType()); //The Endpoint is content if ($request->getEndpointType() === 'upload') { $requestBody = null; //If a File is also being uploaded if ($request->hasFile()) { //Request Body (File Contents) $options = array( "multipart" => array( array( 'name' => 'attributes', 'contents' => json_encode($request->getParams()["attributes"]) ), array( 'name' => 'file', 'contents' => fopen($request->getFile()->getFilePath(), 'r') ) ) ); $contentType = false; } else { //Empty Body $requestBody = null; } } else { //The endpoint is 'api' //Request Body (Parameters) $requestBody = $request->getJsonBody()->getBody(); } //Build headers $headers = array_merge( $this->buildAuthHeader($request->getAccessToken()), $request->getHeaders() ); if ($contentType) $headers[] = $this->buildContentTypeHeader($request->getContentType()); //Return the URL, Headers and Request Body return [$url, $headers, $requestBody, $options]; }
Prepare a Request before being sent to the HTTP Client @param BoxResponse $request @return array [Request URL, Request Headers, Request Body, Options Array]
entailment
function Text_Diff3($orig, $final1, $final2) { if (extension_loaded('xdiff')) { $engine = new Text_Diff_Engine_xdiff(); } else { $engine = new Text_Diff_Engine_native(); } $this->_edits = $this->_diff3($engine->diff($orig, $final1), $engine->diff($orig, $final2)); }
Computes diff between 3 sequences of strings. @param array $orig The original lines to use. @param array $final1 The first version to compare to. @param array $final2 The second version to compare to.
entailment
public function serialize($value) { if ($value instanceof SerializablePersonalDataValue) { return $this->serializePersonalDataValue($value); } elseif ($value instanceof SerializableValue) { return $this->serializeValue($value); } return $value; }
serialize a value object into its string-based persistence form @param $value @return array
entailment
private function serializePersonalDataValue(SerializablePersonalDataValue $value): array { $dataKey = PersonalDataKey::generate(); $dataString = json_encode($value->serialize()); $this->dataStore->storeData($value->personalKey(), $dataKey, PersonalData::fromString($dataString)); return [ 'personalKey' => $value->personalKey()->serialize(), 'dataKey' => $dataKey->serialize(), ]; }
serialize a value that contains personal data @param SerializablePersonalDataValue $value @return array
entailment
public function deserializePersonalValue(string $type, string $json): SerializablePersonalDataValue { $values = json_decode($json); $personalKey = PersonalKey::deserialize($values->personalKey); $dataKey = PersonalDataKey::deserialize($values->dataKey); return $type::deserialize($this->dataStore->retrieveData($personalKey, $dataKey)->toString()); }
deserialize a value that contains personal data @param string $type @param string $json @return SerializablePersonalDataValue
entailment
public function addParameter($parameter) { if ($parameter instanceof Zend_Server_Method_Parameter) { $this->_parameters[] = $parameter; if (null !== ($name = $parameter->getName())) { $this->_parameterNameMap[$name] = count($this->_parameters) - 1; } } else { require_once 'Zend/Server/Method/Parameter.php'; $parameter = new Zend_Server_Method_Parameter(array( 'type' => (string) $parameter, )); $this->_parameters[] = $parameter; } return $this; }
Add a parameter @param string $parameter @return Zend_Server_Method_Prototype
entailment
public function setParameters(array $parameters) { $this->_parameters = array(); $this->_parameterNameMap = array(); $this->addParameters($parameters); return $this; }
Set parameters @param array $parameters @return Zend_Server_Method_Prototype
entailment
public function getParameters() { $types = array(); foreach ($this->_parameters as $parameter) { $types[] = $parameter->getType(); } return $types; }
Retrieve parameters as list of types @return array
entailment
public function getParameter($index) { if (!is_string($index) && !is_numeric($index)) { return null; } if (array_key_exists($index, $this->_parameterNameMap)) { $index = $this->_parameterNameMap[$index]; } if (array_key_exists($index, $this->_parameters)) { return $this->_parameters[$index]; } return null; }
Retrieve a single parameter by name or index @param string|int $index @return null|Zend_Server_Method_Parameter
entailment
public static function create($name, $type, $extension, $vendor) { // Prepare the component name $componentLabel = $componentName = array_pop($name); if (substr($componentName, -9) !== 'Component') { $componentName .= 'Component'; } // Prepare the component directory $componentPath = implode(DIRECTORY_SEPARATOR, $name); $componentAbsPath = GeneralUtility::getFileAbsFileName( 'EXT:'.$extension.DIRECTORY_SEPARATOR.'Components'.DIRECTORY_SEPARATOR .implode(DIRECTORY_SEPARATOR, $name) ); if (!is_dir($componentAbsPath) && !mkdir($componentAbsPath, 06775, true)) { throw new CommandException('Could not create component directory', 1507997978); } // Prepare the component namespace $componentNamespace = rtrim( $vendor.'\\'.GeneralUtility::underscoredToUpperCamelCase($extension) .'\\Component\\'.implode('\\', $name), '\\' ); // Copy the skeleton template $substitute = [ '###extension###' => $extension, '###namespace###' => $componentNamespace, '###label###' => $componentLabel, '###tspath###' => strtolower(implode('.', array_merge($name, [$componentLabel]))), '###path###' => $componentPath, ]; $skeletonTemplate = GeneralUtility::getFileAbsFileName( 'EXT:tw_componentlibrary/Resources/Private/Skeleton/'.ucfirst($type).'.php' ); $skeletonString = strtr(file_get_contents($skeletonTemplate), $substitute); $skeletonFile = $componentAbsPath.DIRECTORY_SEPARATOR.$componentName.'.php'; file_put_contents($skeletonFile, $skeletonString); chmod($skeletonFile, 0664); }
Kickstart a new component @param string $name Component name @param string $type Component type @param string $extension Host extension @throws CommandException If the provider extension is invalid
entailment
protected function processParams(array $params) { //If a file needs to be uploaded if (isset($params['file']) && $params['file'] instanceof BoxFile) { //Set the file property $this->setFile($params['file']); //Remove the file item from the params array unset($params['file']); } //Whether the response needs to be validated //against being a valid JSON response if (isset($params['validateResponse'])) { //Set the validateResponse $this->validateResponse = $params['validateResponse']; //Remove the validateResponse from the params array unset($params['validateResponse']); } return $params; }
Process Params for the File parameter @param array $params Request Params @return array
entailment
public function handleUploadedFiles(UploadedFile $file, $extension, $dir) { $original_file = $file->getClientOriginalName(); $path_parts = pathinfo($original_file); $increment = ''; while (file_exists($dir . FileManager::DS . $path_parts['filename'] . $increment . '.' . $extension)) { $increment++; } $basename = $path_parts['filename'] . $increment . '.' . $extension; $file->move($dir, $basename); }
Upload the files @param UploadedFile $file @param string $extension @param string $dir
entailment
public function makeDir($dir_path) { $fm = new Filesystem(); if (!file_exists($dir_path)) { $fm->mkdir($dir_path, 0755); } else { $this->getFileManager() ->throwError("Cannot create directory '" . $dir_path . "': Directory already exists", 500); } }
Create new directory @param string $dir_path
entailment
public function renameFile(FileInfo $fileInfo, $new_file_name) { try { $this->validateFile($fileInfo, $new_file_name); $fm = new Filesystem(); $old_file = $fileInfo->getFilepath(true); $new_file = $new_file_name; $fm->rename($old_file, $new_file); } catch (\Exception $e) { $this->getFileManager()->throwError("Cannot rename file or directory", 500, $e); } }
Renames the file @param FileInfo $fileInfo @param string $new_file_name
entailment
public function validateFile(FileInfo $fileInfo, $new_filename = null) { $file_path = $fileInfo->getFilePath(true); if (!is_dir($file_path)) { $fm = new Filesystem(); $tmp_dir = $this->createTmpDir($fm); $fm->copy($file_path, $tmp_dir . FileManager::DS . $fileInfo->getFilename()); if (!is_null($new_filename)) { $new_filename = basename($new_filename); $fm->rename($tmp_dir . FileManager::DS . $fileInfo->getFilename(), $tmp_dir . FileManager::DS . $new_filename); } $this->checkFileType($fm, $tmp_dir); } }
Validate the files to check if they have a valid file type @param FileInfo $fileInfo @param null|string $new_filename
entailment
public function createTmpDir(Filesystem $fm) { $tmp_dir = $this->getFileManager()->getUploadPath() . FileManager::DS . "." . strtotime("now"); $fm->mkdir($tmp_dir); return $tmp_dir; }
Create a temporary directory @param Filesystem $fm @return string
entailment
public function checkFileType(Filesystem $fm, $tmp_dir) { $di = new \RecursiveDirectoryIterator($tmp_dir); foreach (new \RecursiveIteratorIterator($di) as $filepath => $file) { $fileInfo = new FileInfo($filepath, $this->getFileManager()); $mime_valid = $this->checkMimeType($fileInfo); if ($mime_valid !== true) { $fm->remove($tmp_dir); $this->getFileManager()->throwError($mime_valid, 500); } } $fm->remove($tmp_dir); }
Check if the file type is an valid file type by extracting the zip inside a temporary directory @param Filesystem $fm @param string $tmp_dir
entailment
public function checkMimeType($fileInfo) { $mime = $fileInfo->getMimetype(); if ($mime != 'directory' && !in_array($mime, $this->getFileManager()->getExtensionsAllowed())) { return 'Mime type "' . $mime . '" not allowed for file "' . $fileInfo->getFilename() . '"'; } return true; }
Check the mimetype @param FileInfo $fileInfo @return string|bool
entailment
public function moveFile(FileInfo $fileInfo, $new_file_name) { try { $this->validateFile($fileInfo); $file_path = $fileInfo->getFilepath(true); $file = new File($file_path, false); $file->move($new_file_name); } catch (\Exception $e) { $this->getFileManager()->throwError("Cannot move file or directory", 500, $e); } }
Move the file @param FileInfo $fileInfo @param string $new_file_name
entailment
public function pasteFile(FileInfo $fileInfo, $type) { try { $target_file_path = $this->getFileManager()->getTargetFile()->getFilepath(true); $source_file_path = $fileInfo->getFilepath(true); $this->validateFile($fileInfo); $fileSystem = new Filesystem(); if (!file_exists($target_file_path)) { $fileSystem->copy($source_file_path, $target_file_path); var_dump($type); if ($type == FileManager::FILE_CUT) { $fileSystem->remove($source_file_path); } } else { $target_file = $this->getFileManager()->getTargetFile()->getFilename(); throw new \Exception(sprintf("File '%s' already exists", $target_file)); } } catch (\Exception $e) { $this->getFileManager()->throwError("Cannot paste file", 500, $e); } }
Paste the file @param FileInfo $fileInfo @param string $type
entailment
public function deleteFile(FileInfo $fileInfo) { try { $fm = new Filesystem(); $file = $fileInfo->getFilepath(true); $fm->remove($file); } catch (\Exception $e) { $this->getFileManager()->throwError("Cannot delete file or directory", 500, $e); } }
Delete the file @param FileInfo $fileInfo
entailment
public function extractZip(FileInfo $fileInfo) { $fm = new Filesystem(); $tmp_dir = $this->createTmpDir($fm); $this->extractZipTo($fileInfo->getFilepath(true), $tmp_dir); $this->checkFileType($fm, $tmp_dir); try { $this->extractZipTo($fileInfo->getFilepath(true), $this->getFileManager()->getDir()); } catch (\Exception $e) { $this->getFileManager()->throwError("Cannot extract zip", 500, $e); } }
Extract the zip @param FileInfo $fileInfo
entailment
public function extractZipTo($filepath, $destination) { $chapterZip = new \ZipArchive (); if ($chapterZip->open($filepath)) { $chapterZip->extractTo($destination); $chapterZip->close(); } }
Extract the zip to the given location @param string $filepath @param string $destination
entailment
function Text_Diff_Mapped($from_lines, $to_lines, $mapped_from_lines, $mapped_to_lines) { assert(count($from_lines) == count($mapped_from_lines)); assert(count($to_lines) == count($mapped_to_lines)); parent::Text_Diff($mapped_from_lines, $mapped_to_lines); $xi = $yi = 0; for ($i = 0; $i < count($this->_edits); $i++) { $orig = &$this->_edits[$i]->orig; if (is_array($orig)) { $orig = array_slice($from_lines, $xi, count($orig)); $xi += count($orig); } $final = &$this->_edits[$i]->final; if (is_array($final)) { $final = array_slice($to_lines, $yi, count($final)); $yi += count($final); } } }
Computes a diff between sequences of strings. This can be used to compute things like case-insensitve diffs, or diffs which ignore changes in white-space. @param array $from_lines An array of strings. @param array $to_lines An array of strings. @param array $mapped_from_lines This array should have the same size number of elements as $from_lines. The elements in $mapped_from_lines and $mapped_to_lines are what is actually compared when computing the diff. @param array $mapped_to_lines This array should have the same number of elements as $to_lines.
entailment
public function getResponseNegotiator() { $neg=parent::getResponseNegotiator(); $controller=$this; $neg->setCallback('CurrentForm', function() use(&$controller) { return $controller->renderWith($controller->getTemplatesWithSuffix('_Content')); }); return $neg; }
@return {PjaxResponseNegotiator} @see LeftAndMain::getResponseNegotiator()
entailment
public function doSave($data, $form) { $config=CodeBankConfig::CurrentConfig(); $form->saveInto($config); $config->write(); $this->response->addHeader('X-Status', rawurlencode(_t('LeftAndMain.SAVEDUP', 'Saved.'))); return $this->getResponseNegotiator()->respond($this->request); }
Saves the snippet to the database @param {array} $data Data submitted by the user @param {Form} $form Submitting form @return {SS_HTTPResponse} Response
entailment
public function import_from_client() { if(!Permission::check('ADMIN')) { Security::permissionFailure($this); return; } $form=$this->ImportFromClientForm(); if(Session::get('reloadOnImportDialogClose')) { Requirements::javascript(CB_DIR.'/javascript/CodeBank.ImportDialog.js'); Session::clear('reloadOnImportDialogClose'); } return $this->customise(array( 'Content'=>' ', 'Form'=>$form ))->renderWith('CMSDialog'); }
Handles requests for the import from client popup @return {string} Rendered template
entailment
public function ImportFromClientForm() { if(!Permission::check('ADMIN')) { Security::permissionFailure($this); return; } $uploadField=new FileField('ImportFile', _t('CodeBank.EXPORT_FILE', '_Client Export File')); $uploadField->getValidator()->setAllowedExtensions(array('cbexport')); File::config()->allowed_extensions=array('cbexport'); $fields=new FieldList( new LiteralField('ImportWarning', '<p class="message warning">'._t('CodeBank.IMPORT_DATA_WARNING', '_Warning clicking import will erase all snippets in the database, it is recommended you backup your database before proceeding').'</p>'), new TabSet('Root', new Tab('Main', $uploadField, new CheckboxField('AppendData', _t('CodeBank.APPEND_IMPORT', '_Import and Append Data (keep your existing data however appending may cause duplicates)')) ) ) ); $actions=new FieldList( FormAction::create('doImportData', _t('CodeBank.IMPORT', '_Import'))->addExtraClass('ss-ui-button ss-ui-action-constructive')->setAttribute('data-icon', 'accept')->setUseButtonTag(true) ); $validator=new RequiredFields( 'ImportFile' ); $form=new Form($this, 'ImportFromClientForm', $fields, $actions, $validator); $form->addExtraClass('member-profile-form'); return $form; }
Form used for importing data from the client @return {Form} Form to be used in the popup
entailment
public function doImportData($data, Form $form) { if(!Permission::check('ADMIN')) { Security::permissionFailure($this); return; } $fileData=$form->Fields()->dataFieldByName('ImportFile')->Value(); //Check that the file uploaded if(!array_key_exists('tmp_name', $fileData) || !file_exists($fileData['tmp_name'])) { $form->sessionMessage(_t('CodeBank.IMPORT_READ_ERROR', '_Could not read the file to be imported'), 'bad'); return $this->redirectBack(); } //Load the file into memory $fileData=file_get_contents($fileData['tmp_name']); if($fileData===false || empty($fileData)) { $form->sessionMessage(_t('CodeBank.IMPORT_READ_ERROR', '_Could not read the file to be imported'), 'bad'); return $this->redirectBack(); } //Decode the json $fileData=json_decode($fileData); if($fileData===false || !is_object($fileData)) { $form->sessionMessage(_t('CodeBank.IMPORT_READ_ERROR', '_Could not read the file to be imported'), 'bad'); return $this->redirectBack(); } //Verify the format is ToServer if($fileData->format!='ToServer') { $form->sessionMessage(_t('CodeBank.IMPORT_FILE_FORMAT_INCORRECT', '_Import file format is incorrect'), 'bad'); return $this->redirectBack(); } //Bump Up the time limit this may take time set_time_limit(480); //Start transaction if supported if(DB::getConn()->supportsTransactions()) { DB::getConn()->transactionStart(); } //If not appending empty the tables if(!isset($data['AppendData'])) { DB::query('DELETE FROM Snippet'); DB::query('DELETE FROM SnippetVersion'); DB::query('DELETE FROM SnippetLanguage'); DB::query('DELETE FROM SnippetPackage'); DB::query('DELETE FROM SnippetFolder'); }else { $langMap=array(); $pkgMap=array(); $folderMap=array(); $snipMap=array(); } //Import Languages foreach($fileData->data->languages as $lang) { if(isset($data['AppendData'])) { $dbLang=SnippetLanguage::get()->filter('Name:ExactMatch:nocase', Convert::raw2sql($lang->language))->first(); if(!empty($dbLang) && $dbLang!==false && $dbLang->ID>0) { $langMap['lang-'.$lang->id]=$dbLang->ID; }else { $newLang=new SnippetLanguage(); $newLang->Name=$lang->language; $newLang->FileExtension=$lang->file_extension; $newLang->HighlightCode=$lang->shjs_code; $newLang->UserLanguage=$lang->user_language; $newLang->write(); $langMap['lang-'.$lang->id]=$newLang->ID; unset($newLang); } }else { DB::query('INSERT INTO "SnippetLanguage" ("ID", "ClassName", "Created", "LastEdited", "Name", "FileExtension", "HighlightCode", "UserLanguage") '. "VALUES(".intval($lang->id).",'SnippetLanguage', '".date('Y-m-d H:i:s')."','".date('Y-m-d H:i:s')."','".Convert::raw2sql($lang->language)."','".Convert::raw2sql($lang->file_extension)."','".Convert::raw2sql($lang->shjs_code)."',".intval($lang->user_language).")"); } } //Import Packages foreach($fileData->data->packages as $pkg) { if(isset($data['AppendData'])) { $newPkg=new SnippetPackage(); $newPkg->Title=$pkg->title; $newPkg->write(); $pkgMap['pkg-'.$pkg->id]=$newPkg->ID; unset($newPkg); }else { DB::query('INSERT INTO "SnippetPackage" ("ID", "ClassName", "Created", "LastEdited", "Title") '. "VALUES(".intval($pkg->id).",'SnippetPackage', '".date('Y-m-d H:i:s')."','".date('Y-m-d H:i:s')."','".Convert::raw2sql($pkg->title)."')"); } } //Import Folders foreach($fileData->data->folders as $folder) { if(isset($data['AppendData'])) { if(!isset($langMap['lang-'.$folder->fkLanguageId])) { if(DB::getConn()->supportsTransactions()) { DB::getConn()->transactionRollback(); } $form->sessionMessage(_t('CodeBank.IMPORT_LANG_NOT_FOUND', '_Import failed language not found'), 'bad'); return $this->redirectBack(); } $newFld=new SnippetFolder(); $newFld->Name=$folder->name; $newFld->ParentID=($folder->fkParentId>0 && isset($folderMap['fld-'.$folder->fkParentId]) ? $folderMap['fld-'.$folder->fkParentId]:0); $newFld->LanguageID=$langMap['lang-'.$folder->fkLanguageId]; $newFld->write(); $folderMap['fld-'.$folder->id]=$newFld->ID; unset($newFld); }else { DB::query('INSERT INTO "SnippetFolder" ("ID", "ClassName", "Created", "LastEdited", "Name", "ParentID", "LanguageID") '. "VALUES(".intval($folder->id).",'SnippetFolder', '".date('Y-m-d H:i:s')."','".date('Y-m-d H:i:s')."','".Convert::raw2sql($folder->name)."', ".intval($folder->fkParentId).", ".intval($folder->fkLanguageId).")"); } } //Import Snippets foreach($fileData->data->snippets as $snip) { if(isset($data['AppendData'])) { if(!isset($langMap['lang-'.$snip->fkLanguage])) { if(DB::getConn()->supportsTransactions()) { DB::getConn()->transactionRollback(); } $form->sessionMessage(_t('CodeBank.IMPORT_LANG_NOT_FOUND', '_Import failed language not found'), 'bad'); return $this->redirectBack(); } $newSnip=new Snippet(); $newSnip->Title=$snip->title; $newSnip->Description=$snip->description; $newSnip->Tags=$snip->tags; $newSnip->LanguageID=$langMap['lang-'.$snip->fkLanguage]; $newSnip->CreatorID=Member::currentUserID(); $newSnip->LastEditorID=Member::currentUserID(); $newSnip->PackageID=($snip->fkPackageID>0 && isset($pkgMap['pkg-'.$snip->fkPackageID]) ? $pkgMap['pkg-'.$snip->fkPackageID]:0); $newSnip->FolderID=($snip->fkFolderID>0 && isset($folderMap['fld-'.$snip->fkFolderID]) ? $folderMap['fld-'.$snip->fkFolderID]:0); $newSnip->write(); $snipMap['snip-'.$snip->id]=$newSnip->ID; unset($newSnip); }else { DB::query('INSERT INTO "Snippet" ("ID", "ClassName", "Created", "LastEdited", "Title", "Description", "Tags", "LanguageID", "CreatorID", "LastEditorID", "PackageID", "FolderID") '. "VALUES(".intval($snip->id).",'Snippet', '".date('Y-m-d H:i:s')."','".date('Y-m-d H:i:s')."','".Convert::raw2sql($snip->title)."', '".Convert::raw2sql($snip->description)."', '".Convert::raw2sql($snip->tags)."', ".intval($snip->fkLanguage).", ".Member::currentUserID().", ".Member::currentUserID().", ".intval($snip->fkPackageID).", ".intval($snip->fkFolderID).")"); } } //Import Snippet Versions foreach($fileData->data->versions as $ver) { if(isset($data['AppendData'])) { if(!isset($snipMap['snip-'.$ver->fkSnippit])) { if(DB::getConn()->supportsTransactions()) { DB::getConn()->transactionRollback(); } $form->sessionMessage(_t('CodeBank.IMPORT_SNIP_NOT_FOUND', '_Import failed snippet not found'), 'bad'); return $this->redirectBack(); } DB::query('INSERT INTO "SnippetVersion" ("ClassName", "Created", "LastEdited", "Text", "ParentID") '. "VALUES('SnippetVersion', '".Convert::raw2sql($ver->date)."','".Convert::raw2sql($ver->date)."','".Convert::raw2sql($ver->text)."', ".intval($snipMap['snip-'.$ver->fkSnippit]).")"); }else { DB::query('INSERT INTO "SnippetVersion" ("ID", "ClassName", "Created", "LastEdited", "Text", "ParentID") '. "VALUES(".intval($ver->id).",'SnippetVersion', '".Convert::raw2sql($ver->date)."','".Convert::raw2sql($ver->date)."','".Convert::raw2sql($ver->text)."', ".intval($ver->fkSnippit).")"); } } //End transaction if supported if(DB::getConn()->supportsTransactions()) { DB::getConn()->transactionEnd(); } //Display success after redirecting back Session::set('reloadOnImportDialogClose', true); $form->sessionMessage(_t('CodeBank.IMPORT_COMPLETE', '_Import Completed'), 'good'); return $this->redirectBack(); }
Processes the upload request @param {array} $data Submitted data @param {Form} $form Submitting form @return {SS_HTTPResponse} Response
entailment
protected function raise(DomainEvent $event): void { $this->apply($event); $this->streamEvents = $this->streamEvents->add( new StreamEvent($this->aggregateId(), $this->aggregateVersion(), $event) ); }
raise an event from within the aggregate. this applies the event to the aggregate state and stores it in the pending stream events collection awaiting flush. @param DomainEvent $event
entailment
public function flushEvents(): StreamEvents { $events = $this->streamEvents->copy(); $this->streamEvents = StreamEvents::make(); return $events; }
returns and clears the internal pending stream events. this DOES violate CQS, however it's important not to retrieve or store these events multiple times. pass these directly into the event store. @return StreamEvents
entailment
public static function buildFrom(StreamEvents $events): Aggregate { $aggregate = new static; $events->each(function (StreamEvent $event) use ($aggregate) { $aggregate->apply($event->event()); if ( ! $event->version()->equals($aggregate->aggregateVersion())) { throw new UnexpectedAggregateVersionWhenBuildingFromEvents("When building from stream events aggregate {$aggregate->aggregateId()->toString()} expected version {$event->version()->toInt()} but got {$aggregate->aggregateVersion()->toInt()}."); } }); return $aggregate; }
reconstruct the aggregate state from domain events @param StreamEvents $events @return Aggregate
entailment
protected function apply(DomainEvent $event): void { $eventName = explode('\\', get_class($event)); $method = 'apply' . $eventName[count($eventName) - 1]; if (method_exists($this, $method)) { $this->$method($event); } $this->version = $this->version->next(); }
apply domain events to aggregate state by mapping the class name to method name using strings @param DomainEvent $event
entailment
public static function types(array $types) { $defined = array('boolean', 'integer', 'double', 'string'); $diff = array_diff($types, $defined); if (empty($diff)) { return true; } throw new dbException('Wrong types: "' . implode(', ', $diff) . '". Available "boolean, integer, double, string, array, object"'); }
Checking that types from array matching with [boolean, integer, string, double, array, object] @param array $types Indexed array @return bool @throws dbException
entailment
public function fields(array $fields) { $fields = self::filter($fields); $diff = array_diff($fields, Config::table($this->name)->fields()); if (empty($diff)) { return true; } throw new dbException('Field(s) "' . implode(', ', $diff) . '" does not exists in table "' . $this->name . '"'); }
Checking that typed fields really exist in table @param array $fields Indexed array @return boolean @throws dbException If field(s) does not exist
entailment
public function field($name) { if (in_array($name, Config::table($this->name)->fields())) { return true; } throw new dbException('Field ' . $name . ' does not exists in table "' . $this->name . '"'); }
Checking that typed field really exist in table @param string $name @return boolean @throws dbException If field does not exist
entailment
public function exists() { if (!Data::table($this->name)->exists()) throw new dbException('Table "' . $this->name . '" does not exists'); if (!Config::table($this->name)->exists()) throw new dbException('Config "' . $this->name . '" does not exists'); return true; }
Checking that Table and Config exists and throw exceptions if not @return boolean @throws dbException
entailment
public function type($name, $value) { $schema = Config::table($this->name)->schema(); if (array_key_exists($name, $schema) && $schema[$name] == gettype($value)) { return true; } throw new dbException('Wrong data type'); }
Checking that typed field have correct type of value @param string $name @param mixed $value @return boolean @throws dbException If type is wrong
entailment