sentence1
stringlengths
52
3.87M
sentence2
stringlengths
1
47.2k
label
stringclasses
1 value
public function optimize() { if (Zend_Search_Lucene_LockManager::obtainOptimizationLock($this->_directory) === false) { return false; } // 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(); $this->_mergeSegments($this->_segmentInfos); Zend_Search_Lucene_LockManager::releaseOptimizationLock($this->_directory); return true; }
Merges all segments together into new one Returns true on success and false if another optimization or auto-optimization process is running now @return boolean
entailment
private function _newSegmentName() { Zend_Search_Lucene_LockManager::obtainWriteLock($this->_directory); $generation = Zend_Search_Lucene::getActualGeneration($this->_directory); $segmentsFile = $this->_directory->getFileObject(Zend_Search_Lucene::getSegmentFileName($generation), false); $segmentsFile->seek(12); // 12 = 4 (int, file format marker) + 8 (long, index version) $segmentNameCounter = $segmentsFile->readInt(); $segmentsFile->seek(12); // 12 = 4 (int, file format marker) + 8 (long, index version) $segmentsFile->writeInt($segmentNameCounter + 1); // Flash output to guarantee that wrong value will not be loaded between unlock and // return (which calls $segmentsFile destructor) $segmentsFile->flush(); Zend_Search_Lucene_LockManager::releaseWriteLock($this->_directory); return '_' . base_convert($segmentNameCounter, 10, 36); }
Get name for new segment @return string
entailment
public function send($recipient, $body, $originator = '') { if (empty($recipient) || empty($body)) { // let's save a request return $this->transformResult(array( 'status' => ResultInterface::STATUS_FAILED, )); } try { $data = $this->getProvider()->send($recipient, $body, $originator); } catch (Exception $e) { throw new WrappedException($e, array('recipient' => $recipient, 'body' => $body, 'originator' => $originator)); } return $this->transformResult($data); }
{@inheritDoc}
entailment
public function registerProvider(ProviderInterface $provider) { if (null !== $provider) { $this->providers[$provider->getName()] = $provider; } return $this; }
Registers a provider. @param \SmsSender\Provider\ProviderInterface $provider @return \SmsSender\SmsSenderInterface
entailment
public function using($name) { if (isset($this->providers[$name])) { $this->provider = $this->providers[$name]; } return $this; }
Sets the provider to use. @param string $name A provider's name @return \SmsSender\SmsSenderInterface
entailment
public function getProvider() { if (null === $this->provider) { if (0 === count($this->providers)) { throw new \RuntimeException('No provider registered.'); } else { $this->provider = $this->providers[key($this->providers)]; } } return $this->provider; }
Returns the provider to use. @return \SmsSender\Provider\ProviderInterface
entailment
public function getField($fieldName) { if (!array_key_exists($fieldName, $this->_fields)) { include_once 'Zend/Search/Lucene/Exception.php'; throw new Zend_Search_Lucene_Exception("Field name \"$fieldName\" not found in document."); } return $this->_fields[$fieldName]; }
Returns Zend_Search_Lucene_Field object for a named field in this document. @param string $fieldName @return Zend_Search_Lucene_Field
entailment
public function getAMFData() { return (object)array( 'serverInfo' => (object)array( 'totalCount' => $this->count(), 'initialData' => $this->getData(), 'cursor' => 1, 'serviceName' => false, 'columnNames' => $this->getColumnNames(), 'version' => 1, 'id' => false, ) ); }
getAMFData @return object
entailment
protected function parserHeaders() { $headers = $this->asArray(); $this->_to = isset($headers['to']) ? self::decodeMimeString(current($headers['to'])) : ''; $this->_cc = isset($headers['cc']) ? self::decodeMimeString(current($headers['cc'])) : ''; $this->_from = isset($headers['from']) ? self::decodeMimeString(current($headers['from'])) : ''; $this->_date = isset($headers['date']) ? current($headers['date']) : ''; preg_match(self::EMAIL_PATTERN, $this->_from, $email); if (!empty($email)) { $email = $email[0]; } else { $email = null; throw new \Exception('Email not found in "'.$this->_from.'"'); } $this->_fromName = str_replace($email, '', $this->_from); $this->_fromName = trim($this->_fromName, '<>,'); $this->_fromName = trim($this->_fromName, ' "'); $this->_from = $email; //TODO может быть несколько получателей preg_match(self::EMAIL_PATTERN, $this->_to, $email); if (!empty($email)) { $this->_to = $email[0]; } if (isset($headers['content-type'])) { $part = current($headers['content-type']); $this->_messageContentType = trim(explode(';', $part)[0]); if (preg_match_all('/(boundary|charset)\s*\=\s*["\']?([\w\-\/\=\.]+)/i', $part, $result)) { foreach ($result[1] as $key => $val) { $val = '_'.strtolower($val); $this->{$val} = $result[2][$key]; } } } else { $this->_messageContentType = Content::CT_TEXT_PLAIN; } $this->_subject = isset($headers['subject']) ? self::decodeMimeString(current($headers['subject']), $this->getCharset()) : ''; $this->parseAutoReply(); if (isset($headers['content-transfer-encoding'])) { $this->_transferEncoding = trim(current($headers['content-transfer-encoding'])); } }
Parser headers
entailment
public static function decodeMimeString($strMime, $charset = null) { $items = preg_split('/[\r\n]{2,}/si', $strMime); $result = ''; $strArray = []; $tmpItems = []; foreach ($items as $key => $item) { $commaArray = explode('>,', $item); if (count($commaArray) > 1) { $last = array_pop($commaArray); foreach ($commaArray as $value) { $tmpItems[] = $value.'>,'; } $tmpItems[] = $last; } else { $tmpItems[] = current($commaArray); } } $items = $tmpItems; foreach ($items as $key => $item) { $data = explode('?', $item); $str = ''; if (!empty($data) && count($data) == 1 && is_null($charset)) { $str = $data[0]; } elseif (!empty($data)) { $lastItem = ''; while (!empty($data)) { $stringPart = self::decodeMimeStringPart($data); if (count($data) == 1) { $lastItem = trim(array_shift($data), ' ='); } if (!empty($stringPart)) { $strArray = array_merge_recursive($strArray, $stringPart); } } if (count($items) === 1 || !empty($lastItem) || (isset($items[$key + 1]) && strpos(trim($items[$key + 1]), '=?') !== 0)) { $str .= self::decodeStrArray($strArray); $strArray = []; } $str .= $lastItem; } $result .= $str; } if (!empty($strArray)) { $result .= self::decodeStrArray($strArray); } if (!empty($charset)) { $strMime = mb_convert_encoding($strMime, 'UTF-8', $charset); } return $result ?: $strMime; }
@param string $strMime @param string $charset @return string
entailment
public static function decodeStrArray($strArray) { $str = ''; foreach ($strArray as $encode => $part) { $encodedStr = ''; foreach ($part as $type => $strings) { if ($type === 'B') { $resultStr = is_array($strings) ? implode(array_map('base64_decode', $strings)) : base64_decode($strings); } elseif ($type === 'Q') { $resultStr = is_array($strings) ? implode($strings) : $strings; $resultStr = quoted_printable_decode($resultStr); } $encodedStr .= $resultStr; } $str .= mb_convert_encoding($encodedStr, 'UTF-8', $encode); } return $str; }
@param array $strArray @return string
entailment
public static function decodeMimeStringPart(&$data) { array_shift($data); $encode = strtoupper(array_shift($data)); $type = strtoupper(array_shift($data)); if ($type === '') { return []; } $str = array_shift($data); return [ $encode => [ $type => $str ] ]; }
@param $data @return array
entailment
public static function toArray($headers) { $headers .= "\r\n\r\n"; preg_match_all('#[\r\n]*([\w-]+\:)(.+?)(?=([\r\n]+[\w-]+\:|[\r\n]{3,}|\n{2,}))#si', $headers, $result); $headers = []; foreach ($result[1] as $k => $header) { $header = strtolower(rtrim($header, ':')); $headers[$header][] = trim($result[2][$k]); } return $headers; }
@param string $headers @return array
entailment
public function readAMFData($settype = null) { if (is_null($settype)) { $settype = $this->stream->readByte(); } switch ($settype) { case SabreAMF_AMF3_Const::DT_UNDEFINED : return null; case SabreAMF_AMF3_Const::DT_NULL : return null; case SabreAMF_AMF3_Const::DT_BOOL_FALSE : return false; case SabreAMF_AMF3_Const::DT_BOOL_TRUE : return true; case SabreAMF_AMF3_Const::DT_INTEGER : return $this->readInt(); case SabreAMF_AMF3_Const::DT_NUMBER : return $this->stream->readDouble(); case SabreAMF_AMF3_Const::DT_STRING : return $this->readString(); case SabreAMF_AMF3_Const::DT_XML : return $this->readString(); case SabreAMF_AMF3_Const::DT_DATE : return $this->readDate(); case SabreAMF_AMF3_Const::DT_ARRAY : return $this->readArray(); case SabreAMF_AMF3_Const::DT_OBJECT : return $this->readObject(); case SabreAMF_AMF3_Const::DT_XMLSTRING : return $this->readXMLString(); case SabreAMF_AMF3_Const::DT_BYTEARRAY : return $this->readByteArray(); default : throw new Exception('Unsupported type: 0x' . strtoupper(str_pad(dechex($settype),2,0,STR_PAD_LEFT))); return false; } }
readAMFData @param mixed $settype @return mixed
entailment
public function readObject() { $objInfo = $this->readU29(); $storedObject = ($objInfo & 0x01)==0; $objInfo = $objInfo >> 1; if ($storedObject) { $objectReference = $objInfo; if (!isset($this->storedObjects[$objectReference])) { throw new Exception('Object reference #' . $objectReference . ' not found'); } else { $rObject = $this->storedObjects[$objectReference]; } } else { $storedClass = ($objInfo & 0x01)==0; $objInfo= $objInfo >> 1; // If this is a stored class.. we have the info if ($storedClass) { $classReference = $objInfo; if (!isset($this->storedClasses[$classReference])) { throw new Exception('Class reference #' . $classReference . ' not found'); } else { $encodingType = $this->storedClasses[$classReference]['encodingType']; $propertyNames = $this->storedClasses[$classReference]['propertyNames']; $className = $this->storedClasses[$classReference]['className']; } } else { $className = $this->readString(); $encodingType = $objInfo & 0x03; $propertyNames = array(); $objInfo = $objInfo >> 2; } //ClassMapping magic if ($className) { if ($localClassName = $this->getLocalClassName($className)) { $rObject = new $localClassName(); } else { $rObject = new SabreAMF_TypedObject($className,array()); } } else { $rObject = new STDClass(); } $this->storedObjects[] =& $rObject; if ($encodingType & SabreAMF_AMF3_Const::ET_EXTERNALIZED) { if (!$storedClass) { $this->storedClasses[] = array('className' => $className,'encodingType'=>$encodingType,'propertyNames'=>$propertyNames); } if ($rObject instanceof SabreAMF_Externalized) { $rObject->readExternal($this->readAMFData()); } elseif ($rObject instanceof SabreAMF_TypedObject) { $rObject->setAMFData(array('externalizedData'=>$this->readAMFData())); } else { $rObject->externalizedData = $this->readAMFData(); } //$properties['externalizedData'] = $this->readAMFData(); } else { if ($encodingType & SabreAMF_AMF3_Const::ET_SERIAL) { if (!$storedClass) { $this->storedClasses[] = array('className' => $className,'encodingType'=>$encodingType,'propertyNames'=>$propertyNames); } $properties = array(); do { $propertyName = $this->readString(); if ($propertyName!="") { $propertyNames[] = $propertyName; $properties[$propertyName] = $this->readAMFData(); } } while ($propertyName!=""); } else { if (!$storedClass) { $propertyCount = $objInfo; for($i=0;$i<$propertyCount;$i++) { $propertyNames[] = $this->readString(); } $this->storedClasses[] = array('className' => $className,'encodingType'=>$encodingType,'propertyNames'=>$propertyNames); } $properties = array(); foreach($propertyNames as $propertyName) { $properties[$propertyName] = $this->readAMFData(); } } if ($rObject instanceof SabreAMF_TypedObject) { $rObject->setAMFData($properties); } else { foreach($properties as $k=>$v) if ($k) $rObject->$k = $v; } } } return $rObject; }
readObject @return object
entailment
public function readArray() { $arrId = $this->readU29(); if (($arrId & 0x01)==0) { $arrId = $arrId >> 1; if ($arrId>=count($this->storedObjects)) { throw new Exception('Undefined array reference: ' . $arrId); return false; } return $this->storedObjects[$arrId]; } $arrId = $arrId >> 1; $data = array(); $this->storedObjects[] &= $data; $key = $this->readString(); while($key!="") { $data[$key] = $this->readAMFData(); $key = $this->readString(); } for($i=0;$i<$arrId;$i++) { $data[] = $this->readAMFData(); } return $data; }
readArray @return array
entailment
public function readString() { $strref = $this->readU29(); if (($strref & 0x01) == 0) { $strref = $strref >> 1; if ($strref>=count($this->storedStrings)) { throw new Exception('Undefined string reference: ' . $strref); return false; } return $this->storedStrings[$strref]; } else { $strlen = $strref >> 1; $str = $this->stream->readBuffer($strlen); if ($str != "") $this->storedStrings[] = $str; return $str; } }
readString @return string
entailment
public function readXMLString() { $strref = $this->readU29(); $strlen = $strref >> 1; $str = $this->stream->readBuffer($strlen); return simplexml_load_string($str); }
readString @return string
entailment
public function readByteArray() { $strref = $this->readU29(); $strlen = $strref >> 1; $str = $this->stream->readBuffer($strlen); return new SabreAMF_ByteArray($str); }
readString @return string
entailment
public function readU29() { $count = 1; $u29 = 0; $byte = $this->stream->readByte(); while((($byte & 0x80) != 0) && $count < 4) { $u29 <<= 7; $u29 |= ($byte & 0x7f); $byte = $this->stream->readByte(); $count++; } if ($count < 4) { $u29 <<= 7; $u29 |= $byte; } else { // Use all 8 bits from the 4th byte $u29 <<= 8; $u29 |= $byte; } return $u29; }
readU29 @return int
entailment
public function readInt() { $int = $this->readU29(); // if int and has the sign bit set // Check if the integer is an int // and is signed if (($int & 0x18000000) == 0x18000000) { $int ^= 0x1fffffff; $int *= -1; $int -= 1; } else if (($int & 0x10000000) == 0x10000000) { // remove the signed flag $int &= 0x0fffffff; } return $int; }
readInt @return int
entailment
public function readDate() { $dateref = $this->readU29(); if (($dateref & 0x01) == 0) { $dateref = $dateref >> 1; if ($dateref>=count($this->storedObjects)) { throw new Exception('Undefined date reference: ' . $dateref); return false; } return $this->storedObjects[$dateref]; } $timestamp = floor($this->stream->readDouble() / 1000); $dateTime = new DateTime('@' . $timestamp); $this->storedObjects[] = $dateTime; return $dateTime; }
readDate @return int
entailment
public function writeAMFData($data,$forcetype=null) { if (is_null($forcetype)) { // Autodetecting data type $type=false; if (!$type && is_null($data)) $type = SabreAMF_AMF3_Const::DT_NULL; if (!$type && is_bool($data)) { $type = $data?SabreAMF_AMF3_Const::DT_BOOL_TRUE:SabreAMF_AMF3_Const::DT_BOOL_FALSE; } if (!$type && is_int($data)) { // We essentially only got 29 bits for integers if ($data > 0xFFFFFFF || $data < -268435456) { $type = SabreAMF_AMF3_Const::DT_NUMBER; } else { $type = SabreAMF_AMF3_Const::DT_INTEGER; } } if (!$type && is_float($data)) $type = SabreAMF_AMF3_Const::DT_NUMBER; if (!$type && is_int($data)) $type = SabreAMF_AMF3_Const::DT_INTEGER; if (!$type && is_string($data)) $type = SabreAMF_AMF3_Const::DT_STRING; if (!$type && is_array($data)) $type = SabreAMF_AMF3_Const::DT_ARRAY; if (!$type && is_object($data)) { if ($data instanceof SabreAMF_ByteArray) $type = SabreAMF_AMF3_Const::DT_BYTEARRAY; elseif ($data instanceof DateTime) $type = SabreAMF_AMF3_Const::DT_DATE; else $type = SabreAMF_AMF3_Const::DT_OBJECT; } if ($type===false) { throw new Exception('Unhandled data-type: ' . gettype($data)); return null; } if ($type == SabreAMF_AMF3_Const::DT_INTEGER && ($data > 268435455 || $data < -268435456)) { $type = SabreAMF_AMF3_Const::DT_NUMBER; } } else $type = $forcetype; $this->stream->writeByte($type); switch ($type) { case SabreAMF_AMF3_Const::DT_NULL : break; case SabreAMF_AMF3_Const::DT_BOOL_FALSE : break; case SabreAMF_AMF3_Const::DT_BOOL_TRUE : break; case SabreAMF_AMF3_Const::DT_INTEGER : $this->writeInt($data); break; case SabreAMF_AMF3_Const::DT_NUMBER : $this->stream->writeDouble($data); break; case SabreAMF_AMF3_Const::DT_STRING : $this->writeString($data); break; case SabreAMF_AMF3_Const::DT_DATE : $this->writeDate($data); break; case SabreAMF_AMF3_Const::DT_ARRAY : $this->writeArray($data); break; case SabreAMF_AMF3_Const::DT_OBJECT : $this->writeObject($data); break; case SabreAMF_AMF3_Const::DT_BYTEARRAY : $this->writeByteArray($data); break; default : throw new Exception('Unsupported type: ' . gettype($data)); return null; } }
writeAMFData @param mixed $data @param int $forcetype @return mixed
entailment
public function writeObject($data) { $encodingType = SabreAMF_AMF3_Const::ET_PROPLIST; if ($data instanceof SabreAMF_ITypedObject) { $classname = $data->getAMFClassName(); $data = $data->getAMFData(); } else if (!$classname = $this->getRemoteClassName(get_class($data))) { $classname = ''; } else { if ($data instanceof SabreAMF_Externalized) { $encodingType = SabreAMF_AMF3_Const::ET_EXTERNALIZED; } } $objectInfo = 0x03; $objectInfo |= $encodingType << 2; switch($encodingType) { case SabreAMF_AMF3_Const::ET_PROPLIST : $propertyCount=0; foreach($data as $k=>$v) { $propertyCount++; } $objectInfo |= ($propertyCount << 4); $this->writeInt($objectInfo); $this->writeString($classname); foreach($data as $k=>$v) { $this->writeString($k); } foreach($data as $k=>$v) { $this->writeAMFData($v); } break; case SabreAMF_AMF3_Const::ET_EXTERNALIZED : $this->writeInt($objectInfo); $this->writeString($classname); $this->writeAMFData($data->writeExternal()); break; } }
writeObject @param mixed $data @return void
entailment
public function writeInt($int) { // Note that this is simply a sanity check of the conversion algorithm; // when live this sanity check should be disabled (overflow check handled in this.writeAMFData). /*if ( ( ( $int & 0x70000000 ) != 0 ) && ( ( $int & 0x80000000 ) == 0 ) ) throw new Exception ( 'Integer overflow during Int32 to AMF3 conversion' );*/ if ( ( $int & 0xffffff80 ) == 0 ) { $this->stream->writeByte ( $int & 0x7f ); return; } if ( ( $int & 0xffffc000 ) == 0 ) { $this->stream->writeByte ( ( $int >> 7 ) | 0x80 ); $this->stream->writeByte ( $int & 0x7f ); return; } if ( ( $int & 0xffe00000 ) == 0 ) { $this->stream->writeByte ( ( $int >> 14 ) | 0x80 ); $this->stream->writeByte ( ( $int >> 7 ) | 0x80 ); $this->stream->writeByte ( $int & 0x7f ); return; } $this->stream->writeByte ( ( $int >> 22 ) | 0x80 ); $this->stream->writeByte ( ( $int >> 15 ) | 0x80 ); $this->stream->writeByte ( ( $int >> 8 ) | 0x80 ); $this->stream->writeByte ( $int & 0xff ); return; }
writeInt @param int $int @return void
entailment
public function writeString($str) { $strref = strlen($str) << 1 | 0x01; $this->writeInt($strref); $this->stream->writeBuffer($str); }
writeString @param string $str @return void
entailment
public function writeArray(array $arr) { //Check if this is an associative array or not. if ( $this->isPureArray( $arr ) ) { // Writing the length for the numeric keys in the array $arrLen = count($arr); $arrId = ($arrLen << 1) | 0x01; $this->writeInt($arrId); $this->writeString(''); foreach($arr as $v) { $this->writeAMFData($v); } } else { $this->writeInt(1); foreach($arr as $key=>$value) { $this->writeString($key); $this->writeAMFData($value); } $this->writeString(''); } }
writeArray @param array $arr @return void
entailment
public function addValueSortToCollection($collection, $dir = 'asc') { $attributeCode = $this->getAttribute()->getAttributeCode(); $attributeId = $this->getAttribute()->getId(); $attributeTable = $this->getAttribute()->getBackend()->getTable(); $linkField = $this->getAttribute()->getEntity()->getLinkField(); if ($this->getAttribute()->isScopeGlobal()) { $tableName = $attributeCode . '_t'; $collection->getSelect()->joinLeft( [$tableName => $attributeTable], "e.{$linkField}={$tableName}.{$linkField}" . " AND {$tableName}.attribute_id='{$attributeId}'" . " AND {$tableName}.store_id='0'", [] ); $valueExpr = $tableName . '.value'; } else { $valueTable1 = $attributeCode . '_t1'; $valueTable2 = $attributeCode . '_t2'; $collection->getSelect()->joinLeft( [$valueTable1 => $attributeTable], "e.{$linkField}={$valueTable1}.{$linkField}" . " AND {$valueTable1}.attribute_id='{$attributeId}'" . " AND {$valueTable1}.store_id='0'", [] )->joinLeft( [$valueTable2 => $attributeTable], "e.{$linkField}={$valueTable2}.{$linkField}" . " AND {$valueTable2}.attribute_id='{$attributeId}'" . " AND {$valueTable2}.store_id='{$collection->getStoreId()}'", [] ); $valueExpr = $collection->getConnection()->getCheckSql( $valueTable2 . '.value_id > 0', $valueTable2 . '.value', $valueTable1 . '.value' ); } $collection->getSelect()->order($valueExpr . ' ' . $dir); return $this; }
Add Value Sort To Collection Select @param \Magento\Eav\Model\Entity\Collection\AbstractCollection $collection @param string $dir direction @return AbstractSource
entailment
public function getMessage($id) { $header = $this->_protocol->top($id); $message = $this->_protocol->retrieve($id); return new Message($header, $message, $id); }
Получение сообщения @param int $id @return Message
entailment
public function getTitle() { if (!$this->title) { $this->title = DocumentationHelper::clean_page_name($this->key); } return $this->title; }
Get the title of this module. @return string
entailment
public function Link($short = false) { if ($this->getIsDefaultEntity()) { $base = Controller::join_links( Director::baseURL(), Config::inst()->get('DocumentationViewer', 'link_base'), $this->getLanguage(), '/' ); } else { $base = Controller::join_links( Director::baseURL(), Config::inst()->get('DocumentationViewer', 'link_base'), $this->getLanguage(), $this->getKey(), '/' ); } if ($short && $this->stable) { return $base; } return Controller::join_links( $base, $this->getVersion(), '/' ); }
Returns the web accessible link to this entity. Includes the version information @param boolean $short If true, will attempt to return a short version of the url This might omit the version number if this is the default version. @return string
entailment
public function hasRecord($page) { if (!$page) { return false; } return strstr($page->getPath(), $this->getPath()) !== false; }
@param DocumentationPage $page @return boolean
entailment
public function compare(DocumentationEntity $other) { $v1 = $this->getVersion(); $v2 = $other->getVersion(); // Normalise versions prior to comparison $dots = substr_count($v1, '.') - substr_count($v2, '.'); while ($dots > 0) { $dots--; $v2 .= '.99999'; } while ($dots < 0) { $dots++; $v1 .= '.99999'; } return version_compare($v1, $v2); }
Returns an integer value based on if a given version is the latest version. Will return -1 for if the version is older, 0 if versions are the same and 1 if the version is greater than. @param DocumentationEntity $other @return int
entailment
public function sumOfSquaredWeights() { // compute idf $this->_idf = $this->_reader->getSimilarity()->idf($this->_query->getTerms(), $this->_reader); // compute query weight $this->_queryWeight = $this->_idf * $this->_query->getBoost(); // square it return $this->_queryWeight * $this->_queryWeight; }
The sum of squared weights of contained query clauses. @return float
entailment
public function normalize($queryNorm) { $this->_queryNorm = $queryNorm; // normalize query weight $this->_queryWeight *= $queryNorm; // idf for documents $this->_value = $this->_queryWeight * $this->_idf; }
Assigns the query normalization factor to this. @param float $queryNorm
entailment
protected function getApiResponseAuthToken($username, $password) { $response = $this->sendRequest('GET', sprintf( self::API_AUTH_URL, urlencode($username), urlencode($password) )); return $response->getBody()->getContents(); }
@param string $username @param string $password @return string
entailment
protected function _initWeight(Zend_Search_Lucene_Interface $reader) { // Check, that it's a top-level query and query weight is not initialized yet. if ($this->_weight !== null) { return $this->_weight; } $this->createWeight($reader); $sum = $this->_weight->sumOfSquaredWeights(); $queryNorm = $reader->getSimilarity()->queryNorm($sum); $this->_weight->normalize($queryNorm); }
Constructs an initializes a Weight for a _top-level_query_. @param Zend_Search_Lucene_Interface $reader
entailment
public function highlightMatches($inputHTML, $defaultEncoding = '', $highlighter = null) { if ($highlighter === null) { include_once 'Zend/Search/Lucene/Search/Highlighter/Default.php'; $highlighter = new Zend_Search_Lucene_Search_Highlighter_Default(); } /** * Zend_Search_Lucene_Document_Html */ include_once 'Zend/Search/Lucene/Document/Html.php'; $doc = Zend_Search_Lucene_Document_Html::loadHTML($inputHTML, false, $defaultEncoding); $highlighter->setDocument($doc); $this->_highlightMatches($highlighter); return $doc->getHTML(); }
Highlight matches in $inputHTML @param string $inputHTML @param string $defaultEncoding HTML encoding, is used if it's not specified using Content-type HTTP-EQUIV meta tag. @param Zend_Search_Lucene_Search_Highlighter_Interface|null $highlighter @return string
entailment
public function htmlFragmentHighlightMatches($inputHtmlFragment, $encoding = 'UTF-8', $highlighter = null) { if ($highlighter === null) { include_once 'Zend/Search/Lucene/Search/Highlighter/Default.php'; $highlighter = new Zend_Search_Lucene_Search_Highlighter_Default(); } $inputHTML = '<html><head><META HTTP-EQUIV="Content-type" CONTENT="text/html; charset=UTF-8"/></head><body>' . iconv($encoding, 'UTF-8//IGNORE', $inputHtmlFragment) . '</body></html>'; /** * Zend_Search_Lucene_Document_Html */ include_once 'Zend/Search/Lucene/Document/Html.php'; $doc = Zend_Search_Lucene_Document_Html::loadHTML($inputHTML); $highlighter->setDocument($doc); $this->_highlightMatches($highlighter); return $doc->getHtmlBody(); }
Highlight matches in $inputHtmlFragment and return it (without HTML header and body tag) @param string $inputHtmlFragment @param string $encoding Input HTML string encoding @param Zend_Search_Lucene_Search_Highlighter_Interface|null $highlighter @return string
entailment
public function countMessages() { $count = 0; // "Declare" variable before first usage. $octets = 0; // "Declare" variable since it's passed by reference $this->_protocol->status($count, $octets); return (int)$count; }
Count Message @return int
entailment
public function getMessage($id) { $bodyLines = 0; $header = $this->_protocol->top($id, $bodyLines, true); $message = $message = $this->getRawContent($id); return new Message($header, $message, $id); }
Fetch message @param int $id @return Message @throws \Exception @throws protocol\Exception
entailment
public function send($recipient, $body, $originator = '') { return array( 'id' => uniqid(), 'recipient' => $recipient, 'body' => $body, 'originator' => $originator, 'status' => ResultInterface::STATUS_SENT, ); }
{@inheritDoc}
entailment
protected function getUserImage(array $response, AccessToken $token) { $guid = $token->getResourceOwnerId(); $url = 'https://social.yahooapis.com/v1/user/' . $guid . '/profile/image/' . $this->imageSize . '?format=json'; $request = $this->getAuthenticatedRequest('get', $url, $token); $response = $this->getResponse($request); return $response; }
Get user image from provider @param array $response @param AccessToken $token @return array
entailment
protected function getUserImageUrl(array $response, AccessToken $token) { $image = $this->getUserImage($response, $token); if (isset($image['image']['imageUrl'])) { return $image['image']['imageUrl']; } return null; }
Get user image url from provider, if available @param array $response @param AccessToken $token @return string
entailment
public function serialize(SabreAMF_OutputStream $stream) { $this->outputStream = $stream; $stream->writeByte(0x00); $stream->writeByte($this->encoding); $stream->writeInt(count($this->headers)); foreach($this->headers as $header) { $serializer = new SabreAMF_AMF0_Serializer($stream); $serializer->writeString($header['name']); $stream->writeByte($header['required']==true); $stream->writeLong(-1); $serializer->writeAMFData($header['data']); } $stream->writeInt(count($this->bodies)); foreach($this->bodies as $body) { $serializer = new SabreAMF_AMF0_Serializer($stream); $serializer->writeString($body['target']); $serializer->writeString($body['response']); $stream->writeLong(-1); switch($this->encoding) { case SabreAMF_Const::AMF0 : $serializer->writeAMFData($body['data']); break; case SabreAMF_Const::AMF3 : $serializer->writeAMFData(new SabreAMF_AMF3_Wrapper($body['data'])); break; } } }
serialize This method serializes a request. It requires an SabreAMF_OutputStream as an argument to read the AMF Data from. After serialization the Outputstream will contain the encoded AMF data. @param SabreAMF_OutputStream $stream @return void
entailment
public function deserialize(SabreAMF_InputStream $stream) { $this->headers = array(); $this->bodies = array(); $this->InputStream = $stream; $stream->readByte(); $this->clientType = $stream->readByte(); $deserializer = new SabreAMF_AMF0_Deserializer($stream); $totalHeaders = $stream->readInt(); for($i=0;$i<$totalHeaders;$i++) { $header = array( 'name' => $deserializer->readString(), 'required' => $stream->readByte()==true ); $stream->readLong(); $header['data'] = $deserializer->readAMFData(null,true); $this->headers[] = $header; } $totalBodies = $stream->readInt(); for($i=0;$i<$totalBodies;$i++) { try { $target = $deserializer->readString(); } catch (Exception $e) { // Could not fetch next body.. this happens with some versions of AMFPHP where the body // count isn't properly set. If this happens we simply stop decoding break; } $body = array( 'target' => $target, 'response' => $deserializer->readString(), 'length' => $stream->readLong(), 'data' => $deserializer->readAMFData(null,true) ); if (is_object($body['data']) && $body['data'] instanceof SabreAMF_AMF3_Wrapper) { $body['data'] = $body['data']->getData(); $this->encoding = SabreAMF_Const::AMF3; } else if (is_array($body['data']) && isset($body['data'][0]) && is_object($body['data'][0]) && $body['data'][0] instanceof SabreAMF_AMF3_Wrapper) { if ( defined('SABREAMF_AMF3_PRESERVE_ARGUMENTS') ) { $body['data'][0] = $body['data'][0]->getData(); } else { $body['data'] = $body['data'][0]->getData(); } $this->encoding = SabreAMF_Const::AMF3; } $this->bodies[] = $body; } }
deserialize This method deserializes a request. It requires an SabreAMF_InputStream with valid AMF data. After deserialization the contents of the request can be found through the getBodies and getHeaders methods @param SabreAMF_InputStream $stream @return void
entailment
public function addDocument(Zend_Search_Lucene_Document $document) { /** * Zend_Search_Lucene_Search_Similarity */ include_once 'Zend/Search/Lucene/Search/Similarity.php'; $storedFields = array(); $docNorms = array(); $similarity = Zend_Search_Lucene_Search_Similarity::getDefault(); foreach ($document->getFieldNames() as $fieldName) { $field = $document->getField($fieldName); if ($field->storeTermVector) { /** * @todo term vector storing support */ include_once 'Zend/Search/Lucene/Exception.php'; throw new Zend_Search_Lucene_Exception('Store term vector functionality is not supported yet.'); } if ($field->isIndexed) { if ($field->isTokenized) { /** * Zend_Search_Lucene_Analysis_Analyzer */ include_once 'Zend/Search/Lucene/Analysis/Analyzer.php'; $analyzer = Zend_Search_Lucene_Analysis_Analyzer::getDefault(); $analyzer->setInput($field->value, $field->encoding); $position = 0; $tokenCounter = 0; while (($token = $analyzer->nextToken()) !== null) { $tokenCounter++; $term = new Zend_Search_Lucene_Index_Term($token->getTermText(), $field->name); $termKey = $term->key(); if (!isset($this->_termDictionary[$termKey])) { // New term $this->_termDictionary[$termKey] = $term; $this->_termDocs[$termKey] = array(); $this->_termDocs[$termKey][$this->_docCount] = array(); } else if (!isset($this->_termDocs[$termKey][$this->_docCount])) { // Existing term, but new term entry $this->_termDocs[$termKey][$this->_docCount] = array(); } $position += $token->getPositionIncrement(); $this->_termDocs[$termKey][$this->_docCount][] = $position; } if ($tokenCounter == 0) { // Field contains empty value. Treat it as non-indexed and non-tokenized $field = clone($field); $field->isIndexed = $field->isTokenized = false; } else { $docNorms[$field->name] = chr( $similarity->encodeNorm( $similarity->lengthNorm( $field->name, $tokenCounter )* $document->boost* $field->boost ) ); } } else if (($fieldUtf8Value = $field->getUtf8Value()) == '') { // Field contains empty value. Treat it as non-indexed and non-tokenized $field = clone($field); $field->isIndexed = $field->isTokenized = false; } else { $term = new Zend_Search_Lucene_Index_Term($fieldUtf8Value, $field->name); $termKey = $term->key(); if (!isset($this->_termDictionary[$termKey])) { // New term $this->_termDictionary[$termKey] = $term; $this->_termDocs[$termKey] = array(); $this->_termDocs[$termKey][$this->_docCount] = array(); } else if (!isset($this->_termDocs[$termKey][$this->_docCount])) { // Existing term, but new term entry $this->_termDocs[$termKey][$this->_docCount] = array(); } $this->_termDocs[$termKey][$this->_docCount][] = 0; // position $docNorms[$field->name] = chr( $similarity->encodeNorm( $similarity->lengthNorm($field->name, 1)* $document->boost* $field->boost ) ); } } if ($field->isStored) { $storedFields[] = $field; } $this->addField($field); } foreach ($this->_fields as $fieldName => $field) { if (!$field->isIndexed) { continue; } if (!isset($this->_norms[$fieldName])) { $this->_norms[$fieldName] = str_repeat( chr($similarity->encodeNorm($similarity->lengthNorm($fieldName, 0))), $this->_docCount ); } if (isset($docNorms[$fieldName])) { $this->_norms[$fieldName] .= $docNorms[$fieldName]; } else { $this->_norms[$fieldName] .= chr($similarity->encodeNorm($similarity->lengthNorm($fieldName, 0))); } } $this->addStoredFields($storedFields); }
Adds a document to this segment. @param Zend_Search_Lucene_Document $document @throws Zend_Search_Lucene_Exception
entailment
protected function _dumpDictionary() { ksort($this->_termDictionary, SORT_STRING); $this->initializeDictionaryFiles(); foreach ($this->_termDictionary as $termId => $term) { $this->addTerm($term, $this->_termDocs[$termId]); } $this->closeDictionaryFiles(); }
Dump Term Dictionary (.tis) and Term Dictionary Index (.tii) segment files
entailment
public function getConfigTreeBuilder() { $tb = new TreeBuilder(); return $tb ->root('atoum_atoum') ->children() ->arrayNode('bundles') ->useAttributeAsKey('name') ->prototype('array') ->children() ->arrayNode('directories') ->defaultValue(array( 'Tests/Units', 'Tests/Controller', )) ->prototype('scalar') ->end() ->end() ->end() ->end() ->end() ->end() ->end() ; }
Generates the configuration tree builder. @return TreeBuilder The tree builder
entailment
public function withSpecialMark($mark, string $name = 'default'): self { $this->special_marks[$name] = $mark; return $this; }
Mark this object @param mixed $mark @return $this
entailment
public function send($recipient, $body, $originator = '') { if (null === $this->api_key || null === $this->api_secret) { 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 = $this->getParameters(array( 'to' => $this->localNumberToInternational($recipient, $this->international_prefix), 'text' => $body, 'from' => $originator, 'type' => $this->containsUnicode($body) ? 'unicode' : 'text', )); return $this->executeQuery(self::SEND_SMS_URL, $params, array( 'recipient' => $recipient, 'body' => $body, 'originator' => $originator, )); }
{@inheritDoc}
entailment
protected function makeResult($response, $method) { //Make sure we got the complete response. if( $method != 'HEAD' && isset($response->headers->{'content-length'}) && strlen($response->body) != $response->headers->{'content-length'} ) { throw new SagException('Unexpected end of packet.'); } /* * HEAD requests can return an HTTP response code >=400, meaning that there * was a CouchDB error, but we don't get a $response->body->error because * HEAD responses don't have bodies. * * We do this before the json_decode() because even running json_decode() * on undefined can take longer than calling it on a JSON string. So no * need to run any of the $json code. */ if($method == 'HEAD') { if($response->status >= 400) { throw new SagCouchException('HTTP/CouchDB error without message body', $response->headers->_HTTP->status); } return $response; } // Decode whether they ask for a raw response or not for error messages. if( !empty($response->headers->{'content-type'}) && $response->headers->{'content-type'} == 'application/json' ) { $json = json_decode($response->body); if(isset($json)) { if(!empty($json->error)) { throw new SagCouchException("{$json->error} ({$json->reason})", $response->headers->_HTTP->status); } if($this->decodeResp) { $response->body = $json; } } } return $response; }
Used by the concrete HTTP adapters, this abstracts out the generic task of turning strings from the net into response objects. @param string $response The body of the HTTP packet. @param string $method The request's HTTP method ("HEAD", etc.). @returns stdClass The response object.
entailment
protected function parseCookieString($cookieStr) { $cookies = new stdClass(); foreach(explode('; ', $cookieStr) as $cookie) { $crumbs = explode('=', $cookie); if(!isset($crumbs[1])) { $crumbs[1] = ''; } $cookies->{trim($crumbs[0])} = trim($crumbs[1]); } return $cookies; }
A utility function for the concrete adapters to turn the HTTP Cookie header's value into an object (map). @param string $cookieStr The HTTP Cookie header value (not including the "Cookie: " key. @returns stdClass An object mapping cookie name to cookie value.
entailment
public function setRWTimeout($seconds, $microseconds) { if(!is_int($microseconds) || $microseconds < 0) { throw new SagException('setRWTimeout() expects $microseconds to be an integer >= 0.'); } //TODO make this better, including checking $microseconds //$seconds can be 0 if $microseconds > 0 if( !is_int($seconds) || ( (!$microseconds && $seconds < 1) || ($microseconds && $seconds < 0) ) ) { throw new SagException('setRWTimeout() expects $seconds to be a positive integer.'); } $this->socketRWTimeoutSeconds = $seconds; $this->socketRWTimeoutMicroseconds = $microseconds; }
Set how long we should wait for an HTTP request to be executed. @param int $seconds The number of seconds. @param int $microseconds The number of microseconds.
entailment
public function setTimeoutsFromArray($arr) { /* * Validation is lax in here because this should only ever be used with * getTimeouts() return values. If people are using it by hand then there * might be something wrong with the API. */ if(!is_array($arr)) { throw SagException('Expected an array and got something else.'); } if(is_int($arr['open'])) { $this->setOpenTimeout($arr['open']); } if(is_int($arr['rwSeconds'])) { if(is_int($arr['rwMicroseconds'])) { $this->setRWTimeout($arr['rwSeconds'], $arr['rwMicroseconds']); } else { $this->setRWTimeout($arr['rwSeconds']); } } }
A utility function that sets the different timeout values based on an associative array. @param array $arr An associative array with the keys 'open', 'rwSeconds', and 'rwMicroseconds'. @see getTimeouts()
entailment
private function makeFollowAdapter($parts) { // re-use $this if we just got a path or the host/proto info matches if(empty($parts['host']) || ($parts['host'] == $this->host && $parts['port'] == $this->port && $parts['scheme'] == $this->proto ) ) { return $this; } if(empty($parts['port'])) { $parts['port'] = ($parts['scheme'] == 'https') ? 443 : 5984; } $adapter = new SagCURLHTTPAdapter($parts['host'], $parts['port']); $adapter->useSSL($parts['scheme'] == 'https'); $adapter->setTimeoutsFromArray($this->getTimeouts()); return $adapter; }
Used when we need to create a new adapter to follow a redirect because cURL can't. @param array $parts Return value from url_parts() for the location header. @return SagCURLHTTPAdapter Returns $this if talking to the same server with the same protocol, otherwise creates a new instance.
entailment
public static function getSubscribingMethods() { $methods = parent::getSubscribingMethods(); foreach (self::$additionalFormats as $format) { $methods[] = [ 'type' => 'DateTime', 'direction' => GraphNavigator::DIRECTION_DESERIALIZATION, 'format' => $format, 'method' => 'deserializeDateTimeFromJson', ]; foreach (self::$types as $type) { $methods[] = [ 'type' => $type, 'format' => $format, 'direction' => GraphNavigator::DIRECTION_SERIALIZATION, 'method' => 'serialize' . $type, ]; } } return $methods; }
{@inheritdoc}
entailment
public function reset() { $this->_position = 0; $this->_bytePosition = 0; // convert input into UTF-8 if (strcasecmp($this->_encoding, 'utf8') != 0 && strcasecmp($this->_encoding, 'utf-8') != 0 ) { $this->_input = iconv($this->_encoding, 'UTF-8', $this->_input); $this->_encoding = 'UTF-8'; } }
Reset token stream
entailment
public function nextToken() { if ($this->_input === null) { return null; } do { if (! preg_match('/[\p{L}\p{N}]+/u', $this->_input, $match, PREG_OFFSET_CAPTURE, $this->_bytePosition)) { // It covers both cases a) there are no matches (preg_match(...) === 0) // b) error occured (preg_match(...) === FALSE) return null; } // matched string $matchedWord = $match[0][0]; // binary position of the matched word in the input stream $binStartPos = $match[0][1]; // character position of the matched word in the input stream $startPos = $this->_position + iconv_strlen( substr( $this->_input, $this->_bytePosition, $binStartPos - $this->_bytePosition ), 'UTF-8' ); // character postion of the end of matched word in the input stream $endPos = $startPos + iconv_strlen($matchedWord, 'UTF-8'); $this->_bytePosition = $binStartPos + strlen($matchedWord); $this->_position = $endPos; $token = $this->normalize(new Zend_Search_Lucene_Analysis_Token($matchedWord, $startPos, $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 multiple(): self { $unique_array = array_unique($this->getArrayCopy()); return new ArrayMap(array_diff_assoc($this->getArrayCopy(), $unique_array)); }
Get duplicate values in an array @return $this
entailment
public function sort($sort_flags = SORT_REGULAR): self { $temp = $this->getArrayCopy(); sort($temp, $sort_flags); return new ArrayMap($temp); }
sort @param int $sort_flags @return $this
entailment
public function register() { $this->app->configure('zendacl'); $this->app->singleton(function (Application $app) { $acl = new Acl; if (file_exists(base_path('app/Http/acl.php'))) { include base_path('app/Http/acl.php'); } return $acl; }); $this->app->singleton('Zend\Permissions\Acl\Acl', function (Application $app) { return $app->make('acl'); }); }
Register the service provider. @return void
entailment
public function put($element) { $nodeId = count($this->_heap); $parentId = ($nodeId-1) >> 1; // floor( ($nodeId-1)/2 ) while ($nodeId != 0 && $this->_less($element, $this->_heap[$parentId])) { // Move parent node down $this->_heap[$nodeId] = $this->_heap[$parentId]; // Move pointer to the next level of tree $nodeId = $parentId; $parentId = ($nodeId-1) >> 1; // floor( ($nodeId-1)/2 ) } // Put new node into the tree $this->_heap[$nodeId] = $element; }
Add element to the queue O(log(N)) time @param mixed $element
entailment
public function pop() { if (count($this->_heap) == 0) { return null; } $top = $this->_heap[0]; $lastId = count($this->_heap) - 1; /** * Find appropriate position for last node */ $nodeId = 0; // Start from a top $childId = 1; // First child // Choose smaller child if ($lastId > 2 && $this->_less($this->_heap[2], $this->_heap[1])) { $childId = 2; } while ($childId < $lastId && $this->_less($this->_heap[$childId], $this->_heap[$lastId]) ) { // Move child node up $this->_heap[$nodeId] = $this->_heap[$childId]; $nodeId = $childId; // Go down $childId = ($nodeId << 1) + 1; // First child // Choose smaller child if (($childId+1) < $lastId && $this->_less($this->_heap[$childId+1], $this->_heap[$childId]) ) { $childId++; } } // Move last element to the new position $this->_heap[$nodeId] = $this->_heap[$lastId]; unset($this->_heap[$lastId]); return $top; }
Removes and return least element of the queue O(log(N)) time @return mixed
entailment
public function VersionWarning() { $page = $this->owner->getPage(); if (!$page) { return false; } $entity = $page->getEntity(); if (!$entity) { return false; } $versions = $this->owner->getManifest()->getAllVersionsOfEntity($entity); if ($entity->getIsStable()) { return false; } $stable = $this->owner->getManifest()->getStableVersion($entity); $compare = $entity->compare($stable); if ($entity->getVersion() == 'master' || $compare > 0) { return $this->owner->customise( new ArrayData( array( 'FutureRelease' => true, 'StableVersion' => DBField::create_field('HTMLText', $stable->getVersion()) ) ) ); } else { return $this->owner->customise( new ArrayData( array( 'OutdatedRelease' => true, 'StableVersion' => DBField::create_field('HTMLText', $stable->getVersion()) ) ) ); } return false; }
Check to see if the currently accessed version is out of date or perhaps a future version rather than the stable edition. @return false|ArrayData
entailment
public function resetTermsStream() { /** * Zend_Search_Lucene_Index_TermsPriorityQueue */ include_once 'Zend/Search/Lucene/Index/TermsPriorityQueue.php'; $this->_termsStreamQueue = new Zend_Search_Lucene_Index_TermsPriorityQueue(); foreach ($this->_termStreams as $termStream) { $termStream->resetTermsStream(); // Skip "empty" containers if ($termStream->currentTerm() !== null) { $this->_termsStreamQueue->put($termStream); } } $this->nextTerm(); }
Reset terms stream.
entailment
public function skipTo(Zend_Search_Lucene_Index_Term $prefix) { $termStreams = array(); while (($termStream = $this->_termsStreamQueue->pop()) !== null) { $termStreams[] = $termStream; } foreach ($termStreams as $termStream) { $termStream->skipTo($prefix); if ($termStream->currentTerm() !== null) { $this->_termsStreamQueue->put($termStream); } } $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
entailment
public function nextTerm() { while (($termStream = $this->_termsStreamQueue->pop()) !== null) { if ($this->_termsStreamQueue->top() === null || $this->_termsStreamQueue->top()->currentTerm()->key() != $termStream->currentTerm()->key() ) { // We got new term $this->_lastTerm = $termStream->currentTerm(); if ($termStream->nextTerm() !== null) { // Put segment back into the priority queue $this->_termsStreamQueue->put($termStream); } return $this->_lastTerm; } if ($termStream->nextTerm() !== null) { // Put segment back into the priority queue $this->_termsStreamQueue->put($termStream); } } // End of stream $this->_lastTerm = null; return null; }
Scans term streams and returns next term @return Zend_Search_Lucene_Index_Term|null
entailment
public function closeTermsStream() { while (($termStream = $this->_termsStreamQueue->pop()) !== null) { $termStream->closeTermsStream(); } $this->_termsStreamQueue = null; $this->_lastTerm = null; }
Close terms stream Should be used for resources clean up if stream is not read up to the end
entailment
public function addTerm(Zend_Search_Lucene_Index_Term $term, $sign = null) { if ($sign !== true || $this->_signs !== null) { // Skip, if all terms are required if ($this->_signs === null) { // Check, If all previous terms are required $this->_signs = array(); foreach ($this->_terms as $prevTerm) { $this->_signs[] = true; } } $this->_signs[] = $sign; } $this->_terms[] = $term; }
Add a $term (Zend_Search_Lucene_Index_Term) to this query. The sign is specified as: TRUE - term is required FALSE - term is prohibited NULL - term is neither prohibited, nor required @param Zend_Search_Lucene_Index_Term $term @param boolean|null $sign @return void
entailment
public function rewrite(Zend_Search_Lucene_Interface $index) { if (count($this->_terms) == 0) { include_once 'Zend/Search/Lucene/Search/Query/Empty.php'; return new Zend_Search_Lucene_Search_Query_Empty(); } // Check, that all fields are qualified $allQualified = true; foreach ($this->_terms as $term) { if ($term->field === null) { $allQualified = false; break; } } if ($allQualified) { return $this; } else { /** * transform multiterm query to boolean and apply rewrite() method to subqueries. */ include_once 'Zend/Search/Lucene/Search/Query/Boolean.php'; $query = new Zend_Search_Lucene_Search_Query_Boolean(); $query->setBoost($this->getBoost()); include_once 'Zend/Search/Lucene/Search/Query/Term.php'; foreach ($this->_terms as $termId => $term) { $subquery = new Zend_Search_Lucene_Search_Query_Term($term); $query->addSubquery( $subquery->rewrite($index), ($this->_signs === null)? true : $this->_signs[$termId] ); } 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
public function optimize(Zend_Search_Lucene_Interface $index) { $terms = $this->_terms; $signs = $this->_signs; foreach ($terms as $id => $term) { if (!$index->hasTerm($term)) { if ($signs === null || $signs[$id] === true) { // Term is required include_once 'Zend/Search/Lucene/Search/Query/Empty.php'; return new Zend_Search_Lucene_Search_Query_Empty(); } else { // Term is optional or prohibited // Remove it from terms and signs list unset($terms[$id]); unset($signs[$id]); } } } // Check if all presented terms are prohibited $allProhibited = true; if ($signs === null) { $allProhibited = false; } else { foreach ($signs as $sign) { if ($sign !== false) { $allProhibited = false; break; } } } if ($allProhibited) { include_once 'Zend/Search/Lucene/Search/Query/Empty.php'; return new Zend_Search_Lucene_Search_Query_Empty(); } /** * @todo make an optimization for repeated terms * (they may have different signs) */ if (count($terms) == 1) { // It's already checked, that it's not a prohibited term // It's one term query with one required or optional element include_once 'Zend/Search/Lucene/Search/Query/Term.php'; $optimizedQuery = new Zend_Search_Lucene_Search_Query_Term(reset($terms)); $optimizedQuery->setBoost($this->getBoost()); return $optimizedQuery; } if (count($terms) == 0) { include_once 'Zend/Search/Lucene/Search/Query/Empty.php'; return new Zend_Search_Lucene_Search_Query_Empty(); } $optimizedQuery = new Zend_Search_Lucene_Search_Query_MultiTerm($terms, $signs); $optimizedQuery->setBoost($this->getBoost()); return $optimizedQuery; }
Optimize query in the context of specified index @param Zend_Search_Lucene_Interface $index @return Zend_Search_Lucene_Search_Query
entailment
public function createWeight(Zend_Search_Lucene_Interface $reader) { include_once 'Zend/Search/Lucene/Search/Weight/MultiTerm.php'; $this->_weight = new Zend_Search_Lucene_Search_Weight_MultiTerm($this, $reader); return $this->_weight; }
Constructs an appropriate Weight implementation for this query. @param Zend_Search_Lucene_Interface $reader @return Zend_Search_Lucene_Search_Weight
entailment
private function _calculateConjunctionResult(Zend_Search_Lucene_Interface $reader) { $this->_resVector = null; if (count($this->_terms) == 0) { $this->_resVector = array(); } // Order terms by selectivity $docFreqs = array(); $ids = array(); foreach ($this->_terms as $id => $term) { $docFreqs[] = $reader->docFreq($term); $ids[] = $id; // Used to keep original order for terms with the same selectivity and omit terms comparison } array_multisort( $docFreqs, SORT_ASC, SORT_NUMERIC, $ids, SORT_ASC, SORT_NUMERIC, $this->_terms ); include_once 'Zend/Search/Lucene/Index/DocsFilter.php'; $docsFilter = new Zend_Search_Lucene_Index_DocsFilter(); foreach ($this->_terms as $termId => $term) { $termDocs = $reader->termDocs($term, $docsFilter); } // Treat last retrieved docs vector as a result set // (filter collects data for other terms) $this->_resVector = array_flip($termDocs); foreach ($this->_terms as $termId => $term) { $this->_termsFreqs[$termId] = $reader->termFreqs($term, $docsFilter); } // ksort($this->_resVector, SORT_NUMERIC); // Docs are returned ordered. Used algorithms doesn't change elements order. }
Calculate result vector for Conjunction query (like '+something +another') @param Zend_Search_Lucene_Interface $reader
entailment
private function _calculateNonConjunctionResult(Zend_Search_Lucene_Interface $reader) { $requiredVectors = array(); $requiredVectorsSizes = array(); $requiredVectorsIds = array(); // is used to prevent arrays comparison $optional = array(); $prohibited = array(); foreach ($this->_terms as $termId => $term) { $termDocs = array_flip($reader->termDocs($term)); if ($this->_signs[$termId] === true) { // required $requiredVectors[] = $termDocs; $requiredVectorsSizes[] = count($termDocs); $requiredVectorsIds[] = $termId; } elseif ($this->_signs[$termId] === false) { // prohibited // array union $prohibited += $termDocs; } else { // neither required, nor prohibited // array union $optional += $termDocs; } $this->_termsFreqs[$termId] = $reader->termFreqs($term); } // sort resvectors in order of subquery cardinality increasing array_multisort( $requiredVectorsSizes, SORT_ASC, SORT_NUMERIC, $requiredVectorsIds, SORT_ASC, SORT_NUMERIC, $requiredVectors ); $required = null; foreach ($requiredVectors as $nextResVector) { if($required === null) { $required = $nextResVector; } else { //$required = array_intersect_key($required, $nextResVector); /** * This code is used as workaround for array_intersect_key() slowness problem. */ $updatedVector = array(); foreach ($required as $id => $value) { if (isset($nextResVector[$id])) { $updatedVector[$id] = $value; } } $required = $updatedVector; } if (count($required) == 0) { // Empty result set, we don't need to check other terms break; } } if ($required !== null) { $this->_resVector = $required; } else { $this->_resVector = $optional; } if (count($prohibited) != 0) { // $this->_resVector = array_diff_key($this->_resVector, $prohibited); /** * This code is used as workaround for array_diff_key() slowness problem. */ if (count($this->_resVector) < count($prohibited)) { $updatedVector = $this->_resVector; foreach ($this->_resVector as $id => $value) { if (isset($prohibited[$id])) { unset($updatedVector[$id]); } } $this->_resVector = $updatedVector; } else { $updatedVector = $this->_resVector; foreach ($prohibited as $id => $value) { unset($updatedVector[$id]); } $this->_resVector = $updatedVector; } } ksort($this->_resVector, SORT_NUMERIC); }
Calculate result vector for non Conjunction query (like '+something -another') @param Zend_Search_Lucene_Interface $reader
entailment
public function _conjunctionScore($docId, Zend_Search_Lucene_Interface $reader) { if ($this->_coord === null) { $this->_coord = $reader->getSimilarity()->coord( count($this->_terms), count($this->_terms) ); } $score = 0.0; foreach ($this->_terms as $termId => $term) { /** * We don't need to check that term freq is not 0 * Score calculation is performed only for matched docs */ $score += $reader->getSimilarity()->tf($this->_termsFreqs[$termId][$docId]) * $this->_weights[$termId]->getValue() * $reader->norm($docId, $term->field); } return $score * $this->_coord * $this->getBoost(); }
Score calculator for conjunction queries (all terms are required) @param integer $docId @param Zend_Search_Lucene_Interface $reader @return float
entailment
public function _nonConjunctionScore($docId, $reader) { if ($this->_coord === null) { $this->_coord = array(); $maxCoord = 0; foreach ($this->_signs as $sign) { if ($sign !== false /* not prohibited */) { $maxCoord++; } } for ($count = 0; $count <= $maxCoord; $count++) { $this->_coord[$count] = $reader->getSimilarity()->coord($count, $maxCoord); } } $score = 0.0; $matchedTerms = 0; foreach ($this->_terms as $termId=>$term) { // Check if term is if ($this->_signs[$termId] !== false // not prohibited && isset($this->_termsFreqs[$termId][$docId]) // matched ) { $matchedTerms++; /** * We don't need to check that term freq is not 0 * Score calculation is performed only for matched docs */ $score += $reader->getSimilarity()->tf($this->_termsFreqs[$termId][$docId]) * $this->_weights[$termId]->getValue() * $reader->norm($docId, $term->field); } } return $score * $this->_coord[$matchedTerms] * $this->getBoost(); }
Score calculator for non conjunction queries (not all terms are required) @param integer $docId @param Zend_Search_Lucene_Interface $reader @return float
entailment
public function execute(Zend_Search_Lucene_Interface $reader, $docsFilter = null) { if ($this->_signs === null) { $this->_calculateConjunctionResult($reader); } else { $this->_calculateNonConjunctionResult($reader); } // Initialize weight if it's not done yet $this->_initWeight($reader); }
Execute query in context of index reader It also initializes necessary internal structures @param Zend_Search_Lucene_Interface $reader @param Zend_Search_Lucene_Index_DocsFilter|null $docsFilter
entailment
public function getQueryTerms() { if ($this->_signs === null) { return $this->_terms; } $terms = array(); foreach ($this->_signs as $id => $sign) { if ($sign !== false) { $terms[] = $this->_terms[$id]; } } return $terms; }
Return query terms @return array
entailment
protected function _highlightMatches(Zend_Search_Lucene_Search_Highlighter_Interface $highlighter) { $words = array(); if ($this->_signs === null) { foreach ($this->_terms as $term) { $words[] = $term->text; } } else { foreach ($this->_signs as $id => $sign) { if ($sign !== false) { $words[] = $this->_terms[$id]->text; } } } $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 normalize(Zend_Search_Lucene_Analysis_Token $srcToken) { $newToken = new Zend_Search_Lucene_Analysis_Token( mb_strtolower($srcToken->getTermText(), 'UTF-8'), $srcToken->getStartOffset(), $srcToken->getEndOffset() ); $newToken->setPositionIncrement($srcToken->getPositionIncrement()); return $newToken; }
Normalize Token or remove it (if null is returned) @param Zend_Search_Lucene_Analysis_Token $srcToken @return Zend_Search_Lucene_Analysis_Token
entailment
public function addField(Zend_Search_Lucene_Field $field) { if (!isset($this->_fields[$field->name])) { $fieldNumber = count($this->_fields); $this->_fields[$field->name] = new Zend_Search_Lucene_Index_FieldInfo( $field->name, $field->isIndexed, $fieldNumber, $field->storeTermVector ); return $fieldNumber; } else { $this->_fields[$field->name]->isIndexed |= $field->isIndexed; $this->_fields[$field->name]->storeTermVector |= $field->storeTermVector; return $this->_fields[$field->name]->number; } }
Add field to the segment Returns actual field number @param Zend_Search_Lucene_Field $field @return integer
entailment
public function addFieldInfo(Zend_Search_Lucene_Index_FieldInfo $fieldInfo) { if (!isset($this->_fields[$fieldInfo->name])) { $fieldNumber = count($this->_fields); $this->_fields[$fieldInfo->name] = new Zend_Search_Lucene_Index_FieldInfo( $fieldInfo->name, $fieldInfo->isIndexed, $fieldNumber, $fieldInfo->storeTermVector ); return $fieldNumber; } else { $this->_fields[$fieldInfo->name]->isIndexed |= $fieldInfo->isIndexed; $this->_fields[$fieldInfo->name]->storeTermVector |= $fieldInfo->storeTermVector; return $this->_fields[$fieldInfo->name]->number; } }
Add fieldInfo to the segment Returns actual field number @param Zend_Search_Lucene_Index_FieldInfo $fieldInfo @return integer
entailment
public function addStoredFields($storedFields) { if (!isset($this->_fdxFile)) { $this->_fdxFile = $this->_directory->createFile($this->_name . '.fdx'); $this->_fdtFile = $this->_directory->createFile($this->_name . '.fdt'); $this->_files[] = $this->_name . '.fdx'; $this->_files[] = $this->_name . '.fdt'; } $this->_fdxFile->writeLong($this->_fdtFile->tell()); $this->_fdtFile->writeVInt(count($storedFields)); foreach ($storedFields as $field) { $this->_fdtFile->writeVInt($this->_fields[$field->name]->number); $fieldBits = ($field->isTokenized ? 0x01 : 0x00) | ($field->isBinary ? 0x02 : 0x00) | 0x00; /* 0x04 - third bit, compressed (ZLIB) */ $this->_fdtFile->writeByte($fieldBits); if ($field->isBinary) { $this->_fdtFile->writeVInt(strlen($field->value)); $this->_fdtFile->writeBytes($field->value); } else { $this->_fdtFile->writeString($field->getUtf8Value()); } } $this->_docCount++; }
Add stored fields information @param array $storedFields array of Zend_Search_Lucene_Field objects
entailment
protected function _dumpFNM() { $fnmFile = $this->_directory->createFile($this->_name . '.fnm'); $fnmFile->writeVInt(count($this->_fields)); $nrmFile = $this->_directory->createFile($this->_name . '.nrm'); // Write header $nrmFile->writeBytes('NRM'); // Write format specifier $nrmFile->writeByte((int)0xFF); foreach ($this->_fields as $field) { $fnmFile->writeString($field->name); $fnmFile->writeByte( ($field->isIndexed ? 0x01 : 0x00) | ($field->storeTermVector ? 0x02 : 0x00) // not supported yet 0x04 /* term positions are stored with the term vectors */ | // not supported yet 0x08 /* term offsets are stored with the term vectors */ | ); if ($field->isIndexed) { // pre-2.1 index mode (not used now) // $normFileName = $this->_name . '.f' . $field->number; // $fFile = $this->_directory->createFile($normFileName); // $fFile->writeBytes($this->_norms[$field->name]); // $this->_files[] = $normFileName; $nrmFile->writeBytes($this->_norms[$field->name]); } } $this->_files[] = $this->_name . '.fnm'; $this->_files[] = $this->_name . '.nrm'; }
Dump Field Info (.fnm) segment file
entailment
public function initializeDictionaryFiles() { $this->_tisFile = $this->_directory->createFile($this->_name . '.tis'); $this->_tisFile->writeInt((int)0xFFFFFFFD); $this->_tisFile->writeLong(0 /* dummy data for terms count */); $this->_tisFile->writeInt(self::$indexInterval); $this->_tisFile->writeInt(self::$skipInterval); $this->_tisFile->writeInt(self::$maxSkipLevels); $this->_tiiFile = $this->_directory->createFile($this->_name . '.tii'); $this->_tiiFile->writeInt((int)0xFFFFFFFD); $this->_tiiFile->writeLong(0 /* dummy data for terms count */); $this->_tiiFile->writeInt(self::$indexInterval); $this->_tiiFile->writeInt(self::$skipInterval); $this->_tiiFile->writeInt(self::$maxSkipLevels); /** * Dump dictionary header */ $this->_tiiFile->writeVInt(0); // preffix length $this->_tiiFile->writeString(''); // suffix $this->_tiiFile->writeInt((int)0xFFFFFFFF); // field number $this->_tiiFile->writeByte((int)0x0F); $this->_tiiFile->writeVInt(0); // DocFreq $this->_tiiFile->writeVInt(0); // FreqDelta $this->_tiiFile->writeVInt(0); // ProxDelta $this->_tiiFile->writeVInt(24); // IndexDelta $this->_frqFile = $this->_directory->createFile($this->_name . '.frq'); $this->_prxFile = $this->_directory->createFile($this->_name . '.prx'); $this->_files[] = $this->_name . '.tis'; $this->_files[] = $this->_name . '.tii'; $this->_files[] = $this->_name . '.frq'; $this->_files[] = $this->_name . '.prx'; $this->_prevTerm = null; $this->_prevTermInfo = null; $this->_prevIndexTerm = null; $this->_prevIndexTermInfo = null; $this->_lastIndexPosition = 24; $this->_termCount = 0; }
Create dicrionary, frequency and positions files and write necessary headers
entailment
public function addTerm($termEntry, $termDocs) { $freqPointer = $this->_frqFile->tell(); $proxPointer = $this->_prxFile->tell(); $prevDoc = 0; foreach ($termDocs as $docId => $termPositions) { $docDelta = ($docId - $prevDoc)*2; $prevDoc = $docId; if (count($termPositions) > 1) { $this->_frqFile->writeVInt($docDelta); $this->_frqFile->writeVInt(count($termPositions)); } else { $this->_frqFile->writeVInt($docDelta + 1); } $prevPosition = 0; foreach ($termPositions as $position) { $this->_prxFile->writeVInt($position - $prevPosition); $prevPosition = $position; } } if (count($termDocs) >= self::$skipInterval) { /** * @todo Write Skip Data to a freq file. * It's not used now, but make index more optimal */ $skipOffset = $this->_frqFile->tell() - $freqPointer; } else { $skipOffset = 0; } $term = new Zend_Search_Lucene_Index_Term( $termEntry->text, $this->_fields[$termEntry->field]->number ); $termInfo = new Zend_Search_Lucene_Index_TermInfo( count($termDocs), $freqPointer, $proxPointer, $skipOffset ); $this->_dumpTermDictEntry($this->_tisFile, $this->_prevTerm, $term, $this->_prevTermInfo, $termInfo); if (($this->_termCount + 1) % self::$indexInterval == 0) { $this->_dumpTermDictEntry($this->_tiiFile, $this->_prevIndexTerm, $term, $this->_prevIndexTermInfo, $termInfo); $indexPosition = $this->_tisFile->tell(); $this->_tiiFile->writeVInt($indexPosition - $this->_lastIndexPosition); $this->_lastIndexPosition = $indexPosition; } $this->_termCount++; }
Add term Term positions is an array( docId => array(pos1, pos2, pos3, ...), ... ) @param Zend_Search_Lucene_Index_Term $termEntry @param array $termDocs
entailment
public function closeDictionaryFiles() { $this->_tisFile->seek(4); $this->_tisFile->writeLong($this->_termCount); $this->_tiiFile->seek(4); // + 1 is used to count an additional special index entry (empty term at the start of the list) $this->_tiiFile->writeLong(($this->_termCount - $this->_termCount % self::$indexInterval)/self::$indexInterval + 1); }
Close dictionary
entailment
protected function _dumpTermDictEntry(Zend_Search_Lucene_Storage_File $dicFile, &$prevTerm, Zend_Search_Lucene_Index_Term $term, &$prevTermInfo, Zend_Search_Lucene_Index_TermInfo $termInfo ) { if (isset($prevTerm) && $prevTerm->field == $term->field) { $matchedBytes = 0; $maxBytes = min(strlen($prevTerm->text), strlen($term->text)); while ($matchedBytes < $maxBytes && $prevTerm->text[$matchedBytes] == $term->text[$matchedBytes]) { $matchedBytes++; } // Calculate actual matched UTF-8 pattern $prefixBytes = 0; $prefixChars = 0; while ($prefixBytes < $matchedBytes) { $charBytes = 1; if ((ord($term->text[$prefixBytes]) & 0xC0) == 0xC0) { $charBytes++; if (ord($term->text[$prefixBytes]) & 0x20 ) { $charBytes++; if (ord($term->text[$prefixBytes]) & 0x10 ) { $charBytes++; } } } if ($prefixBytes + $charBytes > $matchedBytes) { // char crosses matched bytes boundary // skip char break; } $prefixChars++; $prefixBytes += $charBytes; } // Write preffix length $dicFile->writeVInt($prefixChars); // Write suffix $dicFile->writeString(substr($term->text, $prefixBytes)); } else { // Write preffix length $dicFile->writeVInt(0); // Write suffix $dicFile->writeString($term->text); } // Write field number $dicFile->writeVInt($term->field); // DocFreq (the count of documents which contain the term) $dicFile->writeVInt($termInfo->docFreq); $prevTerm = $term; if (!isset($prevTermInfo)) { // Write FreqDelta $dicFile->writeVInt($termInfo->freqPointer); // Write ProxDelta $dicFile->writeVInt($termInfo->proxPointer); } else { // Write FreqDelta $dicFile->writeVInt($termInfo->freqPointer - $prevTermInfo->freqPointer); // Write ProxDelta $dicFile->writeVInt($termInfo->proxPointer - $prevTermInfo->proxPointer); } // Write SkipOffset - it's not 0 when $termInfo->docFreq > self::$skipInterval if ($termInfo->skipOffset != 0) { $dicFile->writeVInt($termInfo->skipOffset); } $prevTermInfo = $termInfo; }
Dump Term Dictionary segment file entry. Used to write entry to .tis or .tii files @param Zend_Search_Lucene_Storage_File $dicFile @param Zend_Search_Lucene_Index_Term $prevTerm @param Zend_Search_Lucene_Index_Term $term @param Zend_Search_Lucene_Index_TermInfo $prevTermInfo @param Zend_Search_Lucene_Index_TermInfo $termInfo
entailment
protected function _generateCFS() { $cfsFile = $this->_directory->createFile($this->_name . '.cfs'); $cfsFile->writeVInt(count($this->_files)); $dataOffsetPointers = array(); foreach ($this->_files as $fileName) { $dataOffsetPointers[$fileName] = $cfsFile->tell(); $cfsFile->writeLong(0); // write dummy data $cfsFile->writeString($fileName); } foreach ($this->_files as $fileName) { // Get actual data offset $dataOffset = $cfsFile->tell(); // Seek to the data offset pointer $cfsFile->seek($dataOffsetPointers[$fileName]); // Write actual data offset value $cfsFile->writeLong($dataOffset); // Seek back to the end of file $cfsFile->seek($dataOffset); $dataFile = $this->_directory->getFileObject($fileName); $byteCount = $this->_directory->fileLength($fileName); while ($byteCount > 0) { $data = $dataFile->readBytes(min($byteCount, 131072 /*128Kb*/)); $byteCount -= strlen($data); $cfsFile->writeBytes($data); } $this->_directory->deleteFile($fileName); } }
Generate compound index file
entailment
public function getDocument() { if (!$this->_document instanceof Zend_Search_Lucene_Document) { $this->_document = $this->_index->getDocument($this->id); } return $this->_document; }
Return the document object for this hit @return Zend_Search_Lucene_Document
entailment
public function register() { $this->mergeConfigFrom( dirname(dirname(__DIR__)) . '/config/zendacl.php', 'zendacl' ); $this->app->singleton('acl', function (Application $app) { $acl = new Acl; if (file_exists(base_path('routes/acl.php'))) { include base_path('routes/acl.php'); } elseif (file_exists(app_path('Http/acl.php'))) { include app_path('Http/acl.php'); } return $acl; }); $this->app->singleton('Zend\Permissions\Acl\Acl', function (Application $app) { return $app->make('acl'); }); }
Register the service provider. @return void
entailment
protected function withBulk(array $data = []) { if (!$this->isArray($data)) { return; } foreach ($data['data'] as $index => $element) { $row = $this->data->addChild('row'); $row->addAttribute('no', ++$index); foreach ($element as $key => $value) { $child = $row->addChild('FL', $value); $child->addAttribute('val', $key); } } }
One or more elements in data array. @param array $data
entailment
protected function withoutBulk(array $data = []) { if ($this->isArray($data)) { return; } $row = $this->data->addChild('row'); $row->addAttribute('no', 1); foreach ($data['data'] as $key => $value) { $child = $row->addChild('FL', $value); $child->addAttribute('val', $key); } }
Only one element in data array. For BC. @param array $data
entailment
public function setHTTPAdapter($type = null) { if(!$type) { $type = extension_loaded("curl") ? self::$HTTP_CURL : self::$HTTP_NATIVE_SOCKETS; } // nothing to be done if($type === $this->httpAdapterType) { return true; } // remember what was already set (ie., might have called decode() already) $prevDecode = null; $prevTimeouts = null; if($this->httpAdapter) { $prevDecode = $this->httpAdapter->decodeResp; $prevTimeouts = $this->httpAdapter->getTimeouts(); } // the glue switch($type) { case self::$HTTP_NATIVE_SOCKETS: $this->httpAdapter = new SagNativeHTTPAdapter($this->host, $this->port); break; case self::$HTTP_CURL: $this->httpAdapter = new SagCURLHTTPAdapter($this->host, $this->port); break; default: throw SagException("Invalid Sag HTTP adapter specified: $type"); } // restore previous decode value, if any if(is_bool($prevDecode)) { $this->httpAdapter->decodeResp = $prevDecode; } // restore previous timeout vlaues, if any if(is_array($prevTimeouts)) { $this->httpAdapter->setTimeoutsFromArray($prevTimeouts); } $this->httpAdapterType = $type; return $this; }
Set which HTTP library you want to use for communicating with CouchDB. @param string $type The type of adapter you want to use. Should be one of the Sag::$HTTP_* variables. @return Sag Returns $this. @see Sag::$HTTP_NATIVE_SOCKETS @see Sag::$HTTP_CURL
entailment
public function login($user, $pass, $type = null) { if($type == null) { $type = Sag::$AUTH_BASIC; } $this->authType = $type; switch($type) { case Sag::$AUTH_BASIC: //these will end up in a header, so don't URL encode them $this->user = $user; $this->pass = $pass; return true; break; case Sag::$AUTH_COOKIE: $user = urlencode($user); $pass = urlencode($pass); $res = $this->procPacket( 'POST', '/_session', sprintf('name=%s&password=%s', $user, $pass), array('Content-Type' => 'application/x-www-form-urlencoded') ); $this->authSession = $res->cookies->AuthSession; return $this->authSession; break; } //should never reach this line throw new SagException("Unknown auth type for login()."); }
Updates the login credentials in Sag that will be used for all further communications. Pass null to both $user and $pass to turn off authentication, as Sag does support blank usernames and passwords - only one of them has to be set for packets to be sent with authentication. Cookie authentication will cause a call to the server to establish the session, and will throw an exception if the credentials weren't valid. @param string $user The username you want to login with. (null for none) @param string $pass The password you want to login with. (null for none) @param string $type The type of login system being used. Defaults to Sag::$AUTH_BASIC. @return mixed Returns true if the input was valid. If using $AUTH_COOKIE, then the autoSession value will be returned. Throws on failure. @see $AUTH_BASIC @see $AUTH_COOKIE
entailment
public function decode($decode) { if(!is_bool($decode)) { throw new SagException('decode() expected a boolean'); } $this->httpAdapter->decodeResp = $decode; return $this; }
Sets whether Sag will decode CouchDB's JSON responses with json_decode() or to simply return the JSON as a string. Defaults to true. @param bool $decode True to decode, false to not decode. @return Sag Returns $this.
entailment
public function get($url) { if(!$this->db) { throw new SagException('No database specified'); } //The first char of the URL should be a slash. if(strpos($url, '/') !== 0) { $url = "/$url"; } $url = "/{$this->db}$url"; if($this->staleDefault) { $url = self::setURLParameter($url, 'stale', 'ok'); } //Deal with cached items $response = null; if($this->cache) { $prevResponse = $this->cache->get($url); if($prevResponse) { $response = $this->procPacket('GET', $url, null, array('If-None-Match' => $prevResponse->headers->etag)); if($response->headers->_HTTP->status == 304) { //cache hit $response->fromCache = true; return $prevResponse; } $this->cache->remove($url); } unset($prevResponse); } /* * Not caching, or we are caching but there's nothing cached yet, or our * cached item is no longer good. */ if(!$response) { $response = $this->procPacket('GET', $url); } if($this->cache) { $this->cache->set($url, $response); } return $response; }
Performs an HTTP GET operation for the supplied URL. The database name you provided is automatically prepended to the URL, so you only need to give the portion of the URL that comes after the database name. You are responsible for URL encoding your own parameters. @param string $url The URL, with or without the leading slash. @return mixed
entailment
public function head($url) { if(!$this->db) { throw new SagException('No database specified'); } //The first char of the URL should be a slash. if(strpos($url, '/') !== 0) { $url = "/$url"; } if($this->staleDefault) { $url = self::setURLParameter($url, 'stale', 'ok'); } //we're only asking for the HEAD so no caching is needed return $this->procPacket('HEAD', "/{$this->db}$url"); }
Performs an HTTP HEAD operation for the supplied document. This operation does not try to read from a provided cache, and does not cache its results. @see http://wiki.apache.org/couchdb/HTTP_Document_API#HEAD @param string $url The URL, with or without the leading slash. @return mixed
entailment
public function delete($id, $rev) { if(!$this->db) { throw new SagException('No database specified'); } if(!is_string($id) || !is_string($rev) || empty($id) || empty($rev)) { throw new SagException('delete() expects two strings.'); } $url = "/{$this->db}/$id"; if($this->cache) { $this->cache->remove($url); } return $this->procPacket('DELETE', $url.'?rev='.urlencode($rev)); }
DELETE's the specified document. @param string $id The document's _id. @param string $rev The document's _rev. @return mixed
entailment