sentence1
stringlengths 52
3.87M
| sentence2
stringlengths 1
47.2k
| label
stringclasses 1
value |
---|---|---|
public function writeDouble($double) {
$bin = pack("d",$double);
$testEndian = unpack("C*",pack("S*",256));
$bigEndian = !$testEndian[1]==1;
if ($bigEndian) $bin = strrev($bin);
$this->rawData.=$bin;
} | writeDouble
@param float $double
@return void | entailment |
public function send($recipient, $body, $originator = '')
{
if (null === $this->username || null === $this->password || null === $this->accountRef) {
throw new Exception\InvalidCredentialsException('No API credentials provided');
}
$params = $this->getParameters(array(
'recipient' => $recipient,
'body' => $body,
'originator' => $originator,
'type' => 'Text',
));
return $this->executeQuery(self::SEND_SMS_URL, $params, array(
'recipient' => $recipient,
'body' => $body,
'originator' => $originator,
));
} | {@inheritDoc} | entailment |
public function getStatus($messageId)
{
if (null === $this->username || null === $this->password || null === $this->accountRef) {
throw new Exception\InvalidCredentialsException('No API credentials provided');
}
$params = $this->getParameters(array(
'messageID' => $messageId,
));
return $this->executeQuery(self::SMS_STATUS_URL, $params);
} | Retrieves the status of a message
@param string $messageId The message Id.
@return array | entailment |
public function getParameters(array $additionnal_parameters = array())
{
return array_merge(array(
'username' => $this->username,
'password' => $this->password,
'account' => $this->accountRef,
'plainText' => '1',
), $additionnal_parameters);
} | Builds the parameters list to send to the API.
@return array
@author Kevin Gomez <[email protected]> | entailment |
protected function parseResults($result, array $extra_result_data = array())
{
// the data sent by the API looks like this
// Result=OK
// MessageIDs=3c13bbba-a9c2-460c-961b-4d6772960af0
$data = array();
// split the lines
$result_lines = explode("\n", $result);
// handle the key <-> value pairs
foreach ($result_lines as $line) {
if (empty($line)) {
continue;
}
$line_data = explode('=', $line);
if (count($line_data) === 2) {
$data[$line_data[0]] = trim(urldecode($line_data[1]));
}
}
// and now, clean a bit the data
if (isset($data['Result'])) {
$data['status'] = $data['Result'] == 'OK'
? ResultInterface::STATUS_SENT
: ResultInterface::STATUS_FAILED;
unset($data['Result']);
}
if (isset($data['MessageIDs'])) {
$data['id'] = $data['MessageIDs'];
unset($data['MessageIDs']);
}
return array_merge($this->getDefaults(), $data, $extra_result_data);
} | Parse the data returned by the API.
@param string $result The raw result string.
@return array | entailment |
public function count()
{
$count = 0;
foreach ($this->_indices as $index) {
$count += $this->_indices->count();
}
return $count;
} | Returns the total number of documents in this index (including deleted documents).
@return integer | entailment |
public function numDocs()
{
$docs = 0;
foreach ($this->_indices as $index) {
$docs += $this->_indices->numDocs();
}
return $docs;
} | Returns the total number of non-deleted documents in this index.
@return integer | entailment |
public static function getDefaultSearchField()
{
if (count($this->_indices) == 0) {
include_once 'Zend/Search/Lucene/Exception.php';
throw new Zend_Search_Lucene_Exception('Indices list is empty');
}
$defaultSearchField = reset($this->_indices)->getDefaultSearchField();
foreach ($this->_indices as $index) {
if ($index->getDefaultSearchField() !== $defaultSearchField) {
include_once 'Zend/Search/Lucene/Exception.php';
throw new Zend_Search_Lucene_Exception('Indices have different default search field.');
}
}
return $defaultSearchField;
} | Get default search field.
Null means, that search is performed through all fields by default
@return string
@throws Zend_Search_Lucene_Exception | entailment |
public static function getResultSetLimit()
{
if (count($this->_indices) == 0) {
include_once 'Zend/Search/Lucene/Exception.php';
throw new Zend_Search_Lucene_Exception('Indices list is empty');
}
$defaultResultSetLimit = reset($this->_indices)->getResultSetLimit();
foreach ($this->_indices as $index) {
if ($index->getResultSetLimit() !== $defaultResultSetLimit) {
include_once 'Zend/Search/Lucene/Exception.php';
throw new Zend_Search_Lucene_Exception('Indices have different default search field.');
}
}
return $defaultResultSetLimit;
} | Set result set limit.
0 means no limit
@return integer
@throws Zend_Search_Lucene_Exception | entailment |
public function getMaxBufferedDocs()
{
if (count($this->_indices) == 0) {
include_once 'Zend/Search/Lucene/Exception.php';
throw new Zend_Search_Lucene_Exception('Indices list is empty');
}
$maxBufferedDocs = reset($this->_indices)->getMaxBufferedDocs();
foreach ($this->_indices as $index) {
if ($index->getMaxBufferedDocs() !== $maxBufferedDocs) {
include_once 'Zend/Search/Lucene/Exception.php';
throw new Zend_Search_Lucene_Exception('Indices have different default search field.');
}
}
return $maxBufferedDocs;
} | Retrieve index maxBufferedDocs option
maxBufferedDocs is a minimal number of documents required before
the buffered in-memory documents are written into a new Segment
Default value is 10
@return integer
@throws Zend_Search_Lucene_Exception | entailment |
public function getMaxMergeDocs()
{
if (count($this->_indices) == 0) {
include_once 'Zend/Search/Lucene/Exception.php';
throw new Zend_Search_Lucene_Exception('Indices list is empty');
}
$maxMergeDocs = reset($this->_indices)->getMaxMergeDocs();
foreach ($this->_indices as $index) {
if ($index->getMaxMergeDocs() !== $maxMergeDocs) {
include_once 'Zend/Search/Lucene/Exception.php';
throw new Zend_Search_Lucene_Exception('Indices have different default search field.');
}
}
return $maxMergeDocs;
} | Retrieve index maxMergeDocs option
maxMergeDocs is a largest number of documents ever merged by addDocument().
Small values (e.g., less than 10,000) are best for interactive indexing,
as this limits the length of pauses while indexing to a few seconds.
Larger values are best for batched indexing and speedier searches.
Default value is PHP_INT_MAX
@return integer
@throws Zend_Search_Lucene_Exception | entailment |
public function getMergeFactor()
{
if (count($this->_indices) == 0) {
include_once 'Zend/Search/Lucene/Exception.php';
throw new Zend_Search_Lucene_Exception('Indices list is empty');
}
$mergeFactor = reset($this->_indices)->getMergeFactor();
foreach ($this->_indices as $index) {
if ($index->getMergeFactor() !== $mergeFactor) {
include_once 'Zend/Search/Lucene/Exception.php';
throw new Zend_Search_Lucene_Exception('Indices have different default search field.');
}
}
return $mergeFactor;
} | Retrieve index mergeFactor option
mergeFactor determines how often segment indices are merged by addDocument().
With smaller values, less RAM is used while indexing,
and searches on unoptimized indices are faster,
but indexing speed is slower.
With larger values, more RAM is used during indexing,
and while searches on unoptimized indices are slower,
indexing is faster.
Thus larger values (> 10) are best for batch index creation,
and smaller values (< 10) for indices that are interactively maintained.
Default value is 10
@return integer
@throws Zend_Search_Lucene_Exception | entailment |
public function find($query)
{
if (count($this->_indices) == 0) {
return array();
}
$hitsList = array();
$indexShift = 0;
foreach ($this->_indices as $index) {
$hits = $index->find($query);
if ($indexShift != 0) {
foreach ($hits as $hit) {
$hit->id += $indexShift;
}
}
$indexShift += $index->count();
$hitsList[] = $hits;
}
/**
* @todo Implement advanced sorting
*/
return call_user_func_array('array_merge', $hitsList);
} | Performs a query against the index and returns an array
of Zend_Search_Lucene_Search_QueryHit objects.
Input is a string or Zend_Search_Lucene_Search_Query.
@param mixed $query
@return array Zend_Search_Lucene_Search_QueryHit
@throws Zend_Search_Lucene_Exception | entailment |
public function getFieldNames($indexed = false)
{
$fieldNamesList = array();
foreach ($this->_indices as $index) {
$fieldNamesList[] = $index->getFieldNames($indexed);
}
return array_unique(call_user_func_array('array_merge', $fieldNamesList));
} | Returns a list of all unique field names that exist in this index.
@param boolean $indexed
@return array | entailment |
public function getDocument($id)
{
if ($id instanceof Zend_Search_Lucene_Search_QueryHit) {
/* @var $id Zend_Search_Lucene_Search_QueryHit */
$id = $id->id;
}
foreach ($this->_indices as $index) {
$indexCount = $index->count();
if ($indexCount > $id) {
return $index->getDocument($id);
}
$id -= $indexCount;
}
include_once 'Zend/Search/Lucene/Exception.php';
throw new Zend_Search_Lucene_Exception('Document id is out of the range.');
} | Returns a Zend_Search_Lucene_Document object for the document
number $id in this index.
@param integer|Zend_Search_Lucene_Search_QueryHit $id
@return Zend_Search_Lucene_Document
@throws Zend_Search_Lucene_Exception Exception is thrown if $id is out of the range | entailment |
public function hasTerm(Zend_Search_Lucene_Index_Term $term)
{
foreach ($this->_indices as $index) {
if ($index->hasTerm($term)) {
return true;
}
}
return false;
} | Returns true if index contain documents with specified term.
Is used for query optimization.
@param Zend_Search_Lucene_Index_Term $term
@return boolean | entailment |
public function termDocs(Zend_Search_Lucene_Index_Term $term, $docsFilter = null)
{
if ($docsFilter != null) {
include_once 'Zend/Search/Lucene/Exception.php';
throw new Zend_Search_Lucene_Exception('Document filters could not used with multi-searcher');
}
$docsList = array();
$indexShift = 0;
foreach ($this->_indices as $index) {
$docs = $index->termDocs($term);
if ($indexShift != 0) {
foreach ($docs as $id => $docId) {
$docs[$id] += $indexShift;
}
}
$indexShift += $index->count();
$docsList[] = $docs;
}
return call_user_func_array('array_merge', $docsList);
} | Returns IDs of all the documents containing term.
@param Zend_Search_Lucene_Index_Term $term
@param Zend_Search_Lucene_Index_DocsFilter|null $docsFilter
@return array
@throws Zend_Search_Lucene_Exception | entailment |
public function termFreqs(Zend_Search_Lucene_Index_Term $term, $docsFilter = null)
{
if ($docsFilter != null) {
include_once 'Zend/Search/Lucene/Exception.php';
throw new Zend_Search_Lucene_Exception('Document filters could not used with multi-searcher');
}
$freqsList = array();
$indexShift = 0;
foreach ($this->_indices as $index) {
$freqs = $index->termFreqs($term);
if ($indexShift != 0) {
$freqsShifted = array();
foreach ($freqs as $docId => $freq) {
$freqsShifted[$docId + $indexShift] = $freq;
}
$freqs = $freqsShifted;
}
$indexShift += $index->count();
$freqsList[] = $freqs;
}
return call_user_func_array('array_merge', $freqsList);
} | Returns an array of all term freqs.
Return array structure: array( docId => freq, ...)
@param Zend_Search_Lucene_Index_Term $term
@param Zend_Search_Lucene_Index_DocsFilter|null $docsFilter
@return integer
@throws Zend_Search_Lucene_Exception | entailment |
public function termPositions(Zend_Search_Lucene_Index_Term $term, $docsFilter = null)
{
if ($docsFilter != null) {
include_once 'Zend/Search/Lucene/Exception.php';
throw new Zend_Search_Lucene_Exception('Document filters could not used with multi-searcher');
}
$termPositionsList = array();
$indexShift = 0;
foreach ($this->_indices as $index) {
$termPositions = $index->termPositions($term);
if ($indexShift != 0) {
$termPositionsShifted = array();
foreach ($termPositions as $docId => $positions) {
$termPositions[$docId + $indexShift] = $positions;
}
$termPositions = $termPositionsShifted;
}
$indexShift += $index->count();
$termPositionsList[] = $termPositions;
}
return call_user_func_array('array_merge', $termPositions);
} | Returns an array of all term positions in the documents.
Return array structure: array( docId => array( pos1, pos2, ...), ...)
@param Zend_Search_Lucene_Index_Term $term
@param Zend_Search_Lucene_Index_DocsFilter|null $docsFilter
@return array
@throws Zend_Search_Lucene_Exception | entailment |
public function docFreq(Zend_Search_Lucene_Index_Term $term)
{
$docFreq = 0;
foreach ($this->_indices as $index) {
$docFreq += $index->docFreq($term);
}
return $docFreq;
} | Returns the number of documents in this index containing the $term.
@param Zend_Search_Lucene_Index_Term $term
@return integer | entailment |
public function getSimilarity()
{
if (count($this->_indices) == 0) {
include_once 'Zend/Search/Lucene/Exception.php';
throw new Zend_Search_Lucene_Exception('Indices list is empty');
}
$similarity = reset($this->_indices)->getSimilarity();
foreach ($this->_indices as $index) {
if ($index->getSimilarity() !== $similarity) {
include_once 'Zend/Search/Lucene/Exception.php';
throw new Zend_Search_Lucene_Exception('Indices have different similarity.');
}
}
return $similarity;
} | Retrive similarity used by index reader
@return Zend_Search_Lucene_Search_Similarity
@throws Zend_Search_Lucene_Exception | entailment |
public function norm($id, $fieldName)
{
foreach ($this->_indices as $index) {
$indexCount = $index->count();
if ($indexCount > $id) {
return $index->norm($id, $fieldName);
}
$id -= $indexCount;
}
return null;
} | Returns a normalization factor for "field, document" pair.
@param integer $id
@param string $fieldName
@return float | entailment |
public function delete($id)
{
foreach ($this->_indices as $index) {
$indexCount = $index->count();
if ($indexCount > $id) {
$index->delete($id);
return;
}
$id -= $indexCount;
}
include_once 'Zend/Search/Lucene/Exception.php';
throw new Zend_Search_Lucene_Exception('Document id is out of the range.');
} | Deletes a document from the index.
$id is an internal document id
@param integer|Zend_Search_Lucene_Search_QueryHit $id
@throws Zend_Search_Lucene_Exception | entailment |
public function setDocumentDistributorCallback($callback)
{
if ($callback !== null && !is_callable($callback)) {
include_once 'Zend/Search/Lucene/Exception.php';
throw new Zend_Search_Lucene_Exception('$callback parameter must be a valid callback.');
}
$this->_documentDistributorCallBack = $callback;
} | Set callback for choosing target index.
@param callback $callback
@throws Zend_Search_Lucene_Exception | entailment |
public function addDocument(Zend_Search_Lucene_Document $document)
{
if ($this->_documentDistributorCallBack !== null) {
$index = call_user_func($this->_documentDistributorCallBack, $document, $this->_indices);
} else {
$index = $this->_indices[array_rand($this->_indices)];
}
$index->addDocument($document);
} | Adds a document to this index.
@param Zend_Search_Lucene_Document $document
@throws Zend_Search_Lucene_Exception | entailment |
public function terms()
{
$termsList = array();
foreach ($this->_indices as $index) {
$termsList[] = $index->terms();
}
return array_unique(call_user_func_array('array_merge', $termsList));
} | Returns an array of all terms in this index.
@return array | entailment |
public function resetTermsStream()
{
if ($this->_termsStream === null) {
/**
* Zend_Search_Lucene_TermStreamsPriorityQueue
*/
include_once 'Zend/Search/Lucene/TermStreamsPriorityQueue.php';
$this->_termsStream = new Zend_Search_Lucene_TermStreamsPriorityQueue($this->_indices);
} else {
$this->_termsStream->resetTermsStream();
}
} | Reset terms stream. | entailment |
public function getDataRegexMatch(string $regex, $group = null, int $fill_size = 0)
{
$is_matched = preg_match($regex, $this->stringDataIsWaitingToBeParsed, $matches);
if ($group !== null && $group >= 0) {
if ($is_matched) {
return $matches[$group] ?? '';
} else {
return '';
}
} else {
if ($is_matched) {
if ($group !== null) {
array_shift($matches);
}
return $matches ?: [];
} else {
return $fill_size > 0 ? array_fill(0, $fill_size, '') : $matches;
}
}
} | @param string $regex
@param int|string $group
@param int $fill_size Fill the array to the fixed size
@return array|string | entailment |
public static function getTypes()
{
return array( self::TT_WORD,
self::TT_PHRASE,
self::TT_FIELD,
self::TT_FIELD_INDICATOR,
self::TT_REQUIRED,
self::TT_PROHIBITED,
self::TT_FUZZY_PROX_MARK,
self::TT_BOOSTING_MARK,
self::TT_RANGE_INCL_START,
self::TT_RANGE_INCL_END,
self::TT_RANGE_EXCL_START,
self::TT_RANGE_EXCL_END,
self::TT_SUBQUERY_START,
self::TT_SUBQUERY_END,
self::TT_AND_LEXEME,
self::TT_OR_LEXEME,
self::TT_NOT_LEXEME,
self::TT_TO_LEXEME,
self::TT_NUMBER
);
} | Returns all possible lexeme types.
It's used for syntax analyzer state machine initialization
@return array | entailment |
public static function loadDocxFile($fileName, $storeContent = false)
{
if (!is_readable($fileName)) {
include_once 'Zend/Search/Lucene/Document/Exception.php';
throw new Zend_Search_Lucene_Document_Exception('Provided file \'' . $fileName . '\' is not readable.');
}
return new Zend_Search_Lucene_Document_Docx($fileName, $storeContent);
} | Load Docx document from a file
@param string $fileName
@param boolean $storeContent
@return Zend_Search_Lucene_Document_Docx
@throws Zend_Search_Lucene_Document_Exception | entailment |
public function send($recipient, $body, $originator = '')
{
if (empty($originator)) {
throw new InvalidArgumentException('The originator parameter is required for this provider.');
}
$internationalOriginator = $this->localNumberToInternational($originator, $this->international_prefix);
$url = sprintf($this->getEndPointUrl(), urlencode('tel:' . $internationalOriginator));
$data = array(
'to' => $this->localNumberToInternational($recipient, $this->international_prefix),
'text' => $body,
'from' => $originator,
);
return $this->executeQuery($url, $data, array(
'recipient' => $recipient,
'body' => $body,
'originator' => $originator,
));
} | {@inheritDoc} | entailment |
private function executeQuery($url, array $data = array(), array $extra_result_data = array())
{
$request = array(
'outboundSMSMessageRequest' => array(
'address' => array(sprintf('tel:%s', $data['to'])),
'senderAddress' => sprintf('tel:%s', $data['from']),
'outboundSMSTextMessage' => array(
'message' => $data['text']
),
),
);
$content = $this->getAdapter()->getContent($url, 'POST', $this->getHeaders(), json_encode($request));
if (null == $content) {
$results = $this->getDefaults();
}
if (is_string($content)) {
$content = json_decode($content, true);
$results['id'] = $content['outboundSMSMessageRequest']['clientCorrelator'];
switch ($content['outboundSMSMessageRequest']['deliveryInfoList']['deliveryInfo'][0]['deliveryStatus']) {
case 'DeliveredToNetwork':
$results['status'] = ResultInterface::STATUS_SENT;
break;
case 'DeliveryImpossible':
$results['status'] = ResultInterface::STATUS_FAILED;
break;
}
}
return array_merge($results, $extra_result_data);
} | do the query | entailment |
public function setNextEntrySign($sign)
{
if ($this->_mode === self::GM_BOOLEAN) {
include_once 'Zend/Search/Lucene/Search/QueryParserException.php';
throw new Zend_Search_Lucene_Search_QueryParserException('It\'s not allowed to mix boolean and signs styles in the same subquery.');
}
$this->_mode = self::GM_SIGNS;
if ($sign == Zend_Search_Lucene_Search_QueryToken::TT_REQUIRED) {
$this->_nextEntrySign = true;
} else if ($sign == Zend_Search_Lucene_Search_QueryToken::TT_PROHIBITED) {
$this->_nextEntrySign = false;
} else {
include_once 'Zend/Search/Lucene/Exception.php';
throw new Zend_Search_Lucene_Exception('Unrecognized sign type.');
}
} | Set sign for next entry
@param integer $sign
@throws Zend_Search_Lucene_Exception | entailment |
public function addEntry(Zend_Search_Lucene_Search_QueryEntry $entry)
{
if ($this->_mode !== self::GM_BOOLEAN) {
$this->_signs[] = $this->_nextEntrySign;
}
$this->_entries[] = $entry;
$this->_nextEntryField = null;
$this->_nextEntrySign = null;
} | Add entry to a query
@param Zend_Search_Lucene_Search_QueryEntry $entry | entailment |
public function processFuzzyProximityModifier($parameter = null)
{
// Check, that modifier has came just after word or phrase
if ($this->_nextEntryField !== null || $this->_nextEntrySign !== null) {
include_once 'Zend/Search/Lucene/Search/QueryParserException.php';
throw new Zend_Search_Lucene_Search_QueryParserException('\'~\' modifier must follow word or phrase.');
}
$lastEntry = array_pop($this->_entries);
if (!$lastEntry instanceof Zend_Search_Lucene_Search_QueryEntry) {
// there are no entries or last entry is boolean operator
include_once 'Zend/Search/Lucene/Search/QueryParserException.php';
throw new Zend_Search_Lucene_Search_QueryParserException('\'~\' modifier must follow word or phrase.');
}
$lastEntry->processFuzzyProximityModifier($parameter);
$this->_entries[] = $lastEntry;
} | Process fuzzy search or proximity search modifier
@throws Zend_Search_Lucene_Search_QueryParserException | entailment |
public function boost($boostFactor)
{
// Check, that modifier has came just after word or phrase
if ($this->_nextEntryField !== null || $this->_nextEntrySign !== null) {
include_once 'Zend/Search/Lucene/Search/QueryParserException.php';
throw new Zend_Search_Lucene_Search_QueryParserException('\'^\' modifier must follow word, phrase or subquery.');
}
$lastEntry = array_pop($this->_entries);
if (!$lastEntry instanceof Zend_Search_Lucene_Search_QueryEntry) {
// there are no entries or last entry is boolean operator
include_once 'Zend/Search/Lucene/Search/QueryParserException.php';
throw new Zend_Search_Lucene_Search_QueryParserException('\'^\' modifier must follow word, phrase or subquery.');
}
$lastEntry->boost($boostFactor);
$this->_entries[] = $lastEntry;
} | Set boost factor to the entry
@param float $boostFactor | entailment |
public function addLogicalOperator($operator)
{
if ($this->_mode === self::GM_SIGNS) {
include_once 'Zend/Search/Lucene/Search/QueryParserException.php';
throw new Zend_Search_Lucene_Search_QueryParserException('It\'s not allowed to mix boolean and signs styles in the same subquery.');
}
$this->_mode = self::GM_BOOLEAN;
$this->_entries[] = $operator;
} | Process logical operator
@param integer $operator | entailment |
public function _signStyleExpressionQuery()
{
include_once 'Zend/Search/Lucene/Search/Query/Boolean.php';
$query = new Zend_Search_Lucene_Search_Query_Boolean();
include_once 'Zend/Search/Lucene/Search/QueryParser.php';
if (Zend_Search_Lucene_Search_QueryParser::getDefaultOperator() == Zend_Search_Lucene_Search_QueryParser::B_AND) {
$defaultSign = true; // required
} else {
// Zend_Search_Lucene_Search_QueryParser::B_OR
$defaultSign = null; // optional
}
foreach ($this->_entries as $entryId => $entry) {
$sign = ($this->_signs[$entryId] !== null) ? $this->_signs[$entryId] : $defaultSign;
$query->addSubquery($entry->getQuery($this->_encoding), $sign);
}
return $query;
} | Generate 'signs style' query from the context
'+term1 term2 -term3 +(<subquery1>) ...'
@return Zend_Search_Lucene_Search_Query | entailment |
private function _booleanExpressionQuery()
{
/**
* We treat each level of an expression as a boolean expression in
* a Disjunctive Normal Form
*
* AND operator has higher precedence than OR
*
* Thus logical query is a disjunction of one or more conjunctions of
* one or more query entries
*/
include_once 'Zend/Search/Lucene/Search/BooleanExpressionRecognizer.php';
$expressionRecognizer = new Zend_Search_Lucene_Search_BooleanExpressionRecognizer();
include_once 'Zend/Search/Lucene/Exception.php';
try {
foreach ($this->_entries as $entry) {
if ($entry instanceof Zend_Search_Lucene_Search_QueryEntry) {
$expressionRecognizer->processLiteral($entry);
} else {
switch ($entry) {
case Zend_Search_Lucene_Search_QueryToken::TT_AND_LEXEME:
$expressionRecognizer->processOperator(Zend_Search_Lucene_Search_BooleanExpressionRecognizer::IN_AND_OPERATOR);
break;
case Zend_Search_Lucene_Search_QueryToken::TT_OR_LEXEME:
$expressionRecognizer->processOperator(Zend_Search_Lucene_Search_BooleanExpressionRecognizer::IN_OR_OPERATOR);
break;
case Zend_Search_Lucene_Search_QueryToken::TT_NOT_LEXEME:
$expressionRecognizer->processOperator(Zend_Search_Lucene_Search_BooleanExpressionRecognizer::IN_NOT_OPERATOR);
break;
default:
throw new Zend_Search_Lucene('Boolean expression error. Unknown operator type.');
}
}
}
$conjuctions = $expressionRecognizer->finishExpression();
} catch (Zend_Search_Exception $e) {
// throw new Zend_Search_Lucene_Search_QueryParserException('Boolean expression error. Error message: \'' .
// $e->getMessage() . '\'.' );
// It's query syntax error message and it should be user friendly. So FSM message is omitted
include_once 'Zend/Search/Lucene/Search/QueryParserException.php';
throw new Zend_Search_Lucene_Search_QueryParserException('Boolean expression error.', 0, $e);
}
// Remove 'only negative' conjunctions
foreach ($conjuctions as $conjuctionId => $conjuction) {
$nonNegativeEntryFound = false;
foreach ($conjuction as $conjuctionEntry) {
if ($conjuctionEntry[1]) {
$nonNegativeEntryFound = true;
break;
}
}
if (!$nonNegativeEntryFound) {
unset($conjuctions[$conjuctionId]);
}
}
$subqueries = array();
foreach ($conjuctions as $conjuction) {
// Check, if it's a one term conjuction
if (count($conjuction) == 1) {
$subqueries[] = $conjuction[0][0]->getQuery($this->_encoding);
} else {
include_once 'Zend/Search/Lucene/Search/Query/Boolean.php';
$subquery = new Zend_Search_Lucene_Search_Query_Boolean();
foreach ($conjuction as $conjuctionEntry) {
$subquery->addSubquery($conjuctionEntry[0]->getQuery($this->_encoding), $conjuctionEntry[1]);
}
$subqueries[] = $subquery;
}
}
if (count($subqueries) == 0) {
include_once 'Zend/Search/Lucene/Search/Query/Insignificant.php';
return new Zend_Search_Lucene_Search_Query_Insignificant();
}
if (count($subqueries) == 1) {
return $subqueries[0];
}
include_once 'Zend/Search/Lucene/Search/Query/Boolean.php';
$query = new Zend_Search_Lucene_Search_Query_Boolean();
foreach ($subqueries as $subquery) {
// Non-requirered entry/subquery
$query->addSubquery($subquery);
}
return $query;
} | Generate 'boolean style' query from the context
'term1 and term2 or term3 and (<subquery1>) and not (<subquery2>)'
@return Zend_Search_Lucene_Search_Query
@throws Zend_Search_Lucene | entailment |
public function readInt()
{
$str = $this->_fread(4);
return ord($str[0]) << 24 |
ord($str[1]) << 16 |
ord($str[2]) << 8 |
ord($str[3]);
} | Reads an integer from the current position in the file
and advances the file pointer.
@return integer | entailment |
public function writeInt($value)
{
settype($value, 'integer');
$this->_fwrite(
chr($value>>24 & 0xFF) .
chr($value>>16 & 0xFF) .
chr($value>>8 & 0xFF) .
chr($value & 0xFF), 4
);
} | Writes an integer to the end of file.
@param integer $value | entailment |
public function readLong()
{
/**
* Check, that we work in 64-bit mode.
* fseek() uses long for offset. Thus, largest index segment file size in 32bit mode is 2Gb
*/
if (PHP_INT_SIZE > 4) {
$str = $this->_fread(8);
return ord($str[0]) << 56 |
ord($str[1]) << 48 |
ord($str[2]) << 40 |
ord($str[3]) << 32 |
ord($str[4]) << 24 |
ord($str[5]) << 16 |
ord($str[6]) << 8 |
ord($str[7]);
} else {
return $this->readLong32Bit();
}
} | Returns a long integer from the current position in the file
and advances the file pointer.
@return integer|float
@throws Zend_Search_Lucene_Exception | entailment |
public function writeLong($value)
{
/**
* Check, that we work in 64-bit mode.
* fseek() and ftell() use long for offset. Thus, largest index segment file size in 32bit mode is 2Gb
*/
if (PHP_INT_SIZE > 4) {
settype($value, 'integer');
$this->_fwrite(
chr($value>>56 & 0xFF) .
chr($value>>48 & 0xFF) .
chr($value>>40 & 0xFF) .
chr($value>>32 & 0xFF) .
chr($value>>24 & 0xFF) .
chr($value>>16 & 0xFF) .
chr($value>>8 & 0xFF) .
chr($value & 0xFF), 8
);
} else {
$this->writeLong32Bit($value);
}
} | Writes long integer to the end of file
@param integer $value
@throws Zend_Search_Lucene_Exception | entailment |
public function readLong32Bit()
{
$wordHigh = $this->readInt();
$wordLow = $this->readInt();
if ($wordHigh & (int)0x80000000) {
// It's a negative value since the highest bit is set
if ($wordHigh == (int)0xFFFFFFFF && ($wordLow & (int)0x80000000)) {
return $wordLow;
} else {
include_once 'Zend/Search/Lucene/Exception.php';
throw new Zend_Search_Lucene_Exception('Long integers lower than -2147483648 (0x80000000) are not supported on 32-bit platforms.');
}
}
if ($wordLow < 0) {
// Value is large than 0x7FFF FFFF. Represent low word as float.
$wordLow &= 0x7FFFFFFF;
$wordLow += (float)0x80000000;
}
if ($wordHigh == 0) {
// Return value as integer if possible
return $wordLow;
}
return $wordHigh*(float)0x100000000/* 0x00000001 00000000 */ + $wordLow;
} | Returns a long integer from the current position in the file,
advances the file pointer and return it as float (for 32-bit platforms).
@return integer|float
@throws Zend_Search_Lucene_Exception | entailment |
public function writeLong32Bit($value)
{
if ($value < (int)0x80000000) {
include_once 'Zend/Search/Lucene/Exception.php';
throw new Zend_Search_Lucene_Exception('Long integers lower than -2147483648 (0x80000000) are not supported on 32-bit platforms.');
}
if ($value < 0) {
$wordHigh = (int)0xFFFFFFFF;
$wordLow = (int)$value;
} else {
$wordHigh = (int)($value/(float)0x100000000/* 0x00000001 00000000 */);
$wordLow = $value - $wordHigh*(float)0x100000000/* 0x00000001 00000000 */;
if ($wordLow > 0x7FFFFFFF) {
// Highest bit of low word is set. Translate it to the corresponding negative integer value
$wordLow -= 0x80000000;
$wordLow |= 0x80000000;
}
}
$this->writeInt($wordHigh);
$this->writeInt($wordLow);
} | Writes long integer to the end of file (32-bit platforms implementation)
@param integer|float $value
@throws Zend_Search_Lucene_Exception | entailment |
public function readVInt()
{
$nextByte = ord($this->_fread(1));
$val = $nextByte & 0x7F;
for ($shift=7; ($nextByte & 0x80) != 0; $shift += 7) {
$nextByte = ord($this->_fread(1));
$val |= ($nextByte & 0x7F) << $shift;
}
return $val;
} | Returns a variable-length integer from the current
position in the file and advances the file pointer.
@return integer | entailment |
public function writeVInt($value)
{
settype($value, 'integer');
while ($value > 0x7F) {
$this->_fwrite(chr(($value & 0x7F)|0x80));
$value >>= 7;
}
$this->_fwrite(chr($value));
} | Writes a variable-length integer to the end of file.
@param integer $value | entailment |
public function readString()
{
$strlen = $this->readVInt();
if ($strlen == 0) {
return '';
} else {
/**
* This implementation supports only Basic Multilingual Plane
* (BMP) characters (from 0x0000 to 0xFFFF) and doesn't support
* "supplementary characters" (characters whose code points are
* greater than 0xFFFF)
* Java 2 represents these characters as a pair of char (16-bit)
* values, the first from the high-surrogates range (0xD800-0xDBFF),
* the second from the low-surrogates range (0xDC00-0xDFFF). Then
* they are encoded as usual UTF-8 characters in six bytes.
* Standard UTF-8 representation uses four bytes for supplementary
* characters.
*/
$str_val = $this->_fread($strlen);
for ($count = 0; $count < $strlen; $count++ ) {
if (( ord($str_val[$count]) & 0xC0 ) == 0xC0) {
$addBytes = 1;
if (ord($str_val[$count]) & 0x20 ) {
$addBytes++;
// Never used. Java2 doesn't encode strings in four bytes
if (ord($str_val[$count]) & 0x10 ) {
$addBytes++;
}
}
$str_val .= $this->_fread($addBytes);
$strlen += $addBytes;
// Check for null character. Java2 encodes null character
// in two bytes.
if (ord($str_val[$count]) == 0xC0
&& ord($str_val[$count+1]) == 0x80
) {
$str_val[$count] = 0;
$str_val = substr($str_val, 0, $count+1)
. substr($str_val, $count+2);
}
$count += $addBytes;
}
}
return $str_val;
}
} | Reads a string from the current position in the file
and advances the file pointer.
@return string | entailment |
public function writeString($str)
{
/**
* This implementation supports only Basic Multilingual Plane
* (BMP) characters (from 0x0000 to 0xFFFF) and doesn't support
* "supplementary characters" (characters whose code points are
* greater than 0xFFFF)
* Java 2 represents these characters as a pair of char (16-bit)
* values, the first from the high-surrogates range (0xD800-0xDBFF),
* the second from the low-surrogates range (0xDC00-0xDFFF). Then
* they are encoded as usual UTF-8 characters in six bytes.
* Standard UTF-8 representation uses four bytes for supplementary
* characters.
*/
// convert input to a string before iterating string characters
settype($str, 'string');
$chars = $strlen = strlen($str);
$containNullChars = false;
for ($count = 0; $count < $strlen; $count++ ) {
/**
* String is already in Java 2 representation.
* We should only calculate actual string length and replace
* \x00 by \xC0\x80
*/
if ((ord($str[$count]) & 0xC0) == 0xC0) {
$addBytes = 1;
if (ord($str[$count]) & 0x20 ) {
$addBytes++;
// Never used. Java2 doesn't encode strings in four bytes
// and we dont't support non-BMP characters
if (ord($str[$count]) & 0x10 ) {
$addBytes++;
}
}
$chars -= $addBytes;
if (ord($str[$count]) == 0 ) {
$containNullChars = true;
}
$count += $addBytes;
}
}
if ($chars < 0) {
include_once 'Zend/Search/Lucene/Exception.php';
throw new Zend_Search_Lucene_Exception('Invalid UTF-8 string');
}
$this->writeVInt($chars);
if ($containNullChars) {
$this->_fwrite(str_replace($str, "\x00", "\xC0\x80"));
} else {
$this->_fwrite($str);
}
} | Writes a string to the end of file.
@param string $str
@throws Zend_Search_Lucene_Exception | entailment |
protected function mayCache($item) {
return (
isset($item) &&
is_object($item) &&
isset($item->headers) &&
is_string($item->headers->etag) &&
!empty($item->headers->etag) &&
isset($item->body) &&
is_object($item->body)
);
} | Returns whether or not the item may be cached. It has to be a stdClass
that Sag would return, with a valid E-Tag, and no cache headers that tell
us to not cache.
@param The item that we're trying to cache - it should be a response as a
stdClass.
@return bool | entailment |
public function beginTransaction()
{
if ($this->disableTransactionHandling) {
return;
}
if (null !== $this->session) {
throw new \RuntimeException('Transaction already started');
}
$this->session = $this->mongoClient->startSession();
$this->session->startTransaction([
'readConcern' => new \MongoDB\Driver\ReadConcern('snapshot'),
'writeConcern' => new \MongoDB\Driver\WriteConcern(\MongoDB\Driver\WriteConcern::MAJORITY),
]);
} | Begin transaction
@return void | entailment |
public function commit()
{
if ($this->disableTransactionHandling) {
return;
}
if (null === $this->session) {
throw new RuntimeAdapterException('Transaction not started');
}
$this->session->commitTransaction();
$this->session->endSession();
$this->session = null;
} | Commit transaction
@return void | entailment |
public function rollback()
{
if ($this->disableTransactionHandling) {
return;
}
if (null === $this->session) {
throw new RuntimeAdapterException('Transaction not started');
}
$this->session->abortTransaction();
$this->session->endSession();
$this->session = null;
} | Rollback transaction
@return void | entailment |
private function getCollection(StreamName $streamName): Collection
{
$collection = $this->mongoClient->selectCollection($this->dbName, $this->getCollectionName($streamName));
return $collection;
} | Get mongo db stream collection
@param StreamName $streamName
@return Collection | entailment |
public function performSearch()
{
try {
$index = Zend_Search_Lucene::open(self::get_index_location());
Zend_Search_Lucene::setResultSetLimit(100);
$query = new Zend_Search_Lucene_Search_Query_Boolean();
$term = Zend_Search_Lucene_Search_QueryParser::parse($this->getQuery());
$query->addSubquery($term, true);
if ($this->modules) {
$moduleQuery = new Zend_Search_Lucene_Search_Query_MultiTerm();
foreach ($this->modules as $module) {
$moduleQuery->addTerm(new Zend_Search_Lucene_Index_Term($module, 'Entity'));
}
$query->addSubquery($moduleQuery, true);
}
if ($this->versions) {
$versionQuery = new Zend_Search_Lucene_Search_Query_MultiTerm();
foreach ($this->versions as $version) {
$versionQuery->addTerm(new Zend_Search_Lucene_Index_Term($version, 'Version'));
}
$query->addSubquery($versionQuery, true);
}
$er = error_reporting();
error_reporting('E_ALL ^ E_NOTICE');
$this->results = $index->find($query);
error_reporting($er);
$this->totalResults = $index->numDocs();
} catch (Zend_Search_Lucene_Exception $e) {
user_error($e .'. Ensure you have run the rebuld task (/dev/tasks/RebuildLuceneDocsIndex)', E_USER_ERROR);
}
} | Perform a search query on the index | entailment |
private function buildQueryUrl($params)
{
$url = parse_url($_SERVER['REQUEST_URI']);
if (! array_key_exists('query', $url)) {
$url['query'] = '';
}
parse_str($url['query'], $url['query']);
if (! is_array($url['query'])) {
$url['query'] = array();
}
// Remove 'start parameter if it exists
if (array_key_exists('start', $url['query'])) {
unset($url['query']['start']);
}
// Add extra parameters from argument
$url['query'] = array_merge($url['query'], $params);
$url['query'] = http_build_query($url['query']);
$url = $url['path'] . ($url['query'] ? '?'.$url['query'] : '');
return $url;
} | Build a nice query string for the results
@return string | entailment |
public static function set_meta_data($data)
{
if (is_array($data)) {
foreach ($data as $key => $value) {
self::$meta_data[strtolower($key)] = $value;
}
} else {
user_error("set_meta_data must be passed an array", E_USER_ERROR);
}
} | OpenSearch MetaData fields. For a list of fields consult
{@link self::get_meta_data()}
@param array | entailment |
public static function get_meta_data()
{
$data = self::$meta_data;
$defaults = array(
'Description' => _t('DocumentationViewer.OPENSEARCHDESC', 'Search the documentation'),
'Tags' => _t('DocumentationViewer.OPENSEARCHTAGS', 'documentation'),
'Contact' => Config::inst()->get('Email', 'admin_email'),
'ShortName' => _t('DocumentationViewer.OPENSEARCHNAME', 'Documentation Search'),
'Author' => 'SilverStripe'
);
foreach ($defaults as $key => $value) {
if (isset($data[$key])) {
$defaults[$key] = $data[$key];
}
}
return $defaults;
} | Returns the meta data needed by opensearch.
@return array | entailment |
public function renderResults()
{
if (!$this->results && $this->query) {
$this->performSearch();
}
if (!$this->outputController) {
return user_error('Call renderResults() on a DocumentationViewer instance.', E_USER_ERROR);
}
$request = $this->outputController->getRequest();
$data = $this->getSearchResults($request);
$templates = array('DocumentationViewer_search');
if ($request->requestVar('format') && $request->requestVar('format') == "atom") {
// alter the fields for the opensearch xml.
$title = ($title = $this->getTitle()) ? ' - '. $title : "";
$link = Controller::join_links(
$this->outputController->Link(),
'DocumentationOpenSearchController/description/'
);
$data->setField('Title', $data->Title . $title);
$data->setField('DescriptionURL', $link);
array_unshift($templates, 'OpenSearchResults');
}
return $this->outputController->customise($data)->renderWith($templates);
} | Renders the search results into a template. Either the search results
template or the Atom feed. | entailment |
public function merge()
{
if ($this->_mergeDone) {
include_once 'Zend/Search/Lucene/Exception.php';
throw new Zend_Search_Lucene_Exception('Merge is already done.');
}
if (count($this->_segmentInfos) < 1) {
include_once 'Zend/Search/Lucene/Exception.php';
throw new Zend_Search_Lucene_Exception(
'Wrong number of segments to be merged ('
. count($this->_segmentInfos)
. ').'
);
}
$this->_mergeFields();
$this->_mergeNorms();
$this->_mergeStoredFields();
$this->_mergeTerms();
$this->_mergeDone = true;
return $this->_writer->close();
} | Do merge.
Returns number of documents in newly created segment
@return Zend_Search_Lucene_Index_SegmentInfo
@throws Zend_Search_Lucene_Exception | entailment |
private function _mergeFields()
{
foreach ($this->_segmentInfos as $segName => $segmentInfo) {
foreach ($segmentInfo->getFieldInfos() as $fieldInfo) {
$this->_fieldsMap[$segName][$fieldInfo->number] = $this->_writer->addFieldInfo($fieldInfo);
}
}
} | Merge fields information | entailment |
private function _mergeNorms()
{
foreach ($this->_writer->getFieldInfos() as $fieldInfo) {
if ($fieldInfo->isIndexed) {
foreach ($this->_segmentInfos as $segName => $segmentInfo) {
if ($segmentInfo->hasDeletions()) {
$srcNorm = $segmentInfo->normVector($fieldInfo->name);
$norm = '';
$docs = $segmentInfo->count();
for ($count = 0; $count < $docs; $count++) {
if (!$segmentInfo->isDeleted($count)) {
$norm .= $srcNorm[$count];
}
}
$this->_writer->addNorm($fieldInfo->name, $norm);
} else {
$this->_writer->addNorm($fieldInfo->name, $segmentInfo->normVector($fieldInfo->name));
}
}
}
}
} | Merge field's normalization factors | entailment |
private function _mergeStoredFields()
{
$this->_docCount = 0;
foreach ($this->_segmentInfos as $segName => $segmentInfo) {
$fdtFile = $segmentInfo->openCompoundFile('.fdt');
for ($count = 0; $count < $segmentInfo->count(); $count++) {
$fieldCount = $fdtFile->readVInt();
$storedFields = array();
for ($count2 = 0; $count2 < $fieldCount; $count2++) {
$fieldNum = $fdtFile->readVInt();
$bits = $fdtFile->readByte();
$fieldInfo = $segmentInfo->getField($fieldNum);
if (!($bits & 2)) { // Text data
$storedFields[] =
new Zend_Search_Lucene_Field(
$fieldInfo->name,
$fdtFile->readString(),
'UTF-8',
true,
$fieldInfo->isIndexed,
$bits & 1
);
} else { // Binary data
$storedFields[] =
new Zend_Search_Lucene_Field(
$fieldInfo->name,
$fdtFile->readBinary(),
'',
true,
$fieldInfo->isIndexed,
$bits & 1,
true
);
}
}
if (!$segmentInfo->isDeleted($count)) {
$this->_docCount++;
$this->_writer->addStoredFields($storedFields);
}
}
}
} | Merge fields information | entailment |
private function _mergeTerms()
{
/**
* Zend_Search_Lucene_Index_TermsPriorityQueue
*/
include_once 'Zend/Search/Lucene/Index/TermsPriorityQueue.php';
$segmentInfoQueue = new Zend_Search_Lucene_Index_TermsPriorityQueue();
$segmentStartId = 0;
foreach ($this->_segmentInfos as $segName => $segmentInfo) {
$segmentStartId = $segmentInfo->resetTermsStream($segmentStartId, Zend_Search_Lucene_Index_SegmentInfo::SM_MERGE_INFO);
// Skip "empty" segments
if ($segmentInfo->currentTerm() !== null) {
$segmentInfoQueue->put($segmentInfo);
}
}
$this->_writer->initializeDictionaryFiles();
$termDocs = array();
while (($segmentInfo = $segmentInfoQueue->pop()) !== null) {
// Merge positions array
$termDocs += $segmentInfo->currentTermPositions();
if ($segmentInfoQueue->top() === null
|| $segmentInfoQueue->top()->currentTerm()->key() != $segmentInfo->currentTerm()->key()
) {
// We got new term
ksort($termDocs, SORT_NUMERIC);
// Add term if it's contained in any document
if (count($termDocs) > 0) {
$this->_writer->addTerm($segmentInfo->currentTerm(), $termDocs);
}
$termDocs = array();
}
$segmentInfo->nextTerm();
// check, if segment dictionary is finished
if ($segmentInfo->currentTerm() !== null) {
// Put segment back into the priority queue
$segmentInfoQueue->put($segmentInfo);
}
}
$this->_writer->closeDictionaryFiles();
} | Merge fields information | entailment |
public function fromArray(array $data = array())
{
if (!empty($data['id'])) {
$this->id = (string) $data['id'];
}
if (isset($data['recipient'])) {
$this->recipient = (string) $data['recipient'];
}
if (isset($data['body'])) {
$this->body = (string) $data['body'];
}
if (isset($data['originator'])) {
$this->originator = (string) $data['originator'];
}
if (isset($data['status'])) {
if (!in_array($data['status'], $this->getValidStatus())) {
throw new \RuntimeException(sprintf('Invalid status given: "%s"', $data['status']));
}
$this->status = (string) $data['status'];
}
} | {@inheritDoc} | entailment |
public function toArray()
{
return array(
'id' => $this->id,
'recipient' => $this->recipient,
'body' => $this->body,
'originator' => $this->originator,
'status' => $this->status,
'sent' => $this->isSent(),
);
} | {@inheritDoc} | entailment |
public function offsetGet($offset)
{
$offset = strtolower($offset);
return $this->offsetExists($offset) ? $this->$offset : null;
} | {@inheritDoc} | entailment |
public function offsetSet($offset, $value)
{
$offset = strtolower($offset);
if ($this->offsetExists($offset)) {
$this->$offset = $value;
}
} | {@inheritDoc} | entailment |
public function offsetUnset($offset)
{
$offset = strtolower($offset);
if ($this->offsetExists($offset)) {
$this->$offset = null;
}
} | {@inheritDoc} | entailment |
public function canView()
{
return (Director::isDev() || Director::is_cli() ||
!$this->config()->get('check_permission') ||
Permission::check($this->config()->get('check_permission'))
);
} | Can the user view this documentation. Hides all functionality for private
wikis.
@return bool | entailment |
public function handleAction($request, $action)
{
// if we submitted a form, let that pass
if (!$request->isGET() && !$request->isHEAD()) {
return parent::handleAction($request, $action);
}
$url = $request->getURL();
//
// If the current request has an extension attached to it, strip that
// off and redirect the user to the page without an extension.
//
if (DocumentationHelper::get_extension($url)) {
$this->response = new SS_HTTPResponse();
$this->response->redirect(
Director::absoluteURL(DocumentationHelper::trim_extension_off($url)) .'/',
301
);
$request->shift();
$request->shift();
return $this->response;
}
//
// Strip off the base url
//
$base = ltrim(
Config::inst()->get('DocumentationViewer', 'link_base'),
'/'
);
if ($base && strpos($url, $base) !== false) {
$url = substr(
ltrim($url, '/'),
strlen($base)
);
}
//
// Handle any permanent redirections that the developer has defined.
//
if ($link = DocumentationPermalinks::map($url)) {
// the first param is a shortcode for a page so redirect the user to
// the short code.
$this->response = new SS_HTTPResponse();
$this->response->redirect($link, 301);
$request->shift();
$request->shift();
return $this->response;
}
//
// Validate the language provided. Language is a required URL parameter.
// as we use it for generic interfaces and language selection. If
// language is not set, redirects to 'en'
//
$languages = i18n::get_common_languages();
if (!$lang = $request->param('Lang')) {
$lang = $request->param('Action');
$action = $request->param('ID');
} else {
$action = $request->param('Action');
}
if (!$lang) {
return $this->redirect($this->Link('en'));
} elseif (!isset($languages[$lang])) {
return $this->httpError(404);
}
$request->shift(10);
$allowed = $this->config()->allowed_actions;
if (in_array($action, $allowed)) {
//
// if it's one of the allowed actions such as search or all then the
// URL must be prefixed with one of the allowed languages and versions
//
return parent::handleAction($request, $action);
} else {
//
// look up the manifest to see find the nearest match against the
// list of the URL. If the URL exists then set that as the current
// page to match against.
// strip off any extensions.
// if($cleaned !== $url) {
// $redirect = new SS_HTTPResponse();
// return $redirect->redirect($cleaned, 302);
// }
if ($record = $this->getManifest()->getPage($url)) {
// In SS 3 offsetSet() isn't implemented for some reason... this is a workaround
$routeParams = $this->request->routeParams();
$routeParams['Lang'] = $lang;
$this->request->setRouteParams($routeParams);
$this->record = $record;
$this->init();
$type = get_class($this->record);
$body = $this->renderWith(
array(
"DocumentationViewer_{$type}",
'DocumentationViewer'
)
);
return new SS_HTTPResponse($body, 200);
} elseif ($redirect = $this->getManifest()->getRedirect($url)) {
$response = new SS_HTTPResponse();
$to = Controller::join_links(Director::baseURL(), $base, $redirect);
return $response->redirect($to, 301);
} elseif (!$url || $url == $lang) {
$body = $this->renderWith(
array(
'DocumentationViewer_DocumentationFolder',
'DocumentationViewer'
)
);
return new SS_HTTPResponse($body, 200);
}
}
return $this->httpError(404);
} | Overloaded to avoid "action doesn't exist" errors - all URL parts in
this controller are virtual and handled through handleRequest(), not
controller methods.
@param $request
@param $action
@return SS_HTTPResponse | entailment |
public function httpError($status, $message = null)
{
$this->init();
$class = get_class($this);
$body = $this->customise(
new ArrayData(
array(
'Message' => $message
)
)
)->renderWith(array("{$class}_error", $class));
return new SS_HTTPResponse($body, $status);
} | @param int $status
@param string $message
@return SS_HTTPResponse | entailment |
public function getMenu()
{
$entities = $this->getManifest()->getEntities();
$output = new ArrayList();
$record = $this->getPage();
$current = $this->getEntity();
foreach ($entities as $entity) {
$checkLang = $entity->getLanguage();
$checkVers = $entity->getVersion();
// only show entities with the same language or any entity that
// isn't registered under any particular language (auto detected)
if ($checkLang && $checkLang !== $this->getLanguage()) {
continue;
}
if ($current && $checkVers) {
if ($entity->getVersion() !== $current->getVersion()) {
continue;
}
}
$mode = 'link';
$children = new ArrayList();
if ($entity->hasRecord($record) || $entity->getIsDefaultEntity()) {
$mode = 'current';
// add children
$children = $this->getManifest()->getChildrenFor(
$entity->getPath(),
($record) ? $record->getPath() : $entity->getPath()
);
} else {
if ($current && $current->getKey() == $entity->getKey()) {
continue;
}
}
$link = $entity->Link();
$output->push(
new ArrayData(
array(
'Title' => $entity->getTitle(),
'Link' => $link,
'LinkingMode' => $mode,
'DefaultEntity' => $entity->getIsDefaultEntity(),
'Children' => $children
)
)
);
}
return $output;
} | Generate a list of {@link Documentation } which have been registered and which can
be documented.
@return DataObject | entailment |
public function getContent()
{
$page = $this->getPage();
$html = $page->getHTML();
$html = $this->replaceChildrenCalls($html);
return $html;
} | Return the content for the page. If its an actual documentation page then
display the content from the page, otherwise display the contents from
the index.md file if its a folder
@return HTMLText | entailment |
public function includeChildren($args)
{
if (isset($args['Folder'])) {
$children = $this->getManifest()->getChildrenFor(
Controller::join_links(dirname($this->record->getPath()), $args['Folder'])
);
} else {
$children = $this->getManifest()->getChildrenFor(
dirname($this->record->getPath())
);
}
if (isset($args['Exclude'])) {
$exclude = explode(',', $args['Exclude']);
foreach ($children as $k => $child) {
foreach ($exclude as $e) {
if ($child->Link == Controller::join_links($this->record->Link(), strtolower($e), '/')) {
unset($children[$k]);
}
}
}
}
return $this->customise(
new ArrayData(
array(
'Children' => $children
)
)
)->renderWith('Includes/DocumentationPages');
} | Short code parser | entailment |
public function getBreadcrumbs()
{
if ($this->record) {
return $this->getManifest()->generateBreadcrumbs(
$this->record,
$this->record->getEntity()
);
}
} | Generate a list of breadcrumbs for the user.
@return ArrayList | entailment |
public function Link($action = '')
{
$link = Controller::join_links(
Director::baseURL(),
Config::inst()->get('DocumentationViewer', 'link_base'),
$this->getLanguage(),
$action,
'/'
);
return $link;
} | Return the base link to this documentation location.
@return string | entailment |
public function AllPages($version = null)
{
$pages = $this->getManifest()->getPages();
$output = new ArrayList();
$baseLink = $this->getDocumentationBaseHref();
foreach ($pages as $url => $page) {
// Option to skip Pages that do not belong to the current version
if (!is_null($version) && (string) $page['version'] !== (string) $version) {
continue;
}
$first = strtoupper(trim(substr($page['title'], 0, 1)));
if ($first) {
$output->push(
new ArrayData(
array(
'Link' => Controller::join_links($baseLink, $url),
'Title' => $page['title'],
'FirstLetter' => $first
)
)
);
}
}
return GroupedList::create($output->sort('Title', 'ASC'));
} | Generate a list of all the pages in the documentation grouped by the
first letter of the page.
@param string|int|null $version
@return GroupedList | entailment |
public function getEditLink()
{
$editLink = false;
$entity = null;
$page = $this->getPage();
if ($page) {
$entity = $page->getEntity();
if ($entity && isset(self::$edit_links[strtolower($entity->title)])) {
// build the edit link, using the version defined
$url = self::$edit_links[strtolower($entity->title)];
$version = $entity->getVersion();
if ($entity->getBranch()) {
$version = $entity->getBranch();
}
if ($version === 'trunk' && (isset($url['options']['rewritetrunktomaster']))) {
if ($url['options']['rewritetrunktomaster']) {
$version = "master";
}
}
$editLink = str_replace(
array('%entity%', '%lang%', '%version%', '%path%'),
array(
$entity->title,
$this->getLanguage(),
$version,
ltrim($page->getRelativePath(), '/')
),
$url['url']
);
}
}
$this->extend('updateDocumentationEditLink', $editLink, $entity);
return $editLink;
} | Returns an edit link to the current page (optional).
@return string|false | entailment |
public function getNextPage()
{
return ($this->record)
? $this->getManifest()->getNextPage(
$this->record->getPath(),
$this->getEntity()->getPath()
)
: null;
} | Returns the next page. Either retrieves the sibling of the current page
or return the next sibling of the parent page.
@return DocumentationPage|null | entailment |
public function getPreviousPage()
{
return ($this->record)
? $this->getManifest()->getPreviousPage(
$this->record->getPath(),
$this->getEntity()->getPath()
)
: null;
} | Returns the previous page. Either returns the previous sibling or the
parent of this page
@return DocumentationPage|null | entailment |
private function handleCommandMessage(SabreAMF_AMF3_CommandMessage $request) {
switch($request->operation) {
case SabreAMF_AMF3_CommandMessage::CLIENT_PING_OPERATION :
$response = new SabreAMF_AMF3_AcknowledgeMessage($request);
break;
case SabreAMF_AMF3_CommandMessage::LOGIN_OPERATION :
$authData = base64_decode($request->body);
if ($authData) {
$authData = explode(':',$authData,2);
if (count($authData)==2) {
$this->authenticate($authData[0],$authData[1]);
}
}
$response = new SabreAMF_AMF3_AcknowledgeMessage($request);
$response->body = true;
break;
case SabreAMF_AMF3_CommandMessage::DISCONNECT_OPERATION :
$response = new SabreAMF_AMF3_AcknowledgeMessage($request);
break;
default :
throw new Exception('Unsupported CommandMessage operation: ' . $request->operation);
}
return $response;
} | handleCommandMessage
@param SabreAMF_AMF3_CommandMessage $request
@return Sabre_AMF3_AbstractMessage | entailment |
protected function authenticate($username,$password) {
if (is_callable($this->onAuthenticate)) {
call_user_func($this->onAuthenticate,$username,$password);
}
} | authenticate
@param string $username
@param string $password
@return void | entailment |
protected function invokeService($service,$method,$data) {
if (is_callable($this->onInvokeService)) {
return call_user_func_array($this->onInvokeService,array($service,$method,$data));
} else {
throw new Exception('onInvokeService is not defined or not callable');
}
} | invokeService
@param string $service
@param string $method
@param array $data
@return mixed | entailment |
public function exec() {
// First we'll be looping through the headers to see if there's anything we reconize
foreach($this->getRequestHeaders() as $header) {
switch($header['name']) {
// We found a credentials headers, calling the authenticate method
case 'Credentials' :
$this->authenticate($header['data']['userid'],$header['data']['password']);
break;
}
}
foreach($this->getRequests() as $request) {
// Default AMFVersion
$AMFVersion = 0;
$response = null;
try {
if (is_array($request['data']) && isset($request['data'][0]) && $request['data'][0] instanceof SabreAMF_AMF3_AbstractMessage) {
$request['data'] = $request['data'][0];
}
// See if we are dealing with the AMF3 messaging system
if (is_object($request['data']) && $request['data'] instanceof SabreAMF_AMF3_AbstractMessage) {
$AMFVersion = 3;
// See if we are dealing with a CommandMessage
if ($request['data'] instanceof SabreAMF_AMF3_CommandMessage) {
// Handle the command message
$response = $this->handleCommandMessage($request['data']);
}
// Is this maybe a RemotingMessage ?
if ($request['data'] instanceof SabreAMF_AMF3_RemotingMessage) {
// Yes
$response = new SabreAMF_AMF3_AcknowledgeMessage($request['data']);
$response->body = $this->invokeService($request['data']->source,$request['data']->operation,$request['data']->body);
}
} else {
// We are dealing with AMF0
$service = substr($request['target'],0,strrpos($request['target'],'.'));
$method = substr(strrchr($request['target'],'.'),1);
$response = $this->invokeService($service,$method,$request['data']);
}
$status = SabreAMF_Const::R_RESULT;
} catch (Exception $e) {
// We got an exception somewhere, ignore anything that has happened and send back
// exception information
if ($e instanceof SabreAMF_DetailException) {
$detail = $e->getDetail();
} else {
$detail = '';
}
switch($AMFVersion) {
case SabreAMF_Const::AMF0 :
$response = array(
'description' => $e->getMessage(),
'detail' => $detail,
'line' => $e->getLine(),
'code' => $e->getCode()?$e->getCode():get_class($e),
);
break;
case SabreAMF_Const::AMF3 :
$response = new SabreAMF_AMF3_ErrorMessage($request['data']);
$response->faultString = $e->getMessage();
$response->faultCode = $e->getCode();
$response->faultDetail = $detail;
break;
}
$status = SabreAMF_Const::R_STATUS;
}
$this->setResponse($request['response'],$status,$response);
}
$this->sendResponse();
} | exec
@return void | entailment |
public function getMsgBody()
{
$body = null;
if (!empty($this->_parts)) {
if (count($this->_parts) > 1) {
foreach ($this->_parts as $part) {
if ($part->contentType != Content::CT_TEXT_PLAIN && $this->getHeaders()->getMessageContentType() == Content::CT_MULTIPART_ALTERNATIVE) {
$body = $part->getContentDecode();
break;
}
$body .= PHP_EOL.$part->getContentDecode();
}
} else {
$body = $this->_parts[0]->getContentDecode();
}
}
return $body;
} | Текст письма
@return string|null | entailment |
public function getMsgAlternativeBody()
{
if (
!empty($this->_parts)
&& (
$this->getHeaders()->getMessageContentType() == Content::CT_MULTIPART_ALTERNATIVE
|| $this->getHeaders()->getMessageContentType() == Content::CT_MULTIPART_MIXED
)
) {
foreach ($this->_parts as $part) {
if ($part->contentType == Content::CT_TEXT_PLAIN) {
return $part->getContentDecode();
}
}
}
return null;
} | Альтернативный текст письма
@return string|null | entailment |
protected function parserContent($boundary, $content)
{
if ($boundary) {
$parts = preg_split('#--'.$boundary.'(--)?\s*#si', $content, -1, PREG_SPLIT_NO_EMPTY);
foreach ($parts as $part) {
$part = trim($part);
if (empty($part)) {
continue;
}
if (preg_match('/(Content-Type:)(.*)/i', $part, $math)) {
if (preg_match(Headers::BOUNDARY_PATTERN, str_replace("\r\n\t", ' ', $part), $subBoundary)) {
if ($subBoundary[1] != $boundary) {
$this->parserContent($subBoundary[1], $part);
} else {
continue;
}
} else {
$data = explode(';', $math[2]);
$type = trim($data[0]);
$isAttachment = (strpos($part, 'Content-Disposition: attachment;') !== false);
//get body message
if (($type == Content::CT_MULTIPART_ALTERNATIVE || $type == Content::CT_TEXT_HTML || $type == Content::CT_TEXT_PLAIN
|| $type == Content::CT_MESSAGE_DELIVERY)
&& !$isAttachment
) {
$this->parserBodyMessage($part);
} elseif ($type == Content::CT_MESSAGE_RFC822) {
$this->parserBodyMessage($part);
$this->parserAttachment($part);
} else { //attachment
$this->parserAttachment($part);
}
}
}
}
} else {
$content = new Content();
$content->content = $this->_content;
$content->charset = $this->_header->getCharset();
$content->contentType = $this->getHeaders()->getMessageContentType();
$content->transferEncoding = $this->_header->getTransferEncoding();
$this->_parts[] = $content;
}
} | Разбор тела сообщения
@param string $boundary
@param string $content | entailment |
public function toUtf8($string)
{
$encode = mb_detect_encoding(
$string, [
'UTF-8',
'Windows-1251'
]
);
if ($encode && $encode !== 'UTF-8') {
$string = mb_convert_encoding($string, 'UTF-8', $encode);
}
if (!$this->detectUTF8($string)) {
//Скорей всего кодировка не utf-8, пробуем перегнать из 1251
$tmpName = mb_convert_encoding($string, 'UTF-8', 'Windows-1251');
if ($this->detectUTF8($tmpName)) {
$string = $tmpName;
}
}
return $string;
} | Конвертация в utf-8
@param $string
@return false|string|string[]|null | entailment |
protected function decodeFileName($data)
{
array_shift($data);
if (count($data) == 1) {
$name = preg_replace('#.*name\s*\=\s*[\'"]([^\'"]+).*#si', '$1', $data[0]);
} elseif (count($data) > 1) {
foreach ($data as $value) {
if (preg_match(self::FILE_PATTERN, $value, $res)) {
$name = $res[3];
}
}
} else {
return null;
}
$tmpFileName = Headers::decodeMimeString($name);
//TODO не очень хорошее решение, если кто предложит лучше, готов рассмотреть
// Content-Disposition: attachment; filename*=UTF-8''%D0%B7%D0%B0%D1%8F%D0%B2%D0%BA%D0%B0%20%D0%95%D0%B2%D1%80%D0%BE%D0%94%D0%BE%D0%BD%208%D1%84%D0%B5%D0%B2%D1%802017%2Exls
if ($tmpFileName === $name) {
$tmp = explode("''", $name);
if (count($tmp) > 1) {
$tmpFileName = urldecode($tmp[1]);
}
}
return $this->toUtf8($tmpFileName);
} | @param array $data
@return string | entailment |
public function getCustomAttribute($blockThis, $block, $attributeCode)
{
if($this->isEditForm($blockThis)){
$attribute = $block->getCustomer()->getCustomAttribute($attributeCode);
$value = $attribute ? $attribute->getValue() : null;
return $value;
} else {
return $block->getFormData()->getAttribute($attributeCode);
}
} | /*
Return the attribute value for customer,
or Form Data Attribute
@param $blockThis
@param $block
@param $attributeCode
@return string | entailment |
protected function configure()
{
$this
->setName('atoum')
->setDescription('Launch atoum tests.')
->setHelp(<<<EOF
Launch tests of AcmeFooBundle:
<comment>./app/console atoum AcmeFooBundle</comment>
Launch tests of many bundles:
<comment>./app/console atoum AcmeFooBundle bundle_alias_extension ...</comment>
Launch tests of all bundles defined on configuration:
<comment>./app/console atoum</comment>
EOF
)
->addArgument('bundles', InputArgument::IS_ARRAY, 'Launch tests of these bundles.')
->addOption('bootstrap-file', 'bf', InputOption::VALUE_REQUIRED, 'Define the bootstrap file')
->addOption('no-code-coverage', 'ncc', InputOption::VALUE_NONE, 'Disable code coverage (big speed increase)')
->addOption('use-light-report', null, InputOption::VALUE_NONE, 'Reduce the output generated')
->addOption('max-children-number', 'mcn', InputOption::VALUE_REQUIRED, 'Maximum number of sub-processus which will be run simultaneously')
->addOption('xunit-report-file', 'xrf', InputOption::VALUE_REQUIRED, 'Define the xunit report file')
->addOption('clover-report-file', 'crf', InputOption::VALUE_REQUIRED, 'Define the clover report file')
->addOption('loop', 'l', InputOption::VALUE_NONE, 'Enables Atoum loop mode')
->addOption('force-terminal', '', InputOption::VALUE_NONE, '')
->addOption('score-file', '', InputOption::VALUE_REQUIRED, '')
->addOption('debug', 'd', InputOption::VALUE_NONE, 'Enables Atoum debug mode')
;
} | {@inheritdoc} | entailment |
protected function execute(InputInterface $input, OutputInterface $output)
{
$runner = new Runner('atoum');
$bundles = $input->getArgument('bundles');
if (count($bundles) > 0) {
foreach ($bundles as $k => $bundleName) {
$bundles[$k] = $this->extractBundleConfigurationFromKernel($bundleName);
}
} else {
$bundles = $this->getContainer()->get('atoum.configuration.bundle.container')->all();
}
foreach ($bundles as $bundle) {
$directories = array_filter($bundle->getDirectories(), function ($dir) {
return is_dir($dir);
});
if (empty($directories)) {
$output->writeln(sprintf('<error>There is no test found on "%s".</error>', $bundle->getName()));
}
foreach ($directories as $directory) {
$runner->getRunner()->addTestsFromDirectory($directory);
}
}
$defaultBootstrap = sprintf('%s/autoload.php', $this->getApplication()->getKernel()->getRootDir());
$bootstrap = $input->getOption('bootstrap-file') ? : $defaultBootstrap;
$this->setAtoumArgument('--bootstrap-file', $bootstrap);
if ($input->getOption('no-code-coverage')) {
$this->setAtoumArgument('-ncc');
}
if ($input->getOption('use-light-report')) {
$this->setAtoumArgument('-ulr');
}
if ($input->getOption('max-children-number')) {
$this->setAtoumArgument('--max-children-number', (int) $input->getOption('max-children-number'));
}
if ($input->getOption('xunit-report-file')) {
$xunit = new \mageekguy\atoum\reports\asynchronous\xunit();
$runner->addReport($xunit);
$writerXunit = new \mageekguy\atoum\writers\file($input->getOption('xunit-report-file'));
$xunit->addWriter($writerXunit);
}
if ($input->getOption('clover-report-file')) {
$clover = new \mageekguy\atoum\reports\asynchronous\clover();
$runner->addReport($clover);
$writerClover = new \mageekguy\atoum\writers\file($input->getOption('clover-report-file'));
$clover->addWriter($writerClover);
}
if ($input->getOption('xunit-report-file') || $input->getOption('clover-report-file')) {
$reportCli = new \mageekguy\atoum\reports\realtime\cli();
$runner->addReport($reportCli);
$writerCli = new \mageekguy\atoum\writers\std\out();
$reportCli->addWriter($writerCli);
}
try {
$score = $runner->run($this->getAtoumArguments())->getRunner()->getScore();
$isSuccess = $score->getFailNumber() <= 0 && $score->getErrorNumber() <= 0 && $score->getExceptionNumber() <= 0;
if ($runner->shouldFailIfVoidMethods() && $score->getVoidMethodNumber() > 0)
{
$isSuccess = false;
}
if ($runner->shouldFailIfSkippedMethods() && $score->getSkippedMethodNumber() > 0)
{
$isSuccess = false;
}
return $isSuccess ? 0 : 1;
} catch (\Exception $exception) {
$this->getApplication()->renderException($exception, $output);
return 2;
}
if ($input->getOption('loop')) {
$this->setAtoumArgument('--loop');
}
if ($input->getOption('force-terminal')) {
$this->setAtoumArgument('--force-terminal');
}
if ($input->getOption('score-file')) {
$this->setAtoumArgument('--score-file', $input->getOption('score-file'));
}
if ($input->getOption('debug')) {
$this->setAtoumArgument('--debug');
}
$runner->run($this->getAtoumArguments());
} | {@inheritdoc} | entailment |
protected function getAtoumArguments()
{
$inlinedArguments = array();
foreach ($this->atoumArguments as $name => $values) {
$inlinedArguments[] = $name;
if (null !== $values) {
$inlinedArguments[] = $values;
}
}
return $inlinedArguments;
} | Return inlined atoum cli arguments
@return array | entailment |
public function extractBundleConfigurationFromKernel($name)
{
$kernelBundles = $this->getContainer()->get('kernel')->getBundles();
$bundle = null;
if (preg_match('/Bundle$/', $name)) {
if (!isset($kernelBundles[$name])) {
throw new \LogicException(sprintf('Bundle "%s" does not exists or is not activated.', $name));
}
$bundle = $kernelBundles[$name];
} else {
foreach ($kernelBundles as $kernelBundle) {
$extension = $kernelBundle->getContainerExtension();
if ($extension && $extension->getAlias() == $name) {
$bundle = $kernelBundle;
break;
}
}
if (null === $bundle) {
throw new \LogicException(sprintf('Bundle with alias "%s" does not exists or is not activated.', $name));
}
}
$bundleContainer = $this->getContainer()->get('atoum.configuration.bundle.container');
if ($bundleContainer->has($bundle->getName())) {
return $bundleContainer->get($bundle->getName());
} else {
return new BundleConfiguration($bundle->getName(), $this->getDefaultDirectoriesForBundle($bundle));
}
} | @param string $name name
@throws \LogicException
@return BundleConfiguration | entailment |
public function getContent($url, $method = 'GET', array $headers = array(), $data = array())
{
if (is_array($data)) {
$data = $this->encodePostData($data);
}
try {
$response = $this->browser->call($url, $method, $headers, $data);
} catch (\Exception $e) {
return null;
}
return $response ? $response->getContent() : null;
} | {@inheritDoc} | entailment |
public function getResponseObject(string $class, string $json)
{
$object = $this->deserialize($class, $json);
$this->assertValid($object, ValidationException::RESPONSE);
return $object;
} | @param string $class
@param string $json
@throws ValidationException
@throws ParseException
@return mixed | entailment |
public function getRequestString($object): string
{
$this->assertValid($object, ValidationException::RESPONSE);
return $this->serializeBodyObject($object);
} | @param mixed $object
@throws ValidationException
@throws ParseException
@return string | entailment |
private function deserialize(string $class, string $json)
{
try {
return $this->serializer->deserialize($json, $class, 'atol_client');
} catch (\RuntimeException $exception) {
throw ParseException::becauseOfRuntimeException($exception, ParseException::RESPONSE);
}
} | @param string $class
@param string $json
@throws ParseException
@return mixed | entailment |
private function assertValid($object, int $code = 0)
{
$errors = $this->validator->validate($object);
if (count($errors)) {
throw ValidationException::becauseOfValidationErrors($errors, $code);
}
} | Assert that object is valid.
@param mixed $object
@param int $code
@throws ValidationException | entailment |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.