sentence1
stringlengths
52
3.87M
sentence2
stringlengths
1
47.2k
label
stringclasses
1 value
public function put($id, $data) { if(!$this->db) { throw new SagException('No database specified'); } if(!is_string($id)) { throw new SagException('put() expected a string for the doc id.'); } if(!isset($data) || (!is_object($data) && !is_string($data) && !is_array($data))) { throw new SagException('put() needs an object for data - are you trying to use delete()?'); } $toSend = (is_string($data)) ? $data : json_encode($data); $id = urlencode($id); $url = "/{$this->db}/$id"; $response = $this->procPacket('PUT', $url, $toSend); unset($toSend); /* * We're going to pretend like we issued a GET or HEAD by replacing the PUT * response's body with the data we sent. We then update that data with the * _rev from the PUT's response's body. Of course this should only run when * there is a successful write to the database: we don't want to be caching * failures. */ if($this->cache && $response->body->ok) { if(is_string($data)) { $data = json_decode($data); } $data->_rev = $response->body->rev; $toCache = clone $response; $toCache->body = $data; $this->cache->set($url, $toCache); unset($toCache); } return $response; }
PUT's the data to the document. @param string $id The document's _id. @param mixed $data The document, which should have _id and _rev properties. Can be an object, array, or string. @return mixed
entailment
public function post($data, $path = null) { if(!$this->db) { throw new SagException('No database specified'); } if(!isset($data) || (!is_string($data) && !is_object($data) && !is_array($data))) { throw new SagException('post() needs an object for data.'); } if(!is_string($data)) { $data = json_encode($data); } if(is_string($path) && !empty($path)) { if ($path[0] === '/') { $path = '/'.urlencode(substr($path, 1)); } else { $path = '/'.urlencode($path); } } else if(isset($path)) { throw new SagException('post() needs a string for a path.'); } return $this->procPacket('POST', "/{$this->db}{$path}", $data); }
POST's the provided document. When using a SagCache, the created document and response are not cached. @param mixed $data The document that you want created. Can be an object, array, or string. @param string $path Can be the path to a view or /all_docs. The database will be prepended to the value. @return mixed
entailment
public function bulk($docs, $allOrNothing = false) { if(!$this->db) { throw new SagException('No database specified'); } if(!is_array($docs)) { throw new SagException('bulk() expects an array for its first argument'); } if(!is_bool($allOrNothing)) { throw new SagException('bulk() expects a boolean for its second argument'); } $data = new stdClass(); //Only send all_or_nothing if it's non-default (true), saving bandwidth. if($allOrNothing) { $data->all_or_nothing = $allOrNothing; } $data->docs = $docs; return $this->procPacket("POST", "/{$this->db}/_bulk_docs", json_encode($data)); }
Bulk pushes documents to the database. This function does not leverage the caching mechanism you specify with setCache(). @param array $docs An array of the documents you want to be pushed; they can be JSON strings, objects, or arrays. @param bool $allOrNothing Whether to treat the transactions as "all or nothing" or not. Defaults to false. @return mixed
entailment
public function copy($srcID, $dstID, $dstRev = null) { if(!$this->db) { throw new SagException('No database specified'); } if(empty($srcID) || !is_string($srcID)) { throw new SagException('copy() got an invalid source ID'); } if(empty($dstID) || !is_string($dstID)) { throw new SagException('copy() got an invalid destination ID'); } if($dstRev != null && (empty($dstRev) || !is_string($dstRev))) { throw new SagException('copy() got an invalid source revision'); } $headers = array( "Destination" => "$dstID".(($dstRev) ? "?rev=$dstRev" : "") ); $srcID = urlencode($srcID); $response = $this->procPacket('COPY', "/{$this->db}/$srcID", null, $headers); return $response; }
COPY's the document. If you are using a SagCache and are copying to an existing destination, then the result will be cached (ie., what's copied to the /$destID URL). @param string The _id of the document you're copying. @param string The _id of the document you're copying to. @param string The _rev of the document you're copying to. Defaults to null. @return mixed
entailment
public function setDatabase($db, $createIfNotFound = false) { if($this->db != $db || $createIfNotFound) { if(!is_string($db)) { throw new SagException('setDatabase() expected a string.'); } $db = urlencode($db); if($createIfNotFound) { try { self::procPacket('HEAD', "/{$db}"); } catch(SagCouchException $e) { if($e->getCode() != 404) { throw $e; //these are not the errors that we are looking for } self::createDatabase($db); } } $this->db = $db; } return $this; }
Sets which database Sag is going to send all of its database related communications to (ex., dealing with documents). When specifying that the database should be created if it doesn't already exists, this will cause an HTTP GET to be sent to /dbName and createDatabase($db) if a 404 response is returned. So, only turn it on if it makes sense for your application, because it could cause needless HTTP GET calls. @param string $db The database's name, as you'd put in the URL. This string will be URL encoded using PHP's urlencode(). @param bool $createIfNotFound Whether to try and create the specified database if it doesn't exist yet (checks every time this is called). @return Sag Returns $this. Throws on failure.
entailment
public function getAllDocs($incDocs = false, $limit = null, $startKey = null, $endKey = null, $keys = null, $descending = false, $skip = 0) { if(!$this->db) { throw new SagException('No database specified.'); } $qry = array(); if($incDocs !== false) { if(!is_bool($incDocs)) { throw new SagException('getAllDocs() expected a boolean for include_docs.'); } $qry[] = "include_docs=true"; } if(isset($startKey)) { if(!is_string($startKey)) { throw new SagException('getAllDocs() expected a string for startkey.'); } $qry[] = 'startkey='.urlencode($startKey); } if(isset($endKey)) { if(!is_string($endKey)) { throw new SagException('getAllDocs() expected a string for endkey.'); } $qry[] = 'endkey='.urlencode($endKey); } if(isset($limit)) { if(!is_int($limit) || $limit < 0) { throw new SagException('getAllDocs() expected a positive integeter for limit.'); } $qry[] = 'limit='.urlencode($limit); } if($descending !== false) { if(!is_bool($descending)) { throw new SagException('getAllDocs() expected a boolean for descending.'); } $qry[] = "descending=true"; } if(isset($skip)) { if(!is_int($skip) || $skip < 0) { throw new SagException('getAllDocs() expected a non-negative integer for skip'); } $qry[] = 'skip=' . urlencode($skip); } $qry = '?'.implode('&', $qry); if(isset($keys)) { if(!is_array($keys)) { throw new SagException('getAllDocs() expected an array for the keys.'); } $data = new stdClass(); $data->keys = $keys; return $this->procPacket('POST', "/{$this->db}/_all_docs$qry", json_encode($data)); } return $this->procPacket('GET', "/{$this->db}/_all_docs$qry"); }
Gets all the documents in the database with _all_docs. Its results will not be cached by SagCache. @param bool $incDocs Whether to include the documents or not. Defaults to false. @param int $limit Limits the number of documents to return. Must be >= 0, or null for no limit. Defaults to null (no limit). @param string $startKey The startkey variable (valid JSON). Defaults to null. @param string $endKey The endkey variable (valid JSON). Defaults to null. @param array $keys An array of keys (strings) of the specific documents you're trying to get. @param bool $descending Whether to sort the results in descending order or not. @param int $skip Skip this number of records before starting to return the results. Defaults to 0. @return mixed
entailment
public function replicate($src, $target, $continuous = false, $createTarget = null, $filter = null, $filterQueryParams = null) { if(empty($src) || !is_string($src)) { throw new SagException('replicate() is missing a source to replicate from.'); } if(empty($target) || !is_string($target)) { throw new SagException('replicate() is missing a target to replicate to.'); } if(!is_bool($continuous)) { throw new SagException('replicate() expected a boolean for its third argument.'); } if(isset($createTarget) && !is_bool($createTarget)) { throw new SagException('createTarget needs to be a boolean.'); } if(isset($filter)) { if(!is_string($filter)) { throw new SagException('filter must be the name of a design doc\'s filter function: ddoc/filter'); } if(isset($filterQueryParams) && !is_object($filterQueryParams) && !is_array($filterQueryParams)) { throw new SagException('filterQueryParams needs to be an object or an array'); } } $data = new stdClass(); $data->source = $src; $data->target = $target; /* * These guys are optional, so only include them if non-default to save on * packet size. */ if($continuous) { $data->continuous = true; } if($createTarget) { $data->create_target = true; } if($filter) { $data->filter = $filter; if($filterQueryParams) { $data->query_params = $filterQueryParams; } } return $this->procPacket('POST', '/_replicate', json_encode($data)); }
Starts a replication job between two databases, independently of which database you set with Sag. @param string $src The name of the database that you are replicating from. @param string $target The name of the database that you are replicating to. @param bool $continuous Whether to make this a continuous replication job or not. Defaults to false. @param bool $createTarget Specifies create_target, which will create the target database if it does not already exist. (optional) @param string $filter The name of the filter function to use. (optional) @param mixed $filterQueryParams An object or associative array of parameters to be passed to the filter function via query_params. Only used if $filter is set. @return mixed
entailment
public function setAttachment($name, $data, $contentType, $docID, $rev = null) { if(empty($docID)) { throw new SagException('You need to provide a document ID.'); } if(empty($name)) { throw new SagException('You need to provide the attachment\'s name.'); } if(empty($data)) { throw new SagException('You need to provide the attachment\'s data.'); } if(!is_string($data)) { throw new SagException('You need to provide the attachment\'s data as a string.'); } if(empty($contentType)) { throw new SagException('You need to provide the data\'s Content-Type.'); } return $this->procPacket('PUT', "/{$this->db}/{$docID}/{$name}".(($rev) ? "?rev=".urlencode($rev) : ""), $data, array("Content-Type" => $contentType)); }
Create or update attachments on documents by passing in a serialized version of your attachment (a string). @param string $name The attachment's name. @param string $data The attachment's data, in string representation. Ie., you need to serialize your attachment. @param string $contentType The proper Content-Type for your attachment. @param string $docID The _id of the document that the attachment belongs to. @param string $rev optional The _rev of the document that the attachment belongs to. Leave blank if you are creating a new document. @return mixed
entailment
public function setCookie($key, $value) { if(!$key || !is_string($key)) { throw new SagException('Unexpected cookie key.'); } if($value && !is_string($value)) { throw new SagException('Unexpected cookie value.'); } if($value) { $this->globalCookies[$key] = $value; } else { unset($this->globalCookies[$key]); } return $this; }
Sets a global cookie that will overwrite any other internal cookie values that Sag tries to set. For example, if you set AuthSession and call login(), then the AuthSession value you specify will overwrite the value retrieved from the server, so don't set AuthSession while using login(). Setting the value to null will make Sag no longer send the cookie. @param string $key The cookie's key. @param string $value The cookie's value. @return Sag Returns $this. @see getCookie()
entailment
public function getCookie($key) { return (!empty($this->globalCookies[$key])) ? $this->globalCookies[$key] : null; }
Returns the global cookie as set in setCookie(). @return String The cookie's value or null if not set. @see setCookie()
entailment
public function setSSLCert($path) { if($path !== null) { if(!is_string($path) || !$path) { throw new SagException('Invalid file path provided.'); } if(!is_file($path)) { throw new SagException('That path does not point to a file.'); } if(!is_readable($path)) { throw new SagException('PHP does not have read privileges with that file.'); } } $this->httpAdapter->setSSLCert($path); return $this; }
Provide a path to a file that contains one or more certificates to verify the CouchDB host with when using SSL. Only applies if you set useSSL(true). @param string $path File path to the certificate file. Pass null to unset the path. @return Sag Returns $this. @see useSSL()
entailment
private function procPacket($method, $url, $data = null, $headers = array()) { /* * For now we only data data as strings. Streams and other formats will be * permitted later. */ if($data && !is_string($data)) { throw new SagException('Unexpected data format. Please report this bug.'); } if($this->pathPrefix && is_string($this->pathPrefix)) { $url = $this->pathPrefix . $url; } // Filter the use of the Expect header since we don't support Continue headers. $headers['Expect'] = isset($headers['Expect']) ? $headers['Expect'] : null; if(!$headers['Expect']){ /* * PHP cURL will set the Expect header to 100-continue if we don't set it * ourselves. See https://github.com/sbisbee/sag/pull/51 */ $headers['Expect'] = (isset($headers['expect']) && $headers['expect']) ? $headers['expect'] : ' '; //1 char string, so it's == to true } if(strtolower($headers['Expect']) === '100-continue') { throw new SagException('Sag does not support HTTP/1.1\'s Continue.'); } // Build the request packet. $headers["Host"] = "{$this->host}:{$this->port}"; $headers["User-Agent"] = "Sag/%VERSION%"; /* * This prevents some unRESTful requests, such as inline attachments in * CouchDB 1.1.0, from sending multipart responses that would break our * parser. */ $headers['Accept'] = 'application/json'; //usernames and passwords can be blank if($this->authType == Sag::$AUTH_BASIC && (isset($this->user) || isset($this->pass))) { $headers["Authorization"] = 'Basic '.base64_encode("{$this->user}:{$this->pass}"); } elseif($this->authType == Sag::$AUTH_COOKIE && isset($this->authSession)) { $headers['Cookie'] = array( 'AuthSession' => $this->authSession ); $headers['X-CouchDB-WWW-Authenticate'] = 'Cookie'; } if(is_array($this->globalCookies) && sizeof($this->globalCookies)) { //might have been set before by auth handling if($headers['Cookie']) { $headers['Cookie'] = array_merge($headers['Cookie'], $this->globalCookies); } else { $headers['Cookie'] = $this->globalCookies; } } /* * Checking this again because $headers['Cookie'] could be set in two * different logic paths above. */ if(!empty($headers['Cookie'])) { $buff = ''; foreach($headers['Cookie'] as $k => $v) { $buff = (($buff) ? ' ' : '') . "$k=$v;"; } $headers['Cookie'] = $buff; unset($buff); } /* * JSON is our default and most used Content-Type, but others need to be * specified to allow attachments. */ if(!isset($headers['Content-Type'])) { $headers['Content-Type'] = 'application/json'; } if($data) { $headers['Content-Length'] = strlen($data); } return $this->httpAdapter->procPacket($method, $url, $data, $headers); }
The main driver - does all the socket and protocol work.
entailment
private function setURLParameter($url, $key, $value) { $url = parse_url($url); if(!empty($url['query'])) { parse_str($url['query'], $params); } $params[$key] = $value; return $url = $url['path'].'?'.http_build_query($params); }
Takes a URL and k/v combo for a URL parameter, break the query string out of the URL, and sets the parameter to the k/v pair you pass in. This will overwrite a paramter's value if it already exists in the URL, or simply create it if it doesn't already. @param string $url The URL to run against. @param string $key The name of the parameter to set in the URL. @param string $value The value of the parameter to set in the URL. @return string The modified URL.
entailment
protected function extractMetaData(ZipArchive $package) { // Data holders $coreProperties = array(); // Read relations and search for core properties $relations = simplexml_load_string($package->getFromName("_rels/.rels")); foreach ($relations->Relationship as $rel) { if ($rel["Type"] == Zend_Search_Lucene_Document_OpenXml::SCHEMA_COREPROPERTIES) { // Found core properties! Read in contents... $contents = simplexml_load_string( $package->getFromName(dirname($rel["Target"]) . "/" . basename($rel["Target"])) ); foreach ($contents->children(Zend_Search_Lucene_Document_OpenXml::SCHEMA_DUBLINCORE) as $child) { $coreProperties[$child->getName()] = (string)$child; } foreach ($contents->children(Zend_Search_Lucene_Document_OpenXml::SCHEMA_COREPROPERTIES) as $child) { $coreProperties[$child->getName()] = (string)$child; } foreach ($contents->children(Zend_Search_Lucene_Document_OpenXml::SCHEMA_DUBLINCORETERMS) as $child) { $coreProperties[$child->getName()] = (string)$child; } } } return $coreProperties; }
Extract metadata from document @param ZipArchive $package ZipArchive OpenXML package @return array Key-value pairs containing document meta data
entailment
public function send($recipient, $body, $originator = '', $user_ref = null) { $this->checkCredentials(); $this->validateRecipient($recipient); $params = array( 'USERNAME' => $this->username, 'PASSWORD' => $this->password, 'TEXT' => $body, 'FROM' => $originator, 'TO' => $recipient, ); if (null !== $user_ref) { $params['TAG'] = $user_ref; } $xml = $this->buildSendSmsPayload($this->getParameters($params)); return $this->executeQuery(self::SEND_SMS_URL, $xml, array( 'recipient' => $recipient, 'body' => $body, 'originator' => $originator, )); }
{@inheritDoc}
entailment
protected function encodeMessage($msg) { $encodings = array( 9 => '&#009;', 10 => '&#010;', 13 => '&#013;', 32 => '&#032;', 34 => '&quot;', 39 => '&apos;', ); $ret = array(); for ($j = 0; $j < strlen($msg); $j++) { $str = $msg[$j]; $asci = ord($str); if (isset($encodings[ $asci ])) { $ret[] = $encodings[ $asci ]; } elseif ($asci >= 128 || $asci < 32 || in_array($str, array('*', '#', '%', '<', '>', '+' ))) { $ret[] = strtoupper('%' . sprintf("%02s", dechex($asci))); } else { $ret[] = $str; } } return implode('', $ret); }
Encodes the message according to doc @param string $msg @return string
entailment
protected function buildGetCreditPayload() { $xml = new \SimpleXMLElement( '<?xml version="1.0" encoding="ISO-8859-1"?>'. '<!DOCTYPE REQUESTCREDIT SYSTEM "http://127.0.0.1:80/psms/dtd/requestcredit.dtd">'. '<REQUESTCREDIT></REQUESTCREDIT>' ); $xml->addAttribute('USERNAME', $this->username); $xml->addAttribute('PASSWORD', $this->password); return $xml->asXml(); }
Constructs valid XML for sending SMS-CR credit request service @return string
entailment
protected function buildGetStatusPayload($messageId) { $xml = new \SimpleXMLElement( '<?xml version="1.0" encoding="ISO-8859-1"?>'. '<!DOCTYPE STATUSREQUEST SYSTEM "http://127.0.0.1:80/psms/dtd/requeststatusv12.dtd">'. '<STATUSREQUEST VER="1.2"></STATUSREQUEST>' ); $user = $xml->addChild('USER'); $user->addAttribute('USERNAME', $this->username); $user->addAttribute('PASSWORD', $this->password); $guid = $xml->addChild('GUID'); $guid->addAttribute('GUID', $messageId); return $xml->asXml(); }
Constructs valid XML for sending SMS-SR request service @param string $messageId @return string
entailment
protected function buildSendSmsPayload(array $data = array()) { $xml = new \SimpleXMLElement( '<?xml version="1.0" encoding="ISO-8859-1"?>'. '<!DOCTYPE MESSAGE SYSTEM "http://127.0.0.1:80/psms/dtd/messagev12.dtd">'. '<MESSAGE VER="1.2"></MESSAGE>' ); $user = $xml->addChild('USER'); foreach (array('USERNAME', 'PASSWORD') as $key) { if (!isset($data[$key])) { continue; } $user->addAttribute($key, $data[$key]); } $sms = $xml->addChild('SMS'); foreach (array('UDH', 'CODING', 'PROPERTY', 'ID', 'TEXT', 'DLR', 'VALIDITY', 'SEND_ON') as $key) { if (!isset($data[$key])) { continue; } if ('TEXT' === $key) { $sms->addAttribute($key, $this->encodeMessage($data[$key])); } else { $sms->addAttribute($key, $data[$key]); } } $address = $sms->addChild('ADDRESS'); foreach (array('FROM', 'TO', 'SEQ', 'TAG') as $k) { if (isset($data[ $k ])) { $address->addAttribute($k, $data[ $k ]); } } return $xml->asXml(); }
Constructs valid XML for sending SMS-MT message @param array $data @return string
entailment
public function getParameters(array $additionnal_parameters = array()) { $defaults = array( // ------------- USER TAG ------------- /* * User name of the sender of the message. */ 'USERNAME' => null, /* * User password */ 'PASSWORD' => null, // ------------- SMS TAG ------------- /* * UDH is used for sending binary messages. * For text message the value should be 0. */ 'UDH' => 0, /* * Extended type of messages. * For text message the value should be 1. */ 'CODING' => 1, /* * Unique property of message. * Default value is 0. * For sending Flash SMS the value should be 1. */ 'PROPERTY' => 0, /* * Unique ID of message. The client sends this value. In future communication, * server sends this value back to the client. This value is used in future to check * status of the message. */ 'ID' => 1, /* * This field describe the message text to be sent to receiver. * SMS can contain up to 160 characters in Message Text. * API allows user to send Message text of more than 160 characters. * Credits will be deducted in the multiple of 160 characters according to the length of SMS. */ 'TEXT' => null, /* * Delivery Report * Accepted Values are 0 and 1. * When set to 0, the service shall not ask operator for delivery report. * Default is 1. * This parameter is optional */ 'DLR' => null, /* * Set the validity of a message to current SMSC time plus minutes specified in Validity field. * SMSC will not try to send the message after the validity has expired. */ 'VALIDITY' => null, /* * To schedule message to go at a later time, user can specify "SEND_ON" date as attribute of SMS tag. * Only absolute date is supported. * The value should be given in "YYYY-MM-DD HH:MM:SS TIMEZONE" format (eg. 2007-10-15 20:10:10 +0530) * Timezone is difference wrt to GMT. */ 'SEND_ON' => null, // ------------- ADDRESS TAG ------------- // <ADDRESS FROM="9812345678" TO="919812345678" SEQ="1" /> /* * The Sender of the message. * This field should conform to Sender Phone Number guidelines */ 'FROM' => null, /* * Person receiving the SMS, should conform to Receiver Phone Number guidelines */ 'TO' => null, /* * Unique Sequence ID. * Must be an integer and must be unique to each SMS. * While checking message status you must send this value. */ 'SEQ' => 1, /* * A text that identify message. * This is an optional parameter */ 'TAG' => uniqid(), // null, ); return array_filter( array_merge($defaults, $additionnal_parameters), array($this, 'isNotNull') ); }
Builds the parameters list to send to the API. @return array
entailment
protected function parseSendResponse($result, array $extra_result_data = array()) { libxml_use_internal_errors(true); if (false === ($result = simplexml_load_string(trim($result)))) { throw new Exception\RuntimeException('API response isn\'t a valid XML string'); } if (null !== ($error = $this->checkForError($result))) { throw $error; } // The message was successfully sent! return array_merge($this->getDefaults(), $extra_result_data, array( 'status' => ResultInterface::STATUS_SENT, 'id' => (string) $result->GUID['GUID'] )); }
Parses the data returned by the API. @param string $result The raw result string. @param array $extra_result_data @return array @throws Exception if error code found
entailment
protected function checkForError(\SimpleXMLElement $result) { /* -- sample general error -- <?xml version="1.0" encoding="ISO-8859-1"?> <MESSAGEACK> <Err Code="65535" Desc="The Specified message does not conform to DTD"/> </MESSAGEACK> */ if (0 !== $result->Err->count()) { $code = (int) $result->Err['Code']; throw new Exception\RuntimeException($this->getApiMessage($code), $code); } /* -- sample message post error -- <?xml version="1.0" encoding="ISO-8859-1"?> <MESSAGEACK> <GUID GUID="ke3ql370590732f440014mucv1RAPIDOSPOR" SUBMITDATE="2014-03-26 21:37:05" ID="1"> <ERROR SEQ="1" CODE="28682" /> </GUID> </MESSAGEACK> */ if (0 !== $result->GUID->ERROR->count()) { $code = (int) $result->GUID->ERROR['CODE']; throw new Exception\RuntimeException($this->getApiMessage($code), $code); } }
@param SimpleXMLElement $result The raw result string. @return Exception\Exception
entailment
public static function binary($name, $value) { return new self($name, $value, '', true, false, false, true); }
Constructs a Binary String valued Field that is not tokenized nor indexed, but is stored in the index, for return with hits. @param string $name @param string $value @param string $encoding @return Zend_Search_Lucene_Field
entailment
public static function text($name, $value, $encoding = '') { return new self($name, $value, $encoding, true, true, true); }
Constructs a String-valued Field that is tokenized and indexed, and is stored in the index, for return with hits. Useful for short text fields, like "title" or "subject". Term vector will not be stored for this field. @param string $name @param string $value @param string $encoding @return Zend_Search_Lucene_Field
entailment
public static function unStored($name, $value, $encoding = '') { return new self($name, $value, $encoding, false, true, true); }
Constructs a String-valued Field that is tokenized and indexed, but that is not stored in the index. @param string $name @param string $value @param string $encoding @return Zend_Search_Lucene_Field
entailment
public function getUtf8Value() { if (strcasecmp($this->encoding, 'utf8') == 0 || strcasecmp($this->encoding, 'utf-8') == 0 ) { return $this->value; } else { return (PHP_OS != 'AIX') ? iconv($this->encoding, 'UTF-8', $this->value) : iconv('ISO8859-1', 'UTF-8', $this->value); } }
Get field value in UTF-8 encoding @return string
entailment
protected function cleanOriginator($number) { // Remove any invalid characters $ret = preg_replace('/[^a-zA-Z0-9]/', '', (string) $number); if (preg_match('/[a-zA-Z]/', $number)) { // Alphanumeric format so make sure it's < 11 chars $ret = substr($ret, 0, 11); } else { // Numerical, remove any prepending '00' if (substr($ret, 0, 2) == '00') { $ret = substr($ret, 2); $ret = substr($ret, 0, 15); } } return (string) $ret; }
Validate an originator string If the originator ('from' field) is invalid, some networks may reject the network whilst stinging you with the financial cost! While this cannot correct them, it will try its best to correctly format them. @param string $number The phone number to clean. @return string The cleaned phone number.
entailment
public function &readBuffer($length) { if ($length+$this->cursor > strlen($this->rawData)) { throw new Exception('Buffer underrun at position: '. $this->cursor . '. Trying to fetch '. $length . ' bytes'); return false; } $data = substr($this->rawData,$this->cursor,$length); $this->cursor+=$length; return $data; }
&readBuffer @param int $length @return mixed
entailment
public function readDouble() { $double = $this->readBuffer(8); $testEndian = unpack("C*",pack("S*",256)); $bigEndian = !$testEndian[1]==1; if ($bigEndian) $double = strrev($double); $double = unpack("d",$double); return $double[1]; }
readDouble @return float
entailment
function get($key, $default = null) { if (!is_string($key)) { throw new InvalidArgumentException('$key must be a string'); } if (!isset($this->cache[$key])) { return $default; } list($expire, $value) = $this->cache[$key]; if (!is_null($expire) && $expire < time()) { // If a ttl was set and it expired in the past, invalidate the // cache. $this->delete($key); return $default; } return $value; }
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 set($key, $value, $ttl = null) { if (!is_string($key)) { throw new InvalidArgumentException('$key must be a string'); } if ($ttl instanceof DateInterval) { $expire = (new DateTime('now'))->add($ttl)->getTimeStamp(); } elseif (is_int($ttl) || ctype_digit($ttl)) { $expire = time() + $ttl; } else { $expire = null; } $this->cache[$key] = [$expire, $value]; return true; }
Persists data in the cache, uniquely referenced by a key with an optional expiration TTL time. @param string $key The key of the item to store. @param mixed $value The value of the item to store, must be serializable. @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 the $key string is not a legal value. @return bool True on success and false on failure.
entailment
public function connect($host, $port = null, $ssl = false) { $isTls = false; if ($ssl) { $ssl = strtolower($ssl); } switch ($ssl) { case 'ssl': $host = 'ssl://'.$host; if (!$port) { $port = 995; } break; case 'tls': $isTls = true; // break intentionally omitted default: if (!$port) { $port = 110; } } try { $this->_socket = fsockopen($host, $port, $errno, $errstr, $this->timeoutConnection); } catch (\Exception $e) { //throw new \RuntimeException('cannot connect to host '.$host.PHP_EOL.$errstr, $errno); } if (!$this->_socket) { throw new \RuntimeException($e->getMessage()); } $welcome = $this->readResponse(); strtok($welcome, '<'); $this->_timestamp = strtok('>'); if (!strpos($this->_timestamp, '@')) { $this->_timestamp = null; } else { $this->_timestamp = '<'.$this->_timestamp.'>'; } if ($isTls) { $this->request('STLS'); $result = stream_socket_enable_crypto($this->_socket, true, STREAM_CRYPTO_METHOD_TLS_CLIENT); if (!$result) { throw new \RuntimeException('cannot enable TLS'); } } return $welcome; }
Open connection to POP3 server @param string $host hostname or IP address of POP3 server @param int|null $port of POP3 server, default is 110 (995 for ssl) @param string|bool $ssl use 'SSL', 'TLS' or false @throws \RuntimeException @return string welcome message
entailment
public function sendRequest($request) { try { $result = fputs($this->_socket, $request."\r\n"); } catch (\Exception $e) { } if (!$result) { throw new \RuntimeException('send failed - connection closed?'.$e->getMessage()); } }
Send a request @param string $request your request without newline @throws \RuntimeException
entailment
public function readResponse($multiline = false) { try { $result = fgets($this->_socket); } catch (\Exception $e) { } if (!is_string($result)) { throw new \RuntimeException('read failed - connection closed?'.$e->getMessage()); } $result = trim($result); if (strpos($result, ' ')) { list($status, $message) = explode(' ', $result, 2); } else { $status = $result; $message = ''; } if ($status != '+OK') { throw new \RuntimeException($result); } if ($multiline) { $message = ''; $line = fgets($this->_socket); while ($line && rtrim($line, "\r\n") != '.') { if ($line[0] == '.') { $line = substr($line, 1); } $message .= $line; $line = fgets($this->_socket); }; } return $message; }
read a response @param bool $multiline response has multiple lines and should be read until "<nl>.<nl>" @throws \RuntimeException @return string response
entailment
public function logout() { if ($this->_socket) { try { $this->request('QUIT'); } catch (\Exception $e) { // ignore error - we're closing the socket anyway } fclose($this->_socket); $this->_socket = null; } }
End communication with POP3 server (also closes socket)
entailment
public function login($user, $password, $tryApop = true) { if ($tryApop && $this->_timestamp) { try { $this->request("APOP $user ".md5($this->_timestamp.$password)); return; } catch (\Exception $e) { // ignore } } $this->request("USER $user"); $this->request("PASS $password"); }
Login to POP3 server. Can use APOP @param string $user username @param string $password password @param bool $tryApop should APOP be tried?
entailment
private static function _floatToByte($f) { // round negatives up to zero if ($f <= 0.0) { return 0; } // search for appropriate value $lowIndex = 0; $highIndex = 255; while ($highIndex >= $lowIndex) { // $mid = ($highIndex - $lowIndex)/2; $mid = ($highIndex + $lowIndex) >> 1; $delta = $f - self::$_normTable[$mid]; if ($delta < 0) { $highIndex = $mid-1; } elseif ($delta > 0) { $lowIndex = $mid+1; } else { return $mid; // We got it! } } // round to closest value if ($highIndex != 255 && $f - self::$_normTable[$highIndex] > self::$_normTable[$highIndex+1] - $f ) { return $highIndex + 1; } else { return $highIndex; } }
Float to byte conversion @param integer $b @return float
entailment
public function idf($input, Zend_Search_Lucene_Interface $reader) { if (!is_array($input)) { return $this->idfFreq($reader->docFreq($input), $reader->count()); } else { $idf = 0.0; foreach ($input as $term) { $idf += $this->idfFreq($reader->docFreq($term), $reader->count()); } return $idf; } }
Computes a score factor for a simple term or a phrase. The default implementation is: return idfFreq(searcher.docFreq(term), searcher.maxDoc()); input - the term in question or array of terms reader - reader the document collection being searched Returns a score factor for the term @param mixed $input @param Zend_Search_Lucene_Interface $reader @return a score factor for the term
entailment
private function _parseRichText($is = null) { $value = array(); if (isset($is->t)) { $value[] = (string)$is->t; } else { foreach ($is->r as $run) { $value[] = (string)$run->t; } } return implode('', $value); }
Parse rich text XML @param SimpleXMLElement $is @return string
entailment
private function _loadDelFile() { if ($this->_delGen == -1) { // There is no delete file for this segment return null; } else if ($this->_delGen == 0) { // It's a segment with pre-2.1 format delete file // Try to load deletions file return $this->_loadPre21DelFile(); } else { // It's 2.1+ format deleteions file return $this->_load21DelFile(); } }
Load detetions file Returns bitset or an array depending on bitset extension availability @return mixed @throws Zend_Search_Lucene_Exception
entailment
private function _loadPre21DelFile() { require_once 'Zend/Search/Lucene/Exception.php'; try { // '.del' files always stored in a separate file // Segment compound is not used $delFile = $this->_directory->getFileObject($this->_name . '.del'); $byteCount = $delFile->readInt(); $byteCount = ceil($byteCount/8); $bitCount = $delFile->readInt(); if ($bitCount == 0) { $delBytes = ''; } else { $delBytes = $delFile->readBytes($byteCount); } if (extension_loaded('bitset')) { return $delBytes; } else { $deletions = array(); for ($count = 0; $count < $byteCount; $count++) { $byte = ord($delBytes[$count]); for ($bit = 0; $bit < 8; $bit++) { if ($byte & (1<<$bit)) { $deletions[$count*8 + $bit] = 1; } } } return $deletions; } } catch(Zend_Search_Lucene_Exception $e) { if (strpos($e->getMessage(), 'is not readable') === false) { throw new Zend_Search_Lucene_Exception($e->getMessage(), $e->getCode(), $e); } // There is no deletion file $this->_delGen = -1; return null; } }
Load pre-2.1 detetions file Returns bitset or an array depending on bitset extension availability @return mixed @throws Zend_Search_Lucene_Exception
entailment
private function _load21DelFile() { $delFile = $this->_directory->getFileObject($this->_name . '_' . base_convert($this->_delGen, 10, 36) . '.del'); $format = $delFile->readInt(); if ($format == (int)0xFFFFFFFF) { if (extension_loaded('bitset')) { $deletions = bitset_empty(); } else { $deletions = array(); } $byteCount = $delFile->readInt(); $bitCount = $delFile->readInt(); $delFileSize = $this->_directory->fileLength($this->_name . '_' . base_convert($this->_delGen, 10, 36) . '.del'); $byteNum = 0; do { $dgap = $delFile->readVInt(); $nonZeroByte = $delFile->readByte(); $byteNum += $dgap; if (extension_loaded('bitset')) { for ($bit = 0; $bit < 8; $bit++) { if ($nonZeroByte & (1<<$bit)) { bitset_incl($deletions, $byteNum*8 + $bit); } } return $deletions; } else { for ($bit = 0; $bit < 8; $bit++) { if ($nonZeroByte & (1<<$bit)) { $deletions[$byteNum*8 + $bit] = 1; } } return (count($deletions) > 0) ? $deletions : null; } } while ($delFile->tell() < $delFileSize); } else { // $format is actually byte count $byteCount = ceil($format/8); $bitCount = $delFile->readInt(); if ($bitCount == 0) { $delBytes = ''; } else { $delBytes = $delFile->readBytes($byteCount); } if (extension_loaded('bitset')) { return $delBytes; } else { $deletions = array(); for ($count = 0; $count < $byteCount; $count++) { $byte = ord($delBytes[$count]); for ($bit = 0; $bit < 8; $bit++) { if ($byte & (1<<$bit)) { $deletions[$count*8 + $bit] = 1; } } } return (count($deletions) > 0) ? $deletions : null; } } }
Load 2.1+ format detetions file Returns bitset or an array depending on bitset extension availability @return mixed
entailment
public function openCompoundFile($extension, $shareHandler = true) { if (($extension == '.fdx' || $extension == '.fdt') && $this->_usesSharedDocStore) { $fdxFName = $this->_sharedDocStoreOptions['segment'] . '.fdx'; $fdtFName = $this->_sharedDocStoreOptions['segment'] . '.fdt'; if (!$this->_sharedDocStoreOptions['isCompound']) { $fdxFile = $this->_directory->getFileObject($fdxFName, $shareHandler); $fdxFile->seek($this->_sharedDocStoreOptions['offset']*8, SEEK_CUR); if ($extension == '.fdx') { // '.fdx' file is requested return $fdxFile; } else { // '.fdt' file is requested $fdtStartOffset = $fdxFile->readLong(); $fdtFile = $this->_directory->getFileObject($fdtFName, $shareHandler); $fdtFile->seek($fdtStartOffset, SEEK_CUR); return $fdtFile; } } if( !isset($this->_sharedDocStoreOptions['files'][$fdxFName]) ) { require_once 'Zend/Search/Lucene/Exception.php'; throw new Zend_Search_Lucene_Exception('Shared doc storage segment compound file doesn\'t contain ' . $fdxFName . ' file.' ); } if( !isset($this->_sharedDocStoreOptions['files'][$fdtFName]) ) { require_once 'Zend/Search/Lucene/Exception.php'; throw new Zend_Search_Lucene_Exception('Shared doc storage segment compound file doesn\'t contain ' . $fdtFName . ' file.' ); } // Open shared docstore segment file $cfxFile = $this->_directory->getFileObject($this->_sharedDocStoreOptions['segment'] . '.cfx', $shareHandler); // Seek to the start of '.fdx' file within compound file $cfxFile->seek($this->_sharedDocStoreOptions['files'][$fdxFName]); // Seek to the start of current segment documents section $cfxFile->seek($this->_sharedDocStoreOptions['offset']*8, SEEK_CUR); if ($extension == '.fdx') { // '.fdx' file is requested return $cfxFile; } else { // '.fdt' file is requested $fdtStartOffset = $cfxFile->readLong(); // Seek to the start of '.fdt' file within compound file $cfxFile->seek($this->_sharedDocStoreOptions['files'][$fdtFName]); // Seek to the start of current segment documents section $cfxFile->seek($fdtStartOffset, SEEK_CUR); return $fdtFile; } } $filename = $this->_name . $extension; if (!$this->_isCompound) { return $this->_directory->getFileObject($filename, $shareHandler); } if( !isset($this->_segFiles[$filename]) ) { require_once 'Zend/Search/Lucene/Exception.php'; throw new Zend_Search_Lucene_Exception('Segment compound file doesn\'t contain ' . $filename . ' file.' ); } $file = $this->_directory->getFileObject($this->_name . '.cfs', $shareHandler); $file->seek($this->_segFiles[$filename]); return $file; }
Opens index file stoted within compound index file @param string $extension @param boolean $shareHandler @throws Zend_Search_Lucene_Exception @return Zend_Search_Lucene_Storage_File
entailment
public function compoundFileLength($extension) { if (($extension == '.fdx' || $extension == '.fdt') && $this->_usesSharedDocStore) { $filename = $this->_sharedDocStoreOptions['segment'] . $extension; if (!$this->_sharedDocStoreOptions['isCompound']) { return $this->_directory->fileLength($filename); } if( !isset($this->_sharedDocStoreOptions['fileSizes'][$filename]) ) { require_once 'Zend/Search/Lucene/Exception.php'; throw new Zend_Search_Lucene_Exception('Shared doc store compound file doesn\'t contain ' . $filename . ' file.' ); } return $this->_sharedDocStoreOptions['fileSizes'][$filename]; } $filename = $this->_name . $extension; // Try to get common file first if ($this->_directory->fileExists($filename)) { return $this->_directory->fileLength($filename); } if( !isset($this->_segFileSizes[$filename]) ) { require_once 'Zend/Search/Lucene/Exception.php'; throw new Zend_Search_Lucene_Exception('Index compound file doesn\'t contain ' . $filename . ' file.' ); } return $this->_segFileSizes[$filename]; }
Get compound file length @param string $extension @return integer
entailment
public function getFieldNum($fieldName) { foreach( $this->_fields as $field ) { if( $field->name == $fieldName ) { return $field->number; } } return -1; }
Returns field index or -1 if field is not found @param string $fieldName @return integer
entailment
public function getFields($indexed = false) { $result = array(); foreach( $this->_fields as $field ) { if( (!$indexed) || $field->isIndexed ) { $result[ $field->name ] = $field->name; } } return $result; }
Returns array of fields. if $indexed parameter is true, then returns only indexed fields. @param boolean $indexed @return array
entailment
private function _deletedCount() { if ($this->_deleted === null) { return 0; } if (extension_loaded('bitset')) { return count(bitset_to_array($this->_deleted)); } else { return count($this->_deleted); } }
Returns number of deleted documents. @return integer
entailment
private function _getFieldPosition($fieldNum) { // Treat values which are not in a translation table as a 'direct value' return isset($this->_fieldsDicPositions[$fieldNum]) ? $this->_fieldsDicPositions[$fieldNum] : $fieldNum; }
Get field position in a fields dictionary @param integer $fieldNum @return integer
entailment
private function _loadDictionaryIndex() { // Check, if index is already serialized if ($this->_directory->fileExists($this->_name . '.sti')) { // Load serialized dictionary index data $stiFile = $this->_directory->getFileObject($this->_name . '.sti'); $stiFileData = $stiFile->readBytes($this->_directory->fileLength($this->_name . '.sti')); // Load dictionary index data if (($unserializedData = @unserialize($stiFileData)) !== false) { list($this->_termDictionary, $this->_termDictionaryInfos) = $unserializedData; return; } } // Load data from .tii file and generate .sti file // Prefetch dictionary index data $tiiFile = $this->openCompoundFile('.tii'); $tiiFileData = $tiiFile->readBytes($this->compoundFileLength('.tii')); /** Zend_Search_Lucene_Index_DictionaryLoader */ require_once 'Zend/Search/Lucene/Index/DictionaryLoader.php'; // Load dictionary index data list($this->_termDictionary, $this->_termDictionaryInfos) = Zend_Search_Lucene_Index_DictionaryLoader::load($tiiFileData); $stiFileData = serialize(array($this->_termDictionary, $this->_termDictionaryInfos)); $stiFile = $this->_directory->createFile($this->_name . '.sti'); $stiFile->writeBytes($stiFileData); }
Load terms dictionary index @throws Zend_Search_Lucene_Exception
entailment
public function getTermInfo(Zend_Search_Lucene_Index_Term $term) { $termKey = $term->key(); if (isset($this->_termInfoCache[$termKey])) { $termInfo = $this->_termInfoCache[$termKey]; // Move termInfo to the end of cache unset($this->_termInfoCache[$termKey]); $this->_termInfoCache[$termKey] = $termInfo; return $termInfo; } if ($this->_termDictionary === null) { $this->_loadDictionaryIndex(); } $searchField = $this->getFieldNum($term->field); if ($searchField == -1) { return null; } $searchDicField = $this->_getFieldPosition($searchField); // search for appropriate value in dictionary $lowIndex = 0; $highIndex = count($this->_termDictionary)-1; while ($highIndex >= $lowIndex) { // $mid = ($highIndex - $lowIndex)/2; $mid = ($highIndex + $lowIndex) >> 1; $midTerm = $this->_termDictionary[$mid]; $fieldNum = $this->_getFieldPosition($midTerm[0] /* field */); $delta = $searchDicField - $fieldNum; if ($delta == 0) { $delta = strcmp($term->text, $midTerm[1] /* text */); } if ($delta < 0) { $highIndex = $mid-1; } elseif ($delta > 0) { $lowIndex = $mid+1; } else { // return $this->_termDictionaryInfos[$mid]; // We got it! $a = $this->_termDictionaryInfos[$mid]; $termInfo = new Zend_Search_Lucene_Index_TermInfo($a[0], $a[1], $a[2], $a[3], $a[4]); // Put loaded termInfo into cache $this->_termInfoCache[$termKey] = $termInfo; return $termInfo; } } if ($highIndex == -1) { // Term is out of the dictionary range return null; } $prevPosition = $highIndex; $prevTerm = $this->_termDictionary[$prevPosition]; $prevTermInfo = $this->_termDictionaryInfos[$prevPosition]; $tisFile = $this->openCompoundFile('.tis'); $tiVersion = $tisFile->readInt(); if ($tiVersion != (int)0xFFFFFFFE /* pre-2.1 format */ && $tiVersion != (int)0xFFFFFFFD /* 2.1+ format */) { require_once 'Zend/Search/Lucene/Exception.php'; throw new Zend_Search_Lucene_Exception('Wrong TermInfoFile file format'); } $termCount = $tisFile->readLong(); $indexInterval = $tisFile->readInt(); $skipInterval = $tisFile->readInt(); if ($tiVersion == (int)0xFFFFFFFD /* 2.1+ format */) { $maxSkipLevels = $tisFile->readInt(); } $tisFile->seek($prevTermInfo[4] /* indexPointer */ - (($tiVersion == (int)0xFFFFFFFD)? 24 : 20) /* header size*/, SEEK_CUR); $termValue = $prevTerm[1] /* text */; $termFieldNum = $prevTerm[0] /* field */; $freqPointer = $prevTermInfo[1] /* freqPointer */; $proxPointer = $prevTermInfo[2] /* proxPointer */; for ($count = $prevPosition*$indexInterval + 1; $count <= $termCount && ( $this->_getFieldPosition($termFieldNum) < $searchDicField || ($this->_getFieldPosition($termFieldNum) == $searchDicField && strcmp($termValue, $term->text) < 0) ); $count++) { $termPrefixLength = $tisFile->readVInt(); $termSuffix = $tisFile->readString(); $termFieldNum = $tisFile->readVInt(); $termValue = Zend_Search_Lucene_Index_Term::getPrefix($termValue, $termPrefixLength) . $termSuffix; $docFreq = $tisFile->readVInt(); $freqPointer += $tisFile->readVInt(); $proxPointer += $tisFile->readVInt(); if( $docFreq >= $skipInterval ) { $skipOffset = $tisFile->readVInt(); } else { $skipOffset = 0; } } if ($termFieldNum == $searchField && $termValue == $term->text) { $termInfo = new Zend_Search_Lucene_Index_TermInfo($docFreq, $freqPointer, $proxPointer, $skipOffset); } else { $termInfo = null; } // Put loaded termInfo into cache $this->_termInfoCache[$termKey] = $termInfo; if (count($this->_termInfoCache) == 1024) { $this->_cleanUpTermInfoCache(); } return $termInfo; }
Scans terms dictionary and returns term info @param Zend_Search_Lucene_Index_Term $term @return Zend_Search_Lucene_Index_TermInfo
entailment
public function termDocs(Zend_Search_Lucene_Index_Term $term, $shift = 0, $docsFilter = null) { $termInfo = $this->getTermInfo($term); if (!$termInfo instanceof Zend_Search_Lucene_Index_TermInfo) { if ($docsFilter !== null && $docsFilter instanceof Zend_Search_Lucene_Index_DocsFilter) { $docsFilter->segmentFilters[$this->_name] = array(); } return array(); } $frqFile = $this->openCompoundFile('.frq'); $frqFile->seek($termInfo->freqPointer,SEEK_CUR); $docId = 0; $result = array(); if ($docsFilter !== null) { if (!$docsFilter instanceof Zend_Search_Lucene_Index_DocsFilter) { require_once 'Zend/Search/Lucene/Exception.php'; throw new Zend_Search_Lucene_Exception('Documents filter must be an instance of Zend_Search_Lucene_Index_DocsFilter or null.'); } if (isset($docsFilter->segmentFilters[$this->_name])) { // Filter already has some data for the current segment // Make short name for the filter (which doesn't need additional dereferencing) $filter = &$docsFilter->segmentFilters[$this->_name]; // Check if filter is not empty if (count($filter) == 0) { return array(); } if ($this->_docCount/count($filter) < self::FULL_SCAN_VS_FETCH_BOUNDARY) { // Perform fetching // --------------------------------------------------------------- $updatedFilterData = array(); for( $count=0; $count < $termInfo->docFreq; $count++ ) { $docDelta = $frqFile->readVInt(); if( $docDelta % 2 == 1 ) { $docId += ($docDelta-1)/2; } else { $docId += $docDelta/2; // read freq $frqFile->readVInt(); } if (isset($filter[$docId])) { $result[] = $shift + $docId; $updatedFilterData[$docId] = 1; // 1 is just a some constant value, so we don't need additional var dereference here } } $docsFilter->segmentFilters[$this->_name] = $updatedFilterData; // --------------------------------------------------------------- } else { // Perform full scan $updatedFilterData = array(); for( $count=0; $count < $termInfo->docFreq; $count++ ) { $docDelta = $frqFile->readVInt(); if( $docDelta % 2 == 1 ) { $docId += ($docDelta-1)/2; } else { $docId += $docDelta/2; // read freq $frqFile->readVInt(); } if (isset($filter[$docId])) { $result[] = $shift + $docId; $updatedFilterData[$docId] = 1; // 1 is just a some constant value, so we don't need additional var dereference here } } $docsFilter->segmentFilters[$this->_name] = $updatedFilterData; } } else { // Filter is present, but doesn't has data for the current segment yet $filterData = array(); for( $count=0; $count < $termInfo->docFreq; $count++ ) { $docDelta = $frqFile->readVInt(); if( $docDelta % 2 == 1 ) { $docId += ($docDelta-1)/2; } else { $docId += $docDelta/2; // read freq $frqFile->readVInt(); } $result[] = $shift + $docId; $filterData[$docId] = 1; // 1 is just a some constant value, so we don't need additional var dereference here } $docsFilter->segmentFilters[$this->_name] = $filterData; } } else { for( $count=0; $count < $termInfo->docFreq; $count++ ) { $docDelta = $frqFile->readVInt(); if( $docDelta % 2 == 1 ) { $docId += ($docDelta-1)/2; } else { $docId += $docDelta/2; // read freq $frqFile->readVInt(); } $result[] = $shift + $docId; } } return $result; }
Returns IDs of all the documents containing term. @param Zend_Search_Lucene_Index_Term $term @param integer $shift @param Zend_Search_Lucene_Index_DocsFilter|null $docsFilter @return array
entailment
public function termPositions(Zend_Search_Lucene_Index_Term $term, $shift = 0, $docsFilter = null) { $termInfo = $this->getTermInfo($term); if (!$termInfo instanceof Zend_Search_Lucene_Index_TermInfo) { if ($docsFilter !== null && $docsFilter instanceof Zend_Search_Lucene_Index_DocsFilter) { $docsFilter->segmentFilters[$this->_name] = array(); } return array(); } $frqFile = $this->openCompoundFile('.frq'); $frqFile->seek($termInfo->freqPointer,SEEK_CUR); $docId = 0; $freqs = array(); if ($docsFilter !== null) { if (!$docsFilter instanceof Zend_Search_Lucene_Index_DocsFilter) { require_once 'Zend/Search/Lucene/Exception.php'; throw new Zend_Search_Lucene_Exception('Documents filter must be an instance of Zend_Search_Lucene_Index_DocsFilter or null.'); } if (isset($docsFilter->segmentFilters[$this->_name])) { // Filter already has some data for the current segment // Make short name for the filter (which doesn't need additional dereferencing) $filter = &$docsFilter->segmentFilters[$this->_name]; // Check if filter is not empty if (count($filter) == 0) { return array(); } if ($this->_docCount/count($filter) < self::FULL_SCAN_VS_FETCH_BOUNDARY) { // Perform fetching // --------------------------------------------------------------- for ($count = 0; $count < $termInfo->docFreq; $count++) { $docDelta = $frqFile->readVInt(); if ($docDelta % 2 == 1) { $docId += ($docDelta-1)/2; $freqs[$docId] = 1; } else { $docId += $docDelta/2; $freqs[$docId] = $frqFile->readVInt(); } } $updatedFilterData = array(); $result = array(); $prxFile = $this->openCompoundFile('.prx'); $prxFile->seek($termInfo->proxPointer, SEEK_CUR); foreach ($freqs as $docId => $freq) { $termPosition = 0; $positions = array(); // we have to read .prx file to get right position for next doc // even filter doesn't match current document for ($count = 0; $count < $freq; $count++ ) { $termPosition += $prxFile->readVInt(); $positions[] = $termPosition; } // Include into updated filter and into result only if doc is matched by filter if (isset($filter[$docId])) { $updatedFilterData[$docId] = 1; // 1 is just a some constant value, so we don't need additional var dereference here $result[$shift + $docId] = $positions; } } $docsFilter->segmentFilters[$this->_name] = $updatedFilterData; // --------------------------------------------------------------- } else { // Perform full scan for ($count = 0; $count < $termInfo->docFreq; $count++) { $docDelta = $frqFile->readVInt(); if ($docDelta % 2 == 1) { $docId += ($docDelta-1)/2; $freqs[$docId] = 1; } else { $docId += $docDelta/2; $freqs[$docId] = $frqFile->readVInt(); } } $updatedFilterData = array(); $result = array(); $prxFile = $this->openCompoundFile('.prx'); $prxFile->seek($termInfo->proxPointer, SEEK_CUR); foreach ($freqs as $docId => $freq) { $termPosition = 0; $positions = array(); // we have to read .prx file to get right position for next doc // even filter doesn't match current document for ($count = 0; $count < $freq; $count++ ) { $termPosition += $prxFile->readVInt(); $positions[] = $termPosition; } // Include into updated filter and into result only if doc is matched by filter if (isset($filter[$docId])) { $updatedFilterData[$docId] = 1; // 1 is just a some constant value, so we don't need additional var dereference here $result[$shift + $docId] = $positions; } } $docsFilter->segmentFilters[$this->_name] = $updatedFilterData; } } else { // Filter doesn't has data for current segment for ($count = 0; $count < $termInfo->docFreq; $count++) { $docDelta = $frqFile->readVInt(); if ($docDelta % 2 == 1) { $docId += ($docDelta-1)/2; $freqs[$docId] = 1; } else { $docId += $docDelta/2; $freqs[$docId] = $frqFile->readVInt(); } } $filterData = array(); $result = array(); $prxFile = $this->openCompoundFile('.prx'); $prxFile->seek($termInfo->proxPointer, SEEK_CUR); foreach ($freqs as $docId => $freq) { $filterData[$docId] = 1; // 1 is just a some constant value, so we don't need additional var dereference here $termPosition = 0; $positions = array(); for ($count = 0; $count < $freq; $count++ ) { $termPosition += $prxFile->readVInt(); $positions[] = $termPosition; } $result[$shift + $docId] = $positions; } $docsFilter->segmentFilters[$this->_name] = $filterData; } } else { for ($count = 0; $count < $termInfo->docFreq; $count++) { $docDelta = $frqFile->readVInt(); if ($docDelta % 2 == 1) { $docId += ($docDelta-1)/2; $freqs[$docId] = 1; } else { $docId += $docDelta/2; $freqs[$docId] = $frqFile->readVInt(); } } $result = array(); $prxFile = $this->openCompoundFile('.prx'); $prxFile->seek($termInfo->proxPointer, SEEK_CUR); foreach ($freqs as $docId => $freq) { $termPosition = 0; $positions = array(); for ($count = 0; $count < $freq; $count++ ) { $termPosition += $prxFile->readVInt(); $positions[] = $termPosition; } $result[$shift + $docId] = $positions; } } return $result; }
Returns term positions array. Result array structure: array(docId => array(pos1, pos2, ...), ...) @param Zend_Search_Lucene_Index_Term $term @param integer $shift @param Zend_Search_Lucene_Index_DocsFilter|null $docsFilter @return Zend_Search_Lucene_Index_TermInfo
entailment
private function _loadNorm($fieldNum) { if ($this->_hasSingleNormFile) { $normfFile = $this->openCompoundFile('.nrm'); $header = $normfFile->readBytes(3); $headerFormatVersion = $normfFile->readByte(); if ($header != 'NRM' || $headerFormatVersion != (int)0xFF) { require_once 'Zend/Search/Lucene/Exception.php'; throw new Zend_Search_Lucene_Exception('Wrong norms file format.'); } foreach ($this->_fields as $fNum => $fieldInfo) { if ($fieldInfo->isIndexed) { $this->_norms[$fNum] = $normfFile->readBytes($this->_docCount); } } } else { $fFile = $this->openCompoundFile('.f' . $fieldNum); $this->_norms[$fieldNum] = $fFile->readBytes($this->_docCount); } }
Load normalizatin factors from an index file @param integer $fieldNum @throws Zend_Search_Lucene_Exception
entailment
public function norm($id, $fieldName) { $fieldNum = $this->getFieldNum($fieldName); if ( !($this->_fields[$fieldNum]->isIndexed) ) { return null; } if (!isset($this->_norms[$fieldNum])) { $this->_loadNorm($fieldNum); } return Zend_Search_Lucene_Search_Similarity::decodeNorm( ord($this->_norms[$fieldNum][$id]) ); }
Returns normalization factor for specified documents @param integer $id @param string $fieldName @return float
entailment
public function normVector($fieldName) { $fieldNum = $this->getFieldNum($fieldName); if ($fieldNum == -1 || !($this->_fields[$fieldNum]->isIndexed)) { $similarity = Zend_Search_Lucene_Search_Similarity::getDefault(); return str_repeat(chr($similarity->encodeNorm( $similarity->lengthNorm($fieldName, 0) )), $this->_docCount); } if (!isset($this->_norms[$fieldNum])) { $this->_loadNorm($fieldNum); } return $this->_norms[$fieldNum]; }
Returns norm vector, encoded in a byte string @param string $fieldName @return string
entailment
public function delete($id) { $this->_deletedDirty = true; if (extension_loaded('bitset')) { if ($this->_deleted === null) { $this->_deleted = bitset_empty($id); } bitset_incl($this->_deleted, $id); } else { if ($this->_deleted === null) { $this->_deleted = array(); } $this->_deleted[$id] = 1; } }
Deletes a document from the index segment. $id is an internal document id @param integer
entailment
public function isDeleted($id) { if ($this->_deleted === null) { return false; } if (extension_loaded('bitset')) { return bitset_in($this->_deleted, $id); } else { return isset($this->_deleted[$id]); } }
Checks, that document is deleted @param integer @return boolean
entailment
public function writeChanges() { // Get new generation number $latestDelGen = $this->_detectLatestDelGen(); if (!$this->_deletedDirty) { // There was no deletions by current process if ($latestDelGen == $this->_delGen) { // Delete file hasn't been updated by any concurrent process return; } else if ($latestDelGen > $this->_delGen) { // Delete file has been updated by some concurrent process // Reload deletions file $this->_delGen = $latestDelGen; $this->_deleted = $this->_loadDelFile(); return; } else { require_once 'Zend/Search/Lucene/Exception.php'; throw new Zend_Search_Lucene_Exception('Delete file processing workflow is corrupted for the segment \'' . $this->_name . '\'.'); } } if ($latestDelGen > $this->_delGen) { // Merge current deletions with latest deletions file $this->_delGen = $latestDelGen; $latestDelete = $this->_loadDelFile(); if (extension_loaded('bitset')) { $this->_deleted = bitset_union($this->_deleted, $latestDelete); } else { $this->_deleted += $latestDelete; } } if (extension_loaded('bitset')) { $delBytes = $this->_deleted; $bitCount = count(bitset_to_array($delBytes)); } else { $byteCount = floor($this->_docCount/8)+1; $delBytes = str_repeat(chr(0), $byteCount); for ($count = 0; $count < $byteCount; $count++) { $byte = 0; for ($bit = 0; $bit < 8; $bit++) { if (isset($this->_deleted[$count*8 + $bit])) { $byte |= (1<<$bit); } } $delBytes[$count] = chr($byte); } $bitCount = count($this->_deleted); } if ($this->_delGen == -1) { // Set delete file generation number to 1 $this->_delGen = 1; } else { // Increase delete file generation number by 1 $this->_delGen++; } $delFile = $this->_directory->createFile($this->_name . '_' . base_convert($this->_delGen, 10, 36) . '.del'); $delFile->writeInt($this->_docCount); $delFile->writeInt($bitCount); $delFile->writeBytes($delBytes); $this->_deletedDirty = false; }
Write changes if it's necessary. This method must be invoked only from the Writer _updateSegments() method, so index Write lock has to be already obtained. @internal @throws Zend_Search_Lucene_Exceptions
entailment
public function resetTermsStream(/** $startId = 0, $mode = self::SM_TERMS_ONLY */) { /** * SegmentInfo->resetTermsStream() method actually takes two optional parameters: * $startId (default value is 0) * $mode (default value is self::SM_TERMS_ONLY) */ $argList = func_get_args(); if (count($argList) > 2) { require_once 'Zend/Search/Lucene/Exception.php'; throw new Zend_Search_Lucene_Exception('Wrong number of arguments'); } else if (count($argList) == 2) { $startId = $argList[0]; $mode = $argList[1]; } else if (count($argList) == 1) { $startId = $argList[0]; $mode = self::SM_TERMS_ONLY; } else { $startId = 0; $mode = self::SM_TERMS_ONLY; } if ($this->_tisFile !== null) { $this->_tisFile = null; } $this->_tisFile = $this->openCompoundFile('.tis', false); $this->_tisFileOffset = $this->_tisFile->tell(); $tiVersion = $this->_tisFile->readInt(); if ($tiVersion != (int)0xFFFFFFFE /* pre-2.1 format */ && $tiVersion != (int)0xFFFFFFFD /* 2.1+ format */) { require_once 'Zend/Search/Lucene/Exception.php'; throw new Zend_Search_Lucene_Exception('Wrong TermInfoFile file format'); } $this->_termCount = $this->_termNum = $this->_tisFile->readLong(); // Read terms count $this->_indexInterval = $this->_tisFile->readInt(); // Read Index interval $this->_skipInterval = $this->_tisFile->readInt(); // Read skip interval if ($tiVersion == (int)0xFFFFFFFD /* 2.1+ format */) { $maxSkipLevels = $this->_tisFile->readInt(); } if ($this->_frqFile !== null) { $this->_frqFile = null; } if ($this->_prxFile !== null) { $this->_prxFile = null; } $this->_docMap = array(); $this->_lastTerm = new Zend_Search_Lucene_Index_Term('', -1); $this->_lastTermInfo = new Zend_Search_Lucene_Index_TermInfo(0, 0, 0, 0); $this->_lastTermPositions = null; $this->_termsScanMode = $mode; switch ($mode) { case self::SM_TERMS_ONLY: // Do nothing break; case self::SM_FULL_INFO: // break intentionally omitted case self::SM_MERGE_INFO: $this->_frqFile = $this->openCompoundFile('.frq', false); $this->_frqFileOffset = $this->_frqFile->tell(); $this->_prxFile = $this->openCompoundFile('.prx', false); $this->_prxFileOffset = $this->_prxFile->tell(); for ($count = 0; $count < $this->_docCount; $count++) { if (!$this->isDeleted($count)) { $this->_docMap[$count] = $startId + (($mode == self::SM_MERGE_INFO) ? count($this->_docMap) : $count); } } break; default: require_once 'Zend/Search/Lucene/Exception.php'; throw new Zend_Search_Lucene_Exception('Wrong terms scaning mode specified.'); break; } // Calculate next segment start id (since $this->_docMap structure may be cleaned by $this->nextTerm() call) $nextSegmentStartId = $startId + (($mode == self::SM_MERGE_INFO) ? count($this->_docMap) : $this->_docCount); $this->nextTerm(); return $nextSegmentStartId; }
Reset terms stream $startId - id for the fist document $compact - remove deleted documents Returns start document id for the next segment @param integer $startId @param integer $mode @throws Zend_Search_Lucene_Exception @return integer
entailment
public function skipTo(Zend_Search_Lucene_Index_Term $prefix) { if ($this->_termDictionary === null) { $this->_loadDictionaryIndex(); } $searchField = $this->getFieldNum($prefix->field); if ($searchField == -1) { /** * Field is not presented in this segment * Go to the end of dictionary */ $this->_tisFile = null; $this->_frqFile = null; $this->_prxFile = null; $this->_lastTerm = null; $this->_lastTermInfo = null; $this->_lastTermPositions = null; return; } $searchDicField = $this->_getFieldPosition($searchField); // search for appropriate value in dictionary $lowIndex = 0; $highIndex = count($this->_termDictionary)-1; while ($highIndex >= $lowIndex) { // $mid = ($highIndex - $lowIndex)/2; $mid = ($highIndex + $lowIndex) >> 1; $midTerm = $this->_termDictionary[$mid]; $fieldNum = $this->_getFieldPosition($midTerm[0] /* field */); $delta = $searchDicField - $fieldNum; if ($delta == 0) { $delta = strcmp($prefix->text, $midTerm[1] /* text */); } if ($delta < 0) { $highIndex = $mid-1; } elseif ($delta > 0) { $lowIndex = $mid+1; } else { // We have reached term we are looking for break; } } if ($highIndex == -1) { // Term is out of the dictionary range $this->_tisFile = null; $this->_frqFile = null; $this->_prxFile = null; $this->_lastTerm = null; $this->_lastTermInfo = null; $this->_lastTermPositions = null; return; } $prevPosition = $highIndex; $prevTerm = $this->_termDictionary[$prevPosition]; $prevTermInfo = $this->_termDictionaryInfos[$prevPosition]; if ($this->_tisFile === null) { // The end of terms stream is reached and terms dictionary file is closed // Perform mini-reset operation $this->_tisFile = $this->openCompoundFile('.tis', false); if ($this->_termsScanMode == self::SM_FULL_INFO || $this->_termsScanMode == self::SM_MERGE_INFO) { $this->_frqFile = $this->openCompoundFile('.frq', false); $this->_prxFile = $this->openCompoundFile('.prx', false); } } $this->_tisFile->seek($this->_tisFileOffset + $prevTermInfo[4], SEEK_SET); $this->_lastTerm = new Zend_Search_Lucene_Index_Term($prevTerm[1] /* text */, ($prevTerm[0] == -1) ? '' : $this->_fields[$prevTerm[0] /* field */]->name); $this->_lastTermInfo = new Zend_Search_Lucene_Index_TermInfo($prevTermInfo[0] /* docFreq */, $prevTermInfo[1] /* freqPointer */, $prevTermInfo[2] /* proxPointer */, $prevTermInfo[3] /* skipOffset */); $this->_termCount = $this->_termNum - $prevPosition*$this->_indexInterval; if ($highIndex == 0) { // skip start entry $this->nextTerm(); } else if ($prefix->field == $this->_lastTerm->field && $prefix->text == $this->_lastTerm->text) { // We got exact match in the dictionary index if ($this->_termsScanMode == self::SM_FULL_INFO || $this->_termsScanMode == self::SM_MERGE_INFO) { $this->_lastTermPositions = array(); $this->_frqFile->seek($this->_lastTermInfo->freqPointer + $this->_frqFileOffset, SEEK_SET); $freqs = array(); $docId = 0; for( $count = 0; $count < $this->_lastTermInfo->docFreq; $count++ ) { $docDelta = $this->_frqFile->readVInt(); if( $docDelta % 2 == 1 ) { $docId += ($docDelta-1)/2; $freqs[ $docId ] = 1; } else { $docId += $docDelta/2; $freqs[ $docId ] = $this->_frqFile->readVInt(); } } $this->_prxFile->seek($this->_lastTermInfo->proxPointer + $this->_prxFileOffset, SEEK_SET); foreach ($freqs as $docId => $freq) { $termPosition = 0; $positions = array(); for ($count = 0; $count < $freq; $count++ ) { $termPosition += $this->_prxFile->readVInt(); $positions[] = $termPosition; } if (isset($this->_docMap[$docId])) { $this->_lastTermPositions[$this->_docMap[$docId]] = $positions; } } } return; } // Search term matching specified prefix while ($this->_lastTerm !== null) { if ( strcmp($this->_lastTerm->field, $prefix->field) > 0 || ($prefix->field == $this->_lastTerm->field && strcmp($this->_lastTerm->text, $prefix->text) >= 0) ) { // Current term matches or greate than the pattern return; } $this->nextTerm(); } }
Skip terms stream up to specified term preffix. Prefix contains fully specified field info and portion of searched term @param Zend_Search_Lucene_Index_Term $prefix @throws Zend_Search_Lucene_Exception
entailment
public function nextTerm() { if ($this->_tisFile === null || $this->_termCount == 0) { $this->_lastTerm = null; $this->_lastTermInfo = null; $this->_lastTermPositions = null; $this->_docMap = null; // may be necessary for "empty" segment $this->_tisFile = null; $this->_frqFile = null; $this->_prxFile = null; return null; } $termPrefixLength = $this->_tisFile->readVInt(); $termSuffix = $this->_tisFile->readString(); $termFieldNum = $this->_tisFile->readVInt(); $termValue = Zend_Search_Lucene_Index_Term::getPrefix($this->_lastTerm->text, $termPrefixLength) . $termSuffix; $this->_lastTerm = new Zend_Search_Lucene_Index_Term($termValue, $this->_fields[$termFieldNum]->name); $docFreq = $this->_tisFile->readVInt(); $freqPointer = $this->_lastTermInfo->freqPointer + $this->_tisFile->readVInt(); $proxPointer = $this->_lastTermInfo->proxPointer + $this->_tisFile->readVInt(); if ($docFreq >= $this->_skipInterval) { $skipOffset = $this->_tisFile->readVInt(); } else { $skipOffset = 0; } $this->_lastTermInfo = new Zend_Search_Lucene_Index_TermInfo($docFreq, $freqPointer, $proxPointer, $skipOffset); if ($this->_termsScanMode == self::SM_FULL_INFO || $this->_termsScanMode == self::SM_MERGE_INFO) { $this->_lastTermPositions = array(); $this->_frqFile->seek($this->_lastTermInfo->freqPointer + $this->_frqFileOffset, SEEK_SET); $freqs = array(); $docId = 0; for( $count = 0; $count < $this->_lastTermInfo->docFreq; $count++ ) { $docDelta = $this->_frqFile->readVInt(); if( $docDelta % 2 == 1 ) { $docId += ($docDelta-1)/2; $freqs[ $docId ] = 1; } else { $docId += $docDelta/2; $freqs[ $docId ] = $this->_frqFile->readVInt(); } } $this->_prxFile->seek($this->_lastTermInfo->proxPointer + $this->_prxFileOffset, SEEK_SET); foreach ($freqs as $docId => $freq) { $termPosition = 0; $positions = array(); for ($count = 0; $count < $freq; $count++ ) { $termPosition += $this->_prxFile->readVInt(); $positions[] = $termPosition; } if (isset($this->_docMap[$docId])) { $this->_lastTermPositions[$this->_docMap[$docId]] = $positions; } } } $this->_termCount--; if ($this->_termCount == 0) { $this->_tisFile = null; $this->_frqFile = null; $this->_prxFile = null; } return $this->_lastTerm; }
Scans terms dictionary and returns next term @return Zend_Search_Lucene_Index_Term|null
entailment
public function closeTermsStream() { $this->_tisFile = null; $this->_frqFile = null; $this->_prxFile = null; $this->_lastTerm = null; $this->_lastTermInfo = null; $this->_lastTermPositions = null; $this->_docMap = null; }
Close terms stream Should be used for resources clean up if stream is not read up to the end
entailment
public function logout() { if ($this->_mails) { foreach ($this->_mails as $mail) { if ($mail['is_deleted']) { unlink($this->_path.'/'.$mail['file_name']); } } } }
Закрытие протокола, удаление файлов
entailment
public function readDir() { $files = scandir($this->_path); foreach ($files as $file) { $path_info = pathinfo($file); if ($path_info['extension'] == 'eml') { $this->_mails[] = [ 'is_deleted' => 0, 'file_name' => $file ]; } } }
Считывание писем из папки
entailment
public function getList($id = null) { if ($this->_mails) { if ($id != null && isset($this->_mails[$id])) { return [filesize($this->_path.'/'.$this->_mails[$id]['file_name'])]; } $result = []; foreach ($this->_mails as $mail) { $result[] = filesize($this->_path.'/'.$mail['file_name']); } return $result; } return null; }
Получение размера писем @param null|int $id @return array|null
entailment
public function delete($id) { if ($this->_mails && isset($this->_mails[$id])) { $this->_mails[$id]['is_deleted'] = true; } }
Удаление письма по номеру в списке @param int $id
entailment
public function undelete($id = null) { if ($this->_mails) { if ($id != null && isset($this->_mails[$id])) { $this->_mails[$id]['is_deleted'] = false; } else { foreach ($this->_mails as $mail) { $mail['is_deleted'] = false; } } } }
Отмена удаления письмо по id или всех писем в списке @param null|int $id
entailment
public function top($id) { if ($this->_mails && isset($this->_mails[$id])) { $lines = file($this->_path.'/'.$this->_mails[$id]['file_name']); // $data = file_get_contents($this->_path.'/'.$this->_mails[$id]['file_name']); // preg_match(Headers::BOUNDARY_PATTERN, str_replace("\r\n\t", ' ', $data), $subBoundary); // if (isset($subBoundary[1])) { // $data = preg_split('/'.$subBoundary[1].'[\"\r\n]/si', $data)[0].$subBoundary[1].'"'; // } else { // $data = preg_split('/[\n\r]{3,}/s', $data)[0]; // } $data = []; $countEmpty = 0; $isName = false; foreach ($lines as $line) { if ($line[0] !== "\t" && $line[0] !== ' ' && preg_match('/^[A-Z]/', $line) && $line[0] !== '-' && strpos($line, ':') !== false) { $data[] = $line; $countEmpty = 0; $isName = true; } elseif (($line[0] === "\t" || $line[0] === ' ') && !empty(trim($line)) && $isName) { $data[] = $line; $countEmpty = 0; } elseif (empty(trim($line))) { $data[] = $line; $countEmpty++; $isName = false; } elseif ($line[0] === '-' && $line[1] === '-' && $countEmpty > 0) { preg_match(Headers::BOUNDARY_PATTERN, str_replace("\r\n\t", ' ', implode($data)), $subBoundary); if (isset($subBoundary[1]) && strpos($line, $subBoundary[1]) !== false) { break; } $isName = false; } elseif ($countEmpty > 0) { break; } else { //опасный момент } } return implode($data); } return null; }
Получение заголовков письма @param $id @return null|string
entailment
public function retrieve($id) { if ($this->_mails && isset($this->_mails[$id])) { return file_get_contents($this->_path.'/'.$this->_mails[$id]['file_name']); } return null; }
Получение всего контента письма @param $id @return null|string
entailment
public function add_field( array $field, $position = 0 ) { return $this->builder->add_group_field( $this->group_id, $field, $position ); }
{@inheritdoc}
entailment
public function add($line) { $uriParser = new UriParser($line); $uri = $uriParser->encode(); if (!$uriParser->validate() || in_array($uri, $this->sitemaps) ) { return false; } $this->sitemaps[] = $uri; return true; }
Add @param string $line @return bool
entailment
public function render(RenderHandler $handler) { sort($this->sitemaps); foreach ($this->sitemaps as $sitemap) { $handler->add(self::DIRECTIVE_SITEMAP, $sitemap); } return true; }
Render @param RenderHandler $handler @return bool
entailment
public function sendMessage() { try { // First: Send message with given transport $this->_transport->sendMessage(); // Second: Create a mail instance to store $mail = $this->getMail(); $mail->updateWithTransport($this->_transport); $mail->save(); } catch (\Exception $e) { throw new MailException( new Phrase($e->getMessage()), $e ); } return $this; }
Send a mail using this transport @return Base @throws MailException
entailment
public function lookup(Request $request) { $cacheKey = $this->getCacheKey($request); $item = $this->cache->getItem($cacheKey); if (!$item->isHit()) { return null; } $entries = $item->get(); foreach ($entries as $varyKeyResponse => $responseData) { // This can only happen if one entry only if (self::NON_VARYING_KEY === $varyKeyResponse) { return $this->restoreResponse($responseData); } // Otherwise we have to see if Vary headers match $varyKeyRequest = $this->getVaryKey( $responseData['vary'], $request ); if ($varyKeyRequest === $varyKeyResponse) { return $this->restoreResponse($responseData); } } return null; }
Locates a cached Response for the Request provided. @param Request $request A Request instance @return Response|null A Response instance, or null if no cache entry was found
entailment
public function write(Request $request, Response $response) { if (!$response->headers->has('X-Content-Digest')) { $contentDigest = $this->generateContentDigest($response); if (false === $this->saveDeferred($contentDigest, $response->getContent())) { throw new \RuntimeException('Unable to store the entity.'); } $response->headers->set('X-Content-Digest', $contentDigest); if (!$response->headers->has('Transfer-Encoding')) { $response->headers->set('Content-Length', \strlen($response->getContent())); } } $cacheKey = $this->getCacheKey($request); $headers = $response->headers->all(); unset($headers['age']); $item = $this->cache->getItem($cacheKey); if (!$item->isHit()) { $entries = []; } else { $entries = $item->get(); } // Add or replace entry with current Vary header key $entries[$this->getVaryKey($response->getVary(), $request)] = [ 'vary' => $response->getVary(), 'headers' => $headers, 'status' => $response->getStatusCode(), ]; // If the response has a Vary header we remove the non-varying entry if ($response->hasVary()) { unset($entries[self::NON_VARYING_KEY]); } // Tags $tags = []; if ($response->headers->has($this->options['cache_tags_header'])) { foreach ($response->headers->get($this->options['cache_tags_header'], '', false) as $header) { foreach (explode(',', $header) as $tag) { $tags[] = $tag; } } } // Prune expired entries on file system if needed $this->autoPruneExpiredEntries(); $this->saveDeferred($cacheKey, $entries, $response->getMaxAge(), $tags); $this->cache->commit(); return $cacheKey; }
Writes a cache entry to the store for the given Request and Response. Existing entries are read and any that match the response are removed. This method calls write with the new list of cache entries. @param Request $request A Request instance @param Response $response A Response instance @return string The key under which the response is stored
entailment
public function invalidate(Request $request) { $cacheKey = $this->getCacheKey($request); $this->cache->deleteItem($cacheKey); }
Invalidates all cache entries that match the request. @param Request $request A Request instance
entailment
public function lock(Request $request) { $cacheKey = $this->getCacheKey($request); if (isset($this->locks[$cacheKey])) { return false; } $this->locks[$cacheKey] = $this->lockFactory ->createLock($cacheKey); return $this->locks[$cacheKey]->acquire(); }
Locks the cache for a given Request. @param Request $request A Request instance @return bool|string true if the lock is acquired, the path to the current lock otherwise
entailment
public function unlock(Request $request) { $cacheKey = $this->getCacheKey($request); if (!isset($this->locks[$cacheKey])) { return false; } try { $this->locks[$cacheKey]->release(); } catch (LockReleasingException $e) { return false; } finally { unset($this->locks[$cacheKey]); } return true; }
Releases the lock for the given Request. @param Request $request A Request instance @return bool False if the lock file does not exist or cannot be unlocked, true otherwise
entailment
public function isLocked(Request $request) { $cacheKey = $this->getCacheKey($request); if (!isset($this->locks[$cacheKey])) { return false; } return $this->locks[$cacheKey]->isAcquired(); }
Returns whether or not a lock exists. @param Request $request A Request instance @return bool true if lock exists, false otherwise
entailment
public function purge($url) { $cacheKey = $this->getCacheKey(Request::create($url)); return $this->cache->deleteItem($cacheKey); }
Purges data for the given URL. @param string $url A URL @return bool true if the URL exists and has been purged, false otherwise
entailment
public function cleanup() { try { foreach ($this->locks as $lock) { $lock->release(); } } catch (LockReleasingException $e) { // noop } finally { $this->locks = []; } }
Release all locks. {@inheritdoc}
entailment
public function invalidateTags(array $tags) { if (!$this->cache instanceof TagAwareAdapterInterface) { throw new \RuntimeException('Cannot invalidate tags on a cache implementation that does not implement the TagAwareAdapterInterface.'); } try { return $this->cache->invalidateTags($tags); } catch (InvalidArgumentException $e) { return false; } }
The tags are set from the header configured in cache_tags_header. {@inheritdoc}
entailment
public function getCacheKey(Request $request) { // Strip scheme to treat https and http the same $uri = $request->getUri(); $uri = substr($uri, \strlen($request->getScheme().'://')); return 'md'.hash('sha256', $uri); }
@param Request $request @return string
entailment
public function getVaryKey(array $vary, Request $request) { if (0 === \count($vary)) { return self::NON_VARYING_KEY; } sort($vary); $hashData = ''; foreach ($vary as $headerName) { $hashData .= $headerName.':'.$request->headers->get($headerName); } return hash('sha256', $hashData); }
@param array $vary @param Request $request @return string
entailment
private function autoPruneExpiredEntries() { if (0 === $this->options['prune_threshold']) { return; } $item = $this->cache->getItem(self::COUNTER_KEY); $counter = (int) $item->get(); if ($counter > $this->options['prune_threshold']) { $this->prune(); $counter = 0; } else { ++$counter; } $item->set($counter); $this->cache->saveDeferred($item); }
Increases a counter every time an item is stored to the cache and then prunes expired cache entries if a configurable threshold is reached. This only happens during write operations so cache retrieval is not slowed down.
entailment
private function saveDeferred($key, $data, $expiresAfter = null, $tags = []) { $item = $this->cache->getItem($key); $item->set($data); $item->expiresAfter($expiresAfter); if (0 !== \count($tags)) { $item->tag($tags); } return $this->cache->saveDeferred($item); }
@param string $key @param string $data @param int $expiresAfter @param array $tags @return bool
entailment
private function restoreResponse(array $cacheData) { $body = null; if (isset($cacheData['headers']['x-content-digest'][0])) { $item = $this->cache->getItem($cacheData['headers']['x-content-digest'][0]); if ($item->isHit()) { $body = $item->get(); } } return new Response( $body, $cacheData['status'], $cacheData['headers'] ); }
Restores a Response from the cached data. @param array $cacheData An array containing the cache data @return Response|null
entailment
public function handle() { try { $this->info('LaraAdmin Code Editor installation started...'); $from = base_path('vendor/dwij/laeditor/src/Installs'); $to = base_path(); $this->info('from: '.$from." to: ".$to); $this->copyFile($from."/resources/views/index.blade.php", $to."/resources/views/la/editor/index.blade.php"); $this->copyFolder($from."/la-assets/plugins/ace", $to."/public/la-assets/plugins/ace"); $this->info("\nLaraAdmin Code Editor successfully installed."); $this->info("Find it on yourdomain.com/".config('laraadmin.adminRoute')."/laeditor !!!\n"); } catch (Exception $e) { $msg = $e->getMessage(); $this->error("LAEditor::handle exception: ".$e); throw new Exception("LAEditor::handle Unable to install : ".$msg, 1); } }
Generate Whole structure for /admin @return mixed
entailment
private function fileContains($filePath, $text) { $fileData = file_get_contents($filePath); if (strpos($fileData, $text) === false ) { return true; } else { return false; } }
TODO:Method not working properly
entailment
public function load(ServiceContainer $container, array $params): void { if (!$container instanceof IndexedServiceContainer) { throw new \InvalidArgumentException(sprintf( 'Container passed from phpspec must implement "%s"!', IndexedServiceContainer::class )); } $container->define('runner.maintainers.skip_example', function (IndexedServiceContainer $c) { return new Runner\Maintainer\SkipExampleMaintainer(); }, ['runner.maintainers']); }
{@inheritdoc}
entailment
public function debug() { $query = $this->pdo->prepare(<<<SQL SELECT * FROM robotstxt__cache1 WHERE base = :base; SQL ); $query->bindValue('base', $this->base, \PDO::PARAM_STR); $query->execute(); return $query->rowCount() > 0 ? $query->fetch(\PDO::FETCH_ASSOC) : []; }
Debug - Get raw data @return array
entailment
public function client() { $query = $this->pdo->prepare(<<<SQL SELECT content, statusCode, nextUpdate, effective, worker, UNIX_TIMESTAMP() FROM robotstxt__cache1 WHERE base = :base; SQL ); $query->bindValue('base', $this->base, \PDO::PARAM_STR); $query->execute(); if ($query->rowCount() > 0) { $row = $query->fetch(\PDO::FETCH_ASSOC); $this->clockSyncCheck($row['UNIX_TIMESTAMP()'], self::OUT_OF_SYNC_TIME_LIMIT); if ($row['nextUpdate'] >= $row['UNIX_TIMESTAMP()']) { $this->markAsActive($row['worker']); return new TxtClient($this->base, $row['statusCode'], $row['content'], self::ENCODING, $row['effective'], $this->byteLimit); } } $query = $this->pdo->prepare(<<<SQL UPDATE robotstxt__cache1 SET worker = 0 WHERE base = :base; SQL ); $query->bindValue('base', $this->base, \PDO::PARAM_STR); $query->execute(); return $this->refresh(); }
Parser client @return TxtClient @throws Exceptions\OutOfSyncException @throws Exceptions\DatabaseException
entailment
private function markAsActive($workerID = 0) { if ($workerID == 0) { $query = $this->pdo->prepare(<<<SQL UPDATE robotstxt__cache1 SET worker = NULL WHERE base = :base AND worker = 0; SQL ); $query->bindValue('base', $this->base, \PDO::PARAM_STR); return $query->execute(); } return true; }
Mark robots.txt as active @param int|null $workerID @return bool
entailment
public function refresh() { $client = new UriClient($this->base, $this->curlOptions, $this->byteLimit); $effective = $client->getEffectiveUri(); if ($effective == $this->base) { $effective = null; } $statusCode = $client->getStatusCode(); $nextUpdate = $client->nextUpdate(); if (strpos($this->base, 'http') === 0 && ( $statusCode === null || ( $statusCode >= 500 && $statusCode < 600 ) ) && $this->displacePush($nextUpdate) ) { return $client; } $validUntil = $client->validUntil(); $content = $client->render()->compressed(self::RENDER_LINE_SEPARATOR); $query = $this->pdo->prepare(<<<SQL INSERT INTO robotstxt__cache1 (base, content, statusCode, validUntil, nextUpdate, effective) VALUES (:base, :content, :statusCode, :validUntil, :nextUpdate, :effective) ON DUPLICATE KEY UPDATE content = :content, statusCode = :statusCode, validUntil = :validUntil, nextUpdate = :nextUpdate, effective = :effective, worker = 0; SQL ); $query->bindValue('base', $this->base, \PDO::PARAM_STR); $query->bindValue('content', $content, \PDO::PARAM_STR); $query->bindValue('statusCode', $statusCode, \PDO::PARAM_INT | \PDO::PARAM_NULL); $query->bindValue('validUntil', $validUntil, \PDO::PARAM_INT); $query->bindValue('nextUpdate', $nextUpdate, \PDO::PARAM_INT); $query->bindValue('effective', $effective, \PDO::PARAM_STR | \PDO::PARAM_NULL); $query->execute(); return $client; }
Update the robots.txt @return UriClient @throws Exceptions\DatabaseException
entailment
private function displacePush($nextUpdate) { $query = $this->pdo->prepare(<<<SQL SELECT validUntil, UNIX_TIMESTAMP() FROM robotstxt__cache1 WHERE base = :base; SQL ); $query->bindValue('base', $this->base, \PDO::PARAM_STR); $query->execute(); if ($query->rowCount() > 0) { $row = $query->fetch(\PDO::FETCH_ASSOC); $this->clockSyncCheck($row['UNIX_TIMESTAMP()'], self::OUT_OF_SYNC_TIME_LIMIT); if ($row['validUntil'] > $row['UNIX_TIMESTAMP()']) { $nextUpdate = min($row['validUntil'], $nextUpdate); $query = $this->pdo->prepare(<<<SQL UPDATE robotstxt__cache1 SET nextUpdate = :nextUpdate, worker = 0 WHERE base = :base; SQL ); $query->bindValue('base', $this->base, \PDO::PARAM_STR); $query->bindValue('nextUpdate', $nextUpdate, \PDO::PARAM_INT); return $query->execute(); } } return false; }
Displace push timestamp @param int $nextUpdate @return bool @throws Exceptions\OutOfSyncException
entailment
public function invalidate() { $query = $this->pdo->prepare(<<<SQL DELETE FROM robotstxt__cache1 WHERE base = :base; SQL ); $query->bindValue('base', $this->base, \PDO::PARAM_STR); return $query->execute(); }
Invalidate cache @return bool
entailment
private function downloadMetadata() { Logger::debug($this->logLoc.'Downloading metadata from '.var_export($this->url, true)); $context = ['ssl' => []]; if ($this->sslCAFile !== null) { $context['ssl']['cafile'] = Config::getCertPath($this->sslCAFile); Logger::debug($this->logLoc.'Validating https connection against CA certificate(s) found in '. var_export($context['ssl']['cafile'], true)); $context['ssl']['verify_peer'] = true; $context['ssl']['CN_match'] = parse_url($this->url, PHP_URL_HOST); } try { $data = HTTP::fetch($this->url, $context, false); } catch (\SimpleSAML\Error\Exception $e) { Logger::error($this->logLoc.'Unable to load metadata from '.var_export($this->url, true)); return null; } $doc = new \DOMDocument(); /** @var string $data */ $res = $doc->loadXML($data); if (!$res) { Logger::error($this->logLoc.'Error parsing XML from '.var_export($this->url, true)); return null; } $root = Utils::xpQuery($doc->firstChild, '/saml_metadata:EntityDescriptor|/saml_metadata:EntitiesDescriptor'); if (count($root) === 0) { Logger::error($this->logLoc.'No <EntityDescriptor> or <EntitiesDescriptor> in metadata from '. var_export($this->url, true)); return null; } if (count($root) > 1) { Logger::error($this->logLoc.'More than one <EntityDescriptor> or <EntitiesDescriptor> in metadata from '. var_export($this->url, true)); return null; } $root = $root[0]; try { if ($root->localName === 'EntityDescriptor') { $md = new EntityDescriptor($root); } else { $md = new EntitiesDescriptor($root); } } catch (\Exception $e) { Logger::error($this->logLoc.'Unable to parse metadata from '. var_export($this->url, true).': '.$e->getMessage()); return null; } if ($this->certificate !== null) { $file = Config::getCertPath($this->certificate); $certData = file_get_contents($file); if ($certData === false) { throw new Exception('Error loading certificate from '.var_export($file, true)); } // Extract the public key from the certificate for validation $key = new XMLSecurityKey(XMLSecurityKey::RSA_SHA1, ['type'=>'public']); $key->loadKey($file, true); if (!$md->validate($key)) { Logger::error($this->logLoc.'Error validating signature on metadata.'); return null; } Logger::debug($this->logLoc.'Validated signature on metadata from '.var_export($this->url, true)); } return $md; }
Retrieve and parse the metadata. @return \SAML2\XML\md\EntitiesDescriptor|\SAML2\XML\md\EntityDescriptor|null The downloaded metadata or NULL if we were unable to download or parse it.
entailment
public function updateCache() { if ($this->updateAttempted) { return; } $this->updateAttempted = true; $this->metadata = $this->downloadMetadata(); if ($this->metadata === null) { return; } $expires = time() + 24*60*60; // Default expires in one day if ($this->metadata->validUntil !== null && $this->metadata->validUntil < $expires) { $expires = $this->metadata->validUntil; } $metadataSerialized = serialize($this->metadata); $this->aggregator->addCacheItem($this->cacheId, $metadataSerialized, $expires, $this->cacheTag); }
Attempt to update our cache file. @return void
entailment
public function getMetadata() { if ($this->metadata !== null) { /* We have already downloaded the metdata. */ return $this->metadata; } if (!$this->aggregator->isCacheValid($this->cacheId, $this->cacheTag)) { $this->updateCache(); /** @psalm-suppress TypeDoesNotContainType */ if ($this->metadata !== null) { return $this->metadata; } /* We were unable to update the cache - use cached metadata. */ } $cacheFile = $this->aggregator->getCacheFile($this->cacheId); if (is_null($cacheFile) || !file_exists($cacheFile)) { Logger::error($this->logLoc . 'No cached metadata available.'); return null; } Logger::debug($this->logLoc.'Using cached metadata from '.var_export($cacheFile, true)); $metadata = file_get_contents($cacheFile); if ($metadata !== false) { $this->metadata = unserialize($metadata); return $this->metadata; } return null; }
Retrieve the metadata file. This function will check its cached copy, to see whether it can be used. @return \SAML2\XML\md\EntityDescriptor|\SAML2\XML\md\EntitiesDescriptor|null The downloaded metadata.
entailment
public function run() { header('HTTP/1.1 200 OK'); header('Content-Type: text/event-stream;charset=UTF-8'); header('Cache-Control: no-cache, no-store, max-age=0, must-revalidate'); header('Pragma: no-cache'); while (1) { $stats = $this->metricsPoller->getStatsForCommandsRunning(); if (empty($stats)) { echo "ping: \n\n"; } else { foreach ($stats as $commandStats) { echo "data: " . json_encode($commandStats) . "\n\n"; } } ob_flush(); flush(); usleep($this->delay * 1000); } }
Serves text/event-stream format
entailment