sentence1
stringlengths
52
3.87M
sentence2
stringlengths
1
47.2k
label
stringclasses
1 value
public function writeByte($byte) { // We do not need to check if file position points to the end of "file". // Only append operation is supported now $this->_data .= chr($byte); $this->_position = strlen($this->_data); return 1; }
Writes a byte to the end of the file. @param integer $byte
entailment
public function readBytes($num) { $returnValue = substr($this->_data, $this->_position, $num); $this->_position += $num; return $returnValue; }
Read num bytes from the current position in the file and advances the file pointer. @param integer $num @return string
entailment
public function writeBytes($data, $num=null) { // We do not need to check if file position points to the end of "file". // Only append operation is supported now if ($num !== null) { $this->_data .= substr($data, 0, $num); } else { $this->_data .= $data; } $this->_position = strlen($this->_data); }
Writes num bytes of data (all, if $num===null) to the end of the string. @param string $data @param integer $num
entailment
public function readInt() { $str = substr($this->_data, $this->_position, 4); $this->_position += 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) { // We do not need to check if file position points to the end of "file". // Only append operation is supported now settype($value, 'integer'); $this->_data .= chr($value>>24 & 0xFF) . chr($value>>16 & 0xFF) . chr($value>>8 & 0xFF) . chr($value & 0xFF); $this->_position = strlen($this->_data); }
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 = substr($this->_data, $this->_position, 8); $this->_position += 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 @throws Zend_Search_Lucene_Exception
entailment
public function writeLong($value) { // We do not need to check if file position points to the end of "file". // Only append operation is supported now /** * 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->_data .= 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); } else { $this->writeLong32Bit($value); } $this->_position = strlen($this->_data); }
Writes long integer to the end of file @param integer $value @throws Zend_Search_Lucene_Exception
entailment
public function readVInt() { $nextByte = ord($this->_data[$this->_position++]); $val = $nextByte & 0x7F; for ($shift=7; ($nextByte & 0x80) != 0; $shift += 7) { $nextByte = ord($this->_data[$this->_position++]); $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) { // We do not need to check if file position points to the end of "file". // Only append operation is supported now settype($value, 'integer'); while ($value > 0x7F) { $this->_data .= chr(($value & 0x7F)|0x80); $value >>= 7; } $this->_data .= chr($value); $this->_position = strlen($this->_data); }
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 = substr($this->_data, $this->_position, $strlen); $this->_position += $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 .= substr($this->_data, $this->_position, $addBytes); $this->_position += $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 readBinary() { $length = $this->readVInt(); $returnValue = substr($this->_data, $this->_position, $length); $this->_position += $length; return $returnValue; }
Reads binary data from the current position in the file and advances the file pointer. @return string
entailment
public function send($recipient, $body, $originator = '') { if (null == $this->client_id) { throw new InvalidCredentialsException('No API credentials provided'); } return parent::send($recipient, $body, $originator); }
{@inheritDoc}
entailment
protected function _less($termsStream1, $termsStream2) { return strcmp($termsStream1->currentTerm()->key(), $termsStream2->currentTerm()->key()) < 0; }
Compare elements Returns true, if $termsStream1 is "less" than $termsStream2; else otherwise @param mixed $termsStream1 @param mixed $termsStream2 @return boolean
entailment
public function register() { $this->mergeConfigFrom(__DIR__ . '/config/settings.php', 'settings'); $this->app->singleton('settings', function ($app) { $config = $app->config->get('settings', require __DIR__ . '/config/settings.php'); return new DatabaseRepository( $app['db'], new CacheRepository($config['cache_file']), $config ); }); }
Register the service provider. @return void
entailment
public function getStatus() { if (null === $this->username || null === $this->password) { throw new Exception\InvalidCredentialsException('No API credentials provided'); } $res = $this->getAdapter()->getContent(self::SMS_STATUS_URL, 'POST', $headers = array(), $this->getParameters()); return $this->parseStatusResults($res); }
Retrieves the queued delivery receipts @return array
entailment
public function send($recipient, $body, $originator = '', $user_ref = null) { if (null === $this->username || null === $this->password) { throw new Exception\InvalidCredentialsException('No API credentials provided'); } $params = $this->getParameters(array( 'DA' => $recipient, 'SA' => $originator, 'UR' => $user_ref, 'M' => $this->getMessage($body), )); $extra_result_data = array( 'recipient' => $recipient, 'body' => $body, 'originator' => $originator, ); $res = $this->getAdapter()->getContent(self::SEND_SMS_URL, 'POST', $headers = array(), $params); if (null === $res) { return array_merge($this->getDefaults(), $extra_result_data); } return $this->parseSendResults($res, $extra_result_data); }
{@inheritDoc}
entailment
protected function getParameters(array $additionnal_parameters = array()) { return array_filter( array_merge(array( /* * -- system type * Must be set to value: H */ 'S' => 'H', /* * Account username (case sensitive) */ 'UN' => $this->username, /* * Account password (case sensitive) */ 'P' => $this->password, /* * -- dest addr * Destination mobile number in * international format without + prefix. * Up to 10 different numbers can be * supplied separated by commas. */ 'DA' => null, /* * -- source addr * Originator address (sender id). Up to * 16 numeric or 11 alphanumeric * characters. */ 'SA' => null, /* * -- message * The SMS text for plain messages or * UCS2 hex for Unicode. For binary, * hex encoded 8-bit data. */ 'M' => null, /* * -- user data header * Hex encoded UDH to be used with * binary messages. */ 'UD' => null, /* * user reference * -- Unique reference supplied by user to * aid with matching delivery receipts. * Maximum 16 alphanumeric characters * including _ and -. */ 'UR' => null, /* * -- validity period * The number of minutes to attempt * delivery before the message expires. * Maximum 10080 * Default 1440 */ 'VP' => null, 'V' => null, /* * -- source addr ton * Controls the type of originator where: * 1 = International numeric (eg. +447000000000) * 0 = National numeric (eg. 80050) * 5 = Alphanumeric (eg. CallNow) */ 'ST' => null, /* * delay until */ 'DU' => null, /* * local time */ 'LC' => null, /* * -- data coding scheme * 0 - Flash * 1 - Normal (default) * 2 - Binary * 4 - UCS2 * 5 - Flash UCS2 * 6 - Flash GSM * 7 - Normal GSM */ 'DC' => 0, /* * -- delivery receipt * Controls whether a delivery receipt is * requested for this message where: * 0 = No (default) * 1 = Yes * 2 = Record Only */ 'DR' => null, ), $additionnal_parameters ), array($this, 'isNotNull') ); }
Builds the parameters list to send to the API. @return array
entailment
protected function parseStatusResults($result, array $extra_result_data = array()) { $result = trim($result); $this->checkForUnrecoverableError($result); return $this->checkForStatusResult($result); }
Parses the data returned by the API for a "status" request. @param string $result The raw result string. @param array $extra_result_data @return array
entailment
protected function parseSendResults($result, array $extra_result_data = array()) { $result = trim($result); $this->checkForUnrecoverableError($result); if (!$this->isMessageSent($result)) { return array_merge($this->getDefaults(), $extra_result_data); } // The message was successfully sent! $sms_data = array( 'status' => ResultInterface::STATUS_SENT, ); $arr = explode(' ', $result); if (3 === count($arr)) { // eg. OK 375055 UR:LO_5 list($_, $ref) = explode(':', $arr[2]); $sms_data['id'] = $arr[1]; $sms_data['user_ref'] = $ref; } elseif (2 === count($arr)) { // eg. OK 375056 $sms_data['id'] = $arr[1]; } return array_merge($this->getDefaults(), $extra_result_data, $sms_data); }
Parses the data returned by the API for a "send" request. @param string $result The raw result string. @param array $extra_result_data @return array
entailment
function get($key, $default = null) { if (!is_string($key)) { throw new InvalidArgumentException('$key must be a string'); } $result = $this->memcached->get($key); if ($result === false && $this->memcached->getResultCode() === \Memcached::RES_NOTFOUND) { return $default; } return $result; }
Fetches a value from the cache. @param string $key The unique key of this item in the cache. @param mixed $default Default value to return if the key does not exist. @throws \Psr\SimpleCache\InvalidArgumentException MUST be thrown if the $key string is not a legal value. @return mixed The value of the item from the cache, or $default in case of cache miss.
entailment
function has($key) { if (!is_string($key)) { throw new InvalidArgumentException('$key must be a string'); } $result = $this->memcached->get($key); if ($result === false && $this->memcached->getResultCode() === \Memcached::RES_NOTFOUND) { return false; } return true; }
Determines whether an item is present in the cache. NOTE: It is recommended that has() is only to be used for cache warming type purposes and not to be used within your live applications operations for get/set, as this method is subject to a race condition where your has() will return true and immediately after, another script can remove it making the state of your app out of date. @param string $key The cache item key. @throws \Psr\SimpleCache\InvalidArgumentException MUST be thrown if the $key string is not a legal value. @return bool
entailment
function getMultiple($keys, $default = null) { if ($keys instanceof Traversable) { $keys = iterator_to_array($keys); } elseif (!is_array($keys)) { throw new InvalidArgumentException('$keys must be iterable'); } $result = $this->memcached->getMulti($keys); foreach ($keys as $key) { if (!isset($result[$key])) { $result[$key] = $default; } } return $result; }
Obtains multiple cache items by their unique keys. This particular implementation returns its result as a generator. @param iterable $keys A list of keys that can obtained in a single operation. @param mixed $default Default value to return for keys that do not exist. @throws \Psr\SimpleCache\InvalidArgumentException MUST be thrown if $keys is neither an array nor a Traversable, or if any of the $keys are not a legal value. @return iterable A list of key => value pairs. Cache keys that do not exist or are stale will have $default as value.
entailment
function setMultiple($values, $ttl = null) { if ($values instanceof Traversable) { $values = iterator_to_array($values); } elseif (!is_array($values)) { throw new InvalidArgumentException('$values must be iterable'); } if ($ttl instanceof DateInterval) { $expire = (new DateTime('now'))->add($ttl)->getTimeStamp(); } elseif (is_int($ttl) || ctype_digit($ttl)) { $expire = time() + $ttl; } else { $expire = 0; } return $this->memcached->setMulti( $values, $expire ); }
Persists a set of key => value pairs in the cache, with an optional TTL. @param iterable $values A list of key => value pairs for a multiple-set operation. @param null|int|DateInterval $ttl Optional. The TTL value of this item. If no value is sent and the driver supports TTL then the library may set a default value for it or let the driver take care of that. @throws \Psr\SimpleCache\InvalidArgumentException MUST be thrown if $values is neither an array nor a Traversable, or if any of the $values are not a legal value. @return bool True on success and false on failure.
entailment
function deleteMultiple($keys) { if ($keys instanceof Traversable) { $keys = iterator_to_array($keys); } elseif (!is_array($keys)) { throw new InvalidArgumentException('$keys must be iterable'); } $this->memcached->deleteMulti($keys); }
Deletes multiple cache items in a single operation. @param iterable $keys A list of string-based keys to be deleted. @throws \Psr\SimpleCache\InvalidArgumentException MUST be thrown if $keys is neither an array nor a Traversable, or if any of the $keys are not a legal value. @return bool True if the items were successfully removed. False if there was an error.
entailment
public function setResponse($target,$responsetype,$data) { switch($responsetype) { case SabreAMF_Const::R_RESULT : $target = $target.='/onResult'; break; case SabreAMF_Const::R_STATUS : $target = $target.='/onStatus'; break; case SabreAMF_Const::R_DEBUG : $target = '/onDebugEvents'; break; } return $this->amfResponse->addBody(array('target'=>$target,'response'=>'','data'=>$data)); }
setResponse Send a response back to the client (based on a request you got through getRequests) @param string $target This parameter should contain the same as the 'response' item you got through getRequests. This connects the request to the response @param int $responsetype Set as either SabreAMF_Const::R_RESULT or SabreAMF_Const::R_STATUS, depending on if the call succeeded or an error was produced @param mixed $data The result data @return void
entailment
public function sendResponse() { header('Content-Type: ' . SabreAMF_Const::MIMETYPE); $this->amfResponse->setEncoding($this->amfRequest->getEncoding()); $this->amfResponse->serialize($this->amfOutputStream); echo($this->amfOutputStream->getRawData()); }
sendResponse Sends the responses back to the client. Call this after you answered all the requests with setResponse @return void
entailment
public function addHeader($name,$required,$data) { $this->amfResponse->addHeader(array('name'=>$name,'required'=>$required==true,'data'=>$data)); }
addHeader Add a header to the server response @param string $name @param bool $required @param mixed $data @return void
entailment
static public function setInputString($string) { if (!(is_string($string) && strlen($string) > 0)) throw new SabreAMF_InvalidAMFException(); self::$dataInputStream = null; self::$dataInputData = $string; return true; }
setInputString Returns the true/false depended on wheater the string was accepted. That a string is accepted by this method, does NOT mean that it is a valid AMF request. @param string $string New input string @author Asbjørn Sloth Tønnesen <[email protected]> @return bool
entailment
protected function readInput() { if (is_null(self::$dataInputStream)) return self::$dataInputData; $data = file_get_contents(self::$dataInputStream); if (!$data) throw new SabreAMF_InvalidAMFException(); return $data; }
readInput Reads the input from stdin unless it has been overwritten with setInputFile or setInputString. @author Asbjørn Sloth Tønnesen <[email protected]> @return string Binary string containing the AMF data
entailment
public function normalize(Zend_Search_Lucene_Analysis_Token $token) { foreach ($this->_filters as $filter) { $token = $filter->normalize($token); // resulting token can be null if the filter removes it if ($token === null) { return null; } } return $token; }
Apply filters to the token. Can return null when the token was removed. @param Zend_Search_Lucene_Analysis_Token $token @return Zend_Search_Lucene_Analysis_Token
entailment
public function withAddedInterceptor(string $name, array $functions): self { if (!isset($this->interceptors[$name])) { $this->interceptors[$name] = []; } $this->interceptors[$name] = array_merge($this->interceptors[$name], $functions); return $this; }
Add a function to the interceptor @param string $name @param callable|array $functions @return self|$this
entailment
public function removeInterceptor(string $name): self { if (isset($this->interceptors[$name])) { unset($this->interceptors[$name]); } return $this; }
Remove the interceptor @param string $name @return self|$this
entailment
public function callInterceptor(string $name, ...$arguments) { if (!empty($this->interceptors[$name])) { foreach ($this->interceptors[$name] as $function) { $ret = Helper::call($function, ...$arguments); if ($ret !== null) { return $ret; } } } return null; }
Call the interceptor @param string $name @param array ...$arguments @return mixed
entailment
public function prepare(array $query): array { if (isset($query['WHERE']) && sizeof($query['WHERE']) > 1) { $where = $query['WHERE']; $query['WHERE'] = [[ 'expr_type' => 'bracket_expression', 'base_expr' => '', 'sub_tree' => $where, ]]; foreach ($where as $where_data) { $query['WHERE'][0]['base_expr'] .= ' ' . $where_data['base_expr']; } $query['WHERE'][0]['base_expr'] = '(' . trim($query['WHERE'][0]['base_expr']) . ')'; } return $query; }
In case query contains a more complicated query, place it within brackets: (<complicated_expr>)
entailment
public static function parse($strQuery, $encoding = null) { self::_getInstance(); // Reset FSM if previous parse operation didn't return it into a correct state self::$_instance->reset(); include_once 'Zend/Search/Lucene/Search/QueryParserException.php'; try { include_once 'Zend/Search/Lucene/Search/QueryParserContext.php'; self::$_instance->_encoding = ($encoding !== null) ? $encoding : self::$_instance->_defaultEncoding; self::$_instance->_lastToken = null; self::$_instance->_context = new Zend_Search_Lucene_Search_QueryParserContext(self::$_instance->_encoding); self::$_instance->_contextStack = array(); self::$_instance->_tokens = self::$_instance->_lexer->tokenize($strQuery, self::$_instance->_encoding); // Empty query if (count(self::$_instance->_tokens) == 0) { include_once 'Zend/Search/Lucene/Search/Query/Insignificant.php'; return new Zend_Search_Lucene_Search_Query_Insignificant(); } foreach (self::$_instance->_tokens as $token) { try { self::$_instance->_currentToken = $token; self::$_instance->process($token->type); self::$_instance->_lastToken = $token; } catch (Exception $e) { if (strpos($e->getMessage(), 'There is no any rule for') !== false) { throw new Zend_Search_Lucene_Search_QueryParserException('Syntax error at char position ' . $token->position . '.', 0, $e); } include_once 'Zend/Search/Lucene/Exception.php'; throw new Zend_Search_Lucene_Exception($e->getMessage(), $e->getCode(), $e); } } if (count(self::$_instance->_contextStack) != 0) { throw new Zend_Search_Lucene_Search_QueryParserException('Syntax Error: mismatched parentheses, every opening must have closing.'); } return self::$_instance->_context->getQuery(); } catch (Zend_Search_Lucene_Search_QueryParserException $e) { if (self::$_instance->_suppressQueryParsingExceptions) { $queryTokens = Zend_Search_Lucene_Analysis_Analyzer::getDefault()->tokenize($strQuery, self::$_instance->_encoding); include_once 'Zend/Search/Lucene/Search/Query/MultiTerm.php'; $query = new Zend_Search_Lucene_Search_Query_MultiTerm(); $termsSign = (self::$_instance->_defaultOperator == self::B_AND) ? true /* required term */ : null /* optional term */; include_once 'Zend/Search/Lucene/Index/Term.php'; foreach ($queryTokens as $token) { $query->addTerm(new Zend_Search_Lucene_Index_Term($token->getTermText()), $termsSign); } return $query; } else { include_once 'Zend/Search/Lucene/Exception.php'; throw new Zend_Search_Lucene_Exception($e->getMessage(), $e->getCode(), $e); } } }
Parses a query string @param string $strQuery @param string $encoding @return Zend_Search_Lucene_Search_Query @throws Zend_Search_Lucene_Search_QueryParserException
entailment
public function addTermEntry() { include_once 'Zend/Search/Lucene/Search/QueryEntry/Term.php'; $entry = new Zend_Search_Lucene_Search_QueryEntry_Term($this->_currentToken->text, $this->_context->getField()); $this->_context->addEntry($entry); }
Add term to a query
entailment
public function addPhraseEntry() { include_once 'Zend/Search/Lucene/Search/QueryEntry/Phrase.php'; $entry = new Zend_Search_Lucene_Search_QueryEntry_Phrase($this->_currentToken->text, $this->_context->getField()); $this->_context->addEntry($entry); }
Add phrase to a query
entailment
public function processModifierParameter() { if ($this->_lastToken === null) { include_once 'Zend/Search/Lucene/Search/QueryParserException.php'; throw new Zend_Search_Lucene_Search_QueryParserException('Lexeme modifier parameter must follow lexeme modifier. Char position 0.'); } switch ($this->_lastToken->type) { case Zend_Search_Lucene_Search_QueryToken::TT_FUZZY_PROX_MARK: $this->_context->processFuzzyProximityModifier($this->_currentToken->text); break; case Zend_Search_Lucene_Search_QueryToken::TT_BOOSTING_MARK: $this->_context->boost($this->_currentToken->text); break; default: // It's not a user input exception include_once 'Zend/Search/Lucene/Exception.php'; throw new Zend_Search_Lucene_Exception('Lexeme modifier parameter must follow lexeme modifier. Char position 0.'); } }
Process modifier parameter @throws Zend_Search_Lucene_Exception
entailment
public function subqueryStart() { include_once 'Zend/Search/Lucene/Search/QueryParserContext.php'; $this->_contextStack[] = $this->_context; $this->_context = new Zend_Search_Lucene_Search_QueryParserContext($this->_encoding, $this->_context->getField()); }
Start subquery
entailment
public function subqueryEnd() { if (count($this->_contextStack) == 0) { include_once 'Zend/Search/Lucene/Search/QueryParserException.php'; throw new Zend_Search_Lucene_Search_QueryParserException('Syntax Error: mismatched parentheses, every opening must have closing. Char position ' . $this->_currentToken->position . '.'); } $query = $this->_context->getQuery(); $this->_context = array_pop($this->_contextStack); include_once 'Zend/Search/Lucene/Search/QueryEntry/Subquery.php'; $this->_context->addEntry(new Zend_Search_Lucene_Search_QueryEntry_Subquery($query)); }
End subquery
entailment
public function openedRQLastTerm() { $tokens = Zend_Search_Lucene_Analysis_Analyzer::getDefault()->tokenize($this->_rqFirstTerm, $this->_encoding); if (count($tokens) > 1) { include_once 'Zend/Search/Lucene/Search/QueryParserException.php'; throw new Zend_Search_Lucene_Search_QueryParserException('Range query boundary terms must be non-multiple word terms'); } else if (count($tokens) == 1) { include_once 'Zend/Search/Lucene/Index/Term.php'; $from = new Zend_Search_Lucene_Index_Term(reset($tokens)->getTermText(), $this->_context->getField()); } else { $from = null; } $tokens = Zend_Search_Lucene_Analysis_Analyzer::getDefault()->tokenize($this->_currentToken->text, $this->_encoding); if (count($tokens) > 1) { include_once 'Zend/Search/Lucene/Search/QueryParserException.php'; throw new Zend_Search_Lucene_Search_QueryParserException('Range query boundary terms must be non-multiple word terms'); } else if (count($tokens) == 1) { include_once 'Zend/Search/Lucene/Index/Term.php'; $to = new Zend_Search_Lucene_Index_Term(reset($tokens)->getTermText(), $this->_context->getField()); } else { $to = null; } if ($from === null && $to === null) { include_once 'Zend/Search/Lucene/Search/QueryParserException.php'; throw new Zend_Search_Lucene_Search_QueryParserException('At least one range query boundary term must be non-empty term'); } include_once 'Zend/Search/Lucene/Search/Query/Range.php'; $rangeQuery = new Zend_Search_Lucene_Search_Query_Range($from, $to, false); include_once 'Zend/Search/Lucene/Search/QueryEntry/Subquery.php'; $entry = new Zend_Search_Lucene_Search_QueryEntry_Subquery($rangeQuery); $this->_context->addEntry($entry); }
Process last range query term (opened interval) @throws Zend_Search_Lucene_Search_QueryParserException
entailment
public function rewrite(Zend_Search_Lucene_Interface $index) { if ($this->_field === null) { include_once 'Zend/Search/Lucene/Search/Query/Boolean.php'; $query = new Zend_Search_Lucene_Search_Query_Boolean(); $hasInsignificantSubqueries = false; include_once 'Zend/Search/Lucene.php'; if (Zend_Search_Lucene::getDefaultSearchField() === null) { $searchFields = $index->getFieldNames(true); } else { $searchFields = array(Zend_Search_Lucene::getDefaultSearchField()); } include_once 'Zend/Search/Lucene/Search/Query/Preprocessing/Fuzzy.php'; foreach ($searchFields as $fieldName) { $subquery = new Zend_Search_Lucene_Search_Query_Preprocessing_Fuzzy( $this->_word, $this->_encoding, $fieldName, $this->_minimumSimilarity ); $rewrittenSubquery = $subquery->rewrite($index); if (!($rewrittenSubquery instanceof Zend_Search_Lucene_Search_Query_Insignificant || $rewrittenSubquery instanceof Zend_Search_Lucene_Search_Query_Empty) ) { $query->addSubquery($rewrittenSubquery); } if ($rewrittenSubquery instanceof Zend_Search_Lucene_Search_Query_Insignificant) { $hasInsignificantSubqueries = true; } } $subqueries = $query->getSubqueries(); if (count($subqueries) == 0) { $this->_matches = array(); if ($hasInsignificantSubqueries) { include_once 'Zend/Search/Lucene/Search/Query/Insignificant.php'; return new Zend_Search_Lucene_Search_Query_Insignificant(); } else { include_once 'Zend/Search/Lucene/Search/Query/Empty.php'; return new Zend_Search_Lucene_Search_Query_Empty(); } } if (count($subqueries) == 1) { $query = reset($subqueries); } $query->setBoost($this->getBoost()); $this->_matches = $query->getQueryTerms(); return $query; } // ------------------------------------- // Recognize exact term matching (it corresponds to Keyword fields stored in the index) // encoding is not used since we expect binary matching include_once 'Zend/Search/Lucene/Index/Term.php'; $term = new Zend_Search_Lucene_Index_Term($this->_word, $this->_field); if ($index->hasTerm($term)) { include_once 'Zend/Search/Lucene/Search/Query/Fuzzy.php'; $query = new Zend_Search_Lucene_Search_Query_Fuzzy($term, $this->_minimumSimilarity); $query->setBoost($this->getBoost()); // Get rewritten query. Important! It also fills terms matching container. $rewrittenQuery = $query->rewrite($index); $this->_matches = $query->getQueryTerms(); return $rewrittenQuery; } // ------------------------------------- // Recognize wildcard queries /** * @todo check for PCRE unicode support may be performed through Zend_Environment in some future */ if (@preg_match('/\pL/u', 'a') == 1) { $subPatterns = preg_split('/[*?]/u', iconv($this->_encoding, 'UTF-8', $this->_word)); } else { $subPatterns = preg_split('/[*?]/', $this->_word); } if (count($subPatterns) > 1) { include_once 'Zend/Search/Lucene/Search/QueryParserException.php'; throw new Zend_Search_Lucene_Search_QueryParserException('Fuzzy search doesn\'t support wildcards (except within Keyword fields).'); } // ------------------------------------- // Recognize one-term multi-term and "insignificant" queries include_once 'Zend/Search/Lucene/Analysis/Analyzer.php'; $tokens = Zend_Search_Lucene_Analysis_Analyzer::getDefault()->tokenize($this->_word, $this->_encoding); if (count($tokens) == 0) { $this->_matches = array(); include_once 'Zend/Search/Lucene/Search/Query/Insignificant.php'; return new Zend_Search_Lucene_Search_Query_Insignificant(); } if (count($tokens) == 1) { include_once 'Zend/Search/Lucene/Index/Term.php'; $term = new Zend_Search_Lucene_Index_Term($tokens[0]->getTermText(), $this->_field); include_once 'Zend/Search/Lucene/Search/Query/Fuzzy.php'; $query = new Zend_Search_Lucene_Search_Query_Fuzzy($term, $this->_minimumSimilarity); $query->setBoost($this->getBoost()); // Get rewritten query. Important! It also fills terms matching container. $rewrittenQuery = $query->rewrite($index); $this->_matches = $query->getQueryTerms(); return $rewrittenQuery; } // Word is tokenized into several tokens include_once 'Zend/Search/Lucene/Search/QueryParserException.php'; throw new Zend_Search_Lucene_Search_QueryParserException('Fuzzy search is supported only for non-multiple word terms'); }
Re-write query into primitive queries in the context of specified index @param Zend_Search_Lucene_Interface $index @return Zend_Search_Lucene_Search_Query
entailment
protected function _highlightMatches(Zend_Search_Lucene_Search_Highlighter_Interface $highlighter) { /** * Skip fields detection. We don't need it, since we expect all fields presented in the HTML body and don't differentiate them */ /** * Skip exact term matching recognition, keyword fields highlighting is not supported */ // ------------------------------------- // Recognize wildcard queries /** * @todo check for PCRE unicode support may be performed through Zend_Environment in some future */ if (@preg_match('/\pL/u', 'a') == 1) { $subPatterns = preg_split('/[*?]/u', iconv($this->_encoding, 'UTF-8', $this->_word)); } else { $subPatterns = preg_split('/[*?]/', $this->_word); } if (count($subPatterns) > 1) { // Do nothing return; } // ------------------------------------- // Recognize one-term multi-term and "insignificant" queries include_once 'Zend/Search/Lucene/Analysis/Analyzer.php'; $tokens = Zend_Search_Lucene_Analysis_Analyzer::getDefault()->tokenize($this->_word, $this->_encoding); if (count($tokens) == 0) { // Do nothing return; } if (count($tokens) == 1) { include_once 'Zend/Search/Lucene/Index/Term.php'; $term = new Zend_Search_Lucene_Index_Term($tokens[0]->getTermText(), $this->_field); include_once 'Zend/Search/Lucene/Search/Query/Fuzzy.php'; $query = new Zend_Search_Lucene_Search_Query_Fuzzy($term, $this->_minimumSimilarity); $query->_highlightMatches($highlighter); return; } // Word is tokenized into several tokens // But fuzzy search is supported only for non-multiple word terms // Do nothing }
Query specific matches highlighting @param Zend_Search_Lucene_Search_Highlighter_Interface $highlighter Highlighter object (also contains doc for highlighting)
entailment
protected function cached(string $key, Closure $dataGetter) { if ($this->cacheRepository->has($key)) { return $this->cacheRepository->get($key); } $result = $dataGetter(); $this->cacheRepository->put($key, $result, $this->cacheTimeout); return $result; }
Get data from cache. If it not exists in cache got it in repository and store in cache. @param string $key Key to find data in cache @param Closure $dataGetter Function to get data in original repository @return mixed
entailment
public function findOrFail($id): Model { $result = $this->cachedFind($id); if (!$result) { throw new ModelNotFoundException($this, "{$this->repository->getModelClass()} with ID=$id was not found"); } return $result; }
{@inheritdoc}
entailment
public function findWhere(array $fieldValues): ?Model { $key = $this->prefix . ":find:" . md5(serialize($fieldValues)); return $this->cached($key, function () use ($fieldValues) { return $this->repository->findWhere($fieldValues); }); }
{@inheritdoc}
entailment
public function save(Model $model): Model { $result = $this->repository->save($model); $this->invalidate($model); return $result; }
{@inheritdoc}
entailment
public function delete(Model $model): void { $this->repository->delete($model); $this->invalidate($model); }
{@inheritdoc}
entailment
public function getWhere(array $fieldValues): Collection { $key = $this->prefix . ":get:" . md5(serialize($fieldValues)); return $this->cached($key, function () use ($fieldValues) { return $this->repository->getWhere($fieldValues); }); }
{@inheritdoc}
entailment
public function getPage(PagingInfo $paging, array $fieldValues = []): LengthAwarePaginator { $key = $this->prefix . ":page:" . md5(serialize($paging->toArray()) . serialize($fieldValues)); return $this->cached($key, function () use ($paging, $fieldValues) { return $this->repository->getPage($paging, $fieldValues); }); }
{@inheritdoc}
entailment
public function getCursorPage(CursorRequest $cursor, array $fieldValues = []): CursorResult { $key = $this->prefix . ":page:" . md5(serialize($cursor->toArray()) . serialize($fieldValues)); return $this->cached($key, function () use ($cursor, $fieldValues) { return $this->repository->getCursorPage($cursor, $fieldValues); }); }
{@inheritdoc}
entailment
private function find($id): ?Model { try { return $this->repository->findOrFail($id); } catch (ModelNotFoundException $exception) { return null; } }
Find model in original repository. @param string|int id Id to find @return Model|null @throws RepositoryException
entailment
protected function invalidate(Model $model): void { $key = $this->prefix . ":" . $model->getKey(); if ($this->cacheRepository->has($key)) { $this->cacheRepository->forget($key); } $this->cacheRepository->forget("$this->prefix.:all"); }
Invalidate model in cache. @param Model $model Model to invalidate @return void @throws InvalidArgumentException
entailment
public function getWith( array $with, array $withCounts = [], array $where = [], ?SortOptions $sortOptions = null ): Collection { $key = $this->prefix . ":get:" . md5(serialize($with) . serialize($withCounts) . serialize($where)); return $this->cached($key, function () use ($with, $withCounts, $where, $sortOptions) { return $this->repository->getWith($with, $withCounts, $where, $sortOptions); }); }
{@inheritdoc}
entailment
public function count(array $fieldValues = []): int { $key = $this->prefix . ":all:count"; return $this->cached($key, function () use ($fieldValues) { return $this->repository->count($fieldValues); }); }
{@inheritdoc}
entailment
public function setMax(string $key, int $max_size = -1): int { $is_exist = !$this->init($key, $max_size); if ($is_exist && $this->resource_map[$key] instanceof Channel) { $current_max = $this->status_map[$key]['max']; $this->status_map[$key]['max'] = $max_size; if ($max_size > $current_max || $max_size < 0) { // expend or unlimited if ($max_size < 0) { // chan to queue $new_pool = new SplQueue(); } else { $new_pool = new Channel($max_size); } $old_chan = $this->resource_map[$key]; while (!$old_chan->isEmpty()) { $new_pool->push($old_chan->pop()); } $old_chan->close(); return 1; // expend } elseif ($max_size < $this->status_map[$key]['max']) { return -1; // reduce } } return 0; // do nothing }
expend will create the new chan @param string $key @param int $max_size @return int do what
entailment
public static function mkdirs($dir, $mode = 0777, $recursive = true) { if (($dir === null) || $dir === '') { return false; } if (is_dir($dir) || $dir === '/') { return true; } if (self::mkdirs(dirname($dir), $mode, $recursive)) { return mkdir($dir, $mode); } return false; }
Utility function to recursive directory creation @param string $dir @param integer $mode @param boolean $recursive @return boolean
entailment
public function fileList() { $result = array(); $dirContent = opendir($this->_dirPath); while (($file = readdir($dirContent)) !== false) { if (($file == '..')||($file == '.')) { continue; } if(!is_dir($this->_dirPath . '/' . $file) ) { $result[] = $file; } } closedir($dirContent); return $result; }
Returns an array of strings, one for each file in the directory. @return array
entailment
public function createFile($filename) { if (isset($this->_fileHandlers[$filename])) { $this->_fileHandlers[$filename]->close(); } unset($this->_fileHandlers[$filename]); include_once 'Zend/Search/Lucene/Storage/File/Filesystem.php'; $this->_fileHandlers[$filename] = new Zend_Search_Lucene_Storage_File_Filesystem($this->_dirPath . '/' . $filename, 'w+b'); // Set file permissions, but don't care about any possible failures, since file may be already // created by anther user which has to care about right permissions @chmod($this->_dirPath . '/' . $filename, self::$_defaultFilePermissions); return $this->_fileHandlers[$filename]; }
Creates a new, empty file in the directory with the given $filename. @param string $filename @return Zend_Search_Lucene_Storage_File @throws Zend_Search_Lucene_Exception
entailment
public function deleteFile($filename) { if (isset($this->_fileHandlers[$filename])) { $this->_fileHandlers[$filename]->close(); } unset($this->_fileHandlers[$filename]); global $php_errormsg; $trackErrors = ini_get('track_errors'); ini_set('track_errors', '1'); if (!@unlink($this->_dirPath . '/' . $filename)) { ini_set('track_errors', $trackErrors); include_once 'Zend/Search/Lucene/Exception.php'; throw new Zend_Search_Lucene_Exception('Can\'t delete file: ' . $php_errormsg); } ini_set('track_errors', $trackErrors); }
Removes an existing $filename in the directory. @param string $filename @return void @throws Zend_Search_Lucene_Exception
entailment
public function purgeFile($filename) { if (isset($this->_fileHandlers[$filename])) { $this->_fileHandlers[$filename]->close(); } unset($this->_fileHandlers[$filename]); }
Purge file if it's cached by directory object Method is used to prevent 'too many open files' error @param string $filename @return void
entailment
public function fileExists($filename) { return isset($this->_fileHandlers[$filename]) || file_exists($this->_dirPath . '/' . $filename); }
Returns true if a file with the given $filename exists. @param string $filename @return boolean
entailment
public function fileLength($filename) { if (isset($this->_fileHandlers[$filename])) { return $this->_fileHandlers[$filename]->size(); } return filesize($this->_dirPath .'/'. $filename); }
Returns the length of a $filename in the directory. @param string $filename @return integer
entailment
public function renameFile($from, $to) { global $php_errormsg; if (isset($this->_fileHandlers[$from])) { $this->_fileHandlers[$from]->close(); } unset($this->_fileHandlers[$from]); if (isset($this->_fileHandlers[$to])) { $this->_fileHandlers[$to]->close(); } unset($this->_fileHandlers[$to]); if (file_exists($this->_dirPath . '/' . $to)) { if (!unlink($this->_dirPath . '/' . $to)) { include_once 'Zend/Search/Lucene/Exception.php'; throw new Zend_Search_Lucene_Exception('Delete operation failed'); } } $trackErrors = ini_get('track_errors'); ini_set('track_errors', '1'); $success = @rename($this->_dirPath . '/' . $from, $this->_dirPath . '/' . $to); if (!$success) { ini_set('track_errors', $trackErrors); include_once 'Zend/Search/Lucene/Exception.php'; throw new Zend_Search_Lucene_Exception($php_errormsg); } ini_set('track_errors', $trackErrors); return $success; }
Renames an existing file in the directory. @param string $from @param string $to @return void @throws Zend_Search_Lucene_Exception
entailment
public function getFileObject($filename, $shareHandler = true) { $fullFilename = $this->_dirPath . '/' . $filename; include_once 'Zend/Search/Lucene/Storage/File/Filesystem.php'; if (!$shareHandler) { return new Zend_Search_Lucene_Storage_File_Filesystem($fullFilename); } if (isset($this->_fileHandlers[$filename])) { $this->_fileHandlers[$filename]->seek(0); return $this->_fileHandlers[$filename]; } $this->_fileHandlers[$filename] = new Zend_Search_Lucene_Storage_File_Filesystem($fullFilename); return $this->_fileHandlers[$filename]; }
Returns a Zend_Search_Lucene_Storage_File object for a given $filename in the directory. If $shareHandler option is true, then file handler can be shared between File Object requests. It speed-ups performance, but makes problems with file position. Shared handler are good for short atomic requests. Non-shared handlers are useful for stream file reading (especial for compound files). @param string $filename @param boolean $shareHandler @return Zend_Search_Lucene_Storage_File
entailment
public function up() { Schema::connection(config('settings.db_connection'))->create(config('settings.db_table'), function (Blueprint $table) { $table->string('setting_key')->index()->unique(); $table->binary('setting_value')->nullable(); }); }
Run the migrations. @return void
entailment
private function _retrieveNodeText(DOMNode $node, &$text) { if ($node->nodeType == XML_TEXT_NODE) { $text .= $node->nodeValue; if(!in_array($node->parentNode->tagName, $this->_inlineTags)) { $text .= ' '; } } else if ($node->nodeType == XML_ELEMENT_NODE && $node->nodeName != 'script') { foreach ($node->childNodes as $childNode) { $this->_retrieveNodeText($childNode, $text); } } }
Get node text We should exclude scripts, which may be not included into comment tags, CDATA sections, @param DOMNode $node @param string &$text
entailment
public static function loadHTML($data, $storeContent = false, $defaultEncoding = '') { return new Zend_Search_Lucene_Document_Html($data, false, $storeContent, $defaultEncoding); }
Load HTML document from a string @param string $data @param boolean $storeContent @param string $defaultEncoding HTML encoding, is used if it's not specified using Content-type HTTP-EQUIV meta tag. @return Zend_Search_Lucene_Document_Html
entailment
public static function loadHTMLFile($file, $storeContent = false, $defaultEncoding = '') { return new Zend_Search_Lucene_Document_Html($file, true, $storeContent, $defaultEncoding); }
Load HTML document from a file @param string $file @param boolean $storeContent @param string $defaultEncoding HTML encoding, is used if it's not specified using Content-type HTTP-EQUIV meta tag. @return Zend_Search_Lucene_Document_Html
entailment
protected function _highlightTextNode(DOMText $node, $wordsToHighlight, $callback, $params) { /** * Zend_Search_Lucene_Analysis_Analyzer */ include_once 'Zend/Search/Lucene/Analysis/Analyzer.php'; $analyzer = Zend_Search_Lucene_Analysis_Analyzer::getDefault(); $analyzer->setInput($node->nodeValue, 'UTF-8'); $matchedTokens = array(); while (($token = $analyzer->nextToken()) !== null) { if (isset($wordsToHighlight[$token->getTermText()])) { $matchedTokens[] = $token; } } if (count($matchedTokens) == 0) { return; } $matchedTokens = array_reverse($matchedTokens); foreach ($matchedTokens as $token) { // Cut text after matched token $node->splitText($token->getEndOffset()); // Cut matched node $matchedWordNode = $node->splitText($token->getStartOffset()); // Retrieve HTML string representation for highlihted word $fullCallbackparamsList = $params; array_unshift($fullCallbackparamsList, $matchedWordNode->nodeValue); $highlightedWordNodeSetHtml = call_user_func_array($callback, $fullCallbackparamsList); // Transform HTML string to a DOM representation and automatically transform retrieved string // into valid XHTML (It's automatically done by loadHTML() method) $highlightedWordNodeSetDomDocument = new DOMDocument('1.0', 'UTF-8'); $success = @$highlightedWordNodeSetDomDocument-> loadHTML( '<html><head><meta http-equiv="Content-type" content="text/html; charset=UTF-8"/></head><body>' . $highlightedWordNodeSetHtml . '</body></html>' ); if (!$success) { include_once 'Zend/Search/Lucene/Exception.php'; throw new Zend_Search_Lucene_Exception("Error occured while loading highlighted text fragment: '$highlightedWordNodeSetHtml'."); } $highlightedWordNodeSetXpath = new DOMXPath($highlightedWordNodeSetDomDocument); $highlightedWordNodeSet = $highlightedWordNodeSetXpath->query('/html/body')->item(0)->childNodes; for ($count = 0; $count < $highlightedWordNodeSet->length; $count++) { $nodeToImport = $highlightedWordNodeSet->item($count); $node->parentNode->insertBefore( $this->_doc->importNode($nodeToImport, true /* deep copy */), $matchedWordNode ); } $node->parentNode->removeChild($matchedWordNode); } }
Highlight text in text node @param DOMText $node @param array $wordsToHighlight @param callback $callback Callback method, used to transform (highlighting) text. @param array $params Array of additionall callback parameters (first non-optional parameter is a text to transform) @throws Zend_Search_Lucene_Exception
entailment
protected function _highlightNodeRecursive(DOMNode $contextNode, $wordsToHighlight, $callback, $params) { $textNodes = array(); if (!$contextNode->hasChildNodes()) { return; } foreach ($contextNode->childNodes as $childNode) { if ($childNode->nodeType == XML_TEXT_NODE) { // process node later to leave childNodes structure untouched $textNodes[] = $childNode; } else { // Process node if it's not a script node if ($childNode->nodeName != 'script') { $this->_highlightNodeRecursive($childNode, $wordsToHighlight, $callback, $params); } } } foreach ($textNodes as $textNode) { $this->_highlightTextNode($textNode, $wordsToHighlight, $callback, $params); } }
highlight words in content of the specified node @param DOMNode $contextNode @param array $wordsToHighlight @param callback $callback Callback method, used to transform (highlighting) text. @param array $params Array of additionall callback parameters (first non-optional parameter is a text to transform)
entailment
public function highlightExtended($words, $callback, $params = array()) { /** * Zend_Search_Lucene_Analysis_Analyzer */ include_once 'Zend/Search/Lucene/Analysis/Analyzer.php'; if (!is_array($words)) { $words = array($words); } $wordsToHighlightList = array(); $analyzer = Zend_Search_Lucene_Analysis_Analyzer::getDefault(); foreach ($words as $wordString) { $wordsToHighlightList[] = $analyzer->tokenize($wordString); } $wordsToHighlight = call_user_func_array('array_merge', $wordsToHighlightList); if (count($wordsToHighlight) == 0) { return $this->_doc->saveHTML(); } $wordsToHighlightFlipped = array(); foreach ($wordsToHighlight as $id => $token) { $wordsToHighlightFlipped[$token->getTermText()] = $id; } if (!is_callable($callback)) { include_once 'Zend/Search/Lucene/Exception.php'; throw new Zend_Search_Lucene_Exception('$viewHelper parameter mast be a View Helper name, View Helper object or callback.'); } $xpath = new DOMXPath($this->_doc); $matchedNodes = $xpath->query("/html/body"); foreach ($matchedNodes as $matchedNode) { $this->_highlightNodeRecursive($matchedNode, $wordsToHighlightFlipped, $callback, $params); } }
Highlight text using specified View helper or callback function. @param string|array $words Words to highlight. Words could be organized using the array or string. @param callback $callback Callback method, used to transform (highlighting) text. @param array $params Array of additionall callback parameters passed through into it (first non-optional parameter is an HTML fragment for highlighting) (first non-optional parameter is an HTML fragment for highlighting) (first non-optional parameter is an HTML fragment for highlighting) @return string @throws Zend_Search_Lucene_Exception
entailment
public function getHtmlBody() { $xpath = new DOMXPath($this->_doc); $bodyNodes = $xpath->query('/html/body')->item(0)->childNodes; $outputFragments = array(); for ($count = 0; $count < $bodyNodes->length; $count++) { $outputFragments[] = $this->_doc->saveXML($bodyNodes->item($count)); } return implode($outputFragments); }
Get HTML body @return string
entailment
public function rewrite(Zend_Search_Lucene_Interface $index) { if ($this->_field === null) { include_once 'Zend/Search/Lucene/Search/Query/MultiTerm.php'; $query = new Zend_Search_Lucene_Search_Query_MultiTerm(); $query->setBoost($this->getBoost()); $hasInsignificantSubqueries = false; include_once 'Zend/Search/Lucene.php'; if (Zend_Search_Lucene::getDefaultSearchField() === null) { $searchFields = $index->getFieldNames(true); } else { $searchFields = array(Zend_Search_Lucene::getDefaultSearchField()); } include_once 'Zend/Search/Lucene/Search/Query/Preprocessing/Term.php'; foreach ($searchFields as $fieldName) { $subquery = new Zend_Search_Lucene_Search_Query_Preprocessing_Term( $this->_word, $this->_encoding, $fieldName ); $rewrittenSubquery = $subquery->rewrite($index); foreach ($rewrittenSubquery->getQueryTerms() as $term) { $query->addTerm($term); } if ($rewrittenSubquery instanceof Zend_Search_Lucene_Search_Query_Insignificant) { $hasInsignificantSubqueries = true; } } if (count($query->getTerms()) == 0) { $this->_matches = array(); if ($hasInsignificantSubqueries) { include_once 'Zend/Search/Lucene/Search/Query/Insignificant.php'; return new Zend_Search_Lucene_Search_Query_Insignificant(); } else { include_once 'Zend/Search/Lucene/Search/Query/Empty.php'; return new Zend_Search_Lucene_Search_Query_Empty(); } } $this->_matches = $query->getQueryTerms(); return $query; } // ------------------------------------- // Recognize exact term matching (it corresponds to Keyword fields stored in the index) // encoding is not used since we expect binary matching include_once 'Zend/Search/Lucene/Index/Term.php'; $term = new Zend_Search_Lucene_Index_Term($this->_word, $this->_field); if ($index->hasTerm($term)) { include_once 'Zend/Search/Lucene/Search/Query/Term.php'; $query = new Zend_Search_Lucene_Search_Query_Term($term); $query->setBoost($this->getBoost()); $this->_matches = $query->getQueryTerms(); return $query; } // ------------------------------------- // Recognize wildcard queries /** * @todo check for PCRE unicode support may be performed through Zend_Environment in some future */ if (@preg_match('/\pL/u', 'a') == 1) { $word = iconv($this->_encoding, 'UTF-8', $this->_word); $wildcardsPattern = '/[*?]/u'; $subPatternsEncoding = 'UTF-8'; } else { $word = $this->_word; $wildcardsPattern = '/[*?]/'; $subPatternsEncoding = $this->_encoding; } $subPatterns = preg_split($wildcardsPattern, $word, -1, PREG_SPLIT_OFFSET_CAPTURE); if (count($subPatterns) > 1) { // Wildcard query is recognized $pattern = ''; include_once 'Zend/Search/Lucene/Analysis/Analyzer.php'; foreach ($subPatterns as $id => $subPattern) { // Append corresponding wildcard character to the pattern before each sub-pattern (except first) if ($id != 0) { $pattern .= $word[ $subPattern[1] - 1 ]; } // Check if each subputtern is a single word in terms of current analyzer $tokens = Zend_Search_Lucene_Analysis_Analyzer::getDefault()->tokenize($subPattern[0], $subPatternsEncoding); if (count($tokens) > 1) { include_once 'Zend/Search/Lucene/Search/QueryParserException.php'; throw new Zend_Search_Lucene_Search_QueryParserException('Wildcard search is supported only for non-multiple word terms'); } foreach ($tokens as $token) { $pattern .= $token->getTermText(); } } include_once 'Zend/Search/Lucene/Index/Term.php'; $term = new Zend_Search_Lucene_Index_Term($pattern, $this->_field); include_once 'Zend/Search/Lucene/Search/Query/Wildcard.php'; $query = new Zend_Search_Lucene_Search_Query_Wildcard($term); $query->setBoost($this->getBoost()); // Get rewritten query. Important! It also fills terms matching container. $rewrittenQuery = $query->rewrite($index); $this->_matches = $query->getQueryTerms(); return $rewrittenQuery; } // ------------------------------------- // Recognize one-term multi-term and "insignificant" queries include_once 'Zend/Search/Lucene/Analysis/Analyzer.php'; $tokens = Zend_Search_Lucene_Analysis_Analyzer::getDefault()->tokenize($this->_word, $this->_encoding); if (count($tokens) == 0) { $this->_matches = array(); include_once 'Zend/Search/Lucene/Search/Query/Insignificant.php'; return new Zend_Search_Lucene_Search_Query_Insignificant(); } if (count($tokens) == 1) { include_once 'Zend/Search/Lucene/Index/Term.php'; $term = new Zend_Search_Lucene_Index_Term($tokens[0]->getTermText(), $this->_field); include_once 'Zend/Search/Lucene/Search/Query/Term.php'; $query = new Zend_Search_Lucene_Search_Query_Term($term); $query->setBoost($this->getBoost()); $this->_matches = $query->getQueryTerms(); return $query; } //It's not insignificant or one term query include_once 'Zend/Search/Lucene/Search/Query/MultiTerm.php'; $query = new Zend_Search_Lucene_Search_Query_MultiTerm(); /** * @todo Process $token->getPositionIncrement() to support stemming, synonyms and other * analizer design features */ include_once 'Zend/Search/Lucene/Index/Term.php'; foreach ($tokens as $token) { $term = new Zend_Search_Lucene_Index_Term($token->getTermText(), $this->_field); $query->addTerm($term, true); // all subterms are required } $query->setBoost($this->getBoost()); $this->_matches = $query->getQueryTerms(); return $query; }
Re-write query into primitive queries in the context of specified index @param Zend_Search_Lucene_Interface $index @return Zend_Search_Lucene_Search_Query
entailment
protected function _highlightMatches(Zend_Search_Lucene_Search_Highlighter_Interface $highlighter) { /** * Skip fields detection. We don't need it, since we expect all fields presented in the HTML body and don't differentiate them */ /** * Skip exact term matching recognition, keyword fields highlighting is not supported */ // ------------------------------------- // Recognize wildcard queries /** * @todo check for PCRE unicode support may be performed through Zend_Environment in some future */ if (@preg_match('/\pL/u', 'a') == 1) { $word = iconv($this->_encoding, 'UTF-8', $this->_word); $wildcardsPattern = '/[*?]/u'; $subPatternsEncoding = 'UTF-8'; } else { $word = $this->_word; $wildcardsPattern = '/[*?]/'; $subPatternsEncoding = $this->_encoding; } $subPatterns = preg_split($wildcardsPattern, $word, -1, PREG_SPLIT_OFFSET_CAPTURE); if (count($subPatterns) > 1) { // Wildcard query is recognized $pattern = ''; include_once 'Zend/Search/Lucene/Analysis/Analyzer.php'; foreach ($subPatterns as $id => $subPattern) { // Append corresponding wildcard character to the pattern before each sub-pattern (except first) if ($id != 0) { $pattern .= $word[ $subPattern[1] - 1 ]; } // Check if each subputtern is a single word in terms of current analyzer $tokens = Zend_Search_Lucene_Analysis_Analyzer::getDefault()->tokenize($subPattern[0], $subPatternsEncoding); if (count($tokens) > 1) { // Do nothing (nothing is highlighted) return; } foreach ($tokens as $token) { $pattern .= $token->getTermText(); } } include_once 'Zend/Search/Lucene/Index/Term.php'; $term = new Zend_Search_Lucene_Index_Term($pattern, $this->_field); include_once 'Zend/Search/Lucene/Search/Query/Wildcard.php'; $query = new Zend_Search_Lucene_Search_Query_Wildcard($term); $query->_highlightMatches($highlighter); return; } // ------------------------------------- // Recognize one-term multi-term and "insignificant" queries include_once 'Zend/Search/Lucene/Analysis/Analyzer.php'; $tokens = Zend_Search_Lucene_Analysis_Analyzer::getDefault()->tokenize($this->_word, $this->_encoding); if (count($tokens) == 0) { // Do nothing return; } if (count($tokens) == 1) { $highlighter->highlight($tokens[0]->getTermText()); return; } //It's not insignificant or one term query $words = array(); foreach ($tokens as $token) { $words[] = $token->getTermText(); } $highlighter->highlight($words); }
Query specific matches highlighting @param Zend_Search_Lucene_Search_Highlighter_Interface $highlighter Highlighter object (also contains doc for highlighting)
entailment
private function _calculateMaxDistance($prefixLength, $termLength, $length) { $this->_maxDistances[$length] = (int) ((1 - $this->_minimumSimilarity)*(min($termLength, $length) + $prefixLength)); return $this->_maxDistances[$length]; }
Calculate maximum distance for specified word length @param integer $prefixLength @param integer $termLength @param integer $length @return integer
entailment
public function rewrite(Zend_Search_Lucene_Interface $index) { $this->_matches = array(); $this->_scores = array(); $this->_termKeys = array(); if ($this->_term->field === null) { // Search through all fields $fields = $index->getFieldNames(true /* indexed fields list */); } else { $fields = array($this->_term->field); } include_once 'Zend/Search/Lucene/Index/Term.php'; $prefix = Zend_Search_Lucene_Index_Term::getPrefix($this->_term->text, $this->_prefixLength); $prefixByteLength = strlen($prefix); $prefixUtf8Length = Zend_Search_Lucene_Index_Term::getLength($prefix); $termLength = Zend_Search_Lucene_Index_Term::getLength($this->_term->text); $termRest = substr($this->_term->text, $prefixByteLength); // we calculate length of the rest in bytes since levenshtein() is not UTF-8 compatible $termRestLength = strlen($termRest); $scaleFactor = 1/(1 - $this->_minimumSimilarity); include_once 'Zend/Search/Lucene.php'; $maxTerms = Zend_Search_Lucene::getTermsPerQueryLimit(); foreach ($fields as $field) { $index->resetTermsStream(); include_once 'Zend/Search/Lucene/Index/Term.php'; if ($prefix != '') { $index->skipTo(new Zend_Search_Lucene_Index_Term($prefix, $field)); while ($index->currentTerm() !== null && $index->currentTerm()->field == $field && substr($index->currentTerm()->text, 0, $prefixByteLength) == $prefix) { // Calculate similarity $target = substr($index->currentTerm()->text, $prefixByteLength); $maxDistance = isset($this->_maxDistances[strlen($target)])? $this->_maxDistances[strlen($target)] : $this->_calculateMaxDistance($prefixUtf8Length, $termRestLength, strlen($target)); if ($termRestLength == 0) { // we don't have anything to compare. That means if we just add // the letters for current term we get the new word $similarity = (($prefixUtf8Length == 0)? 0 : 1 - strlen($target)/$prefixUtf8Length); } else if (strlen($target) == 0) { $similarity = (($prefixUtf8Length == 0)? 0 : 1 - $termRestLength/$prefixUtf8Length); } else if ($maxDistance < abs($termRestLength - strlen($target))) { //just adding the characters of term to target or vice-versa results in too many edits //for example "pre" length is 3 and "prefixes" length is 8. We can see that //given this optimal circumstance, the edit distance cannot be less than 5. //which is 8-3 or more precisesly abs(3-8). //if our maximum edit distance is 4, then we can discard this word //without looking at it. $similarity = 0; } else { $similarity = 1 - levenshtein($termRest, $target)/($prefixUtf8Length + min($termRestLength, strlen($target))); } if ($similarity > $this->_minimumSimilarity) { $this->_matches[] = $index->currentTerm(); $this->_termKeys[] = $index->currentTerm()->key(); $this->_scores[] = ($similarity - $this->_minimumSimilarity)*$scaleFactor; if ($maxTerms != 0 && count($this->_matches) > $maxTerms) { include_once 'Zend/Search/Lucene/Exception.php'; throw new Zend_Search_Lucene_Exception('Terms per query limit is reached.'); } } $index->nextTerm(); } } else { $index->skipTo(new Zend_Search_Lucene_Index_Term('', $field)); while ($index->currentTerm() !== null && $index->currentTerm()->field == $field) { // Calculate similarity $target = $index->currentTerm()->text; $maxDistance = isset($this->_maxDistances[strlen($target)])? $this->_maxDistances[strlen($target)] : $this->_calculateMaxDistance(0, $termRestLength, strlen($target)); if ($maxDistance < abs($termRestLength - strlen($target))) { //just adding the characters of term to target or vice-versa results in too many edits //for example "pre" length is 3 and "prefixes" length is 8. We can see that //given this optimal circumstance, the edit distance cannot be less than 5. //which is 8-3 or more precisesly abs(3-8). //if our maximum edit distance is 4, then we can discard this word //without looking at it. $similarity = 0; } else { $similarity = 1 - levenshtein($termRest, $target)/min($termRestLength, strlen($target)); } if ($similarity > $this->_minimumSimilarity) { $this->_matches[] = $index->currentTerm(); $this->_termKeys[] = $index->currentTerm()->key(); $this->_scores[] = ($similarity - $this->_minimumSimilarity)*$scaleFactor; if ($maxTerms != 0 && count($this->_matches) > $maxTerms) { include_once 'Zend/Search/Lucene/Exception.php'; throw new Zend_Search_Lucene_Exception('Terms per query limit is reached.'); } } $index->nextTerm(); } } $index->closeTermsStream(); } if (count($this->_matches) == 0) { include_once 'Zend/Search/Lucene/Search/Query/Empty.php'; return new Zend_Search_Lucene_Search_Query_Empty(); } else if (count($this->_matches) == 1) { include_once 'Zend/Search/Lucene/Search/Query/Term.php'; return new Zend_Search_Lucene_Search_Query_Term(reset($this->_matches)); } else { include_once 'Zend/Search/Lucene/Search/Query/Boolean.php'; $rewrittenQuery = new Zend_Search_Lucene_Search_Query_Boolean(); array_multisort( $this->_scores, SORT_DESC, SORT_NUMERIC, $this->_termKeys, SORT_ASC, SORT_STRING, $this->_matches ); $termCount = 0; include_once 'Zend/Search/Lucene/Search/Query/Term.php'; foreach ($this->_matches as $id => $matchedTerm) { $subquery = new Zend_Search_Lucene_Search_Query_Term($matchedTerm); $subquery->setBoost($this->_scores[$id]); $rewrittenQuery->addSubquery($subquery); $termCount++; if ($termCount >= self::MAX_CLAUSE_COUNT) { break; } } return $rewrittenQuery; } }
Re-write query into primitive queries in the context of specified index @param Zend_Search_Lucene_Interface $index @return Zend_Search_Lucene_Search_Query @throws Zend_Search_Lucene_Exception
entailment
protected function _highlightMatches(Zend_Search_Lucene_Search_Highlighter_Interface $highlighter) { $words = array(); include_once 'Zend/Search/Lucene/Index/Term.php'; $prefix = Zend_Search_Lucene_Index_Term::getPrefix($this->_term->text, $this->_prefixLength); $prefixByteLength = strlen($prefix); $prefixUtf8Length = Zend_Search_Lucene_Index_Term::getLength($prefix); $termLength = Zend_Search_Lucene_Index_Term::getLength($this->_term->text); $termRest = substr($this->_term->text, $prefixByteLength); // we calculate length of the rest in bytes since levenshtein() is not UTF-8 compatible $termRestLength = strlen($termRest); $scaleFactor = 1/(1 - $this->_minimumSimilarity); $docBody = $highlighter->getDocument()->getFieldUtf8Value('body'); include_once 'Zend/Search/Lucene/Analysis/Analyzer.php'; $tokens = Zend_Search_Lucene_Analysis_Analyzer::getDefault()->tokenize($docBody, 'UTF-8'); foreach ($tokens as $token) { $termText = $token->getTermText(); if (substr($termText, 0, $prefixByteLength) == $prefix) { // Calculate similarity $target = substr($termText, $prefixByteLength); $maxDistance = isset($this->_maxDistances[strlen($target)])? $this->_maxDistances[strlen($target)] : $this->_calculateMaxDistance($prefixUtf8Length, $termRestLength, strlen($target)); if ($termRestLength == 0) { // we don't have anything to compare. That means if we just add // the letters for current term we get the new word $similarity = (($prefixUtf8Length == 0)? 0 : 1 - strlen($target)/$prefixUtf8Length); } else if (strlen($target) == 0) { $similarity = (($prefixUtf8Length == 0)? 0 : 1 - $termRestLength/$prefixUtf8Length); } else if ($maxDistance < abs($termRestLength - strlen($target))) { //just adding the characters of term to target or vice-versa results in too many edits //for example "pre" length is 3 and "prefixes" length is 8. We can see that //given this optimal circumstance, the edit distance cannot be less than 5. //which is 8-3 or more precisesly abs(3-8). //if our maximum edit distance is 4, then we can discard this word //without looking at it. $similarity = 0; } else { $similarity = 1 - levenshtein($termRest, $target)/($prefixUtf8Length + min($termRestLength, strlen($target))); } if ($similarity > $this->_minimumSimilarity) { $words[] = $termText; } } } $highlighter->highlight($words); }
Query specific matches highlighting @param Zend_Search_Lucene_Search_Highlighter_Interface $highlighter Highlighter object (also contains doc for highlighting)
entailment
public function send($recipient, $body, $originator = '') { $message = new Sms(); $message->fromArray(array( 'recipient' => $recipient, 'body' => $body, 'originator' => $originator, 'status' => ResultInterface::STATUS_QUEUED, )); $this->pool->enqueue($message); return $message; }
{@inheritdoc}
entailment
public function send($recipient, $body, $originator = '') { if (null === $this->accountSid || null === $this->authToken) { throw new Exception\InvalidCredentialsException('No API credentials provided'); } if (empty($originator)) { throw new Exception\InvalidArgumentException('The originator parameter is required for this provider.'); } // clean the originator string to ensure that the sms won't be // rejected because of this $originator = $this->cleanOriginator($originator); $params = array( 'To' => $this->localNumberToInternational($recipient, $this->international_prefix), 'Body' => $body, 'From' => $originator, ); return $this->executeQuery(sprintf(self::SEND_SMS_URL, $this->accountSid), $params, array( 'recipient' => $recipient, 'body' => $body, 'originator' => $originator, )); }
{@inheritDoc}
entailment
protected function parseResults($result, array $extra_result_data = array()) { $data = json_decode($result, true); $sms_data = array(); // there was an error if (empty($data['sid']) || !empty($data['message'])) { return array_merge($this->getDefaults(), $extra_result_data, array( 'status' => ResultInterface::STATUS_FAILED, )); } // get the id $sms_data['id'] = $data['sid']; // get the status switch ($data['status']) { case 'failed': $sms_data['status'] = ResultInterface::STATUS_FAILED; break; case 'received': $sms_data['status'] = ResultInterface::STATUS_DELIVERED; break; default: $sms_data['status'] = ResultInterface::STATUS_SENT; break; } return array_merge($this->getDefaults(), $extra_result_data, $sms_data); }
Parse the data returned by the API. @param string $result The raw result string. @return array
entailment
public function upgrade( ModuleDataSetupInterface $setup, ModuleContextInterface $context ) { $setup->startSetup(); /** @var CustomerSetup $customerSetup */ $customerSetup = $this->customerSetupFactory->create(['setup' => $setup]); if (version_compare($context->getVersion(), "1.0.1", "<")) { $this->upgradeVersionOneZeroOne($customerSetup); } if (version_compare($context->getVersion(), "1.0.2", "<")) { $this->upgradeVersionOneZeroTwo($customerSetup); } $indexer = $this->indexerRegistry->get(Customer::CUSTOMER_GRID_INDEXER_ID); $indexer->reindexAll(); $this->eavConfig->clear(); $setup->endSetup(); }
{@inheritdoc}
entailment
public function deserialize(VisitorInterface $visitor, $data, array $type) { if ($data === null) { return null; } // Return enum if exists: $class = $type['params'][0] ?? null; if (class_exists($class) && isset(class_parents($class)[Enum::class])) { return new $class($data); } throw new \LogicException('Enum class does not exist.'); }
@param VisitorInterface $visitor @param mixed $data @param array $type @throws \Paillechat\Enum\Exception\EnumException @return Enum
entailment
public function serialize(VisitorInterface $visitor, Enum $enum, array $type, Context $context) { $valueType = $type['params'][1] ?? 'string'; switch ($valueType) { case 'string': return $visitor->visitString($enum->getValue(), $type, $context); case 'integer': return $visitor->visitInteger($enum->getValue(), $type, $context); default: throw new \LogicException('Unknown value type '); } }
@param VisitorInterface $visitor @param Enum $enum @param array $type @param Context $context @throws \LogicException @return mixed
entailment
public static function init(array $config) { if (empty($config['storage']) || ($config['storage'] != self::FILE && $config['storage'] != self::POP3)) { throw new \InvalidArgumentException('need at least type in params'); } $className = __NAMESPACE__.'\\'.$config['storage']; return new $className($config); }
@param array $config @return StorageInterface
entailment
public function readAMFData($settype = null,$newscope = false) { if ($newscope) $this->refList = array(); if (is_null($settype)) { $settype = $this->stream->readByte(); } switch ($settype) { case SabreAMF_AMF0_Const::DT_NUMBER : return $this->stream->readDouble(); case SabreAMF_AMF0_Const::DT_BOOL : return $this->stream->readByte()==true; case SabreAMF_AMF0_Const::DT_STRING : return $this->readString(); case SabreAMF_AMF0_Const::DT_OBJECT : return $this->readObject(); case SabreAMF_AMF0_Const::DT_NULL : return null; case SabreAMF_AMF0_Const::DT_UNDEFINED : return null; case SabreAMF_AMF0_Const::DT_REFERENCE : return $this->readReference(); case SabreAMF_AMF0_Const::DT_MIXEDARRAY : return $this->readMixedArray(); case SabreAMF_AMF0_Const::DT_ARRAY : return $this->readArray(); case SabreAMF_AMF0_Const::DT_DATE : return $this->readDate(); case SabreAMF_AMF0_Const::DT_LONGSTRING : return $this->readLongString(); case SabreAMF_AMF0_Const::DT_UNSUPPORTED : return null; case SabreAMF_AMF0_Const::DT_XML : return $this->readLongString(); case SabreAMF_AMF0_Const::DT_TYPEDOBJECT : return $this->readTypedObject(); case SabreAMF_AMF0_Const::DT_AMF3 : return $this->readAMF3Data(); default : throw new Exception('Unsupported type: 0x' . strtoupper(str_pad(dechex($settype),2,0,STR_PAD_LEFT))); return false; } }
readAMFData @param int $settype @param bool $newscope @return mixed
entailment
public function readObject() { $object = array(); $this->refList[] =& $object; while (true) { $key = $this->readString(); $vartype = $this->stream->readByte(); if ($vartype==SabreAMF_AMF0_Const::DT_OBJECTTERM) break; $object[$key] = $this->readAmfData($vartype); } if (defined('SABREAMF_OBJECT_AS_ARRAY')) { $object = (object)$object; } return $object; }
readObject @return object
entailment
public function readReference() { $refId = $this->stream->readInt(); if (isset($this->refList[$refId])) { return $this->refList[$refId]; } else { throw new Exception('Invalid reference offset: ' . $refId); return false; } }
readReference @return object
entailment
public function readArray() { $length = $this->stream->readLong(); $arr = array(); $this->refList[]&=$arr; while($length--) $arr[] = $this->readAMFData(); return $arr; }
readArray @return array
entailment
public function readTypedObject() { $classname = $this->readString(); $isMapped = false; if ($localClassname = $this->getLocalClassName($classname)) { $rObject = new $localClassname(); $isMapped = true; } else { $rObject = new SabreAMF_TypedObject($classname,null); } $this->refList[] =& $rObject; $props = array(); while (true) { $key = $this->readString(); $vartype = $this->stream->readByte(); if ($vartype==SabreAMF_AMF0_Const::DT_OBJECTTERM) break; $props[$key] = $this->readAmfData($vartype); } if ($isMapped) { foreach($props as $k=>$v) $rObject->$k = $v; } else { $rObject->setAMFData($props); } return $rObject; }
readTypedObject @return object
entailment
public function reset() { $this->_position = 0; if ($this->_input === null) { return; } // convert input into ascii if (PHP_OS != 'AIX') { $this->_input = iconv($this->_encoding, 'ASCII//TRANSLIT', $this->_input); } $this->_encoding = 'ASCII'; }
Reset token stream
entailment
public function nextToken() { if ($this->_input === null) { return null; } do { if (! preg_match('/[a-zA-Z0-9]+/', $this->_input, $match, PREG_OFFSET_CAPTURE, $this->_position)) { // It covers both cases a) there are no matches (preg_match(...) === 0) // b) error occured (preg_match(...) === FALSE) return null; } $str = $match[0][0]; $pos = $match[0][1]; $endpos = $pos + strlen($str); $this->_position = $endpos; $token = $this->normalize(new Zend_Search_Lucene_Analysis_Token($str, $pos, $endpos)); } while ($token === null); // try again if token is skipped return $token; }
Tokenization stream API Get next token Returns null at the end of stream @return Zend_Search_Lucene_Analysis_Token|null
entailment
public function install( SchemaSetupInterface $setup, ModuleContextInterface $context ) { $installer = $setup; $installer->startSetup(); $setup->endSetup(); }
{@inheritdoc}
entailment
public static function createIndex(Zend_Search_Lucene_Storage_Directory $directory, $generation, $nameCount) { if ($generation == 0) { // Create index in pre-2.1 mode foreach ($directory->fileList() as $file) { if ($file == 'deletable' || $file == 'segments' || isset(self::$_indexExtensions[ substr($file, strlen($file)-4)]) || preg_match('/\.f\d+$/i', $file) /* matches <segment_name>.f<decimal_nmber> file names */ ) { $directory->deleteFile($file); } } $segmentsFile = $directory->createFile('segments'); $segmentsFile->writeInt((int)0xFFFFFFFF); // write version (initialized by current time) $segmentsFile->writeLong(round(microtime(true))); // write name counter $segmentsFile->writeInt($nameCount); // write segment counter $segmentsFile->writeInt(0); $deletableFile = $directory->createFile('deletable'); // write counter $deletableFile->writeInt(0); } else { $genFile = $directory->createFile('segments.gen'); $genFile->writeInt((int)0xFFFFFFFE); // Write generation two times $genFile->writeLong($generation); $genFile->writeLong($generation); $segmentsFile = $directory->createFile(Zend_Search_Lucene::getSegmentFileName($generation)); $segmentsFile->writeInt((int)0xFFFFFFFD); // write version (initialized by current time) $segmentsFile->writeLong(round(microtime(true))); // write name counter $segmentsFile->writeInt($nameCount); // write segment counter $segmentsFile->writeInt(0); } }
Create empty index @param Zend_Search_Lucene_Storage_Directory $directory @param integer $generation @param integer $nameCount
entailment
public function addDocument(Zend_Search_Lucene_Document $document) { /** * Zend_Search_Lucene_Index_SegmentWriter_DocumentWriter */ include_once 'Zend/Search/Lucene/Index/SegmentWriter/DocumentWriter.php'; if ($this->_currentSegment === null) { $this->_currentSegment = new Zend_Search_Lucene_Index_SegmentWriter_DocumentWriter($this->_directory, $this->_newSegmentName()); } $this->_currentSegment->addDocument($document); if ($this->_currentSegment->count() >= $this->maxBufferedDocs) { $this->commit(); } $this->_maybeMergeSegments(); $this->_versionUpdate++; }
Adds a document to this index. @param Zend_Search_Lucene_Document $document
entailment
private function _hasAnythingToMerge() { $segmentSizes = array(); foreach ($this->_segmentInfos as $segName => $segmentInfo) { $segmentSizes[$segName] = $segmentInfo->count(); } $mergePool = array(); $poolSize = 0; $sizeToMerge = $this->maxBufferedDocs; asort($segmentSizes, SORT_NUMERIC); foreach ($segmentSizes as $segName => $size) { // Check, if segment comes into a new merging block while ($size >= $sizeToMerge) { // Merge previous block if it's large enough if ($poolSize >= $sizeToMerge) { return true; } $mergePool = array(); $poolSize = 0; $sizeToMerge *= $this->mergeFactor; if ($sizeToMerge > $this->maxMergeDocs) { return false; } } $mergePool[] = $this->_segmentInfos[$segName]; $poolSize += $size; } if ($poolSize >= $sizeToMerge) { return true; } return false; }
Check if we have anything to merge @return boolean
entailment
private function _maybeMergeSegments() { if (Zend_Search_Lucene_LockManager::obtainOptimizationLock($this->_directory) === false) { return; } if (!$this->_hasAnythingToMerge()) { Zend_Search_Lucene_LockManager::releaseOptimizationLock($this->_directory); return; } // Update segments list to be sure all segments are not merged yet by another process // // Segment merging functionality is concentrated in this class and surrounded // by optimization lock obtaining/releasing. // _updateSegments() refreshes segments list from the latest index generation. // So only new segments can be added to the index while we are merging some already existing // segments. // Newly added segments will be also included into the index by the _updateSegments() call // either by another process or by the current process with the commit() call at the end of _mergeSegments() method. // That's guaranteed by the serialisation of _updateSegments() execution using exclusive locks. $this->_updateSegments(); // Perform standard auto-optimization procedure $segmentSizes = array(); foreach ($this->_segmentInfos as $segName => $segmentInfo) { $segmentSizes[$segName] = $segmentInfo->count(); } $mergePool = array(); $poolSize = 0; $sizeToMerge = $this->maxBufferedDocs; asort($segmentSizes, SORT_NUMERIC); foreach ($segmentSizes as $segName => $size) { // Check, if segment comes into a new merging block while ($size >= $sizeToMerge) { // Merge previous block if it's large enough if ($poolSize >= $sizeToMerge) { $this->_mergeSegments($mergePool); } $mergePool = array(); $poolSize = 0; $sizeToMerge *= $this->mergeFactor; if ($sizeToMerge > $this->maxMergeDocs) { Zend_Search_Lucene_LockManager::releaseOptimizationLock($this->_directory); return; } } $mergePool[] = $this->_segmentInfos[$segName]; $poolSize += $size; } if ($poolSize >= $sizeToMerge) { $this->_mergeSegments($mergePool); } Zend_Search_Lucene_LockManager::releaseOptimizationLock($this->_directory); }
Merge segments if necessary
entailment
private function _mergeSegments($segments) { $newName = $this->_newSegmentName(); /** * Zend_Search_Lucene_Index_SegmentMerger */ include_once 'Zend/Search/Lucene/Index/SegmentMerger.php'; $merger = new Zend_Search_Lucene_Index_SegmentMerger( $this->_directory, $newName ); foreach ($segments as $segmentInfo) { $merger->addSource($segmentInfo); $this->_segmentsToDelete[$segmentInfo->getName()] = $segmentInfo->getName(); } $newSegment = $merger->merge(); if ($newSegment !== null) { $this->_newSegments[$newSegment->getName()] = $newSegment; } $this->commit(); }
Merge specified segments $segments is an array of SegmentInfo objects @param array $segments
entailment
private function _updateSegments() { // Get an exclusive index lock Zend_Search_Lucene_LockManager::obtainWriteLock($this->_directory); // Write down changes for the segments foreach ($this->_segmentInfos as $segInfo) { $segInfo->writeChanges(); } $generation = Zend_Search_Lucene::getActualGeneration($this->_directory); $segmentsFile = $this->_directory->getFileObject(Zend_Search_Lucene::getSegmentFileName($generation), false); $newSegmentFile = $this->_directory->createFile(Zend_Search_Lucene::getSegmentFileName(++$generation), false); try { $genFile = $this->_directory->getFileObject('segments.gen', false); } catch (Zend_Search_Lucene_Exception $e) { if (strpos($e->getMessage(), 'is not readable') !== false) { $genFile = $this->_directory->createFile('segments.gen'); } else { throw new Zend_Search_Lucene_Exception($e->getMessage(), $e->getCode(), $e); } } $genFile->writeInt((int)0xFFFFFFFE); // Write generation (first copy) $genFile->writeLong($generation); try { // Write format marker if ($this->_targetFormatVersion == Zend_Search_Lucene::FORMAT_2_1) { $newSegmentFile->writeInt((int)0xFFFFFFFD); } else if ($this->_targetFormatVersion == Zend_Search_Lucene::FORMAT_2_3) { $newSegmentFile->writeInt((int)0xFFFFFFFC); } // Read src file format identifier $format = $segmentsFile->readInt(); if ($format == (int)0xFFFFFFFF) { $srcFormat = Zend_Search_Lucene::FORMAT_PRE_2_1; } else if ($format == (int)0xFFFFFFFD) { $srcFormat = Zend_Search_Lucene::FORMAT_2_1; } else if ($format == (int)0xFFFFFFFC) { $srcFormat = Zend_Search_Lucene::FORMAT_2_3; } else { throw new Zend_Search_Lucene_Exception('Unsupported segments file format'); } $version = $segmentsFile->readLong() + $this->_versionUpdate; $this->_versionUpdate = 0; $newSegmentFile->writeLong($version); // Write segment name counter $newSegmentFile->writeInt($segmentsFile->readInt()); // Get number of segments offset $numOfSegmentsOffset = $newSegmentFile->tell(); // Write dummy data (segment counter) $newSegmentFile->writeInt(0); // Read number of segemnts $segmentsCount = $segmentsFile->readInt(); $segments = array(); for ($count = 0; $count < $segmentsCount; $count++) { $segName = $segmentsFile->readString(); $segSize = $segmentsFile->readInt(); if ($srcFormat == Zend_Search_Lucene::FORMAT_PRE_2_1) { // pre-2.1 index format $delGen = 0; $hasSingleNormFile = false; $numField = (int)0xFFFFFFFF; $isCompoundByte = 0; $docStoreOptions = null; } else { $delGen = $segmentsFile->readLong(); if ($srcFormat == Zend_Search_Lucene::FORMAT_2_3) { $docStoreOffset = $segmentsFile->readInt(); if ($docStoreOffset != (int)0xFFFFFFFF) { $docStoreSegment = $segmentsFile->readString(); $docStoreIsCompoundFile = $segmentsFile->readByte(); $docStoreOptions = array('offset' => $docStoreOffset, 'segment' => $docStoreSegment, 'isCompound' => ($docStoreIsCompoundFile == 1)); } else { $docStoreOptions = null; } } else { $docStoreOptions = null; } $hasSingleNormFile = $segmentsFile->readByte(); $numField = $segmentsFile->readInt(); $normGens = array(); if ($numField != (int)0xFFFFFFFF) { for ($count1 = 0; $count1 < $numField; $count1++) { $normGens[] = $segmentsFile->readLong(); } } $isCompoundByte = $segmentsFile->readByte(); } if (!in_array($segName, $this->_segmentsToDelete)) { // Load segment if necessary if (!isset($this->_segmentInfos[$segName])) { if ($isCompoundByte == 0xFF) { // The segment is not a compound file $isCompound = false; } else if ($isCompoundByte == 0x00) { // The status is unknown $isCompound = null; } else if ($isCompoundByte == 0x01) { // The segment is a compound file $isCompound = true; } /** * Zend_Search_Lucene_Index_SegmentInfo */ include_once 'Zend/Search/Lucene/Index/SegmentInfo.php'; $this->_segmentInfos[$segName] = new Zend_Search_Lucene_Index_SegmentInfo( $this->_directory, $segName, $segSize, $delGen, $docStoreOptions, $hasSingleNormFile, $isCompound ); } else { // Retrieve actual deletions file generation number $delGen = $this->_segmentInfos[$segName]->getDelGen(); } $newSegmentFile->writeString($segName); $newSegmentFile->writeInt($segSize); $newSegmentFile->writeLong($delGen); if ($this->_targetFormatVersion == Zend_Search_Lucene::FORMAT_2_3) { if ($docStoreOptions !== null) { $newSegmentFile->writeInt($docStoreOffset); $newSegmentFile->writeString($docStoreSegment); $newSegmentFile->writeByte($docStoreIsCompoundFile); } else { // Set DocStoreOffset to -1 $newSegmentFile->writeInt((int)0xFFFFFFFF); } } else if ($docStoreOptions !== null) { // Release index write lock Zend_Search_Lucene_LockManager::releaseWriteLock($this->_directory); throw new Zend_Search_Lucene_Exception('Index conversion to lower format version is not supported.'); } $newSegmentFile->writeByte($hasSingleNormFile); $newSegmentFile->writeInt($numField); if ($numField != (int)0xFFFFFFFF) { foreach ($normGens as $normGen) { $newSegmentFile->writeLong($normGen); } } $newSegmentFile->writeByte($isCompoundByte); $segments[$segName] = $segSize; } } $segmentsFile->close(); $segmentsCount = count($segments) + count($this->_newSegments); foreach ($this->_newSegments as $segName => $segmentInfo) { $newSegmentFile->writeString($segName); $newSegmentFile->writeInt($segmentInfo->count()); // delete file generation: -1 (there is no delete file yet) $newSegmentFile->writeInt((int)0xFFFFFFFF);$newSegmentFile->writeInt((int)0xFFFFFFFF); if ($this->_targetFormatVersion == Zend_Search_Lucene::FORMAT_2_3) { // docStoreOffset: -1 (segment doesn't use shared doc store) $newSegmentFile->writeInt((int)0xFFFFFFFF); } // HasSingleNormFile $newSegmentFile->writeByte($segmentInfo->hasSingleNormFile()); // NumField $newSegmentFile->writeInt((int)0xFFFFFFFF); // IsCompoundFile $newSegmentFile->writeByte($segmentInfo->isCompound() ? 1 : -1); $segments[$segmentInfo->getName()] = $segmentInfo->count(); $this->_segmentInfos[$segName] = $segmentInfo; } $this->_newSegments = array(); $newSegmentFile->seek($numOfSegmentsOffset); $newSegmentFile->writeInt($segmentsCount); // Update segments count $newSegmentFile->close(); } catch (Exception $e) { /** * Restore previous index generation */ $generation--; $genFile->seek(4, SEEK_SET); // Write generation number twice $genFile->writeLong($generation); $genFile->writeLong($generation); // Release index write lock Zend_Search_Lucene_LockManager::releaseWriteLock($this->_directory); // Throw the exception include_once 'Zend/Search/Lucene/Exception.php'; throw new Zend_Search_Lucene_Exception($e->getMessage(), $e->getCode(), $e); } // Write generation (second copy) $genFile->writeLong($generation); // Check if another update or read process is not running now // If yes, skip clean-up procedure if (Zend_Search_Lucene_LockManager::escalateReadLock($this->_directory)) { /** * Clean-up directory */ $filesToDelete = array(); $filesTypes = array(); $filesNumbers = array(); // list of .del files of currently used segments // each segment can have several generations of .del files // only last should not be deleted $delFiles = array(); foreach ($this->_directory->fileList() as $file) { if ($file == 'deletable') { // 'deletable' file $filesToDelete[] = $file; $filesTypes[] = 0; // delete this file first, since it's not used starting from Lucene v2.1 $filesNumbers[] = 0; } else if ($file == 'segments') { // 'segments' file $filesToDelete[] = $file; $filesTypes[] = 1; // second file to be deleted "zero" version of segments file (Lucene pre-2.1) $filesNumbers[] = 0; } else if (preg_match('/^segments_[a-zA-Z0-9]+$/i', $file)) { // 'segments_xxx' file // Check if it's not a just created generation file if ($file != Zend_Search_Lucene::getSegmentFileName($generation)) { $filesToDelete[] = $file; $filesTypes[] = 2; // first group of files for deletions $filesNumbers[] = (int)base_convert(substr($file, 9), 36, 10); // ordered by segment generation numbers } } else if (preg_match('/(^_([a-zA-Z0-9]+))\.f\d+$/i', $file, $matches)) { // one of per segment files ('<segment_name>.f<decimal_number>') // Check if it's not one of the segments in the current segments set if (!isset($segments[$matches[1]])) { $filesToDelete[] = $file; $filesTypes[] = 3; // second group of files for deletions $filesNumbers[] = (int)base_convert($matches[2], 36, 10); // order by segment number } } else if (preg_match('/(^_([a-zA-Z0-9]+))(_([a-zA-Z0-9]+))\.del$/i', $file, $matches)) { // one of per segment files ('<segment_name>_<del_generation>.del' where <segment_name> is '_<segment_number>') // Check if it's not one of the segments in the current segments set if (!isset($segments[$matches[1]])) { $filesToDelete[] = $file; $filesTypes[] = 3; // second group of files for deletions $filesNumbers[] = (int)base_convert($matches[2], 36, 10); // order by segment number } else { $segmentNumber = (int)base_convert($matches[2], 36, 10); $delGeneration = (int)base_convert($matches[4], 36, 10); if (!isset($delFiles[$segmentNumber])) { $delFiles[$segmentNumber] = array(); } $delFiles[$segmentNumber][$delGeneration] = $file; } } else if (isset(self::$_indexExtensions[substr($file, strlen($file)-4)])) { // one of per segment files ('<segment_name>.<ext>') $segmentName = substr($file, 0, strlen($file) - 4); // Check if it's not one of the segments in the current segments set if (!isset($segments[$segmentName]) && ($this->_currentSegment === null || $this->_currentSegment->getName() != $segmentName) ) { $filesToDelete[] = $file; $filesTypes[] = 3; // second group of files for deletions $filesNumbers[] = (int)base_convert(substr($file, 1 /* skip '_' */, strlen($file)-5), 36, 10); // order by segment number } } } $maxGenNumber = 0; // process .del files of currently used segments foreach ($delFiles as $segmentNumber => $segmentDelFiles) { ksort($delFiles[$segmentNumber], SORT_NUMERIC); array_pop($delFiles[$segmentNumber]); // remove last delete file generation from candidates for deleting end($delFiles[$segmentNumber]); $lastGenNumber = key($delFiles[$segmentNumber]); if ($lastGenNumber > $maxGenNumber) { $maxGenNumber = $lastGenNumber; } } foreach ($delFiles as $segmentNumber => $segmentDelFiles) { foreach ($segmentDelFiles as $delGeneration => $file) { $filesToDelete[] = $file; $filesTypes[] = 4; // third group of files for deletions $filesNumbers[] = $segmentNumber*$maxGenNumber + $delGeneration; // order by <segment_number>,<del_generation> pair } } // Reorder files for deleting array_multisort( $filesTypes, SORT_ASC, SORT_NUMERIC, $filesNumbers, SORT_ASC, SORT_NUMERIC, $filesToDelete, SORT_ASC, SORT_STRING ); foreach ($filesToDelete as $file) { try { /** * Skip shared docstore segments deleting */ /** * @todo Process '.cfx' files to check if them are already unused */ if (substr($file, strlen($file)-4) != '.cfx') { $this->_directory->deleteFile($file); } } catch (Zend_Search_Lucene_Exception $e) { if (strpos($e->getMessage(), 'Can\'t delete file') === false) { // That's not "file is under processing or already deleted" exception // Pass it through throw new Zend_Search_Lucene_Exception($e->getMessage(), $e->getCode(), $e); } } } // Return read lock into the previous state Zend_Search_Lucene_LockManager::deEscalateReadLock($this->_directory); } else { // Only release resources if another index reader is running now foreach ($this->_segmentsToDelete as $segName) { foreach (self::$_indexExtensions as $ext) { $this->_directory->purgeFile($segName . $ext); } } } // Clean-up _segmentsToDelete container $this->_segmentsToDelete = array(); // Release index write lock Zend_Search_Lucene_LockManager::releaseWriteLock($this->_directory); // Remove unused segments from segments list foreach ($this->_segmentInfos as $segName => $segmentInfo) { if (!isset($segments[$segName])) { unset($this->_segmentInfos[$segName]); } } }
Update segments file by adding current segment to a list @throws Zend_Search_Lucene_Exception
entailment
public function commit() { if ($this->_currentSegment !== null) { $newSegment = $this->_currentSegment->close(); if ($newSegment !== null) { $this->_newSegments[$newSegment->getName()] = $newSegment; } $this->_currentSegment = null; } $this->_updateSegments(); }
Commit current changes
entailment