sentence1
stringlengths
52
3.87M
sentence2
stringlengths
1
47.2k
label
stringclasses
1 value
public function deleteUser($data) { $response=CodeBank_ClientAPI::responseBase(); try { $member=Member::get()->filter('ID', intval($data->id))->filter('ID:not', Member::currentUserID())->First(); if(!empty($member) && $member!==false && $member->ID!=0) { $member->delete(); } $response['status']='HELO'; $response['message']=_t('CodeBankAPI.USER_DELETED', '_User deleted successfully'); }catch (Exception $e) { $response['status']='EROR'; $response['message']=_t('CodeBankAPI.SERVER_ERROR', '_Server error has occured, please try again later'); } return $response; }
Deletes a user @param {stdClass} $data Data passed from ActionScript @return {array} Returns a standard response array
entailment
public function changeUserPassword($data) { $response=CodeBank_ClientAPI::responseBase(); try { $member=Member::get()->byID(intval($data->id)); if(empty($member) || $member===false || $member->ID==0) { $response['status']='EROR'; $response['message']=_t('CodeBankAPI.MEMBER_NOT_FOUND', '_Member not found'); return $response; } if(!$member->changePassword($data->password)) { $response['status']='EROR'; $response['message']=_t('CodeBankAPI.NEW_PASSWORD_NOT_VALID', '_New password is not valid'); return $response; } $response['status']='HELO'; $response['message']=_t('CodeBankAPI.PASSWORD_CHANGED', '_User\'s password changed successfully'); }catch (Exception $e) { $response['status']='EROR'; $response['message']=_t('CodeBankAPI.SERVER_ERROR', '_Server error has occured, please try again later'); } return $response; }
Changes a users password @param {stdClass} $data Data passed from ActionScript @return {array} Returns a standard response array
entailment
public function createUser($data) { $response=CodeBank_ClientAPI::responseBase(); try { if(Member::get()->filter('Email', Convert::raw2sql($data->username))->count()>0) { $response['status']='EROR'; $response['message']=_t('CodeBankAPI.EMAIL_EXISTS', '_An account with that email already exists'); return $response; } //Create and write member $member=new Member(); $member->FirstName=(!empty($data->firstname) ? $data->firstname:$data->username); $member->Surname=(!empty($data->surname) ? $data->surname:null); $member->Email=$data->username; $member->Password=$data->Password; $member->UseHeartbeat=0; if(!$member->validate()) { $response['status']='EROR'; $response['message']=_t('CodeBankAPI.PASSWORD_NOT_VALID', '_Password is not valid'); return $response; } $member->write(); $response['status']='HELO'; $response['message']="User added successfully"; }catch (Exception $e) { $response['status']='EROR'; $response['message']=_t('CodeBankAPI.SERVER_ERROR', '_Server error has occured, please try again later'); } return $response; }
Creates a user in the database @param {stdClass} $data Data passed from ActionScript @return {array} Returns a standard response array
entailment
public function getAdminLanguages() { $response=CodeBank_ClientAPI::responseBase(); $languages=SnippetLanguage::get(); foreach($languages as $lang) { $response['data'][]=array( 'id'=>$lang->ID, 'language'=>$lang->Name, 'file_extension'=>$lang->FileExtension, 'shjh_code'=>$lang->HighlightCode, 'user_language'=>$lang->UserLanguage, 'snippetCount'=>$lang->Snippets()->Count(), 'hidden'=>$lang->Hidden ); } return $response; }
Gets the list of languages with snippet counts @return {array} Standard response base
entailment
public function createLanguage($data) { $response=CodeBank_ClientAPI::responseBase(); try { if(SnippetLanguage::get()->filter('Name:nocase', Convert::raw2sql($data->language))->Count()>0) { $response['status']='EROR'; $response['message']=_t('CodeBankAPI.LANGUAGE_EXISTS', '_Language already exists'); return $response; } $lang=new SnippetLanguage(); $lang->Name=$data->language; $lang->FileExtension=$data->fileExtension; $lang->HighlightCode='Plain'; $lang->UserLanguage=1; $lang->write(); $response['status']='HELO'; $response['message']="Language added successfully"; }catch (Exception $e) { $response['status']='EROR'; $response['message']=_t('CodeBankAPI.SERVER_ERROR', '_Server error has occured, please try again later'); } return $response; }
Creates a language in the database @param {stdClass} $data Data passed from ActionScript @return {array} Returns a standard response array
entailment
public function deleteLanguage($data) { $response=CodeBank_ClientAPI::responseBase(); try { $lang=SnippetLanguage::get()->byID(intval($data->id)); if(!empty($lang) && $lang!==false && $lang->ID!=0) { if($lang->canDelete()==false) { $response['status']='EROR'; $response['message']=_t('CodeBankAPI.LANGUAGE_DELETE_ERROR', '_Language cannot be deleted, it is either not a user language or has snippets attached to it'); return $response; } }else { $response['status']='EROR'; $response['message']=_t('CodeBankAPI.LANGUAGE_NOT_FOUND', '_Language not found'); return $response; } $lang->delete(); $response['status']='HELO'; $response['message']="Language deleted successfully"; }catch (Exception $e) { $response['status']='EROR'; $response['message']=_t('CodeBankAPI.SERVER_ERROR', '_Server error has occured, please try again later'); } return $response; }
Deletes a language from the database @param {stdClass} $data Data passed from ActionScript @return {array} Returns a standard response array
entailment
public function editLanguage($data) { $response=CodeBank_ClientAPI::responseBase(); try { if(SnippetLanguage::get()->filter('Name:nocase', Convert::raw2sql($data->language))->Count()>0) { $response['status']='EROR'; $response['message']=_t('CodeBankAPI.LANGUAGE_EXISTS', '_Language already exists'); return $response; } $lang=SnippetLanguage::get()->byID(intval($data->id)); if(empty($lang) || $lang===false || $lang->ID==0) { $response['status']='EROR'; $response['message']=_t('CodeBankAPI.LANGUAGE_NOT_FOUND', '_Language not found'); return $response; } //Update language and write if($lang->UserLanguage==true) { $lang->Name=$data->language; $lang->FileExtension=$data->fileExtension; } $lang->Hidden=$data->hidden; $lang->write(); $response['status']='HELO'; $response['message']="Language edited successfully"; }catch (Exception $e) { $response['status']='EROR'; $response['message']=_t('CodeBankAPI.SERVER_ERROR', '_Server error has occured, please try again later'); } return $response; }
Edits a language @param {stdClass} $data Data passed from ActionScript @return {array} Returns a standard response array
entailment
public static function MakeOfType(array $esHit, $className = "", Client $esClient = null) { if ($className && strpos($className, '{type}') !== false) { $baseClassName = str_replace(' ', '', ucwords(preg_replace('/[^a-zA-Z0-9]+/', ' ', $esHit['_type']))); $fullClassName = str_replace("{type}", $baseClassName, $className); if (!class_exists($fullClassName)) { $fullClassName = array_key_exists('_source', $esHit) ? static::class : ArrayObject::class; } } else { $fullClassName = $className? : static::class; } return $fullClassName::make($esHit, $esClient); }
A custom factory method that will try to detect the correct model class and instantiate and object of it. @param array $esHit @param string $className a class name or pattern. @param Client $esClient ElasticSearch client @return Model
entailment
public function getAttributes() { $values = func_get_args(); if (count($values) === 1) { $result = []; foreach ($values as $value) { $result[$value] = @$this->attributes[$value]; } return $result; } elseif (count($values) > 1) { return @$this->attributes[$values[0]]; } else { return $this->attributes; } }
Return attributes (actual document data) @return array
entailment
public function update(array $data, array $parameters = []) { if (!$this->canAlter()) { throw new Exception('Need index, type, and key to update a document'); } if (!$this->esClient) { throw new Exception('Need ElasticSearch client object for ALTER operations'); } $params = [ 'index' => $this->meta['index'], 'type' => $this->meta['type'], 'id' => $this->meta['id'], 'body' => $data] + $parameters; return $this->esClient->update($params); }
Updates the document @param array $data the normal elastic update parameters to be used @param array $parameters the parameters array @return array @throws Exception
entailment
public function delete(array $parameters = []) { if (!$this->canAlter()) { throw new Exception('Need index, type, and key to delete a document'); } if (!$this->esClient) { throw new Exception('Need ElasticSearch client object for ALTER operations'); } $params = [ 'index' => $this->meta['index'], 'type' => $this->meta['type'], 'id' => $this->meta['id']] + $parameters; $result = $this->esClient->delete($params); return $result; }
Deletes a document @param array $parameters @return array @throws Exception
entailment
protected function buildGraphComponents(array $components) { $graphComponents = array_fill_keys( array_column($components, 'class'), [ 'class' => null, 'id' => null, 'type' => null, 'label' => null, 'variant' => null, 'master' => null, 'variants' => [], 'dependencies' => [], 'path' => [], ] ); // Run through all components /** @var array $component */ foreach ($components as $component) { $graphComponents[$componentClass]['class'] = $componentClass = $component['class']; $graphComponents[$componentClass]['id'] = $component['name']; $graphComponents[$componentClass]['type'] = $component['type']; $graphComponents[$componentClass]['label'] = $component['label'] ?: $component['name']; $graphComponents[$componentClass]['variant'] = $component['variant']; $graphComponents[$componentClass]['path'] = $component['path']; // Link the component dependencies foreach ((new $componentClass)->getDependencies() as $componentDependency) { if (isset($graphComponents[$componentDependency])) { $graphComponents[$componentClass]['dependencies'][$componentDependency] =& $graphComponents[$componentDependency]; } } // If this is a variant: Register it with its master component if ($component['variant']) { list ($masterClass) = explode('_', $componentClass, 2); $masterClass .= 'Component'; if (isset($graphComponents[$masterClass])) { $graphComponents[$componentClass]['master'] =& $graphComponents[$masterClass]; $graphComponents[$masterClass]['variants'][$componentClass] =& $graphComponents[$componentClass]; } } } return $graphComponents; }
Prepare the list of graph components @param array $components Components @return array Graph components
entailment
protected function addToComponentTree($componentId, array $componentPath, array &$tree) { // If the component has to be placed in a subpath if (count($componentPath)) { $subpath = array_shift($componentPath); if (empty($tree[$subpath])) { $tree[$subpath] = []; } $this->addToComponentTree($componentId, $componentPath, $tree[$subpath]); return; } $tree[] = $componentId; }
Add a component to the component tree @param string $componentId Component ID @param array $componentPath Component path @param array $tree Component base tree
entailment
protected function addToComponentTreeSubset(array &$pointer, $componentId) { foreach ($this->graphComponents[$componentId]['path'] as $node) { if (empty($pointer[$node])) { $pointer[$node] = []; } $pointer =& $pointer[$node]; } $pointer[] = $componentId; if ($this->graphComponents[$componentId]['master']) { $dependencies = array_column($this->graphComponents[$componentId]['master']['dependencies'], 'class'); foreach ($this->graphComponents[$componentId]['master']['variants'] as $variant) { $dependencies = array_column($variant['dependencies'], 'class'); } } else { $dependencies = array_column($this->graphComponents[$componentId]['dependencies'], 'class'); } return array_unique($dependencies); }
Recursively add a single component to a component tree subset @param array $pointer Component tree subset @param string $componentId Component class @return array Component dependencies
entailment
protected function addComponents(BaseGraph $graph, array $components, Node $parentNode = null) { // Sort the components // uasort($components, function($component1, $component2) { // $isNode1 = is_array($component1); // $isNode2 = is_array($component2); // // // If both are of the same type // if ($isNode1 == $isNode2) { // return 0; // // // Else // } else { // return $isNode1 ? 1 : -1; // } // }); // Run through all components foreach ($components as $name => $component) { // If this is a subnode if (is_array($component)) { $this->addNode($graph, $name, $component, $parentNode); // Else: Regular component } else { $this->addComponent($graph, $component, $parentNode); } } return $graph; }
Add a list of components to a graph @param BaseGraph $graph Graph @param array $components Component list @param Node $parentNode Parent node @return BaseGraph Graph
entailment
protected function addNode(BaseGraph $graph, $nodeId, array $components, Node $parentNode = null) { $absNodeId = (($parentNode instanceof Node) ? $parentNode->getId() : '/').$nodeId; $graph->node( $absNodeId, [ 'label' => $nodeId, 'shape' => 'none', 'style' => 'none', ] ); if ($parentNode instanceof Node) { $graph->edge( [$parentNode->getId(), $absNodeId], ['arrowhead' => 'none', 'color' => 'darkgrey', 'penwidth' => .5] ); } return $this->addComponents($graph, $components, $graph->get($absNodeId)); }
Add a node to a graph @param BaseGraph $graph Graph @param string $nodeId Node ID @param array $components Component list @param Node $parentNode Parent node @return BaseGraph Graph
entailment
protected function addComponent(BaseGraph $graph, $componentId, Node $parentNode = null) { $component = $this->graphComponents[$componentId]; $origComponentClass = $component['class']; // If this is a variant: Redirect to the master component if ($component['master']) { $component = $component['master']; $componentId = $component['class']; $componentLabel = htmlspecialchars($component['label']); // Else: This is a master component } else { $componentLabel = '<b>'.htmlspecialchars($component['label']).'</b>'; } $componentLabel .= '<br align="left"/>'; $escaped = false; $dependencyNodes = []; if (count($component['variants'])) { uasort( $component['variants'], function(array $variant1, array $variant2) { return strnatcasecmp($variant1['label'], $variant2['label']); } ); // Run through all variants $variantCount = count($component['variants']); foreach (array_values($component['variants']) as $index => $variant) { $variantLabel = '• '.htmlspecialchars($variant['label']); if ($variant['class'] === $origComponentClass) { $variantLabel = "<b>$variantLabel</b>"; } $componentLabel .= $variantLabel.'<br align="left"/>'; foreach ($variant['dependencies'] as $dependency) { $dependencyNodes[$dependency['class']] = true; } } } $isCurrent = $this->rootComponent === $origComponentClass; // Add the component node $graph->node( $this->getComponentTitle($componentId), [ 'label' => "<$componentLabel>", '_escaped' => $escaped, 'margin' => '.15,.15', 'fillcolor' => self::$colors[$component['type']], 'penwidth' => $isCurrent ? 1.5 : .5, ] ); // Add an edge from the parent node if ($parentNode instanceof Node) { $graph->edge( [$parentNode->getId(), $this->getComponentTitle($componentId)], ['arrowhead' => 'none', 'color' => 'darkgrey', 'penwidth' => .5] ); } // Add dependency edges foreach ($component['dependencies'] as $dependency) { $dependencyNodes[$dependency['master'] ? $dependency['master']['class'] : $dependency['class']] = true; } foreach (array_keys($dependencyNodes) as $dependencyNode) { $graph->edge([$this->getComponentTitle($componentId), $this->getComponentTitle($dependencyNode)]); } return $graph; }
Add a component to a graph @param BaseGraph $graph Graph @param string $componentId Component ID @param Node $parentNode Parent node @return BaseGraph Graph
entailment
protected function getComponentTitle($componentId) { $component =& $this->graphComponents[$componentId]; $componentTitle = implode('/', array_filter(array_merge($component['path'], [$component['id']]))); $componentTitle .= ' ('.$component['class'].')'; return $componentTitle; }
Create and return an component title @param string $componentId Component ID @return string Component title
entailment
public function serialize(DomainEvent $event): string { $reflect = new ReflectionObject($event); $props = $reflect->getProperties(ReflectionProperty::IS_PUBLIC | ReflectionProperty::IS_PRIVATE); return json_encode([ 'eventName' => $this->eventNameForClass(get_class($event)), 'fields' => $this->serializeFields($props, $event), ]); }
serialize a domain event into event sourcery library storage conventions @param DomainEvent $event @return string
entailment
private function serializeFields($props, $event) { array_map(function (ReflectionProperty $prop) use (&$fields, $event) { /** @var ReflectionProperty $prop */ $prop->setAccessible(true); $fields[$prop->getName()] = $this->valueSerializer->serialize($prop->getValue($event)); }, $props); return $fields; }
Serialize the fields of a domain event into a key => value hash @param $props @param $event @return mixed
entailment
public function deserialize(array $serialized): DomainEvent { $className = $this->classNameForEvent($serialized['eventName']); $reflect = new ReflectionClass($className); $const = $reflect->getConstructor(); // reflect on constructor to get name / type $constParams = []; foreach ($const->getParameters() as $param) { $constParams[] = [ $param->getType()->getName(), $param->getName(), ]; } // get the values for the constructor fields from the serialized event $constParamValues = []; foreach ($constParams as $constParam) { list($type, $name) = $constParam; $fields = $serialized['fields']; if ( ! isset($fields[$name])) { throw new \Exception("Cannot find serialized field {$name} for {$className}."); } $constParamValues[] = [ $type, $name, $fields[$name], ]; } // reconstruct the serialized values into the correct type return new $className(...array_map([$this, 'deserializeField'], $constParamValues)); }
deserialize a domain event from event sourcery library storage conventions @param array $serialized @return DomainEvent @throws \ReflectionException @throws \Exception
entailment
public function sort($by, $direction = "asc", $override = false) { $this->assertInitiated("sort"); if ($override) { $this->query['sort'] = []; } $this->query['sort'][] = [$by => $direction]; return $this; }
Adds a sort clause to the query @param string $by the key to sort by it @param string|array $direction the direction of the sort. Can be an array for extra sort control. @param boolean $override false by default. if true it will reset the sort first, then add the new sort entry. @return QueryBuilder|static|self
entailment
public function where($key, $value, $compare = "=", $filter = null, $params = []) { //identify the bool part must|should|must_not $compare = trim($compare); $bool = substr($compare, 0, 1) == "!" ? "must_not" : (substr($compare, 0, 1) == "?" ? "should" : "must"); //get the correct compare value if ($bool !== "must") { $compare = substr($compare, 1); } //$suffix and $prefix will be used in regex, wildcard, prefix, and suffix //queries. $tool = $suffix = $prefix = null; //$_filter is the real identifier for the filter $_filter = $filter; //identify the tool, operator, and part switch (strtolower(str_replace("_", " ", $compare))) { case '=': case 'equals': case 'term': default: $tool = "term"; break; case '>': case 'gt': $tool = "range"; $operator = "gt"; break; case '<': case 'lt': $tool = "range"; $operator = "lt"; break; case '><': case '<>': case 'between': $tool = "range"; $operator = ["gt", "lt"]; break; case '>=<=': case '<=>=': case 'between from to': $tool = "range"; $operator = ["gte", "lte"]; break; case '>=<': case '<>=': case 'between from': $tool = "range"; $operator = ["gte", "lt"]; break; case '><=': case '<=>': case 'between to': $tool = "range"; $operator = ["gt", "lte"]; break; case '>=': case 'gte': $tool = "range"; $operator = "gte"; break; case '<=': case 'lte': $tool = "range"; $operator = "lte"; break; case '*=': case 'suffix': case 'suffixed': case 'ends with': case 'ends': $tool = "wildcard"; $prefix = "*"; $_filter = false; break; case '=*': case 'starts': case 'starts with': case 'prefix': case 'prefixed': $tool = "prefix"; break; case '*=*': case 'like': case 'wildcard': $tool = "wildcard"; $prefix = '*'; $suffix = '*'; $_filter = false; break; case '**': case 'r': case 'regexp': case 'regex': case 'rx': $tool = "regexp"; break; case '*': case 'match': $tool = "match"; $_filter = false; break; } //add prefix/suffix to each element in array values if ($suffix || $prefix) { if (is_array($value)) { foreach ($value as $index => $singleValue) { if (is_string($singleValue)) { $value[$index] = $prefix . $singleValue . $suffix; } } } else { $value = ($prefix? : "") . $value . ($suffix? : ""); } } //call the real query builder method switch ($tool) { case 'match': return $this->match($key, $value, $bool, $this->shouldBeFilter($filter, $_filter), $params); case 'regexp': return $this->regexp($key, $value, $bool, $this->shouldBeFilter($filter, $_filter), $params); case 'term': return $this->term($key, $value, $bool, $this->shouldBeFilter($filter, $_filter), $params); case 'range': return $this->range($key, $operator, $value, $bool, $this->shouldBeFilter($filter, $_filter), $params); case 'wildcard': return $this->wildcard($key, $value, $bool, $this->shouldBeFilter($filter, $_filter), $params); case 'prefix': return $this->prefix($key, $value, $bool, $this->shouldBeFilter($filter, $_filter), $params); } }
The basic smart method to build queries. It will automatically identify the correct filter/query tool to use, as well the correct query part to be used in, depending on the content and type of the key, value, and comparison parameters. $comparison parameter will define what filter/query tool to use. @param string|string[] $key the key(s) to check @param string|string[] $value the value(s) to check against @param string $compare the comparison operator or elastic query/filter tool prefix it with ! to negate or with ? to convert to should @param boolean $filter false to add as a query, true as a filter @param array|map $params additional parameters the query/filter can use @return static|QueryBuilder
entailment
public function wildcard($key, $value, $bool = "must", $filter = false, array $params = []) { if (is_array($key)) { return $this->multiWildcard($key, $value, $bool, $filter, $params); } if (is_array($value)) { return $this->wildcards($key, $value, $bool, $filter, $params); } $this->addBool($this->makeFilteredQuery(["wildcard" => [$key => ["wildcard" => $value]]], $filter), $bool, $filter, $params); return $this; }
Creates a wildcard query part. It will automatically detect the $key and $value types to create the required number of clauses, as follows: $key $value result single single {wildcard:{$key:{wildcard:$value}}} single array or:[wildcard($key, $value[1]), ...] array single or:[wildcard($key[1], $value), ...] array array or:[wildcard($key[1], $value[1]), wildcard($key[1], $value[2]), ... wildcard($key[2], $value[1]), ... ] If $filter is true, it will enclose the wildcard query with `query` filter and add it to the DSL query filter section instead the query section. @param string|string[] $key the key(s) to wildcard search in. @param string|string[] $value the value(s) to wildcard search against. @param string $bool severity of the query/filter. [must]|must_not|should @param bool $filter if true, DSL query filter section will be used after enclosing in a `query` filter. @param array $params extra parameters for the query tool @return QueryBuilder|static|self
entailment
public function wildcards($key, array $values, $bool = "must", $filter = false, array $params = []) { $subQuery = $this->orWhere($bool); foreach ($values as $value) { $subQuery->wildcard($key, $value, $bool, true, $params); } $subQuery->endSubQuery(); return $this; }
Creates wildcard query for each $value grouped by OR clause @see QueryBuilder::wildcard() for more information @param string|string[] $key the key(s) to wildcard search in. @param string[] $values the value(s) to wildcard search against. @param string $bool severity of the query/filter. [must]|must_not|should @param bool $filter if true, DSL query filter section will be used after enclosing in a `query` filter. @param array $params extra parameters for the query tool @return QueryBuilder|static|self
entailment
public function multiWildcard(array $keys, $value, $bool = "must", $filter = false, array $params = []) { $subQuery = $this->orWhere($bool); foreach ($keys as $key) { $subQuery->wildcard($key, $value, $bool, true, $params); } $subQuery->endSubQuery(); return $this; }
Creates wildcard query for each $key grouped by OR clause @see QueryBuilder::wildcard() for more information @param string[] $keys the key(s) to wildcard search in. @param string|string[] $value the value(s) to wildcard search against. @param string $bool severity of the query/filter. [must]|must_not|should @param bool $filter if true, DSL query filter section will be used after enclosing in a `query` filter. @param array $params extra parameters for the query tool @return QueryBuilder|static|self
entailment
public function multiWildcards(array $keys, array $values, $bool = "must", $filter = false, array $params = []) { $subQuery = $this->orWhere($bool); foreach ($keys as $key) { $subQuery->wildcards($key, $values, $bool, true, $params); } $subQuery->endSubQuery(); return $this; }
Creates wildcard query for each $key/$value pair grouped by OR clause @see QueryBuilder::wildcard() for more information @param string[] $keys the key(s) to wildcard search in. @param string[] $values the value(s) to wildcard search against. @param string $bool severity of the query/filter. [must]|must_not|should @param bool $filter if true, DSL query filter section will be used after enclosing in a `query` filter. @param array $params extra parameters for the query tool @return QueryBuilder|static|self
entailment
public function regexp($key, $value, $bool = "must", $filter = false, array $params = []) { if (is_array($key)) { return $this->multiRegexp($key, $value, $bool, $filter, $params); } if (is_array($value)) { return $this->regexps($key, $value, $bool, $filter, $params); } $this->addBool($this->makeFilteredQuery(["regexp" => [$key => ["value" => $value]]], $filter), $bool, $filter, $params); return $this; }
Creates a regexp query part. It will automatically detect the $key and $value types to create the required number of clauses, as follows: $key $value result single single {regexp:{$key:{regexp:$value}}} single array or:[regexp($key, $value[1]), ...] array single or:[regexp($key[1], $value), ...] array array or:[regexp($key[1], $value[1]), regexp($key[1], $value[2]), ... regexp($key[2], $value[1]), ... ] If $filter is true, it will enclose the regexp query with `query` filter and add it to the DSL query filter section instead the query section. @param string|string[] $key the key(s) to regexp search in. @param string|string[] $value the value(s) to regexp search against. @param string $bool severity of the query/filter. [must]|must_not|should @param bool $filter if true, DSL query filter section will be used after enclosing in a `query` filter. @param array $params extra parameters for the query tool @return QueryBuilder|static|self
entailment
public function regexps($key, array $values, $bool = "must", $filter = false, array $params = []) { $subQuery = $this->orWhere($bool); foreach ($values as $value) { $subQuery->regexp($key, $value, $bool, true, $params); } $subQuery->endSubQuery(); return $this; }
Creates regexp query for each $value grouped by OR clause @see QueryBuilder::regexp() for more information @param string|string[] $key the key(s) to regexp search in. @param string[] $values the value(s) to regexp search against. @param string $bool severity of the query/filter. [must]|must_not|should @param bool $filter if true, DSL query filter section will be used after enclosing in a `query` filter. @param array $params extra parameters for the query tool @return QueryBuilder|static|self
entailment
public function multiRegexp(array $keys, $value, $bool = "must", $filter = false, array $params = []) { $subQuery = $this->orWhere($bool); foreach ($keys as $key) { $subQuery->regexp($key, $value, $bool, true, $params); } $subQuery->endSubQuery(); return $this; }
Creates regexp query for each $key grouped by OR clause @see QueryBuilder::regexp() for more information @param string[] $keys the key(s) to regexp search in. @param string|string[] $value the value(s) to regexp search against. @param string $bool severity of the query/filter. [must]|must_not|should @param bool $filter if true, DSL query filter section will be used after enclosing in a `query` filter. @param array $params extra parameters for the query tool @return QueryBuilder|static|self
entailment
public function multiRegexps(array $keys, array $values, $bool = "must", $filter = false, array $params = []) { $subQuery = $this->orWhere($bool); foreach ($keys as $key) { $subQuery->regexps($key, $values, $bool, true, $params); } $subQuery->endSubQuery(); return $this; }
Creates regexp query for each $key/$value pair grouped by OR clause @see QueryBuilder::regexp() for more information @param string[] $keys the key(s) to regexp search in. @param string[] $values the value(s) to regexp search against. @param string $bool severity of the query/filter. [must]|must_not|should @param bool $filter if true, DSL query filter section will be used after enclosing in a `query` filter. @param array $params extra parameters for the query tool @return QueryBuilder|static|self
entailment
public function prefix($key, $value, $bool = "must", $filter = false, array $params = []) { if (is_array($key)) { return $this->multiPrefix($key, $value, $bool, $filter, $params); } if (is_array($value)) { return $this->prefixs($key, $value, $bool, $filter, $params); } $this->addBool($this->makeFilteredQuery(["prefix" => [$key => $value]], $filter), $bool, $filter, $params); return $this; }
Creates a prefix query part. It will automatically detect the $key and $value types to create the required number of clauses, as follows: $key $value result single single {prefix:{$key:{prefix:$value}}} single array or:[prefix($key, $value[1]), ...] array single or:[prefix($key[1], $value), ...] array array or:[prefix($key[1], $value[1]), prefix($key[1], $value[2]), ... prefix($key[2], $value[1]), ... ] If $filter is true, it will enclose the prefix query with `query` filter and add it to the DSL query filter section instead the query section. @param string|string[] $key the key(s) to prefix search in. @param string|string[] $value the value(s) to prefix search against. @param string $bool severity of the query/filter. [must]|must_not|should @param bool $filter if true, DSL query filter section will be used after enclosing in a `query` filter. @param array $params extra parameters for the query tool @return QueryBuilder|static|self
entailment
public function prefixs($key, array $values, $bool = "must", $filter = false, array $params = []) { $subQuery = $this->orWhere($bool); foreach ($values as $value) { $subQuery->prefix($key, $value, $bool, true, $params); } $subQuery->endSubQuery(); return $this; }
Creates prefix query for each $value grouped by OR clause @see QueryBuilder::prefix() for more information @param string|string[] $key the key(s) to prefix search in. @param string[] $values the value(s) to prefix search against. @param string $bool severity of the query/filter. [must]|must_not|should @param bool $filter if true, DSL query filter section will be used after enclosing in a `query` filter. @param array $params extra parameters for the query tool @return QueryBuilder|static|self
entailment
public function multiPrefix(array $keys, $value, $bool = "must", $filter = false, array $params = []) { $subQuery = $this->orWhere($bool); foreach ($keys as $key) { $subQuery->prefix($key, $value, $bool, true, $params); } $subQuery->endSubQuery(); return $this; }
Creates OR-joined multiple prefix queries for the list of keys Creates a prefix query for the $value for each key in the $keys @param array $keys @param type $value @param type $bool @param array $params @return QueryBuilder|static|self
entailment
public function multiPrefixs(array $keys, array $values, $bool = "must", $filter = false, array $params = []) { $subQuery = $this->orWhere($bool); foreach ($keys as $key) { $subQuery->prefixs($key, $values, $bool, true, $params); } $subQuery->endSubQuery(); return $this; }
Creates multiple prefixes queries for the list of keys Two keys and two values will results in 4 prefix queries @param array $keys @param array $values @param type $bool @param array $params @return QueryBuilder|static|self
entailment
public function term($key, $value, $bool = "must", $filter = false, array $params = []) { if (is_array($key)) { return $this->multiTerm($key, $value, $bool, $filter, $params); } $tool = "term" . (is_array($value) ? "s" : ""); $this->addBool([$tool => [$key => (is_array($value) ? $value : ["value" => $value])]], $bool, $filter, $params); return $this; }
A normal term/terms query It will automatically use term or terms query depending on the type of $value parameter whether it is an array or not. @param type $key @param type $value @param type $bool @param type $filter @param array $params @return QueryBuilder|static|self
entailment
public function multiTerm(array $keys, $value, $bool = "must", $filter = false, array $params = []) { $subQuery = $this->orWhere($bool); foreach ($keys as $key) { $subQuery->term($key, $value, $bool, true, $params); } $subQuery->endSubQuery(); return $this; }
Multiple OR joined term queries @param array $keys @param type $value @param type $bool @param type $filter @param array $params @return QueryBuilder|static|self
entailment
public function match($key, $value, $bool, $filter = false, array $params = []) { if (is_array($key)) { return $this->multiMatch($key, $value, $bool, $filter, $params); } if (is_array($value)) { return $this->matches($key, $value, $bool, $filter, $params); } $this->addBool($this->makeFilteredQuery(["match" => [$key => ["query" => $value] + $params]], $filter), $bool, $filter); return $this; }
A match query @param type $key @param type $value @param type $bool @param boolean $filter @param array $params @return QueryBuilder|static|self
entailment
public function matches($key, array $values, $bool, $filter = false, array $params = []) { $subQuery = $this->orWhere($bool); foreach ($values as $value) { $subQuery->match($key, $value, $bool, true, $params); } $subQuery->endSubQuery(); return $this; }
Creates multiple match queries for each value in the array Queries will be joined by an OR filter @param string $key the key to create the matches for @param array $values a list of values to create a match query for each @param type $bool @param array $params @return QueryBuilder|static|self
entailment
public function multiMatch(array $keys, $value, $bool, $filter = false, array $params = []) { $this->addBool($this->makeFilteredQuery(["multi_match" => ["query" => $value, "fields" => $keys] + $params], $filter), $bool, $filter); return $this; }
Creates a mutli_match query @param array $keys keys(fields) of the multimatch @param type $value @param type $bool @param array $params @return QueryBuilder|static|self
entailment
public function multiMatches(array $keys, array $values, $bool, $filter = false, array $params = []) { $subQuery = $this->orWhere($bool); foreach ($values as $value) { $subQuery->multiMatch($keys, $value, $bool, true, $params); } $subQuery->endSubQuery(); return $this; }
Creates multiple mutli_match queries for each value in the array Queries will be joined by an OR filter @param array $keys keys(fields) of the multimatch @param scalar[] $values a list of values to create a multimatch query for @param type $bool @param array $params @return QueryBuilder|static|self
entailment
public function range($key, $operator, $value, $bool, $filter, array $params = []) { if (is_array($operator) && !is_array($value) || !is_array($operator) && is_array($value) || is_array($operator) && count($operator) !== count($value)) { throw new \BadMethodCallException("Operator and value parameters should be both a scalar type or both an array with same number of elements"); } if (is_array($key)) { return $this->multiRange($key, $operator, $value, $bool, $filter, $params); } $query = []; $operators = (array) $operator; $values = (array) $value; foreach ($operators as $index => $operator) { $query[$operator] = $values[$index]; } $this->addBool(["range" => [$key => $query]], $bool, $filter, $params); return $this; }
Creates a range query @param string $key The key to create the range query for @param string|string[] $operator lt, gt, lte, gte. Can be an array of mixed lt,gt,lte,gte; and if so, it should match the number of elements in the $value array too. @param scalar|scalar[] $value the value for the range comparison. Should be an array of same element count if the $operator is also an array. @param string $bool must, should, or must_not @param boolean $filter to use the filter part instead of the query part @param array $params additional query parameters for the range query @return QueryBuilder|static|self @throws \BadMethodCallException
entailment
public function multiRange(array $keys, $operator, $value, $bool, $filter, array $params = []) { $subQuery = $this->orWhere($bool); foreach ($keys as $key) { $subQuery->range($key, $operator, $value, $bool, true, $params); } $subQuery->endSubQuery(); return $this; }
Creates multiple range queries joined by OR For each key in the keys, a new range query will be created @param array $keys keys to create a range query for each of them @param string|string[] $operator lt, gt, lte, gte. Can be an array of mixed lt,gt,lte,gte; and if so, it should match the number of elements in the $value array too. @param scalar|scalar[] $value the value for the range comparison. Should be an array of same element count if the $operator is also an array. @param string $bool must, should, or must_not @param boolean $filter to use the filter part instead of the query part @param array $params additional query parameters for the range query @return QueryBuilder|static|self
entailment
public function andWhere($bool = "must", array $params = []) { $callback = function(SubQueryBuilder $subQuery) use ($bool, $params) { return $this->_endChildSubQuery("and", $subQuery->toArray(), $bool, $params); }; return SubQueryBuilder::make($callback); }
Creates an AND filter subquery @param string $bool must, should, or must_not @param array $params extra params for and filter @return SubQueryBuilder
entailment
protected function _endChildSubQuery($tool, array $subQuery, $bool, array $params = []) { $this->addBool([$tool => $subQuery], $bool, true, $params); return $this; }
Receives the end signal from the sub query object @param string $tool [and|or] @param array $subQuery @param type $bool @param array $params @return QueryBuilder|static|self
entailment
protected function assertInitiated($key) { $current = &$this->query; $keys = explode(".", $key); foreach ($keys as $element) { if (!array_key_exists($element, $current)) { $current[$element] = []; } $current = &$current[$element]; } }
Checks and creates the required structure @param string $key A dot [.] separated path to be created/checked @return void
entailment
protected function addBool(array $query, $bool, $filter = false, array $params = []) { $filtered = $filter ? "filter" : "query"; $key = "query.filtered.{$filtered}.bool.{$bool}"; if ($filter) { $this->assertInitiated($key); } $this->query["query"]["filtered"][$filtered]["bool"][$bool][] = array_merge_recursive($query, $params); }
Adds a new bool query part to the query array @param array $query the bool query part to be added @param string $bool the bool group (must, should, must_not) @param boolean $filter weither to be added to the filter or the query party @param array $params extra parameters for the query part (will be merged into the original part) @return void
entailment
public function page($size, $from = null) { if ($from) { $this->from($from); } if ($size) { $this->size($size); } return $this; }
Set the from and size (paging) of the results @param integer $size @param integer $from @return QueryBuilder|static|self
entailment
public function authenticate(TokenInterface $token) { if($this->userProvider instanceof ChainUserProvider) { foreach ($this->userProvider->getProviders() as $provider) { $result = $this->doAuth($provider, $token); if($result !== false) { return $result; } } } else { $result = $this->doAuth($this->userProvider, $token); if ($result !== false) { return $result; } } }
Attempts to authenticate a TokenInterface object. @param TokenInterface $token The TokenInterface instance to authenticate @return TokenInterface An authenticated TokenInterface instance, never null @throws AuthenticationException if the authentication fails
entailment
protected function doAuth($provider, TokenInterface $token) { if (! $provider instanceof ApiKeyUserProviderInterface) { return false; } /** @var UserInterface $user */ $user = $provider->loadUserByApiKey($token->getCredentials()); if ($user) { $authenticatedToken = new ApiKeyUserToken($user->getRoles()); $authenticatedToken->setUser($user); return $authenticatedToken; } throw new AuthenticationException("The API Key authentication failed."); }
@param UserProviderInterface $provider @param TokenInterface $token @return bool|ApiKeyUserToken @throws AuthenticationException
entailment
public function saveIPMessage($data) { $response=CodeBank_ClientAPI::responseBase(); if(!Permission::check('ADMIN')) { $response['status']='EROR'; $response['message']=_t('CodeBankAPI.PERMISSION_DENINED', '_Permission Denied'); return $response; } try { $codeBankConfig=CodeBankConfig::CurrentConfig(); $codeBankConfig->IPMessage=$data->message; $codeBankConfig->write(); $response['status']='HELO'; $response['message']=_t('CodeBankAPI.IP_MESSAGE_CHANGE', '_Intellectual Property message changed successfully'); }catch (Exception $e) { $response['status']='EROR'; $response['message']=_t('CodeBankAPI.SERVER_ERROR', '_Server error has occured, please try again later'); } return $response; }
Saves the IP Message @param {stdClass} $data Data passed from ActionScript @return {array} Returns a standard response array
entailment
public function savePreferences($data) { $response=CodeBank_ClientAPI::responseBase(); try { $member=Member::currentUser(); if($member && $member->ID!=0) { $member->UseHeartbeat=($data->heartbeat==1 ? true:false); $member->write(); }else { throw new Exception('Not Logged In!'); } $response['status']='HELO'; $response['message']=_t('CodeBankAPI.PREFERENCES_SAVED', '_Preferences saved successfully'); }catch (Exception $e) { $response['status']='EROR'; $response['message']=_t('CodeBankAPI.SERVER_ERROR', '_Server error has occured, please try again later'); } return $response; }
Saves users server preferences @param {stdClass} $data Data passed from ActionScript @return {array} Standard response base
entailment
public function changePassword($data) { $response=CodeBank_ClientAPI::responseBase(); try { $member=Member::currentUser(); $e=PasswordEncryptor::create_for_algorithm($member->PasswordEncryption); if(!$e->check($member->Password, $data->currPassword, $member->Salt, $member)) { $response['status']='EROR'; $response['message']=_t('CodeBankAPI.CURRENT_PASSWORD_MATCH', '_Current password does not match'); return $response; } if(!$member->changePassword($data->password)) { $response['status']='EROR'; $response['message']=_t('CodeBankAPI.NEW_PASSWORD_NOT_VALID', '_New password is not valid'); return $response; } $response['status']='HELO'; $response['message']=_t('CodeBankAPI.PASSWORD_CHANGED', '_User\'s password changed successfully'); }catch (Exception $e) { $response['status']='EROR'; $response['message']=_t('CodeBankAPI.SERVER_ERROR', '_Server error has occured, please try again later'); } return $response; }
Changes a users password @param {stdClass} $data Data passed from ActionScript @return {array} Returns a standard response array
entailment
public function setLdap(Zend_Ldap $ldap) { $this->_ldap = $ldap; $this->setOptions(array($ldap->getOptions())); return $this; }
Set an Ldap connection @param Zend_Ldap $ldap An existing Ldap object @return Zend_Auth_Adapter_Ldap Provides a fluent interface
entailment
protected function _getAuthorityName() { $options = $this->getLdap()->getOptions(); $name = $options['accountDomainName']; if (!$name) $name = $options['accountDomainNameShort']; return $name ? $name : ''; }
Returns a domain name for the current LDAP options. This is used for skipping redundant operations (e.g. authentications). @return string
entailment
public function authenticate() { /** * @see Zend_Ldap_Exception */ require_once 'Zend/Ldap/Exception.php'; $messages = array(); $messages[0] = ''; // reserved $messages[1] = ''; // reserved $username = $this->_username; $password = $this->_password; if (!$username) { $code = Zend_Auth_Result::FAILURE_IDENTITY_NOT_FOUND; $messages[0] = 'A username is required'; return new Zend_Auth_Result($code, '', $messages); } if (!$password) { /* A password is required because some servers will * treat an empty password as an anonymous bind. */ $code = Zend_Auth_Result::FAILURE_CREDENTIAL_INVALID; $messages[0] = 'A password is required'; return new Zend_Auth_Result($code, '', $messages); } $ldap = $this->getLdap(); $code = Zend_Auth_Result::FAILURE; $messages[0] = "Authority not found: $username"; $failedAuthorities = array(); /* Iterate through each server and try to authenticate the supplied * credentials against it. */ foreach ($this->_options as $name => $options) { if (!is_array($options)) { /** * @see Zend_Auth_Adapter_Exception */ require_once 'Zend/Auth/Adapter/Exception.php'; throw new Zend_Auth_Adapter_Exception('Adapter options array not an array'); } $adapterOptions = $this->_prepareOptions($ldap, $options); $dname = ''; try { if ($messages[1]) $messages[] = $messages[1]; $messages[1] = ''; $messages[] = $this->_optionsToString($options); $dname = $this->_getAuthorityName(); if (isset($failedAuthorities[$dname])) { /* If multiple sets of server options for the same domain * are supplied, we want to skip redundant authentications * where the identity or credentials where found to be * invalid with another server for the same domain. The * $failedAuthorities array tracks this condition (and also * serves to supply the original error message). * This fixes issue ZF-4093. */ $messages[1] = $failedAuthorities[$dname]; $messages[] = "Skipping previously failed authority: $dname"; continue; } $canonicalName = $ldap->getCanonicalAccountName($username); $ldap->bind($canonicalName, $password); /* * Fixes problem when authenticated user is not allowed to retrieve * group-membership information or own account. * This requires that the user specified with "username" and optionally * "password" in the Zend_Ldap options is able to retrieve the required * information. */ $requireRebind = false; if (isset($options['username'])) { $ldap->bind(); $requireRebind = true; } $dn = $ldap->getCanonicalAccountName($canonicalName, Zend_Ldap::ACCTNAME_FORM_DN); $groupResult = $this->_checkGroupMembership($ldap, $canonicalName, $dn, $adapterOptions); if ($groupResult === true) { $this->_authenticatedDn = $dn; $messages[0] = ''; $messages[1] = ''; $messages[] = "$canonicalName authentication successful"; if ($requireRebind === true) { // rebinding with authenticated user $ldap->bind($dn, $password); } return new Zend_Auth_Result(Zend_Auth_Result::SUCCESS, $canonicalName, $messages); } else { $messages[0] = 'Account is not a member of the specified group'; $messages[1] = $groupResult; $failedAuthorities[$dname] = $groupResult; } } catch (Zend_Ldap_Exception $zle) { /* LDAP based authentication is notoriously difficult to diagnose. Therefore * we bend over backwards to capture and record every possible bit of * information when something goes wrong. */ $err = $zle->getCode(); if ($err == Zend_Ldap_Exception::LDAP_X_DOMAIN_MISMATCH) { /* This error indicates that the domain supplied in the * username did not match the domains in the server options * and therefore we should just skip to the next set of * server options. */ continue; } else if ($err == Zend_Ldap_Exception::LDAP_NO_SUCH_OBJECT) { $code = Zend_Auth_Result::FAILURE_IDENTITY_NOT_FOUND; $messages[0] = "Account not found: $username"; $failedAuthorities[$dname] = $zle->getMessage(); } else if ($err == Zend_Ldap_Exception::LDAP_INVALID_CREDENTIALS) { $code = Zend_Auth_Result::FAILURE_CREDENTIAL_INVALID; $messages[0] = 'Invalid credentials'; $failedAuthorities[$dname] = $zle->getMessage(); } else { $line = $zle->getLine(); $messages[] = $zle->getFile() . "($line): " . $zle->getMessage(); $messages[] = str_replace($password, '*****', $zle->getTraceAsString()); $messages[0] = 'An unexpected failure occurred'; } $messages[1] = $zle->getMessage(); } } $msg = isset($messages[1]) ? $messages[1] : $messages[0]; $messages[] = "$username authentication failed: $msg"; return new Zend_Auth_Result($code, $username, $messages); }
Authenticate the user @throws Zend_Auth_Adapter_Exception @return Zend_Auth_Result
entailment
protected function _prepareOptions(Zend_Ldap $ldap, array $options) { $adapterOptions = array( 'group' => null, 'groupDn' => $ldap->getBaseDn(), 'groupScope' => Zend_Ldap::SEARCH_SCOPE_SUB, 'groupAttr' => 'cn', 'groupFilter' => 'objectClass=groupOfUniqueNames', 'memberAttr' => 'uniqueMember', 'memberIsDn' => true ); foreach ($adapterOptions as $key => $value) { if (array_key_exists($key, $options)) { $value = $options[$key]; unset($options[$key]); switch ($key) { case 'groupScope': $value = (int)$value; if (in_array($value, array(Zend_Ldap::SEARCH_SCOPE_BASE, Zend_Ldap::SEARCH_SCOPE_ONE, Zend_Ldap::SEARCH_SCOPE_SUB), true)) { $adapterOptions[$key] = $value; } break; case 'memberIsDn': $adapterOptions[$key] = ($value === true || $value === '1' || strcasecmp($value, 'true') == 0); break; default: $adapterOptions[$key] = trim($value); break; } } } $ldap->setOptions($options); return $adapterOptions; }
Sets the LDAP specific options on the Zend_Ldap instance @param Zend_Ldap $ldap @param array $options @return array of auth-adapter specific options
entailment
protected function _checkGroupMembership(Zend_Ldap $ldap, $canonicalName, $dn, array $adapterOptions) { if ($adapterOptions['group'] === null) { return true; } if ($adapterOptions['memberIsDn'] === false) { $user = $canonicalName; } else { $user = $dn; } /** * @see Zend_Ldap_Filter */ require_once 'Zend/Ldap/Filter.php'; $groupName = Zend_Ldap_Filter::equals($adapterOptions['groupAttr'], $adapterOptions['group']); $membership = Zend_Ldap_Filter::equals($adapterOptions['memberAttr'], $user); $group = Zend_Ldap_Filter::andFilter($groupName, $membership); $groupFilter = $adapterOptions['groupFilter']; if (!empty($groupFilter)) { $group = $group->addAnd($groupFilter); } $result = $ldap->count($group, $adapterOptions['groupDn'], $adapterOptions['groupScope']); if ($result === 1) { return true; } else { return 'Failed to verify group membership with ' . $group->toString(); } }
Checks the group membership of the bound user @param Zend_Ldap $ldap @param string $canonicalName @param string $dn @param array $adapterOptions @return string|true
entailment
public function getAccountObject(array $returnAttribs = array(), array $omitAttribs = array()) { if (!$this->_authenticatedDn) { return false; } $returnObject = new stdClass(); $returnAttribs = array_map('strtolower', $returnAttribs); $omitAttribs = array_map('strtolower', $omitAttribs); $returnAttribs = array_diff($returnAttribs, $omitAttribs); $entry = $this->getLdap()->getEntry($this->_authenticatedDn, $returnAttribs, true); foreach ($entry as $attr => $value) { if (in_array($attr, $omitAttribs)) { // skip attributes marked to be omitted continue; } if (is_array($value)) { $returnObject->$attr = (count($value) > 1) ? $value : $value[0]; } else { $returnObject->$attr = $value; } } return $returnObject; }
getAccountObject() - Returns the result entry as a stdClass object This resembles the feature {@see Zend_Auth_Adapter_DbTable::getResultRowObject()}. Closes ZF-6813 @param array $returnAttribs @param array $omitAttribs @return stdClass|boolean
entailment
private function _optionsToString(array $options) { $str = ''; foreach ($options as $key => $val) { if ($key === 'password') $val = '*****'; if ($str) $str .= ','; $str .= $key . '=' . $val; } return $str; }
Converts options to string @param array $options @return string
entailment
public static function lowerCase(&$value, &$key) { trigger_error(__CLASS__ . '::' . __METHOD__ . '() is deprecated and will be removed in a future version', E_USER_NOTICE); return $value = strtolower($value); }
Lowercase a string Lowercase's a string by reference @deprecated @param string $string value @param string $key @return string Lower cased string
entailment
protected function _buildCallback(Zend_Server_Reflection_Function_Abstract $reflection) { $callback = new Zend_Server_Method_Callback(); if ($reflection instanceof Zend_Server_Reflection_Method) { $callback->setType($reflection->isStatic() ? 'static' : 'instance') ->setClass($reflection->getDeclaringClass()->getName()) ->setMethod($reflection->getName()); } elseif ($reflection instanceof Zend_Server_Reflection_Function) { $callback->setType('function') ->setFunction($reflection->getName()); } return $callback; }
Build callback for method signature @param Zend_Server_Reflection_Function_Abstract $reflection @return Zend_Server_Method_Callback
entailment
protected function _buildSignature(Zend_Server_Reflection_Function_Abstract $reflection, $class = null) { $ns = $reflection->getNamespace(); $name = $reflection->getName(); $method = empty($ns) ? $name : $ns . '.' . $name; if (!$this->_overwriteExistingMethods && $this->_table->hasMethod($method)) { require_once 'Zend/Server/Exception.php'; throw new Zend_Server_Exception('Duplicate method registered: ' . $method); } $definition = new Zend_Server_Method_Definition(); $definition->setName($method) ->setCallback($this->_buildCallback($reflection)) ->setMethodHelp($reflection->getDescription()) ->setInvokeArguments($reflection->getInvokeArguments()); foreach ($reflection->getPrototypes() as $proto) { $prototype = new Zend_Server_Method_Prototype(); $prototype->setReturnType($this->_fixType($proto->getReturnType())); foreach ($proto->getParameters() as $parameter) { $param = new Zend_Server_Method_Parameter(array( 'type' => $this->_fixType($parameter->getType()), 'name' => $parameter->getName(), 'optional' => $parameter->isOptional(), )); if ($parameter->isDefaultValueAvailable()) { $param->setDefaultValue($parameter->getDefaultValue()); } $prototype->addParameter($param); } $definition->addPrototype($prototype); } if (is_object($class)) { $definition->setObject($class); } $this->_table->addMethod($definition); return $definition; }
Build a method signature @param Zend_Server_Reflection_Function_Abstract $reflection @param null|string|object $class @return Zend_Server_Method_Definition @throws Zend_Server_Exception on duplicate entry
entailment
protected function _dispatch(Zend_Server_Method_Definition $invocable, array $params) { $callback = $invocable->getCallback(); $type = $callback->getType(); if ('function' == $type) { $function = $callback->getFunction(); return call_user_func_array($function, $params); } $class = $callback->getClass(); $method = $callback->getMethod(); if ('static' == $type) { return call_user_func_array(array($class, $method), $params); } $object = $invocable->getObject(); if (!is_object($object)) { $invokeArgs = $invocable->getInvokeArguments(); if (!empty($invokeArgs)) { $reflection = new ReflectionClass($class); $object = $reflection->newInstanceArgs($invokeArgs); } else { $object = new $class; } } return call_user_func_array(array($object, $method), $params); }
Dispatch method @param Zend_Server_Method_Definition $invocable @param array $params @return mixed
entailment
public function it_fails_if_a_collection_doesnt_have_a_matching_event() { $events = DomainEvents::make([]); expect($events)->shouldNotContainEvent( new EventStub(3, 2, 1) ); $events = DomainEvents::make([ new EventStub(3, 2, 1), ]); expect($events)->shouldNotContainEvent( new EventStub(4, 4, 4) ); }
when you get time
entailment
public function requireDefaultRecords() { parent::requireDefaultRecords(); $defaultLangs=array_keys($this->defaultLanguages); $dbLangCount=SnippetLanguage::get() ->filter('Name', $defaultLangs) ->filter('UserLanguage', 0) ->Count(); if($dbLangCount<count($defaultLangs)) { foreach($this->defaultLanguages as $name=>$data) { if(!SnippetLanguage::get()->find('Name', $name)) { $lang=new SnippetLanguage(); $lang->Name=$name; $lang->FileExtension=$data['Extension']; $lang->HighlightCode=$data['HighlightCode']; $lang->UserLanguage=false; $lang->write(); DB::alteration_message('Created snippet language "'.$name.'"', 'created'); } } } //Look for config languages $configLanguages=CodeBank::config()->extra_languages; if(!empty($configLanguages)) { foreach($configLanguages as $language) { //Validate languages if(empty($language['Name']) || empty($language['FileName']) || empty($language['HighlightCode']) || empty($language['Brush'])) { user_error('Invalid snippet user language found in config, user languages defined in config must contain a Name, FileName, HighlightCode and Brush file path', E_USER_WARNING); continue; } $lang=SnippetLanguage::get() ->filter('Name', Convert::raw2sql($language['Name'])) ->filter('HighlightCode', Convert::raw2sql($language['HighlightCode'])) ->filter('UserLanguage', true) ->first(); if(empty($lang) || $lang===false || $lang->ID<=0) { if(Director::is_absolute($language['Brush']) || Director::is_absolute_url($language['Brush'])) { user_error('Invalid snippet user language found in config, user languages defined in config must contain a path to the brush relative to the SilverStripe base ('.Director::baseFolder().')', E_USER_WARNING); continue; } if(preg_match('/\.js$/', $language['Brush'])==0) { user_error('Invalid snippet user language found in config, user languages defined in config must be javascript files', E_USER_WARNING); continue; } //Add language $lang=new SnippetLanguage(); $lang->Name=$language['Name']; $lang->FileExtension=$language['FileName']; $lang->HighlightCode=$language['HighlightCode']; $lang->BrushFile=$language['Brush']; $lang->UserLanguage=true; $lang->write(); DB::alteration_message('Created snippet user language "'.$language['Name'].'"', 'created'); } } } }
Adds the default languages if they are missing
entailment
public function canDelete($member=null) { $parentResult=parent::canDelete($member); if($parentResult==false || $this->UserLanguage==false) { return false; } if($this->Folders()->count()>0 || $this->Snippets()->count()>0) { return false; } return true; }
Checks to see if the given member can delete this object or not @param {Member} $member Member instance or member id to check @return {bool} Returns boolean true or false depending if the user can delete this object
entailment
public function getCMSFields() { $fields=new FieldList( new TextField('Name', _t('SnippetLanguage.NAME', '_Name'), null, 100), new TextField('FileExtension', _t('SnippetLanguage.FILE_EXTENSION', '_File Extension'), null, 45), new CheckboxField('Hidden', _t('SnippetLanguage.HIDDEN', '_Hidden')) ); if($this->UserLanguage==false) { $fields->replaceField('Name', $fields->dataFieldByName('Name')->performReadonlyTransformation()); $fields->replaceField('FileExtension', $fields->dataFieldByName('FileExtension')->performReadonlyTransformation()); } return $fields; }
Gets fields used in the cms @return {FieldSet} Fields to be used
entailment
public function allowedChildren() { $allowedChildren = array(); $candidates = $this->stat('allowed_children'); if($candidates && $candidates != "none") { foreach($candidates as $candidate) { // If a classname is prefixed by "*", such as "*Page", then only that // class is allowed - no subclasses. Otherwise, the class and all its subclasses are allowed. if(substr($candidate,0,1) == '*') { $allowedChildren[] = substr($candidate,1); } else { $subclasses = ClassInfo::subclassesFor($candidate); foreach($subclasses as $subclass) { $allowedChildren[] = $subclass; } } } } return $allowedChildren; }
Returns an array of the class names of classes that are allowed to be children of this class. @return {array} Array of children
entailment
public function transformImage ($asset = null, $transforms = null, $defaultOptions = []) { return Imgix::$plugin->imgixService->transformImage($asset, $transforms, $defaultOptions); }
@param null $asset @param null $transforms @param array $defaultOptions @return string
entailment
public function addMethod($method, $name = null) { if (is_array($method)) { require_once 'Zend/Server/Method/Definition.php'; $method = new Zend_Server_Method_Definition($method); } elseif (!$method instanceof Zend_Server_Method_Definition) { require_once 'Zend/Server/Exception.php'; throw new Zend_Server_Exception('Invalid method provided'); } if (is_numeric($name)) { $name = null; } if (null !== $name) { $method->setName($name); } else { $name = $method->getName(); } if (null === $name) { require_once 'Zend/Server/Exception.php'; throw new Zend_Server_Exception('No method name provided'); } if (!$this->_overwriteExistingMethods && array_key_exists($name, $this->_methods)) { require_once 'Zend/Server/Exception.php'; throw new Zend_Server_Exception(sprintf('Method by name of "%s" already exists', $name)); } $this->_methods[$name] = $method; return $this; }
Add method to definition @param array|Zend_Server_Method_Definition $method @param null|string $name @return Zend_Server_Definition @throws Zend_Server_Exception if duplicate or invalid method provided
entailment
public function addMethods(array $methods) { foreach ($methods as $key => $method) { $this->addMethod($method, $key); } return $this; }
Add multiple methods @param array $methods Array of Zend_Server_Method_Definition objects or arrays @return Zend_Server_Definition
entailment
public function toArray() { $methods = array(); foreach ($this->getMethods() as $key => $method) { $methods[$key] = $method->toArray(); } return $methods; }
Cast definition to an array @return array
entailment
function encrypt(PersonalData $data, CryptographicDetails $crypto): EncryptedPersonalData { if ( ! $crypto->encryption() == 'libsodium') { throw new CryptographicDetailsNotCompatibleWithEncryption("{$crypto->encryption()} received, expected 'libsodium'"); } $dataString = $data->toString(); $secretKey = $crypto->key('secretKey'); $nonce = $crypto->key('nonce'); $encrypted = sodium_crypto_secretbox($dataString, $nonce, $secretKey); return EncryptedPersonalData::fromString($encrypted); }
encrypt personal data and return an encrypted form @param PersonalData $data @param CryptographicDetails $crypto @throws CryptographicDetailsDoNotContainKey @throws CryptographicDetailsNotCompatibleWithEncryption @return EncryptedPersonalData
entailment
function decrypt(EncryptedPersonalData $data, CryptographicDetails $crypto): PersonalData { if ( ! $crypto->encryption() == 'libsodium') { throw new CryptographicDetailsNotCompatibleWithEncryption("{$crypto->encryption()} received, expected 'libsodium'"); } $encrypted = $data->toString(); $secretKey = $crypto->key('secretKey'); $nonce = $crypto->key('nonce'); $decrypted = sodium_crypto_secretbox_open($encrypted, $nonce, $secretKey); return PersonalData::fromString($decrypted); }
decrypted encrypted personal data and return a decrypted form @param EncryptedPersonalData $data @param CryptographicDetails $crypto @throws CryptographicDetailsDoNotContainKey @throws CryptographicDetailsNotCompatibleWithEncryption @return PersonalData
entailment
public function discoverCommand() { $setup = $this->objectManager->get(BackendConfigurationManager::class)->getTypoScriptSetup(); /** @var TypoScriptService $typoscriptService */ $typoscriptService = $this->objectManager->get(TypoScriptService::class); $config = $typoscriptService->convertTypoScriptArrayToPlainArray((array)$setup['plugin.']['tx_twcomponentlibrary.']); // Register common stylesheets & scripts FluidTemplate::addCommonStylesheets($config['settings']['stylesheets']); FluidTemplate::addCommonHeaderScripts($config['settings']['headerScripts']); FluidTemplate::addCommonFooterScripts($config['settings']['footerScripts']); echo json_encode(Scanner::discoverAll(), JSON_PRETTY_PRINT); }
Discover and extract all components
entailment
public function createCommand($name, $type, $extension = null, $vendor = null) { // Prepare the component name $name = GeneralUtility::trimExplode('/', $name, true); if (!count($name)) { throw new CommandException('Empty / invalid component name', 1507996606); } // Prepare the component type $type = strtolower($type); if (!in_array($type, ComponentInterface::TYPES)) { throw new CommandException(sprintf('Invalid component type "%s"', $type), 1507996917); } // Prepare the provider extension name $extension = trim($extension ?: $GLOBALS['TYPO3_CONF_VARS']['EXT']['extParams']['tw_componentlibrary']['defaultextension']); if (!strlen($extension) || !ExtensionManagementUtility::isLoaded($extension)) { throw new CommandException(sprintf('Invalid provider extension "%s"', $extension), 1507997408); } // Prepare the provider extension vendor name $vendor = trim($vendor ?: $GLOBALS['TYPO3_CONF_VARS']['EXT']['extParams']['tw_componentlibrary']['defaultvendor']); if (!strlen($vendor)) { throw new CommandException(sprintf('Invalid provider extension vendor name "%s"', $vendor), 1507998569); } Kickstarter::create($name, $type, $extension, $vendor); }
Create a new component @param string $name Component path and name @param string $type Component type @param string $extension Host extension @param string $vendor Host extension vendor name @throws CommandException If the component name is empty / invalid @throws CommandException If the component type is invalid @throws CommandException If the provider extension is invalid @throws CommandException If the provider extension vendor name is invalid
entailment
public function color($name, $value = null, $options = array()) { return $this->input('color', $name, $value, $options); }
Create a form color field. @param string $name @param string $value @param array $options @return string
entailment
public function date($name, $value = null, $min = null, $max = null, $options = array()) { if( !isset($min) && !isset($max) ) return 'The date field "'.$name.'" must have a min, max or both.'; if( isset($min) ) $options['min'] = $min; if( isset($max) ) $options['max'] = $max; return $this->input('date', $name, $value, $options); }
Create a form date field. @param string $name @param date $value @param date $min @param date $max @param array $options @return string
entailment
public function week($name, $value = null, $options = array()) { return $this->input('week', $name, $value, $options); }
Create a form week field. @param string $name @param string $value @param array $options @return string
entailment
public function month($name, $value = null, $options = array()) { return $this->input('month', $name, $value, $options); }
Create a form month field. @param string $name @param string $value @param array $options @return string
entailment
public function number($name, $value = null, $step = null, $options = array()) { if( isset($step) ) $options['step'] = $step; $options = $this->setNumberMinMax($options); return $this->input('number', $name, $value, $options); }
Create a form number field. @param string $name @param string $value @param int $step @param array $options @return string
entailment
public function range($name, $value = null, $options = array()) { $options = $this->setNumberMinMax($options); return $this->input('range', $name, $value, $options); }
Create a form range field. @param string $name @param string $value @param array $options @return string
entailment
public function search($name, $value = null, $options = array()) { return $this->input('search', $name, $value, $options); }
Create a form search field. @param string $name @param string $value @param array $options @return string
entailment
protected function setNumberMinMax($options) { if (isset($options['minmax'])) { // If "minmax" is false, then don't set any min/max and remove it from the options array if ( $options['minmax'] == false){ unset($options['minmax']); return $options; } return $this->setQuickNumberMinMax($options); } // If the "minmax" attribute was not specified, we will just look for the regular // min and max attributes, using sane defaults if these do not exist on // the attributes array. We'll then return this entire options array back. $min = array_get($options, 'min', 0); $max = array_get($options, 'max', 10); return array_merge($options, compact('min', 'max')); }
Set the number min max on the attributes. @param array $options @return array
entailment
public function img($attributes = null) { if ($image = $this->transformed) { if ($image && isset($image['url'])) { $lazyLoad = false; if (isset($attributes['lazyLoad'])) { $lazyLoad = $attributes['lazyLoad']; unset($attributes['lazyLoad']); // unset to remove it from the html output } $tagAttributes = $this->getTagAttributes($attributes); return Template::raw('<img ' . ($lazyLoad ? $this->lazyLoadPrefix : '') . 'src="' . $image['url'] . '" ' . $tagAttributes . ' />'); } } return null; }
@param null $attributes @return null|\Twig_Markup
entailment
public function srcset($attributes = []) { if ($images = $this->transformed) { $widths = []; $result = ''; foreach ($images as $image) { $keys = array_keys($image); $width = $image['width'] ?? $image['w'] ?? null; if ($width && !isset($widths[ $width ])) { $withs[ $width ] = true; $result .= $image['url'] . ' ' . $width . 'w, '; } } $srcset = substr($result, 0, strlen($result) - 2); $lazyLoad = false; if (isset($attributes['lazyLoad'])) { $lazyLoad = $attributes['lazyLoad']; unset($attributes['lazyLoad']); // unset to remove it from the html output } $tagAttributes = $this->getTagAttributes($attributes); return Template::raw('<img ' . ($lazyLoad ? $this->lazyLoadPrefix : '') . 'src="' . $images[0]['url'] . '" ' . ($lazyLoad ? $this->lazyLoadPrefix : '') . 'srcset="' . $srcset . '" ' . $tagAttributes . ' />'); } return null; }
@param $attributes @return null|\Twig_Markup
entailment
protected function transform($transforms) { if (!$transforms) { return null; } if (isset($transforms[0])) { $images = []; foreach ($transforms as $transform) { $transform = array_merge($this->defaultOptions, $transform); $transform = $this->calculateTargetSizeFromRatio($transform); $url = $this->buildTransform($this->imagePath, $transform); $images[] = array_merge($transform, ['url' => $url]); } $this->transformed = $images; } else { $transforms = array_merge($this->defaultOptions, $transforms); $transforms = $this->calculateTargetSizeFromRatio($transforms); $url = $this->buildTransform($this->imagePath, $transforms); $image = array_merge($transforms, ['url' => $url]); $this->transformed = $image; } }
@param $transforms @return null
entailment
private function buildTransform($filename, $transform) { $parameters = $this->translateAttributes($transform); return $this->builder->createURL($filename, $parameters); }
@param $filename @param $transform @return string
entailment
private function translateAttributes($attributes) { $translatedAttributes = []; foreach ($attributes as $key => $setting) { if (array_key_exists($key, $this->attributesTranslate)) { $key = $this->attributesTranslate[ $key ]; } $translatedAttributes[ $key ] = $setting; } return $translatedAttributes; }
@param $attributes @return array
entailment
private function getTagAttributes($attributes) { if (!$attributes) { return ''; } $tagAttributes = ''; foreach ($attributes as $key => $attribute) { $tagAttributes .= ' ' . $key . '="' . $attribute . '"'; } return $tagAttributes; }
@param $attributes @return string
entailment
protected function calculateTargetSizeFromRatio($transform) { if (!isset($transform['ratio'])) { return $transform; } $ratio = (float)$transform['ratio']; $w = isset($transform['w']) ? $transform['w'] : null; $h = isset($transform['h']) ? $transform['h'] : null; // If both sizes and ratio is specified, let ratio take control based on width if ($w and $h) { $transform['h'] = round($w / $ratio); } else { if ($w) { $transform['h'] = round($w / $ratio); } elseif ($h) { $transform['w'] = round($h * $ratio); } else { // TODO: log that neither w nor h is specified with ratio // no idea what to do, return return $transform; } } unset($transform['ratio']); // remove the ratio setting so that it doesn't gets processed in the URL return $transform; }
@param $transform @return mixed
entailment
public static function regenerateId() { if (!self::$_unitTestEnabled && headers_sent($filename, $linenum)) { /** @see Zend_Session_Exception */ require_once 'Zend/Session/Exception.php'; throw new Zend_Session_Exception("You must call " . __CLASS__ . '::' . __FUNCTION__ . "() before any output has been sent to the browser; output started in {$filename}/{$linenum}"); } if ( !self::$_sessionStarted ) { self::$_regenerateIdState = -1; } else { if (!self::$_unitTestEnabled) { session_regenerate_id(true); } self::$_regenerateIdState = 1; } }
regenerateId() - Regenerate the session id. Best practice is to call this after session is started. If called prior to session starting, session id will be regenerated at start time. @throws Zend_Session_Exception @return void
entailment
public static function writeClose($readonly = true) { if (self::$_unitTestEnabled) { return; } if (self::$_writeClosed) { return; } if ($readonly) { parent::$_writable = false; } session_write_close(); self::$_writeClosed = true; }
writeClose() - Shutdown the sesssion, close writing and detach $_SESSION from the back-end storage mechanism. This will complete the internal data transformation on this request. @param bool $readonly - OPTIONAL remove write access (i.e. throw error if Zend_Session's attempt writes) @return void
entailment
private static function _processValidators() { foreach ($_SESSION['__ZF']['VALID'] as $validator_name => $valid_data) { if (!class_exists($validator_name)) { require_once 'Zend/Loader.php'; Zend_Loader::loadClass($validator_name); } $validator = new $validator_name; if ($validator->validate() === false) { /** @see Zend_Session_Exception */ require_once 'Zend/Session/Exception.php'; throw new Zend_Session_Exception("This session is not valid according to {$validator_name}."); } } }
_processValidator() - internal function that is called in the existence of VALID metadata @throws Zend_Session_Exception @return void
entailment
public static function getIterator() { if (parent::$_readable === false) { /** @see Zend_Session_Exception */ require_once 'Zend/Session/Exception.php'; throw new Zend_Session_Exception(parent::_THROW_NOT_READABLE_MSG); } $spaces = array(); if (isset($_SESSION)) { $spaces = array_keys($_SESSION); foreach($spaces as $key => $space) { if (!strncmp($space, '__', 2) || !is_array($_SESSION[$space])) { unset($spaces[$key]); } } } return new ArrayObject(array_merge($spaces, array_keys(parent::$_expiringData))); }
getIterator() - return an iteratable object for use in foreach and the like, this completes the IteratorAggregate interface @throws Zend_Session_Exception @return ArrayObject
entailment
public function run($request) { //Check for tables $tables=DB::tableList(); if(!array_key_exists('languages', $tables) || !array_key_exists('snippits', $tables) || !array_key_exists('snippit_history', $tables) || !array_key_exists('preferences', $tables) || !array_key_exists('settings', $tables) || !array_key_exists('snippit_search', $tables) || !array_key_exists('users', $tables)) { echo '<b>'._t('CodeBankLegacyMigrate.TABLES_NOT_FOUND', '_Could not find Code Bank 2.2 database tables, cannot migrate').'</b>'; exit; } //Ensure Empty if(Snippet::get()->Count()>0) { echo '<b>'._t('CodeBankLegacyMigrate.SNIPPETS_PRESENT', '_Already appears to be snippets present in the database, please start with a clean database, cannot migrate.').'</b>'; exit; } //Increase Timeout, since 30s probably won't be enough in huge databases increase_time_limit_to(600); //Find Other language $plainTextID=SnippetLanguage::get()->filter('Name', 'Other')->first(); if(empty($plainTextID) || $plainTextID==false || $plainTextID->ID==0) { echo _t('CodeBankLegacyMigrate.OTHER_NOT_FOUND', '_Could not find the Other Language, cannot migrate, please run dev/build first'); exit; }else { $plainTextID=$plainTextID->ID; } //Check for users group $usersGroup=Group::get()->filter('Code', 'code-bank-api')->first(); if(empty($usersGroup) || $usersGroup==false || $usersGroup->ID==0) { //Rollback Transaction if(DB::getConn()->supportsTransactions()) { DB::getConn()->transactionRollback(); } echo _t('CodeBankLegacyMigrate.GROUP_NOT_FOUND', '_Could not find users group, cannot migrate, please run dev/build first'); exit; } //Start Transaction if(DB::getConn()->supportsTransactions()) { DB::getConn()->transactionStart(); } //Migrate Languages echo '<b>'._t('CodeBankLegacyMigrate.MIGRATE_USER_LANGUAGES', '_Migrating User Languages').'</b>... '; $results=DB::query('SELECT * FROM "languages" WHERE "user_language"=1'); if($results->numRecords()>0) { foreach($results as $row) { DB::query('INSERT INTO "SnippetLanguage" ("ClassName","Created", "LastEdited", "Name", "FileExtension", "HighlightCode", "UserLanguage") '. "VALUES('SnippetLanguage','".date('Y-m-d H:i:s')."','".date('Y-m-d H:i:s')."','".Convert::raw2sql($row['language'])."','".Convert::raw2sql($row['file_extension'])."','".Convert::raw2sql($row['sjhs_code'])."',1)"); } echo _t('CodeBankLegacyMigrate.DONE', '_Done').'<br/>'; }else { echo _t('CodeBankLegacyMigrate.NOT_FOUND', '_None Found').'<br/>'; } //Migrate Users echo '<b>'._t('CodeBankLegacyMigrate.MIGRATE_USERS', '_Migrating Users').'</b>...'; $results=DB::query('SELECT * FROM "users"'); if($results->numRecords()>0) { foreach($results as $row) { if($row['deleted']==true) { echo '<br/><i>'._t('CodeBankLegacyMigrate.DELETED_MEMBER_SKIP', '_WARNING: Skipping deleted member {username}, deleted members in Code Bank 3 are not supported', array('username'=>$row['username'])).'</i><br/>'; continue; } //Get user heartbeat preference $useHeartbeat=DB::query('SELECT "value" FROM "preferences" WHERE "code"=\'heartbeat\' AND "fkUser"='.$row['id'])->value(); //Insert User $member=Member::get()->filter('Email', Convert::raw2sql($row['username']))->first(); if(empty($member) || $member===false || $member->ID==0) { $member=new Member(); $member->FirstName=$row['username']; $member->Email=$row['username']; $member->Password=$row['password']; $member->PasswordEncryption='sha1'; $member->Locale='en_US'; $member->DateFormat='MMM d, yyyy'; $member->TimeFormat='h:mm:ss a'; $member->UseHeartbeat=intval($useHeartbeat); $member->write(); DB::query('UPDATE "Member" '. 'SET "Password"=\''.substr(base_convert($row['password'], 16, 36), 0, 64).'\', '. '"Salt"=NULL '. 'WHERE "ID"='.$member->ID); //Add to security group if($row['username']=='admin') { //For admin add to administrators group $member->addToGroupByCode('administrators'); }else { //For all others add to code-bank-api $member->addToGroupByCode('code-bank-api'); } }else { //Add to code-bank-api if not admin if($row['username']!='admin') { $member->addToGroupByCode('code-bank-api'); } $member->UseHeartbeat=intval($useHeartbeat); $member->write(); echo '<br/><i>'._t('CodeBankLegacyMigrate.MEMBER_EXISTS', '_WARNING: Member {username} already exists in the database, no changes have been made to this member. If you are unsure of the password please ask an administrator to have it reset or use the forgot password link', array('username'=>$row['username'])).'</i><br/>'; } } echo _t('CodeBankLegacyMigrate.DONE', '_Done').'<br/>'; }else { //Rollback Transaction if(DB::getConn()->supportsTransactions()) { DB::getConn()->transactionRollback(); } echo _t('CodeBankLegacyMigrate.NO_USERS_FOUND', '_No users found, Code Bank 2.2 appears to have not been properly setup cannot continue with migration'); exit; } //Migrate IP Message echo '<b>Migrating IP Message</b>...'; $ipMessage=DB::query('SELECT "value" FROM "settings" WHERE "code"=\'ipMessage\'')->value(); $config=CodeBankConfig::CurrentConfig(); $config->IPMessage=$ipMessage; $config->write(); echo _t('CodeBankLegacyMigrate.DONE', '_Done').'<br/>'; //Migrate Snippets echo '<b>'._t('CodeBankLegacyMigrate.MIGRATE_SNIPPETS', '_Migrating Snippets').'</b>...'; $results=DB::query('SELECT "snippits".*, "languages"."language", "creator"."username" AS "creatorUsername", "lastEditor"."username" AS "lastEditorUsername" '. 'FROM "snippits" '. 'INNER JOIN "languages" ON "snippits"."fkLanguage"="languages"."id" '. 'LEFT JOIN "users" "creator" ON "snippits"."fkCreatorUser"="creator"."id" '. 'LEFT JOIN "users" "lastEditor" ON "snippits"."fkLastEditUser"="lastEditor"."id"'); if($results->numRecords()>0) { foreach($results as $row) { //Get Creator ID $creator=Member::get()->filter('Email', Convert::raw2sql($row['creatorUsername']))->first(); if(!empty($creator) && $creator!==false && $creator->ID!=0) { $creatorID=$creator->ID; }else { $creatorID=0; } //Get Last Editor ID $lastEditor=Member::get()->filter('Email', Convert::raw2sql($row['lastEditorUsername']))->first(); if(!empty($lastEditor) && $lastEditor!==false && $lastEditor->ID!=0) { $lastEditorID=$lastEditor->ID; }else { $lastEditorID=0; } //Get Language ID $language=SnippetLanguage::get()->filter('Name', Convert::raw2sql($row['language']))->first(); if(!empty($language) && $language!==false && $language->ID!=0) { $languageID=$language->ID; }else { $languageID=$plainTextID; } //Insert Snippet Info DB::query('INSERT INTO "Snippet" ("ID", "ClassName", "Created", "LastEdited", "Title", "Description", "Tags", "LanguageID", "CreatorID", "LastEditorID") '. "VALUES(".$row['id'].",'Snippet','".date('Y-m-d H:i:s')."','".date('Y-m-d H:i:s')."','".Convert::raw2sql($row['title'])."','".Convert::raw2sql($row['description'])."','".Convert::raw2sql($row['tags'])."',".$languageID.",".$creatorID.",".$lastEditorID.")"); //Get History $versions=DB::query('SELECT * FROM "snippit_history" WHERE "fkSnippit"='.$row['id']); foreach($versions as $version) { DB::query('INSERT INTO "SnippetVersion" ("ClassName", "Created", "LastEdited", "Text", "ParentID") '. "VALUES('SnippetVersion','".date('Y-m-d H:i:s', strtotime($version['date']))."','".date('Y-m-d H:i:s', strtotime($version['date']))."','".Convert::raw2sql($version['text'])."',".$row['id'].")"); } } echo _t('CodeBankLegacyMigrate.DONE', '_Done').'<br/>'; }else { echo _t('CodeBankLegacyMigrate.NO_SNIPPETS_FOUND', '_No snippets found').'<br/>'; } //Rename tables DB::getConn()->renameTable('snippits', '_obsolete_snippits'); DB::getConn()->renameTable('snippit_search', '_obsolete_snippit_search'); DB::getConn()->renameTable('snippit_history', '_obsolete_snippit_history'); DB::getConn()->renameTable('languages', '_obsolete_languages'); DB::getConn()->renameTable('settings', '_obsolete_settings'); DB::getConn()->renameTable('preferences', '_obsolete_preferences'); DB::getConn()->renameTable('users', '_obsolete_users'); //Complete Transaction if(DB::getConn()->supportsTransactions()) { DB::getConn()->transactionEnd(); } //Mark Migrated touch(ASSETS_PATH.'/.codeBankMigrated'); echo '<br/><h4>'._t('CodeBankLegacyMigrate.MIGRATION_COMPLETE', '_Migration Completed').'</h4>'; exit; }
Performs the migration
entailment
public function setTargetUri($targetUri) { if (null === $targetUri) { $targetUri = ''; } $this->_targetUri = (string) $targetUri; return $this; }
Set target Uri @param string $targetUri @return Zend_Amf_Value_MessageBody
entailment
public function setReplyMethod($methodName) { if (!preg_match('#^[/?]#', $methodName)) { $this->_targetUri = rtrim($this->_targetUri, '/') . '/'; } $this->_targetUri = $this->_targetUri . $methodName; return $this; }
Set reply method @param string $methodName @return Zend_Amf_Value_MessageBody
entailment
public static function reflectClass($class, $argv = false, $namespace = '') { if (is_object($class)) { $reflection = new ReflectionObject($class); } elseif (class_exists($class)) { $reflection = new ReflectionClass($class); } else { require_once 'Zend/Server/Reflection/Exception.php'; throw new Zend_Server_Reflection_Exception('Invalid class or object passed to attachClass()'); } if ($argv && !is_array($argv)) { require_once 'Zend/Server/Reflection/Exception.php'; throw new Zend_Server_Reflection_Exception('Invalid argv argument passed to reflectClass'); } return new Zend_Server_Reflection_Class($reflection, $namespace, $argv); }
Perform class reflection to create dispatch signatures Creates a {@link Zend_Server_Reflection_Class} object for the class or object provided. If extra arguments should be passed to dispatchable methods, these may be provided as an array to $argv. @param string|object $class Class name or object @param null|array $argv Optional arguments to be used during the method call @param string $namespace Optional namespace with which to prefix the method name (used for the signature key). Primarily to avoid collisions, also for XmlRpc namespacing @return Zend_Server_Reflection_Class @throws Zend_Server_Reflection_Exception
entailment