diff --git a/library/Zend/Amf/Adobe/Auth.php b/library/Zend/Amf/Adobe/Auth.php deleted file mode 100755 index d34e585126..0000000000 --- a/library/Zend/Amf/Adobe/Auth.php +++ /dev/null @@ -1,136 +0,0 @@ -_acl = new Zend_Acl(); - $xml = Zend_Xml_Security::scanFile($rolefile); -/* -Roles file format: - - - - - - - - -*/ - foreach($xml->role as $role) { - $this->_acl->addRole(new Zend_Acl_Role((string)$role["id"])); - foreach($role->user as $user) { - $this->_users[(string)$user["name"]] = array("password" => (string)$user["password"], - "role" => (string)$role["id"]); - } - } - } - - /** - * Get ACL with roles from XML file - * - * @return Zend_Acl - */ - public function getAcl() - { - return $this->_acl; - } - - /** - * Perform authentication - * - * @throws Zend_Auth_Adapter_Exception - * @return Zend_Auth_Result - * @see Zend_Auth_Adapter_Interface#authenticate() - */ - public function authenticate() - { - if (empty($this->_username) || - empty($this->_password)) { - /** - * @see Zend_Auth_Adapter_Exception - */ - #require_once 'Zend/Auth/Adapter/Exception.php'; - throw new Zend_Auth_Adapter_Exception('Username/password should be set'); - } - - if(!isset($this->_users[$this->_username])) { - return new Zend_Auth_Result(Zend_Auth_Result::FAILURE_IDENTITY_NOT_FOUND, - null, - array('Username not found') - ); - } - - $user = $this->_users[$this->_username]; - if($user["password"] != $this->_password) { - return new Zend_Auth_Result(Zend_Auth_Result::FAILURE_CREDENTIAL_INVALID, - null, - array('Authentication failed') - ); - } - - $id = new stdClass(); - $id->role = $user["role"]; - $id->name = $this->_username; - return new Zend_Auth_Result(Zend_Auth_Result::SUCCESS, $id); - } -} diff --git a/library/Zend/Amf/Adobe/DbInspector.php b/library/Zend/Amf/Adobe/DbInspector.php deleted file mode 100755 index a25c3a2b16..0000000000 --- a/library/Zend/Amf/Adobe/DbInspector.php +++ /dev/null @@ -1,103 +0,0 @@ -describeTable('Pdo_Mysql', - * array( - * 'host' => '127.0.0.1', - * 'username' => 'webuser', - * 'password' => 'xxxxxxxx', - * 'dbname' => 'test' - * ), - * 'mytable' - * ); - * - * @param string $dbType Database adapter type for Zend_Db - * @param array|object $dbDescription Adapter-specific connection settings - * @param string $tableName Table name - * @return array Table description - * @see Zend_Db::describeTable() - * @see Zend_Db::factory() - */ - public function describeTable($dbType, $dbDescription, $tableName) - { - $db = $this->_connect($dbType, $dbDescription); - return $db->describeTable($tableName); - } - - /** - * Test database connection - * - * @param string $dbType Database adapter type for Zend_Db - * @param array|object $dbDescription Adapter-specific connection settings - * @return bool - * @see Zend_Db::factory() - */ - public function connect($dbType, $dbDescription) - { - $db = $this->_connect($dbType, $dbDescription); - $db->listTables(); - return true; - } - - /** - * Get the list of database tables - * - * @param string $dbType Database adapter type for Zend_Db - * @param array|object $dbDescription Adapter-specific connection settings - * @return array List of the tables - */ - public function getTables($dbType, $dbDescription) - { - $db = $this->_connect($dbType, $dbDescription); - return $db->listTables(); - } -} diff --git a/library/Zend/Amf/Adobe/Introspector.php b/library/Zend/Amf/Adobe/Introspector.php deleted file mode 100755 index c25828d5f8..0000000000 --- a/library/Zend/Amf/Adobe/Introspector.php +++ /dev/null @@ -1,318 +0,0 @@ -_xml = new DOMDocument('1.0', 'utf-8'); - } - - /** - * Create XML definition on an AMF service class - * - * @param string $serviceClass Service class name - * @param array $options invocation options - * @return string XML with service class introspection - */ - public function introspect($serviceClass, $options = array()) - { - $this->_options = $options; - - if (strpbrk($serviceClass, '\\/<>')) { - return $this->_returnError('Invalid service name'); - } - - // Transform com.foo.Bar into com_foo_Bar - $serviceClass = str_replace('.' , '_', $serviceClass); - - // Introspect! - if (!class_exists($serviceClass)) { - #require_once 'Zend/Loader.php'; - Zend_Loader::loadClass($serviceClass, $this->_getServicePath()); - } - - $serv = $this->_xml->createElement('service-description'); - $serv->setAttribute('xmlns', 'http://ns.adobe.com/flex/service-description/2008'); - - $this->_types = $this->_xml->createElement('types'); - $this->_ops = $this->_xml->createElement('operations'); - - $r = Zend_Server_Reflection::reflectClass($serviceClass); - $this->_addService($r, $this->_ops); - - $serv->appendChild($this->_types); - $serv->appendChild($this->_ops); - $this->_xml->appendChild($serv); - - return $this->_xml->saveXML(); - } - - /** - * Authentication handler - * - * @param Zend_Acl $acl - * @return unknown_type - */ - public function initAcl(Zend_Acl $acl) - { - return false; // we do not need auth for this class - } - - /** - * Generate map of public class attributes - * - * @param string $typename type name - * @param DOMElement $typexml target XML element - * @return void - */ - protected function _addClassAttributes($typename, DOMElement $typexml) - { - // Do not try to autoload here because _phpTypeToAS should - // have already attempted to load this class - if (!class_exists($typename, false)) { - return; - } - - $rc = new Zend_Reflection_Class($typename); - foreach ($rc->getProperties() as $prop) { - if (!$prop->isPublic()) { - continue; - } - - $propxml = $this->_xml->createElement('property'); - $propxml->setAttribute('name', $prop->getName()); - - $type = $this->_registerType($this->_getPropertyType($prop)); - $propxml->setAttribute('type', $type); - - $typexml->appendChild($propxml); - } - } - - /** - * Build XML service description from reflection class - * - * @param Zend_Server_Reflection_Class $refclass - * @param DOMElement $target target XML element - * @return void - */ - protected function _addService(Zend_Server_Reflection_Class $refclass, DOMElement $target) - { - foreach ($refclass->getMethods() as $method) { - if (!$method->isPublic() - || $method->isConstructor() - || ('__' == substr($method->name, 0, 2)) - ) { - continue; - } - - foreach ($method->getPrototypes() as $proto) { - $op = $this->_xml->createElement('operation'); - $op->setAttribute('name', $method->getName()); - - $rettype = $this->_registerType($proto->getReturnType()); - $op->setAttribute('returnType', $rettype); - - foreach ($proto->getParameters() as $param) { - $arg = $this->_xml->createElement('argument'); - $arg->setAttribute('name', $param->getName()); - - $type = $param->getType(); - if ($type == 'mixed' && ($pclass = $param->getClass())) { - $type = $pclass->getName(); - } - - $ptype = $this->_registerType($type); - $arg->setAttribute('type', $ptype); - - if($param->isDefaultValueAvailable()) { - $arg->setAttribute('defaultvalue', $param->getDefaultValue()); - } - - $op->appendChild($arg); - } - - $target->appendChild($op); - } - } - } - - /** - * Extract type of the property from DocBlock - * - * @param Zend_Reflection_Property $prop reflection property object - * @return string Property type - */ - protected function _getPropertyType(Zend_Reflection_Property $prop) - { - $docBlock = $prop->getDocComment(); - - if (!$docBlock) { - return 'Unknown'; - } - - if (!$docBlock->hasTag('var')) { - return 'Unknown'; - } - - $tag = $docBlock->getTag('var'); - return trim($tag->getDescription()); - } - - /** - * Get the array of service directories - * - * @return array Service class directories - */ - protected function _getServicePath() - { - if (isset($this->_options['server'])) { - return $this->_options['server']->getDirectory(); - } - - if (isset($this->_options['directories'])) { - return $this->_options['directories']; - } - - return array(); - } - - /** - * Map from PHP type name to AS type name - * - * @param string $typename PHP type name - * @return string AS type name - */ - protected function _phpTypeToAS($typename) - { - if (class_exists($typename)) { - $vars = get_class_vars($typename); - - if (isset($vars['_explicitType'])) { - return $vars['_explicitType']; - } - } - - if (false !== ($asname = Zend_Amf_Parse_TypeLoader::getMappedClassName($typename))) { - return $asname; - } - - return $typename; - } - - /** - * Register new type on the system - * - * @param string $typename type name - * @return string New type name - */ - protected function _registerType($typename) - { - // Known type - return its AS name - if (isset($this->_typesMap[$typename])) { - return $this->_typesMap[$typename]; - } - - // Standard types - if (in_array($typename, array('void', 'null', 'mixed', 'unknown_type'))) { - return 'Unknown'; - } - - // Arrays - if ('array' == $typename) { - return 'Unknown[]'; - } - - if (in_array($typename, array('int', 'integer', 'bool', 'boolean', 'float', 'string', 'object', 'Unknown', 'stdClass'))) { - return $typename; - } - - // Resolve and store AS name - $asTypeName = $this->_phpTypeToAS($typename); - $this->_typesMap[$typename] = $asTypeName; - - // Create element for the name - $typeEl = $this->_xml->createElement('type'); - $typeEl->setAttribute('name', $asTypeName); - $this->_addClassAttributes($typename, $typeEl); - $this->_types->appendChild($typeEl); - - return $asTypeName; - } - - /** - * Return error with error message - * - * @param string $msg Error message - * @return string - */ - protected function _returnError($msg) - { - return 'ERROR: $msg'; - } -} diff --git a/library/Zend/Amf/Auth/Abstract.php b/library/Zend/Amf/Auth/Abstract.php deleted file mode 100755 index 643c927e5b..0000000000 --- a/library/Zend/Amf/Auth/Abstract.php +++ /dev/null @@ -1,42 +0,0 @@ -_username = $username; - $this->_password = $password; - } -} diff --git a/library/Zend/Amf/Constants.php b/library/Zend/Amf/Constants.php deleted file mode 100644 index 723d8ba4fd..0000000000 --- a/library/Zend/Amf/Constants.php +++ /dev/null @@ -1,87 +0,0 @@ -_stream->readByte(); - } - - switch($typeMarker) { - // number - case Zend_Amf_Constants::AMF0_NUMBER: - return $this->_stream->readDouble(); - - // boolean - case Zend_Amf_Constants::AMF0_BOOLEAN: - return (boolean) $this->_stream->readByte(); - - // string - case Zend_Amf_Constants::AMF0_STRING: - return $this->_stream->readUTF(); - - // object - case Zend_Amf_Constants::AMF0_OBJECT: - return $this->readObject(); - - // null - case Zend_Amf_Constants::AMF0_NULL: - return null; - - // undefined - case Zend_Amf_Constants::AMF0_UNDEFINED: - return null; - - // Circular references are returned here - case Zend_Amf_Constants::AMF0_REFERENCE: - return $this->readReference(); - - // mixed array with numeric and string keys - case Zend_Amf_Constants::AMF0_MIXEDARRAY: - return $this->readMixedArray(); - - // array - case Zend_Amf_Constants::AMF0_ARRAY: - return $this->readArray(); - - // date - case Zend_Amf_Constants::AMF0_DATE: - return $this->readDate(); - - // longString strlen(string) > 2^16 - case Zend_Amf_Constants::AMF0_LONGSTRING: - return $this->_stream->readLongUTF(); - - //internal AS object, not supported - case Zend_Amf_Constants::AMF0_UNSUPPORTED: - return null; - - // XML - case Zend_Amf_Constants::AMF0_XML: - return $this->readXmlString(); - - // typed object ie Custom Class - case Zend_Amf_Constants::AMF0_TYPEDOBJECT: - return $this->readTypedObject(); - - //AMF3-specific - case Zend_Amf_Constants::AMF0_AMF3: - return $this->readAmf3TypeMarker(); - - default: - #require_once 'Zend/Amf/Exception.php'; - throw new Zend_Amf_Exception('Unsupported marker type: ' . $typeMarker); - } - } - - /** - * Read AMF objects and convert to PHP objects - * - * Read the name value pair objects form the php message and convert them to - * a php object class. - * - * Called when the marker type is 3. - * - * @param array|null $object - * @return object - */ - public function readObject($object = null) - { - if ($object === null) { - $object = array(); - } - - while (true) { - $key = $this->_stream->readUTF(); - $typeMarker = $this->_stream->readByte(); - if ($typeMarker != Zend_Amf_Constants::AMF0_OBJECTTERM ){ - //Recursivly call readTypeMarker to get the types of properties in the object - $object[$key] = $this->readTypeMarker($typeMarker); - } else { - //encountered AMF object terminator - break; - } - } - $this->_reference[] = $object; - return (object) $object; - } - - /** - * Read reference objects - * - * Used to gain access to the private array of reference objects. - * Called when marker type is 7. - * - * @return object - * @throws Zend_Amf_Exception for invalid reference keys - */ - public function readReference() - { - $key = $this->_stream->readInt(); - if (!array_key_exists($key, $this->_reference)) { - #require_once 'Zend/Amf/Exception.php'; - throw new Zend_Amf_Exception('Invalid reference key: '. $key); - } - return $this->_reference[$key]; - } - - /** - * Reads an array with numeric and string indexes. - * - * Called when marker type is 8 - * - * @todo As of Flash Player 9 there is not support for mixed typed arrays - * so we handle this as an object. With the introduction of vectors - * in Flash Player 10 this may need to be reconsidered. - * @return array - */ - public function readMixedArray() - { - $length = $this->_stream->readLong(); - return $this->readObject(); - } - - /** - * Converts numerically indexed actiosncript arrays into php arrays. - * - * Called when marker type is 10 - * - * @return array - */ - public function readArray() - { - $length = $this->_stream->readLong(); - $array = array(); - while ($length--) { - $array[] = $this->readTypeMarker(); - } - return $array; - } - - /** - * Convert AS Date to Zend_Date - * - * @return Zend_Date - */ - public function readDate() - { - // get the unix time stamp. Not sure why ActionScript does not use - // milliseconds - $timestamp = floor($this->_stream->readDouble() / 1000); - - // The timezone offset is never returned to the server; it is always 0, - // so read and ignore. - $offset = $this->_stream->readInt(); - - #require_once 'Zend/Date.php'; - $date = new Zend_Date($timestamp); - return $date; - } - - /** - * Convert XML to SimpleXml - * If user wants DomDocument they can use dom_import_simplexml - * - * @return SimpleXml Object - */ - public function readXmlString() - { - $string = $this->_stream->readLongUTF(); - return Zend_Xml_Security::scan($string); //simplexml_load_string($string); - } - - /** - * Read Class that is to be mapped to a server class. - * - * Commonly used for Value Objects on the server - * - * @todo implement Typed Class mapping - * @return object|array - * @throws Zend_Amf_Exception if unable to load type - */ - public function readTypedObject() - { - #require_once 'Zend/Amf/Parse/TypeLoader.php'; - // get the remote class name - $className = $this->_stream->readUTF(); - $loader = Zend_Amf_Parse_TypeLoader::loadType($className); - $returnObject = new $loader(); - $properties = get_object_vars($this->readObject()); - foreach($properties as $key=>$value) { - if($key) { - $returnObject->$key = $value; - } - } - if($returnObject instanceof Zend_Amf_Value_Messaging_ArrayCollection) { - $returnObject = get_object_vars($returnObject); - } - return $returnObject; - } - - /** - * AMF3 data type encountered load AMF3 Deserializer to handle - * type markers. - * - * @return string - */ - public function readAmf3TypeMarker() - { - #require_once 'Zend/Amf/Parse/Amf3/Deserializer.php'; - $deserializer = new Zend_Amf_Parse_Amf3_Deserializer($this->_stream); - $this->_objectEncoding = Zend_Amf_Constants::AMF3_OBJECT_ENCODING; - return $deserializer->readTypeMarker(); - } - - /** - * Return the object encoding to check if an AMF3 object - * is going to be return. - * - * @return int - */ - public function getObjectEncoding() - { - return $this->_objectEncoding; - } -} diff --git a/library/Zend/Amf/Parse/Amf0/Serializer.php b/library/Zend/Amf/Parse/Amf0/Serializer.php deleted file mode 100644 index 8748cf0a35..0000000000 --- a/library/Zend/Amf/Parse/Amf0/Serializer.php +++ /dev/null @@ -1,362 +0,0 @@ -writeObjectReference($data, $markerType)) { - // Write the Type Marker to denote the following action script data type - $this->_stream->writeByte($markerType); - switch($markerType) { - case Zend_Amf_Constants::AMF0_NUMBER: - $this->_stream->writeDouble($data); - break; - case Zend_Amf_Constants::AMF0_BOOLEAN: - $this->_stream->writeByte($data); - break; - case Zend_Amf_Constants::AMF0_STRING: - $this->_stream->writeUTF($data); - break; - case Zend_Amf_Constants::AMF0_OBJECT: - $this->writeObject($data); - break; - case Zend_Amf_Constants::AMF0_NULL: - break; - case Zend_Amf_Constants::AMF0_REFERENCE: - $this->_stream->writeInt($data); - break; - case Zend_Amf_Constants::AMF0_MIXEDARRAY: - // Write length of numeric keys as zero. - $this->_stream->writeLong(0); - $this->writeObject($data); - break; - case Zend_Amf_Constants::AMF0_ARRAY: - $this->writeArray($data); - break; - case Zend_Amf_Constants::AMF0_DATE: - $this->writeDate($data); - break; - case Zend_Amf_Constants::AMF0_LONGSTRING: - $this->_stream->writeLongUTF($data); - break; - case Zend_Amf_Constants::AMF0_TYPEDOBJECT: - $this->writeTypedObject($data); - break; - case Zend_Amf_Constants::AMF0_AMF3: - $this->writeAmf3TypeMarker($data); - break; - default: - #require_once 'Zend/Amf/Exception.php'; - throw new Zend_Amf_Exception("Unknown Type Marker: " . $markerType); - } - } - } else { - if (is_resource($data)) { - $data = Zend_Amf_Parse_TypeLoader::handleResource($data); - } - switch (true) { - case (is_int($data) || is_float($data)): - $markerType = Zend_Amf_Constants::AMF0_NUMBER; - break; - case (is_bool($data)): - $markerType = Zend_Amf_Constants::AMF0_BOOLEAN; - break; - case (is_string($data) && (($this->_mbStringFunctionsOverloaded ? mb_strlen($data, '8bit') : strlen($data)) > 65536)): - $markerType = Zend_Amf_Constants::AMF0_LONGSTRING; - break; - case (is_string($data)): - $markerType = Zend_Amf_Constants::AMF0_STRING; - break; - case (is_object($data)): - if (($data instanceof DateTime) || ($data instanceof Zend_Date)) { - $markerType = Zend_Amf_Constants::AMF0_DATE; - } else { - - if($className = $this->getClassName($data)){ - //Object is a Typed object set classname - $markerType = Zend_Amf_Constants::AMF0_TYPEDOBJECT; - $this->_className = $className; - } else { - // Object is a generic classname - $markerType = Zend_Amf_Constants::AMF0_OBJECT; - } - break; - } - break; - case (null === $data): - $markerType = Zend_Amf_Constants::AMF0_NULL; - break; - case (is_array($data)): - // check if it is an associative array - $i = 0; - foreach (array_keys($data) as $key) { - // check if it contains non-integer keys - if (!is_numeric($key) || intval($key) != $key) { - $markerType = Zend_Amf_Constants::AMF0_OBJECT; - break; - // check if it is a sparse indexed array - } else if ($key != $i) { - $markerType = Zend_Amf_Constants::AMF0_MIXEDARRAY; - break; - } - $i++; - } - // Dealing with a standard numeric array - if(!$markerType){ - $markerType = Zend_Amf_Constants::AMF0_ARRAY; - break; - } - break; - default: - #require_once 'Zend/Amf/Exception.php'; - throw new Zend_Amf_Exception('Unsupported data type: ' . gettype($data)); - } - - $this->writeTypeMarker($data, $markerType); - } - return $this; - } - - /** - * Check if the given object is in the reference table, write the reference if it exists, - * otherwise add the object to the reference table - * - * @param mixed $object object reference to check for reference - * @param string $markerType AMF type of the object to write - * @param mixed $objectByVal object to check for reference - * @return Boolean true, if the reference was written, false otherwise - */ - protected function writeObjectReference(&$object, $markerType, $objectByVal = false) - { - // Workaround for PHP5 with E_STRICT enabled complaining about "Only - // variables should be passed by reference" - if ((null === $object) && ($objectByVal !== false)) { - $object = &$objectByVal; - } - - if ($markerType == Zend_Amf_Constants::AMF0_OBJECT - || $markerType == Zend_Amf_Constants::AMF0_MIXEDARRAY - || $markerType == Zend_Amf_Constants::AMF0_ARRAY - || $markerType == Zend_Amf_Constants::AMF0_TYPEDOBJECT - ) { - $ref = array_search($object, $this->_referenceObjects, true); - //handle object reference - if($ref !== false){ - $this->writeTypeMarker($ref,Zend_Amf_Constants::AMF0_REFERENCE); - return true; - } - - $this->_referenceObjects[] = $object; - } - - return false; - } - - /** - * Write a PHP array with string or mixed keys. - * - * @param object $data - * @return Zend_Amf_Parse_Amf0_Serializer - */ - public function writeObject($object) - { - // Loop each element and write the name of the property. - foreach ($object as $key => &$value) { - // skip variables starting with an _ private transient - if( $key[0] == "_") continue; - $this->_stream->writeUTF($key); - $this->writeTypeMarker($value); - } - - // Write the end object flag - $this->_stream->writeInt(0); - $this->_stream->writeByte(Zend_Amf_Constants::AMF0_OBJECTTERM); - return $this; - } - - /** - * Write a standard numeric array to the output stream. If a mixed array - * is encountered call writeTypeMarker with mixed array. - * - * @param array $array - * @return Zend_Amf_Parse_Amf0_Serializer - */ - public function writeArray(&$array) - { - $length = count($array); - if (!$length < 0) { - // write the length of the array - $this->_stream->writeLong(0); - } else { - // Write the length of the numeric array - $this->_stream->writeLong($length); - for ($i=0; $i<$length; $i++) { - $value = isset($array[$i]) ? $array[$i] : null; - $this->writeTypeMarker($value); - } - } - return $this; - } - - /** - * Convert the DateTime into an AMF Date - * - * @param DateTime|Zend_Date $data - * @return Zend_Amf_Parse_Amf0_Serializer - */ - public function writeDate($data) - { - if ($data instanceof DateTime) { - $dateString = $data->format('U'); - } elseif ($data instanceof Zend_Date) { - $dateString = $data->toString('U'); - } else { - #require_once 'Zend/Amf/Exception.php'; - throw new Zend_Amf_Exception('Invalid date specified; must be a DateTime or Zend_Date object'); - } - $dateString *= 1000; - - // Make the conversion and remove milliseconds. - $this->_stream->writeDouble($dateString); - - // Flash does not respect timezone but requires it. - $this->_stream->writeInt(0); - - return $this; - } - - /** - * Write a class mapped object to the output stream. - * - * @param object $data - * @return Zend_Amf_Parse_Amf0_Serializer - */ - public function writeTypedObject($data) - { - $this->_stream->writeUTF($this->_className); - $this->writeObject($data); - return $this; - } - - /** - * Encountered and AMF3 Type Marker use AMF3 serializer. Once AMF3 is - * encountered it will not return to AMf0. - * - * @param string $data - * @return Zend_Amf_Parse_Amf0_Serializer - */ - public function writeAmf3TypeMarker(&$data) - { - #require_once 'Zend/Amf/Parse/Amf3/Serializer.php'; - $serializer = new Zend_Amf_Parse_Amf3_Serializer($this->_stream); - $serializer->writeTypeMarker($data); - return $this; - } - - /** - * Find if the class name is a class mapped name and return the - * respective classname if it is. - * - * @param object $object - * @return false|string $className - */ - protected function getClassName($object) - { - #require_once 'Zend/Amf/Parse/TypeLoader.php'; - //Check to see if the object is a typed object and we need to change - $className = ''; - switch (true) { - // the return class mapped name back to actionscript class name. - case Zend_Amf_Parse_TypeLoader::getMappedClassName(get_class($object)): - $className = Zend_Amf_Parse_TypeLoader::getMappedClassName(get_class($object)); - break; - // Check to see if the user has defined an explicit Action Script type. - case isset($object->_explicitType): - $className = $object->_explicitType; - break; - // Check if user has defined a method for accessing the Action Script type - case method_exists($object, 'getASClassName'): - $className = $object->getASClassName(); - break; - // No return class name is set make it a generic object - case ($object instanceof stdClass): - $className = ''; - break; - // By default, use object's class name - default: - $className = get_class($object); - break; - } - if(!$className == '') { - return $className; - } else { - return false; - } - } -} diff --git a/library/Zend/Amf/Parse/Amf3/Deserializer.php b/library/Zend/Amf/Parse/Amf3/Deserializer.php deleted file mode 100644 index a058fa19c5..0000000000 --- a/library/Zend/Amf/Parse/Amf3/Deserializer.php +++ /dev/null @@ -1,425 +0,0 @@ -_stream->readByte(); - } - - switch($typeMarker) { - case Zend_Amf_Constants::AMF3_UNDEFINED: - return null; - case Zend_Amf_Constants::AMF3_NULL: - return null; - case Zend_Amf_Constants::AMF3_BOOLEAN_FALSE: - return false; - case Zend_Amf_Constants::AMF3_BOOLEAN_TRUE: - return true; - case Zend_Amf_Constants::AMF3_INTEGER: - return $this->readInteger(); - case Zend_Amf_Constants::AMF3_NUMBER: - return $this->_stream->readDouble(); - case Zend_Amf_Constants::AMF3_STRING: - return $this->readString(); - case Zend_Amf_Constants::AMF3_DATE: - return $this->readDate(); - case Zend_Amf_Constants::AMF3_ARRAY: - return $this->readArray(); - case Zend_Amf_Constants::AMF3_OBJECT: - return $this->readObject(); - case Zend_Amf_Constants::AMF3_XML: - case Zend_Amf_Constants::AMF3_XMLSTRING: - return $this->readXmlString(); - case Zend_Amf_Constants::AMF3_BYTEARRAY: - return $this->readString(); - default: - #require_once 'Zend/Amf/Exception.php'; - throw new Zend_Amf_Exception('Unsupported type marker: ' . $typeMarker); - } - } - - /** - * Read and deserialize an integer - * - * AMF 3 represents smaller integers with fewer bytes using the most - * significant bit of each byte. The worst case uses 32-bits - * to represent a 29-bit number, which is what we would have - * done with no compression. - * - 0x00000000 - 0x0000007F : 0xxxxxxx - * - 0x00000080 - 0x00003FFF : 1xxxxxxx 0xxxxxxx - * - 0x00004000 - 0x001FFFFF : 1xxxxxxx 1xxxxxxx 0xxxxxxx - * - 0x00200000 - 0x3FFFFFFF : 1xxxxxxx 1xxxxxxx 1xxxxxxx xxxxxxxx - * - 0x40000000 - 0xFFFFFFFF : throw range exception - * - * 0x04 -> integer type code, followed by up to 4 bytes of data. - * - * Parsing integers on OSFlash for the AMF3 integer data format: - * @link http://osflash.org/amf3/parsing_integers - * @return int|float - */ - public function readInteger() - { - $count = 1; - $intReference = $this->_stream->readByte(); - $result = 0; - while ((($intReference & 0x80) != 0) && $count < 4) { - $result <<= 7; - $result |= ($intReference & 0x7f); - $intReference = $this->_stream->readByte(); - $count++; - } - if ($count < 4) { - $result <<= 7; - $result |= $intReference; - } else { - // Use all 8 bits from the 4th byte - $result <<= 8; - $result |= $intReference; - - // Check if the integer should be negative - if (($result & 0x10000000) != 0) { - //and extend the sign bit - $result |= ~0xFFFFFFF; - } - } - return $result; - } - - /** - * Read and deserialize a string - * - * Strings can be sent as a reference to a previously - * occurring String by using an index to the implicit string reference table. - * Strings are encoding using UTF-8 - however the header may either - * describe a string literal or a string reference. - * - * - string = 0x06 string-data - * - string-data = integer-data [ modified-utf-8 ] - * - modified-utf-8 = *OCTET - * - * @return String - */ - public function readString() - { - $stringReference = $this->readInteger(); - - //Check if this is a reference string - if (($stringReference & 0x01) == 0) { - // reference string - $stringReference = $stringReference >> 1; - if ($stringReference >= count($this->_referenceStrings)) { - #require_once 'Zend/Amf/Exception.php'; - throw new Zend_Amf_Exception('Undefined string reference: ' . $stringReference); - } - // reference string found - return $this->_referenceStrings[$stringReference]; - } - - $length = $stringReference >> 1; - if ($length) { - $string = $this->_stream->readBytes($length); - $this->_referenceStrings[] = $string; - } else { - $string = ""; - } - return $string; - } - - /** - * Read and deserialize a date - * - * Data is the number of milliseconds elapsed since the epoch - * of midnight, 1st Jan 1970 in the UTC time zone. - * Local time zone information is not sent to flash. - * - * - date = 0x08 integer-data [ number-data ] - * - * @return Zend_Date - */ - public function readDate() - { - $dateReference = $this->readInteger(); - if (($dateReference & 0x01) == 0) { - $dateReference = $dateReference >> 1; - if ($dateReference>=count($this->_referenceObjects)) { - #require_once 'Zend/Amf/Exception.php'; - throw new Zend_Amf_Exception('Undefined date reference: ' . $dateReference); - } - return $this->_referenceObjects[$dateReference]; - } - - $timestamp = floor($this->_stream->readDouble() / 1000); - - #require_once 'Zend/Date.php'; - $dateTime = new Zend_Date($timestamp); - $this->_referenceObjects[] = $dateTime; - return $dateTime; - } - - /** - * Read amf array to PHP array - * - * - array = 0x09 integer-data ( [ 1OCTET *amf3-data ] | [OCTET *amf3-data 1] | [ OCTET *amf-data ] ) - * - * @return array - */ - public function readArray() - { - $arrayReference = $this->readInteger(); - if (($arrayReference & 0x01)==0){ - $arrayReference = $arrayReference >> 1; - if ($arrayReference>=count($this->_referenceObjects)) { - #require_once 'Zend/Amf/Exception.php'; - throw new Zend_Amf_Exception('Unknow array reference: ' . $arrayReference); - } - return $this->_referenceObjects[$arrayReference]; - } - - // Create a holder for the array in the reference list - $data = array(); - $this->_referenceObjects[] =& $data; - $key = $this->readString(); - - // Iterating for string based keys. - while ($key != '') { - $data[$key] = $this->readTypeMarker(); - $key = $this->readString(); - } - - $arrayReference = $arrayReference >>1; - - //We have a dense array - for ($i=0; $i < $arrayReference; $i++) { - $data[] = $this->readTypeMarker(); - } - - return $data; - } - - /** - * Read an object from the AMF stream and convert it into a PHP object - * - * @todo Rather than using an array of traitsInfo create Zend_Amf_Value_TraitsInfo - * @return object|array - */ - public function readObject() - { - $traitsInfo = $this->readInteger(); - $storedObject = ($traitsInfo & 0x01)==0; - $traitsInfo = $traitsInfo >> 1; - - // Check if the Object is in the stored Objects reference table - if ($storedObject) { - $ref = $traitsInfo; - if (!isset($this->_referenceObjects[$ref])) { - #require_once 'Zend/Amf/Exception.php'; - throw new Zend_Amf_Exception('Unknown Object reference: ' . $ref); - } - $returnObject = $this->_referenceObjects[$ref]; - } else { - // Check if the Object is in the stored Definitions reference table - $storedClass = ($traitsInfo & 0x01) == 0; - $traitsInfo = $traitsInfo >> 1; - if ($storedClass) { - $ref = $traitsInfo; - if (!isset($this->_referenceDefinitions[$ref])) { - #require_once 'Zend/Amf/Exception.php'; - throw new Zend_Amf_Exception('Unknows Definition reference: '. $ref); - } - // Populate the reference attributes - $className = $this->_referenceDefinitions[$ref]['className']; - $encoding = $this->_referenceDefinitions[$ref]['encoding']; - $propertyNames = $this->_referenceDefinitions[$ref]['propertyNames']; - } else { - // The class was not in the reference tables. Start reading rawdata to build traits. - // Create a traits table. Zend_Amf_Value_TraitsInfo would be ideal - $className = $this->readString(); - $encoding = $traitsInfo & 0x03; - $propertyNames = array(); - $traitsInfo = $traitsInfo >> 2; - } - - // We now have the object traits defined in variables. Time to go to work: - if (!$className) { - // No class name generic object - $returnObject = new stdClass(); - } else { - // Defined object - // Typed object lookup against registered classname maps - if ($loader = Zend_Amf_Parse_TypeLoader::loadType($className)) { - $returnObject = new $loader(); - } else { - //user defined typed object - #require_once 'Zend/Amf/Exception.php'; - throw new Zend_Amf_Exception('Typed object not found: '. $className . ' '); - } - } - - // Add the Object to the reference table - $this->_referenceObjects[] = $returnObject; - - $properties = array(); // clear value - // Check encoding types for additional processing. - switch ($encoding) { - case (Zend_Amf_Constants::ET_EXTERNAL): - // Externalizable object such as {ArrayCollection} and {ObjectProxy} - if (!$storedClass) { - $this->_referenceDefinitions[] = array( - 'className' => $className, - 'encoding' => $encoding, - 'propertyNames' => $propertyNames, - ); - } - $returnObject->externalizedData = $this->readTypeMarker(); - break; - case (Zend_Amf_Constants::ET_DYNAMIC): - // used for Name-value encoding - if (!$storedClass) { - $this->_referenceDefinitions[] = array( - 'className' => $className, - 'encoding' => $encoding, - 'propertyNames' => $propertyNames, - ); - } - // not a reference object read name value properties from byte stream - do { - $property = $this->readString(); - if ($property != "") { - $propertyNames[] = $property; - $properties[$property] = $this->readTypeMarker(); - } - } while ($property !=""); - break; - default: - // basic property list object. - if (!$storedClass) { - $count = $traitsInfo; // Number of properties in the list - for($i=0; $i< $count; $i++) { - $propertyNames[] = $this->readString(); - } - // Add a reference to the class. - $this->_referenceDefinitions[] = array( - 'className' => $className, - 'encoding' => $encoding, - 'propertyNames' => $propertyNames, - ); - } - foreach ($propertyNames as $property) { - $properties[$property] = $this->readTypeMarker(); - } - break; - } - - // Add properties back to the return object. - if (!is_array($properties)) $properties = array(); - foreach($properties as $key=>$value) { - if($key) { - $returnObject->$key = $value; - } - } - - - } - - if ($returnObject instanceof Zend_Amf_Value_Messaging_ArrayCollection) { - if (isset($returnObject->externalizedData)) { - $returnObject = $returnObject->externalizedData; - } else { - $returnObject = get_object_vars($returnObject); - } - } - - return $returnObject; - } - - /** - * Convert XML to SimpleXml - * If user wants DomDocument they can use dom_import_simplexml - * - * @return SimpleXml Object - */ - public function readXmlString() - { - $xmlReference = $this->readInteger(); - $length = $xmlReference >> 1; - $string = $this->_stream->readBytes($length); - return Zend_Xml_Security::scan($string); - } -} diff --git a/library/Zend/Amf/Parse/Amf3/Serializer.php b/library/Zend/Amf/Parse/Amf3/Serializer.php deleted file mode 100644 index 8e00e62e4d..0000000000 --- a/library/Zend/Amf/Parse/Amf3/Serializer.php +++ /dev/null @@ -1,534 +0,0 @@ -_stream->writeByte($markerType); - - switch ($markerType) { - case Zend_Amf_Constants::AMF3_NULL: - break; - case Zend_Amf_Constants::AMF3_BOOLEAN_FALSE: - break; - case Zend_Amf_Constants::AMF3_BOOLEAN_TRUE: - break; - case Zend_Amf_Constants::AMF3_INTEGER: - $this->writeInteger($data); - break; - case Zend_Amf_Constants::AMF3_NUMBER: - $this->_stream->writeDouble($data); - break; - case Zend_Amf_Constants::AMF3_STRING: - $this->writeString($data); - break; - case Zend_Amf_Constants::AMF3_DATE: - $this->writeDate($data); - break; - case Zend_Amf_Constants::AMF3_ARRAY: - $this->writeArray($data); - break; - case Zend_Amf_Constants::AMF3_OBJECT: - $this->writeObject($data); - break; - case Zend_Amf_Constants::AMF3_BYTEARRAY: - $this->writeByteArray($data); - break; - case Zend_Amf_Constants::AMF3_XMLSTRING; - $this->writeXml($data); - break; - default: - #require_once 'Zend/Amf/Exception.php'; - throw new Zend_Amf_Exception('Unknown Type Marker: ' . $markerType); - } - } else { - // Detect Type Marker - if (is_resource($data)) { - $data = Zend_Amf_Parse_TypeLoader::handleResource($data); - } - switch (true) { - case (null === $data): - $markerType = Zend_Amf_Constants::AMF3_NULL; - break; - case (is_bool($data)): - if ($data){ - $markerType = Zend_Amf_Constants::AMF3_BOOLEAN_TRUE; - } else { - $markerType = Zend_Amf_Constants::AMF3_BOOLEAN_FALSE; - } - break; - case (is_int($data)): - if (($data > 0xFFFFFFF) || ($data < -268435456)) { - $markerType = Zend_Amf_Constants::AMF3_NUMBER; - } else { - $markerType = Zend_Amf_Constants::AMF3_INTEGER; - } - break; - case (is_float($data)): - $markerType = Zend_Amf_Constants::AMF3_NUMBER; - break; - case (is_string($data)): - $markerType = Zend_Amf_Constants::AMF3_STRING; - break; - case (is_array($data)): - $markerType = Zend_Amf_Constants::AMF3_ARRAY; - break; - case (is_object($data)): - // Handle object types. - if (($data instanceof DateTime) || ($data instanceof Zend_Date)) { - $markerType = Zend_Amf_Constants::AMF3_DATE; - } else if ($data instanceof Zend_Amf_Value_ByteArray) { - $markerType = Zend_Amf_Constants::AMF3_BYTEARRAY; - } else if (($data instanceof DOMDocument) || ($data instanceof SimpleXMLElement)) { - $markerType = Zend_Amf_Constants::AMF3_XMLSTRING; - } else { - $markerType = Zend_Amf_Constants::AMF3_OBJECT; - } - break; - default: - #require_once 'Zend/Amf/Exception.php'; - throw new Zend_Amf_Exception('Unsupported data type: ' . gettype($data)); - } - $this->writeTypeMarker($data, $markerType); - } - } - - /** - * Write an AMF3 integer - * - * @param int|float $data - * @return Zend_Amf_Parse_Amf3_Serializer - */ - public function writeInteger($int) - { - if (($int & 0xffffff80) == 0) { - $this->_stream->writeByte($int & 0x7f); - return $this; - } - - if (($int & 0xffffc000) == 0 ) { - $this->_stream->writeByte(($int >> 7 ) | 0x80); - $this->_stream->writeByte($int & 0x7f); - return $this; - } - - if (($int & 0xffe00000) == 0) { - $this->_stream->writeByte(($int >> 14 ) | 0x80); - $this->_stream->writeByte(($int >> 7 ) | 0x80); - $this->_stream->writeByte($int & 0x7f); - return $this; - } - - $this->_stream->writeByte(($int >> 22 ) | 0x80); - $this->_stream->writeByte(($int >> 15 ) | 0x80); - $this->_stream->writeByte(($int >> 8 ) | 0x80); - $this->_stream->writeByte($int & 0xff); - return $this; - } - - /** - * Send string to output stream, without trying to reference it. - * The string is prepended with strlen($string) << 1 | 0x01 - * - * @param string $string - * @return Zend_Amf_Parse_Amf3_Serializer - */ - protected function writeBinaryString(&$string){ - $ref = ($this->_mbStringFunctionsOverloaded ? mb_strlen($string, '8bit') : strlen($string)) << 1 | 0x01; - $this->writeInteger($ref); - $this->_stream->writeBytes($string); - - return $this; - } - - /** - * Send string to output stream - * - * @param string $string - * @return Zend_Amf_Parse_Amf3_Serializer - */ - public function writeString(&$string) - { - $len = $this->_mbStringFunctionsOverloaded ? mb_strlen($string, '8bit') : strlen($string); - if(!$len){ - $this->writeInteger(0x01); - return $this; - } - - $ref = array_key_exists($string, $this->_referenceStrings) - ? $this->_referenceStrings[$string] - : false; - if ($ref === false){ - $this->_referenceStrings[$string] = count($this->_referenceStrings); - $this->writeBinaryString($string); - } else { - $ref <<= 1; - $this->writeInteger($ref); - } - - return $this; - } - - /** - * Send ByteArray to output stream - * - * @param string|Zend_Amf_Value_ByteArray $data - * @return Zend_Amf_Parse_Amf3_Serializer - */ - public function writeByteArray(&$data) - { - if ($this->writeObjectReference($data)) { - return $this; - } - - if (is_string($data)) { - //nothing to do - } else if ($data instanceof Zend_Amf_Value_ByteArray) { - $data = $data->getData(); - } else { - #require_once 'Zend/Amf/Exception.php'; - throw new Zend_Amf_Exception('Invalid ByteArray specified; must be a string or Zend_Amf_Value_ByteArray'); - } - - $this->writeBinaryString($data); - - return $this; - } - - /** - * Send xml to output stream - * - * @param DOMDocument|SimpleXMLElement $xml - * @return Zend_Amf_Parse_Amf3_Serializer - */ - public function writeXml($xml) - { - if ($this->writeObjectReference($xml)) { - return $this; - } - - if(is_string($xml)) { - //nothing to do - } else if ($xml instanceof DOMDocument) { - $xml = $xml->saveXml(); - } else if ($xml instanceof SimpleXMLElement) { - $xml = $xml->asXML(); - } else { - #require_once 'Zend/Amf/Exception.php'; - throw new Zend_Amf_Exception('Invalid xml specified; must be a DOMDocument or SimpleXMLElement'); - } - - $this->writeBinaryString($xml); - - return $this; - } - - /** - * Convert DateTime/Zend_Date to AMF date - * - * @param DateTime|Zend_Date $date - * @return Zend_Amf_Parse_Amf3_Serializer - */ - public function writeDate($date) - { - if ($this->writeObjectReference($date)) { - return $this; - } - - if ($date instanceof DateTime) { - $dateString = $date->format('U') * 1000; - } elseif ($date instanceof Zend_Date) { - $dateString = $date->toString('U') * 1000; - } else { - #require_once 'Zend/Amf/Exception.php'; - throw new Zend_Amf_Exception('Invalid date specified; must be a string DateTime or Zend_Date object'); - } - - $this->writeInteger(0x01); - // write time to stream minus milliseconds - $this->_stream->writeDouble($dateString); - return $this; - } - - /** - * Write a PHP array back to the amf output stream - * - * @param array $array - * @return Zend_Amf_Parse_Amf3_Serializer - */ - public function writeArray(&$array) - { - // arrays aren't reference here but still counted - $this->_referenceObjects[] = $array; - - // have to seperate mixed from numberic keys. - $numeric = array(); - $string = array(); - foreach ($array as $key => &$value) { - if (is_int($key)) { - $numeric[] = $value; - } else { - $string[$key] = $value; - } - } - - // write the preamble id of the array - $length = count($numeric); - $id = ($length << 1) | 0x01; - $this->writeInteger($id); - - //Write the mixed type array to the output stream - foreach($string as $key => &$value) { - $this->writeString($key) - ->writeTypeMarker($value); - } - $this->writeString($this->_strEmpty); - - // Write the numeric array to ouput stream - foreach($numeric as &$value) { - $this->writeTypeMarker($value); - } - return $this; - } - - /** - * Check if the given object is in the reference table, write the reference if it exists, - * otherwise add the object to the reference table - * - * @param mixed $object object reference to check for reference - * @param mixed $objectByVal object to check for reference - * @return Boolean true, if the reference was written, false otherwise - */ - protected function writeObjectReference(&$object, $objectByVal = false) - { - // Workaround for PHP5 with E_STRICT enabled complaining about "Only - // variables should be passed by reference" - if ((null === $object) && ($objectByVal !== false)) { - $object = &$objectByVal; - } - - $hash = spl_object_hash($object); - $ref = array_key_exists($hash, $this->_referenceObjects) - ? $this->_referenceObjects[$hash] - : false; - - // quickly handle object references - if ($ref !== false){ - $ref <<= 1; - $this->writeInteger($ref); - return true; - } - $this->_referenceObjects[$hash] = count($this->_referenceObjects); - return false; - } - - /** - * Write object to ouput stream - * - * @param mixed $data - * @return Zend_Amf_Parse_Amf3_Serializer - */ - public function writeObject($object) - { - if($this->writeObjectReference($object)){ - return $this; - } - - $className = ''; - - //Check to see if the object is a typed object and we need to change - switch (true) { - // the return class mapped name back to actionscript class name. - case ($className = Zend_Amf_Parse_TypeLoader::getMappedClassName(get_class($object))): - break; - - // Check to see if the user has defined an explicit Action Script type. - case isset($object->_explicitType): - $className = $object->_explicitType; - break; - - // Check if user has defined a method for accessing the Action Script type - case method_exists($object, 'getASClassName'): - $className = $object->getASClassName(); - break; - - // No return class name is set make it a generic object - case ($object instanceof stdClass): - $className = ''; - break; - - // By default, use object's class name - default: - $className = get_class($object); - break; - } - - $writeTraits = true; - - //check to see, if we have a corresponding definition - if(array_key_exists($className, $this->_referenceDefinitions)){ - $traitsInfo = $this->_referenceDefinitions[$className]['id']; - $encoding = $this->_referenceDefinitions[$className]['encoding']; - $propertyNames = $this->_referenceDefinitions[$className]['propertyNames']; - - $traitsInfo = ($traitsInfo << 2) | 0x01; - - $writeTraits = false; - } else { - $propertyNames = array(); - - if($className == ''){ - //if there is no className, we interpret the class as dynamic without any sealed members - $encoding = Zend_Amf_Constants::ET_DYNAMIC; - } else { - $encoding = Zend_Amf_Constants::ET_PROPLIST; - - foreach($object as $key => $value) { - if( $key[0] != "_") { - $propertyNames[] = $key; - } - } - } - - $this->_referenceDefinitions[$className] = array( - 'id' => count($this->_referenceDefinitions), - 'encoding' => $encoding, - 'propertyNames' => $propertyNames, - ); - - $traitsInfo = Zend_Amf_Constants::AMF3_OBJECT_ENCODING; - $traitsInfo |= $encoding << 2; - $traitsInfo |= (count($propertyNames) << 4); - } - - $this->writeInteger($traitsInfo); - - if($writeTraits){ - $this->writeString($className); - foreach ($propertyNames as $value) { - $this->writeString($value); - } - } - - try { - switch($encoding) { - case Zend_Amf_Constants::ET_PROPLIST: - //Write the sealed values to the output stream. - foreach ($propertyNames as $key) { - $this->writeTypeMarker($object->$key); - } - break; - case Zend_Amf_Constants::ET_DYNAMIC: - //Write the sealed values to the output stream. - foreach ($propertyNames as $key) { - $this->writeTypeMarker($object->$key); - } - - //Write remaining properties - foreach($object as $key => $value){ - if(!in_array($key,$propertyNames) && $key[0] != "_"){ - $this->writeString($key); - $this->writeTypeMarker($value); - } - } - - //Write an empty string to end the dynamic part - $this->writeString($this->_strEmpty); - break; - case Zend_Amf_Constants::ET_EXTERNAL: - #require_once 'Zend/Amf/Exception.php'; - throw new Zend_Amf_Exception('External Object Encoding not implemented'); - break; - default: - #require_once 'Zend/Amf/Exception.php'; - throw new Zend_Amf_Exception('Unknown Object Encoding type: ' . $encoding); - } - } catch (Exception $e) { - #require_once 'Zend/Amf/Exception.php'; - throw new Zend_Amf_Exception('Unable to writeObject output: ' . $e->getMessage(), 0, $e); - } - - return $this; - } -} diff --git a/library/Zend/Amf/Parse/Deserializer.php b/library/Zend/Amf/Parse/Deserializer.php deleted file mode 100644 index e6d4b1a853..0000000000 --- a/library/Zend/Amf/Parse/Deserializer.php +++ /dev/null @@ -1,65 +0,0 @@ -_stream = $stream; - } - - /** - * Checks for AMF marker types and calls the appropriate methods - * for deserializing those marker types. Markers are the data type of - * the following value. - * - * @param int $typeMarker - * @return mixed Whatever the data type is of the marker in php - */ - public abstract function readTypeMarker($markerType = null); -} diff --git a/library/Zend/Amf/Parse/InputStream.php b/library/Zend/Amf/Parse/InputStream.php deleted file mode 100644 index 180a465b06..0000000000 --- a/library/Zend/Amf/Parse/InputStream.php +++ /dev/null @@ -1,39 +0,0 @@ - Value is Mysql type (exact string) => PHP type - */ - static public $fieldTypes = array( - "int" => "int", - "timestamp" => "int", - "year" => "int", - "real" => "float", - ); - /** - * Parse resource into array - * - * @param resource $resource - * @return array - */ - public function parse($resource) { - $result = array(); - $fieldcnt = mysql_num_fields($resource); - $fields_transform = array(); - for($i=0;$i<$fieldcnt;$i++) { - $type = mysql_field_type($resource, $i); - if(isset(self::$fieldTypes[$type])) { - $fields_transform[mysql_field_name($resource, $i)] = self::$fieldTypes[$type]; - } - } - - while($row = mysql_fetch_object($resource)) { - foreach($fields_transform as $fieldname => $fieldtype) { - settype($row->$fieldname, $fieldtype); - } - $result[] = $row; - } - return $result; - } -} diff --git a/library/Zend/Amf/Parse/Resource/MysqliResult.php b/library/Zend/Amf/Parse/Resource/MysqliResult.php deleted file mode 100644 index 45f53d4b73..0000000000 --- a/library/Zend/Amf/Parse/Resource/MysqliResult.php +++ /dev/null @@ -1,128 +0,0 @@ - "MYSQLI_TYPE_DECIMAL", - 1 => "MYSQLI_TYPE_TINYINT", - 2 => "MYSQLI_TYPE_SMALLINT", - 3 => "MYSQLI_TYPE_INTEGER", - 4 => "MYSQLI_TYPE_FLOAT", - 5 => "MYSQLI_TYPE_DOUBLE", - 7 => "MYSQLI_TYPE_TIMESTAMP", - 8 => "MYSQLI_TYPE_BIGINT", - 9 => "MYSQLI_TYPE_MEDIUMINT", - 10 => "MYSQLI_TYPE_DATE", - 11 => "MYSQLI_TYPE_TIME", - 12 => "MYSQLI_TYPE_DATETIME", - 13 => "MYSQLI_TYPE_YEAR", - 14 => "MYSQLI_TYPE_DATE", - 16 => "MYSQLI_TYPE_BIT", - 246 => "MYSQLI_TYPE_DECIMAL", - 247 => "MYSQLI_TYPE_ENUM", - 248 => "MYSQLI_TYPE_SET", - 249 => "MYSQLI_TYPE_TINYBLOB", - 250 => "MYSQLI_TYPE_MEDIUMBLOB", - 251 => "MYSQLI_TYPE_LONGBLOB", - 252 => "MYSQLI_TYPE_BLOB", - 253 => "MYSQLI_TYPE_VARCHAR", - 254 => "MYSQLI_TYPE_CHAR", - 255 => "MYSQLI_TYPE_GEOMETRY", - ); - - // Build an associative array for a type look up - static $mysqli_to_php = array( - "MYSQLI_TYPE_DECIMAL" => 'float', - "MYSQLI_TYPE_NEWDECIMAL" => 'float', - "MYSQLI_TYPE_BIT" => 'integer', - "MYSQLI_TYPE_TINYINT" => 'integer', - "MYSQLI_TYPE_SMALLINT" => 'integer', - "MYSQLI_TYPE_MEDIUMINT" => 'integer', - "MYSQLI_TYPE_BIGINT" => 'integer', - "MYSQLI_TYPE_INTEGER" => 'integer', - "MYSQLI_TYPE_FLOAT" => 'float', - "MYSQLI_TYPE_DOUBLE" => 'float', - "MYSQLI_TYPE_NULL" => 'null', - "MYSQLI_TYPE_TIMESTAMP" => 'string', - "MYSQLI_TYPE_INT24" => 'integer', - "MYSQLI_TYPE_DATE" => 'string', - "MYSQLI_TYPE_TIME" => 'string', - "MYSQLI_TYPE_DATETIME" => 'string', - "MYSQLI_TYPE_YEAR" => 'string', - "MYSQLI_TYPE_NEWDATE" => 'string', - "MYSQLI_TYPE_ENUM" => 'string', - "MYSQLI_TYPE_SET" => 'string', - "MYSQLI_TYPE_TINYBLOB" => 'object', - "MYSQLI_TYPE_MEDIUMBLOB" => 'object', - "MYSQLI_TYPE_LONGBLOB" => 'object', - "MYSQLI_TYPE_BLOB" => 'object', - "MYSQLI_TYPE_CHAR" => 'string', - "MYSQLI_TYPE_VARCHAR" => 'string', - "MYSQLI_TYPE_GEOMETRY" => 'object', - "MYSQLI_TYPE_BIT" => 'integer', - ); - - /** - * Parse resource into array - * - * @param resource $resource - * @return array - */ - public function parse($resource) { - - $result = array(); - $fieldcnt = mysqli_num_fields($resource); - - - $fields_transform = array(); - - for($i=0;$i<$fieldcnt;$i++) { - $finfo = mysqli_fetch_field_direct($resource, $i); - - if(isset(self::$mysqli_type[$finfo->type])) { - $fields_transform[$finfo->name] = self::$mysqli_to_php[self::$mysqli_type[$finfo->type]]; - } - } - - while($row = mysqli_fetch_assoc($resource)) { - foreach($fields_transform as $fieldname => $fieldtype) { - settype($row[$fieldname], $fieldtype); - } - $result[] = $row; - } - return $result; - } -} diff --git a/library/Zend/Amf/Parse/Resource/Stream.php b/library/Zend/Amf/Parse/Resource/Stream.php deleted file mode 100755 index b8afa148ac..0000000000 --- a/library/Zend/Amf/Parse/Resource/Stream.php +++ /dev/null @@ -1,42 +0,0 @@ -_stream = $stream; - $this->_mbStringFunctionsOverloaded = function_exists('mb_strlen') && (ini_get('mbstring.func_overload') !== '') && ((int)ini_get('mbstring.func_overload') & 2); - } - - /** - * Find the PHP object type and convert it into an AMF object type - * - * @param mixed $content - * @param int $markerType - * @param mixed $contentByVal - * @return void - */ - public abstract function writeTypeMarker(&$content, $markerType = null, $contentByVal = false); -} diff --git a/library/Zend/Amf/Parse/TypeLoader.php b/library/Zend/Amf/Parse/TypeLoader.php deleted file mode 100644 index 6be80cf079..0000000000 --- a/library/Zend/Amf/Parse/TypeLoader.php +++ /dev/null @@ -1,231 +0,0 @@ - 'Zend_Amf_Value_Messaging_AcknowledgeMessage', - 'flex.messaging.messages.ErrorMessage' => 'Zend_Amf_Value_Messaging_AsyncMessage', - 'flex.messaging.messages.CommandMessage' => 'Zend_Amf_Value_Messaging_CommandMessage', - 'flex.messaging.messages.ErrorMessage' => 'Zend_Amf_Value_Messaging_ErrorMessage', - 'flex.messaging.messages.RemotingMessage' => 'Zend_Amf_Value_Messaging_RemotingMessage', - 'flex.messaging.io.ArrayCollection' => 'Zend_Amf_Value_Messaging_ArrayCollection', - ); - - /** - * @var array Default class map - */ - protected static $_defaultClassMap = array( - 'flex.messaging.messages.AcknowledgeMessage' => 'Zend_Amf_Value_Messaging_AcknowledgeMessage', - 'flex.messaging.messages.ErrorMessage' => 'Zend_Amf_Value_Messaging_AsyncMessage', - 'flex.messaging.messages.CommandMessage' => 'Zend_Amf_Value_Messaging_CommandMessage', - 'flex.messaging.messages.ErrorMessage' => 'Zend_Amf_Value_Messaging_ErrorMessage', - 'flex.messaging.messages.RemotingMessage' => 'Zend_Amf_Value_Messaging_RemotingMessage', - 'flex.messaging.io.ArrayCollection' => 'Zend_Amf_Value_Messaging_ArrayCollection', - ); - - /** - * @var Zend_Loader_PluginLoader_Interface - */ - protected static $_resourceLoader = null; - - - /** - * Load the mapped class type into a callback. - * - * @param string $className - * @return object|false - */ - public static function loadType($className) - { - $class = self::getMappedClassName($className); - if(!$class) { - $class = str_replace('.', '_', $className); - } - if (!class_exists($class)) { - return "stdClass"; - } - return $class; - } - - /** - * Looks up the supplied call name to its mapped class name - * - * @param string $className - * @return string - */ - public static function getMappedClassName($className) - { - $mappedName = array_search($className, self::$classMap); - - if ($mappedName) { - return $mappedName; - } - - $mappedName = array_search($className, array_flip(self::$classMap)); - - if ($mappedName) { - return $mappedName; - } - - return false; - } - - /** - * Map PHP class names to ActionScript class names - * - * Allows users to map the class names of there action script classes - * to the equivelent php class name. Used in deserialization to load a class - * and serialiation to set the class name of the returned object. - * - * @param string $asClassName - * @param string $phpClassName - * @return void - */ - public static function setMapping($asClassName, $phpClassName) - { - self::$classMap[$asClassName] = $phpClassName; - } - - /** - * Reset type map - * - * @return void - */ - public static function resetMap() - { - self::$classMap = self::$_defaultClassMap; - } - - /** - * Set loader for resource type handlers - * - * @param Zend_Loader_PluginLoader_Interface $loader - */ - public static function setResourceLoader(Zend_Loader_PluginLoader_Interface $loader) - { - self::$_resourceLoader = $loader; - } - - /** - * Add directory to the list of places where to look for resource handlers - * - * @param string $prefix - * @param string $dir - */ - public static function addResourceDirectory($prefix, $dir) - { - if(self::$_resourceLoader) { - self::$_resourceLoader->addPrefixPath($prefix, $dir); - } - } - - /** - * Get plugin class that handles this resource - * - * @param resource $resource Resource type - * @return string Class name - */ - public static function getResourceParser($resource) - { - if(self::$_resourceLoader) { - $type = preg_replace("/[^A-Za-z0-9_]/", " ", get_resource_type($resource)); - $type = str_replace(" ","", ucwords($type)); - return self::$_resourceLoader->load($type); - } - return false; - } - - /** - * Convert resource to a serializable object - * - * @param resource $resource - * @return mixed - */ - public static function handleResource($resource) - { - if(!self::$_resourceLoader) { - #require_once 'Zend/Amf/Exception.php'; - throw new Zend_Amf_Exception('Unable to handle resources - resource plugin loader not set'); - } - try { - while(is_resource($resource)) { - $resclass = self::getResourceParser($resource); - if(!$resclass) { - #require_once 'Zend/Amf/Exception.php'; - throw new Zend_Amf_Exception('Can not serialize resource type: '. get_resource_type($resource)); - } - $parser = new $resclass(); - if(is_callable(array($parser, 'parse'))) { - $resource = $parser->parse($resource); - } else { - #require_once 'Zend/Amf/Exception.php'; - throw new Zend_Amf_Exception("Could not call parse() method on class $resclass"); - } - } - return $resource; - } catch(Zend_Amf_Exception $e) { - throw new Zend_Amf_Exception($e->getMessage(), $e->getCode(), $e); - } catch(Exception $e) { - #require_once 'Zend/Amf/Exception.php'; - throw new Zend_Amf_Exception('Can not serialize resource type: '. get_resource_type($resource), 0, $e); - } - } -} diff --git a/library/Zend/Amf/Request.php b/library/Zend/Amf/Request.php deleted file mode 100644 index 38cc4c879d..0000000000 --- a/library/Zend/Amf/Request.php +++ /dev/null @@ -1,251 +0,0 @@ -_inputStream = new Zend_Amf_Parse_InputStream($request); - $this->_deserializer = new Zend_Amf_Parse_Amf0_Deserializer($this->_inputStream); - $this->readMessage($this->_inputStream); - return $this; - } - - /** - * Takes the raw AMF input stream and converts it into valid PHP objects - * - * @param Zend_Amf_Parse_InputStream - * @return Zend_Amf_Request - */ - public function readMessage(Zend_Amf_Parse_InputStream $stream) - { - $clientVersion = $stream->readUnsignedShort(); - if (($clientVersion != Zend_Amf_Constants::AMF0_OBJECT_ENCODING) - && ($clientVersion != Zend_Amf_Constants::AMF3_OBJECT_ENCODING) - && ($clientVersion != Zend_Amf_Constants::FMS_OBJECT_ENCODING) - ) { - #require_once 'Zend/Amf/Exception.php'; - throw new Zend_Amf_Exception('Unknown Player Version ' . $clientVersion); - } - - $this->_bodies = array(); - $this->_headers = array(); - $headerCount = $stream->readInt(); - - // Iterate through the AMF envelope header - while ($headerCount--) { - $this->_headers[] = $this->readHeader(); - } - - // Iterate through the AMF envelope body - $bodyCount = $stream->readInt(); - while ($bodyCount--) { - $this->_bodies[] = $this->readBody(); - } - - return $this; - } - - /** - * Deserialize a message header from the input stream. - * - * A message header is structured as: - * - NAME String - * - MUST UNDERSTAND Boolean - * - LENGTH Int - * - DATA Object - * - * @return Zend_Amf_Value_MessageHeader - */ - public function readHeader() - { - $name = $this->_inputStream->readUTF(); - $mustRead = (bool)$this->_inputStream->readByte(); - $length = $this->_inputStream->readLong(); - - try { - $data = $this->_deserializer->readTypeMarker(); - } catch (Exception $e) { - #require_once 'Zend/Amf/Exception.php'; - throw new Zend_Amf_Exception('Unable to parse ' . $name . ' header data: ' . $e->getMessage() . ' '. $e->getLine(), 0, $e); - } - - $header = new Zend_Amf_Value_MessageHeader($name, $mustRead, $data, $length); - return $header; - } - - /** - * Deserialize a message body from the input stream - * - * @return Zend_Amf_Value_MessageBody - */ - public function readBody() - { - $targetURI = $this->_inputStream->readUTF(); - $responseURI = $this->_inputStream->readUTF(); - $length = $this->_inputStream->readLong(); - - try { - $data = $this->_deserializer->readTypeMarker(); - } catch (Exception $e) { - #require_once 'Zend/Amf/Exception.php'; - throw new Zend_Amf_Exception('Unable to parse ' . $targetURI . ' body data ' . $e->getMessage(), 0, $e); - } - - // Check for AMF3 objectEncoding - if ($this->_deserializer->getObjectEncoding() == Zend_Amf_Constants::AMF3_OBJECT_ENCODING) { - /* - * When and AMF3 message is sent to the server it is nested inside - * an AMF0 array called Content. The following code gets the object - * out of the content array and sets it as the message data. - */ - if(is_array($data) && $data[0] instanceof Zend_Amf_Value_Messaging_AbstractMessage){ - $data = $data[0]; - } - - // set the encoding so we return our message in AMF3 - $this->_objectEncoding = Zend_Amf_Constants::AMF3_OBJECT_ENCODING; - } - - $body = new Zend_Amf_Value_MessageBody($targetURI, $responseURI, $data); - return $body; - } - - /** - * Return an array of the body objects that were found in the amf request. - * - * @return array {target, response, length, content} - */ - public function getAmfBodies() - { - return $this->_bodies; - } - - /** - * Accessor to private array of message bodies. - * - * @param Zend_Amf_Value_MessageBody $message - * @return Zend_Amf_Request - */ - public function addAmfBody(Zend_Amf_Value_MessageBody $message) - { - $this->_bodies[] = $message; - return $this; - } - - /** - * Return an array of headers that were found in the amf request. - * - * @return array {operation, mustUnderstand, length, param} - */ - public function getAmfHeaders() - { - return $this->_headers; - } - - /** - * Return the either 0 or 3 for respect AMF version - * - * @return int - */ - public function getObjectEncoding() - { - return $this->_objectEncoding; - } - - /** - * Set the object response encoding - * - * @param mixed $int - * @return Zend_Amf_Request - */ - public function setObjectEncoding($int) - { - $this->_objectEncoding = $int; - return $this; - } -} diff --git a/library/Zend/Amf/Request/Http.php b/library/Zend/Amf/Request/Http.php deleted file mode 100644 index c8e4dfaca5..0000000000 --- a/library/Zend/Amf/Request/Http.php +++ /dev/null @@ -1,80 +0,0 @@ -_rawRequest = $amfRequest; - $this->initialize($amfRequest); - } else { - echo '

Zend Amf Endpoint

' ; - } - } - - /** - * Retrieve raw AMF Request - * - * @return string - */ - public function getRawRequest() - { - return $this->_rawRequest; - } -} diff --git a/library/Zend/Amf/Response.php b/library/Zend/Amf/Response.php deleted file mode 100644 index 280556ceed..0000000000 --- a/library/Zend/Amf/Response.php +++ /dev/null @@ -1,205 +0,0 @@ -_outputStream = new Zend_Amf_Parse_OutputStream(); - $this->writeMessage($this->_outputStream); - return $this; - } - - /** - * Serialize the PHP data types back into Actionscript and - * create and AMF stream. - * - * @param Zend_Amf_Parse_OutputStream $stream - * @return Zend_Amf_Response - */ - public function writeMessage(Zend_Amf_Parse_OutputStream $stream) - { - $objectEncoding = $this->_objectEncoding; - - //Write encoding to start of stream. Preamble byte is written of two byte Unsigned Short - $stream->writeByte(0x00); - $stream->writeByte($objectEncoding); - - // Loop through the AMF Headers that need to be returned. - $headerCount = count($this->_headers); - $stream->writeInt($headerCount); - foreach ($this->getAmfHeaders() as $header) { - $serializer = new Zend_Amf_Parse_Amf0_Serializer($stream); - $stream->writeUTF($header->name); - $stream->writeByte($header->mustRead); - $stream->writeLong(Zend_Amf_Constants::UNKNOWN_CONTENT_LENGTH); - if (is_object($header->data)) { - // Workaround for PHP5 with E_STRICT enabled complaining about - // "Only variables should be passed by reference" - $placeholder = null; - $serializer->writeTypeMarker($placeholder, null, $header->data); - } else { - $serializer->writeTypeMarker($header->data); - } - } - - // loop through the AMF bodies that need to be returned. - $bodyCount = count($this->_bodies); - $stream->writeInt($bodyCount); - foreach ($this->_bodies as $body) { - $serializer = new Zend_Amf_Parse_Amf0_Serializer($stream); - $stream->writeUTF($body->getTargetURI()); - $stream->writeUTF($body->getResponseURI()); - $stream->writeLong(Zend_Amf_Constants::UNKNOWN_CONTENT_LENGTH); - $bodyData = $body->getData(); - $markerType = ($this->_objectEncoding == Zend_Amf_Constants::AMF0_OBJECT_ENCODING) ? null : Zend_Amf_Constants::AMF0_AMF3; - if (is_object($bodyData)) { - // Workaround for PHP5 with E_STRICT enabled complaining about - // "Only variables should be passed by reference" - $placeholder = null; - $serializer->writeTypeMarker($placeholder, $markerType, $bodyData); - } else { - $serializer->writeTypeMarker($bodyData, $markerType); - } - } - - return $this; - } - - /** - * Return the output stream content - * - * @return string The contents of the output stream - */ - public function getResponse() - { - return $this->_outputStream->getStream(); - } - - /** - * Return the output stream content - * - * @return string - */ - public function __toString() - { - return $this->getResponse(); - } - - /** - * Add an AMF body to be sent to the Flash Player - * - * @param Zend_Amf_Value_MessageBody $body - * @return Zend_Amf_Response - */ - public function addAmfBody(Zend_Amf_Value_MessageBody $body) - { - $this->_bodies[] = $body; - return $this; - } - - /** - * Return an array of AMF bodies to be serialized - * - * @return array - */ - public function getAmfBodies() - { - return $this->_bodies; - } - - /** - * Add an AMF Header to be sent back to the flash player - * - * @param Zend_Amf_Value_MessageHeader $header - * @return Zend_Amf_Response - */ - public function addAmfHeader(Zend_Amf_Value_MessageHeader $header) - { - $this->_headers[] = $header; - return $this; - } - - /** - * Retrieve attached AMF message headers - * - * @return array Array of Zend_Amf_Value_MessageHeader objects - */ - public function getAmfHeaders() - { - return $this->_headers; - } - - /** - * Set the AMF encoding that will be used for serialization - * - * @param int $encoding - * @return Zend_Amf_Response - */ - public function setObjectEncoding($encoding) - { - $this->_objectEncoding = $encoding; - return $this; - } -} diff --git a/library/Zend/Amf/Response/Http.php b/library/Zend/Amf/Response/Http.php deleted file mode 100644 index d9afaf4dcb..0000000000 --- a/library/Zend/Amf/Response/Http.php +++ /dev/null @@ -1,73 +0,0 @@ -isIeOverSsl()) { - header('Cache-Control: cache, must-revalidate'); - header('Pragma: public'); - } else { - header('Cache-Control: no-cache, must-revalidate'); - header('Pragma: no-cache'); - } - header('Expires: Thu, 19 Nov 1981 08:52:00 GMT'); - header('Content-Type: application/x-amf'); - } - return parent::getResponse(); - } - - protected function isIeOverSsl() - { - $ssl = isset($_SERVER['HTTPS']) ? $_SERVER['HTTPS'] : false; - if (!$ssl || ($ssl == 'off')) { - // IIS reports "off", whereas other browsers simply don't populate - return false; - } - - $ua = $_SERVER['HTTP_USER_AGENT']; - if (!preg_match('/; MSIE \d+\.\d+;/', $ua)) { - // Not MicroSoft Internet Explorer - return false; - } - - return true; - } -} diff --git a/library/Zend/Amf/Server.php b/library/Zend/Amf/Server.php deleted file mode 100644 index e8f429bfc1..0000000000 --- a/library/Zend/Amf/Server.php +++ /dev/null @@ -1,1048 +0,0 @@ - method pairs - * @var array - */ - protected $_table = array(); - - /** - * - * @var bool session flag; whether or not to add a session to each response. - */ - protected $_session = false; - - /** - * Namespace allows all AMF calls to not clobber other PHP session variables - * @var Zend_Session_NameSpace default session namespace zend_amf - */ - protected $_sesionNamespace = 'zend_amf'; - - /** - * Set the default session.name if php_ - * @var string - */ - protected $_sessionName = 'PHPSESSID'; - - /** - * Authentication handler object - * - * @var Zend_Amf_Auth_Abstract - */ - protected $_auth; - /** - * ACL handler object - * - * @var Zend_Acl - */ - protected $_acl; - /** - * The server constructor - */ - public function __construct() - { - Zend_Amf_Parse_TypeLoader::setResourceLoader(new Zend_Loader_PluginLoader(array("Zend_Amf_Parse_Resource" => "Zend/Amf/Parse/Resource"))); - } - - /** - * Set authentication adapter - * - * If the authentication adapter implements a "getAcl()" method, populate - * the ACL of this instance with it (if none exists already). - * - * @param Zend_Amf_Auth_Abstract $auth - * @return Zend_Amf_Server - */ - public function setAuth(Zend_Amf_Auth_Abstract $auth) - { - $this->_auth = $auth; - if ((null === $this->getAcl()) && method_exists($auth, 'getAcl')) { - $this->setAcl($auth->getAcl()); - } - return $this; - } - /** - * Get authentication adapter - * - * @return Zend_Amf_Auth_Abstract - */ - public function getAuth() - { - return $this->_auth; - } - - /** - * Set ACL adapter - * - * @param Zend_Acl $acl - * @return Zend_Amf_Server - */ - public function setAcl(Zend_Acl $acl) - { - $this->_acl = $acl; - return $this; - } - /** - * Get ACL adapter - * - * @return Zend_Acl - */ - public function getAcl() - { - return $this->_acl; - } - - /** - * Set production flag - * - * @param bool $flag - * @return Zend_Amf_Server - */ - public function setProduction($flag) - { - $this->_production = (bool) $flag; - return $this; - } - - /** - * Whether or not the server is in production - * - * @return bool - */ - public function isProduction() - { - return $this->_production; - } - - /** - * @param namespace of all incoming sessions defaults to Zend_Amf - * @return Zend_Amf_Server - */ - public function setSession($namespace = 'Zend_Amf') - { - #require_once 'Zend/Session.php'; - $this->_session = true; - $this->_sesionNamespace = new Zend_Session_Namespace($namespace); - return $this; - } - - /** - * Whether of not the server is using sessions - * @return bool - */ - public function isSession() - { - return $this->_session; - } - - /** - * Check if the ACL allows accessing the function or method - * - * @param string|object $object Object or class being accessed - * @param string $function Function or method being accessed - * @return unknown_type - */ - protected function _checkAcl($object, $function) - { - if(!$this->_acl) { - return true; - } - if($object) { - $class = is_object($object)?get_class($object):$object; - if(!$this->_acl->has($class)) { - #require_once 'Zend/Acl/Resource.php'; - $this->_acl->add(new Zend_Acl_Resource($class)); - } - $call = array($object, "initAcl"); - if(is_callable($call) && !call_user_func($call, $this->_acl)) { - // if initAcl returns false, no ACL check - return true; - } - } else { - $class = null; - } - - $auth = Zend_Auth::getInstance(); - if($auth->hasIdentity()) { - $role = $auth->getIdentity()->role; - } else { - if($this->_acl->hasRole(Zend_Amf_Constants::GUEST_ROLE)) { - $role = Zend_Amf_Constants::GUEST_ROLE; - } else { - #require_once 'Zend/Amf/Server/Exception.php'; - throw new Zend_Amf_Server_Exception("Unauthenticated access not allowed"); - } - } - if($this->_acl->isAllowed($role, $class, $function)) { - return true; - } else { - #require_once 'Zend/Amf/Server/Exception.php'; - throw new Zend_Amf_Server_Exception("Access not allowed"); - } - } - - /** - * Get PluginLoader for the Server - * - * @return Zend_Loader_PluginLoader - */ - protected function getLoader() - { - if(empty($this->_loader)) { - #require_once 'Zend/Loader/PluginLoader.php'; - $this->_loader = new Zend_Loader_PluginLoader(); - } - return $this->_loader; - } - - /** - * Loads a remote class or method and executes the function and returns - * the result - * - * @param string $method Is the method to execute - * @param mixed $param values for the method - * @return mixed $response the result of executing the method - * @throws Zend_Amf_Server_Exception - */ - protected function _dispatch($method, $params = null, $source = null) - { - if($source) { - if(($mapped = Zend_Amf_Parse_TypeLoader::getMappedClassName($source)) !== false) { - $source = $mapped; - } - } - $qualifiedName = empty($source) ? $method : $source . '.' . $method; - - if (!isset($this->_table[$qualifiedName])) { - // if source is null a method that was not defined was called. - if ($source) { - $className = str_replace('.', '_', $source); - if(class_exists($className, false) && !isset($this->_classAllowed[$className])) { - #require_once 'Zend/Amf/Server/Exception.php'; - throw new Zend_Amf_Server_Exception('Can not call "' . $className . '" - use setClass()'); - } - try { - $this->getLoader()->load($className); - } catch (Exception $e) { - #require_once 'Zend/Amf/Server/Exception.php'; - throw new Zend_Amf_Server_Exception('Class "' . $className . '" does not exist: '.$e->getMessage(), 0, $e); - } - // Add the new loaded class to the server. - #require_once 'Zend/Amf/Server/Exception.php'; - $this->setClass($className, $source); - } - - if (!isset($this->_table[$qualifiedName])) { - // Source is null or doesn't contain specified method - #require_once 'Zend/Amf/Server/Exception.php'; - throw new Zend_Amf_Server_Exception('Method "' . $method . '" does not exist'); - } - } - - $info = $this->_table[$qualifiedName]; - $argv = $info->getInvokeArguments(); - - if (0 < count($argv)) { - $params = array_merge($params, $argv); - } - - $params = $this->_castParameters($info, $params); - - if ($info instanceof Zend_Server_Reflection_Function) { - $func = $info->getName(); - $this->_checkAcl(null, $func); - $return = call_user_func_array($func, $params); - } elseif ($info instanceof Zend_Server_Reflection_Method) { - // Get class - $class = $info->getDeclaringClass()->getName(); - if ('static' == $info->isStatic()) { - // for some reason, invokeArgs() does not work the same as - // invoke(), and expects the first argument to be an object. - // So, using a callback if the method is static. - $this->_checkAcl($class, $info->getName()); - $return = call_user_func_array(array($class, $info->getName()), $params); - } else { - // Object methods - try { - $object = $info->getDeclaringClass()->newInstance(); - } catch (Exception $e) { - #require_once 'Zend/Amf/Server/Exception.php'; - throw new Zend_Amf_Server_Exception('Error instantiating class ' . $class . ' to invoke method ' . $info->getName() . ': '.$e->getMessage(), 621, $e); - } - $this->_checkAcl($object, $info->getName()); - $return = $info->invokeArgs($object, $params); - } - } else { - #require_once 'Zend/Amf/Server/Exception.php'; - throw new Zend_Amf_Server_Exception('Method missing implementation ' . get_class($info)); - } - - return $return; - } - - /** - * Handles each of the 11 different command message types. - * - * A command message is a flex.messaging.messages.CommandMessage - * - * @see Zend_Amf_Value_Messaging_CommandMessage - * @param Zend_Amf_Value_Messaging_CommandMessage $message - * @return Zend_Amf_Value_Messaging_AcknowledgeMessage - */ - protected function _loadCommandMessage(Zend_Amf_Value_Messaging_CommandMessage $message) - { - #require_once 'Zend/Amf/Value/Messaging/AcknowledgeMessage.php'; - switch($message->operation) { - case Zend_Amf_Value_Messaging_CommandMessage::DISCONNECT_OPERATION : - case Zend_Amf_Value_Messaging_CommandMessage::CLIENT_PING_OPERATION : - $return = new Zend_Amf_Value_Messaging_AcknowledgeMessage($message); - break; - case Zend_Amf_Value_Messaging_CommandMessage::LOGIN_OPERATION : - $data = explode(':', base64_decode($message->body)); - $userid = $data[0]; - $password = isset($data[1])?$data[1]:""; - if(empty($userid)) { - #require_once 'Zend/Amf/Server/Exception.php'; - throw new Zend_Amf_Server_Exception('Login failed: username not supplied'); - } - if(!$this->_handleAuth($userid, $password)) { - #require_once 'Zend/Amf/Server/Exception.php'; - throw new Zend_Amf_Server_Exception('Authentication failed'); - } - $return = new Zend_Amf_Value_Messaging_AcknowledgeMessage($message); - break; - case Zend_Amf_Value_Messaging_CommandMessage::LOGOUT_OPERATION : - if($this->_auth) { - Zend_Auth::getInstance()->clearIdentity(); - } - $return = new Zend_Amf_Value_Messaging_AcknowledgeMessage($message); - break; - default : - #require_once 'Zend/Amf/Server/Exception.php'; - throw new Zend_Amf_Server_Exception('CommandMessage::' . $message->operation . ' not implemented'); - break; - } - return $return; - } - - /** - * Create appropriate error message - * - * @param int $objectEncoding Current AMF encoding - * @param string $message Message that was being processed when error happened - * @param string $description Error description - * @param mixed $detail Detailed data about the error - * @param int $code Error code - * @param int $line Error line - * @return Zend_Amf_Value_Messaging_ErrorMessage|array - */ - protected function _errorMessage($objectEncoding, $message, $description, $detail, $code, $line) - { - $return = null; - switch ($objectEncoding) { - case Zend_Amf_Constants::AMF0_OBJECT_ENCODING : - return array ( - 'description' => ($this->isProduction ()) ? '' : $description, - 'detail' => ($this->isProduction ()) ? '' : $detail, - 'line' => ($this->isProduction ()) ? 0 : $line, - 'code' => $code - ); - case Zend_Amf_Constants::AMF3_OBJECT_ENCODING : - #require_once 'Zend/Amf/Value/Messaging/ErrorMessage.php'; - $return = new Zend_Amf_Value_Messaging_ErrorMessage ( $message ); - $return->faultString = $this->isProduction () ? '' : $description; - $return->faultCode = $code; - $return->faultDetail = $this->isProduction () ? '' : $detail; - break; - } - return $return; - } - - /** - * Handle AMF authentication - * - * @param string $userid - * @param string $password - * @return boolean - */ - protected function _handleAuth( $userid, $password) - { - if (!$this->_auth) { - return true; - } - $this->_auth->setCredentials($userid, $password); - $auth = Zend_Auth::getInstance(); - $result = $auth->authenticate($this->_auth); - if ($result->isValid()) { - if (!$this->isSession()) { - $this->setSession(); - } - return true; - } else { - // authentication failed, good bye - #require_once 'Zend/Amf/Server/Exception.php'; - throw new Zend_Amf_Server_Exception( - "Authentication failed: " . join("\n", - $result->getMessages()), $result->getCode()); - } - - } - - /** - * Takes the deserialized AMF request and performs any operations. - * - * @todo should implement and SPL observer pattern for custom AMF headers - * @todo DescribeService support - * @param Zend_Amf_Request $request - * @return Zend_Amf_Response - * @throws Zend_Amf_server_Exception|Exception - */ - protected function _handle(Zend_Amf_Request $request) - { - // Get the object encoding of the request. - $objectEncoding = $request->getObjectEncoding(); - - // create a response object to place the output from the services. - $response = $this->getResponse(); - - // set response encoding - $response->setObjectEncoding($objectEncoding); - - // Authenticate, if we have credential headers - $error = false; - $headers = $request->getAmfHeaders(); - if (isset($headers[Zend_Amf_Constants::CREDENTIALS_HEADER]) - && isset($headers[Zend_Amf_Constants::CREDENTIALS_HEADER]->userid) - && isset($headers[Zend_Amf_Constants::CREDENTIALS_HEADER]->password) - ) { - try { - if ($this->_handleAuth( - $headers[Zend_Amf_Constants::CREDENTIALS_HEADER]->userid, - $headers[Zend_Amf_Constants::CREDENTIALS_HEADER]->password - )) { - // use RequestPersistentHeader to clear credentials - $response->addAmfHeader( - new Zend_Amf_Value_MessageHeader( - Zend_Amf_Constants::PERSISTENT_HEADER, - false, - new Zend_Amf_Value_MessageHeader( - Zend_Amf_Constants::CREDENTIALS_HEADER, - false, null - ) - ) - ); - } - } catch (Exception $e) { - // Error during authentication; report it - $error = $this->_errorMessage( - $objectEncoding, - '', - $e->getMessage(), - $e->getTraceAsString(), - $e->getCode(), - $e->getLine() - ); - $responseType = Zend_AMF_Constants::STATUS_METHOD; - } - } - - // Iterate through each of the service calls in the AMF request - foreach($request->getAmfBodies() as $body) - { - if ($error) { - // Error during authentication; just report it and be done - $responseURI = $body->getResponseURI() . $responseType; - $newBody = new Zend_Amf_Value_MessageBody($responseURI, null, $error); - $response->addAmfBody($newBody); - continue; - } - try { - switch ($objectEncoding) { - case Zend_Amf_Constants::AMF0_OBJECT_ENCODING: - // AMF0 Object Encoding - $targetURI = $body->getTargetURI(); - $message = ''; - - // Split the target string into its values. - $source = substr($targetURI, 0, strrpos($targetURI, '.')); - - if ($source) { - // Break off method name from namespace into source - $method = substr(strrchr($targetURI, '.'), 1); - $return = $this->_dispatch($method, $body->getData(), $source); - } else { - // Just have a method name. - $return = $this->_dispatch($targetURI, $body->getData()); - } - break; - case Zend_Amf_Constants::AMF3_OBJECT_ENCODING: - default: - // AMF3 read message type - $message = $body->getData(); - if ($message instanceof Zend_Amf_Value_Messaging_CommandMessage) { - // async call with command message - $return = $this->_loadCommandMessage($message); - } elseif ($message instanceof Zend_Amf_Value_Messaging_RemotingMessage) { - #require_once 'Zend/Amf/Value/Messaging/AcknowledgeMessage.php'; - $return = new Zend_Amf_Value_Messaging_AcknowledgeMessage($message); - $return->body = $this->_dispatch($message->operation, $message->body, $message->source); - } else { - // Amf3 message sent with netConnection - $targetURI = $body->getTargetURI(); - - // Split the target string into its values. - $source = substr($targetURI, 0, strrpos($targetURI, '.')); - - if ($source) { - // Break off method name from namespace into source - $method = substr(strrchr($targetURI, '.'), 1); - $return = $this->_dispatch($method, $body->getData(), $source); - } else { - // Just have a method name. - $return = $this->_dispatch($targetURI, $body->getData()); - } - } - break; - } - $responseType = Zend_AMF_Constants::RESULT_METHOD; - } catch (Exception $e) { - $return = $this->_errorMessage($objectEncoding, $message, - $e->getMessage(), $e->getTraceAsString(),$e->getCode(), $e->getLine()); - $responseType = Zend_AMF_Constants::STATUS_METHOD; - } - - $responseURI = $body->getResponseURI() . $responseType; - $newBody = new Zend_Amf_Value_MessageBody($responseURI, null, $return); - $response->addAmfBody($newBody); - } - // Add a session header to the body if session is requested. - if($this->isSession()) { - $currentID = session_id(); - $joint = "?"; - if(isset($_SERVER['QUERY_STRING'])) { - if(!strpos($_SERVER['QUERY_STRING'], $currentID) !== FALSE) { - if(strrpos($_SERVER['QUERY_STRING'], "?") !== FALSE) { - $joint = "&"; - } - } - } - - // create a new AMF message header with the session id as a variable. - $sessionValue = $joint . $this->_sessionName . "=" . $currentID; - $sessionHeader = new Zend_Amf_Value_MessageHeader(Zend_Amf_Constants::URL_APPEND_HEADER, false, $sessionValue); - $response->addAmfHeader($sessionHeader); - } - - // serialize the response and return serialized body. - $response->finalize(); - } - - /** - * Handle an AMF call from the gateway. - * - * @param null|Zend_Amf_Request $request Optional - * @return Zend_Amf_Response - */ - public function handle($request = null) - { - // Check if request was passed otherwise get it from the server - if ($request === null || !$request instanceof Zend_Amf_Request) { - $request = $this->getRequest(); - } else { - $this->setRequest($request); - } - if ($this->isSession()) { - // Check if a session is being sent from the amf call - if (isset($_COOKIE[$this->_sessionName])) { - session_id($_COOKIE[$this->_sessionName]); - } - } - - // Check for errors that may have happend in deserialization of Request. - try { - // Take converted PHP objects and handle service call. - // Serialize to Zend_Amf_response for output stream - $this->_handle($request); - $response = $this->getResponse(); - } catch (Exception $e) { - // Handle any errors in the serialization and service calls. - #require_once 'Zend/Amf/Server/Exception.php'; - throw new Zend_Amf_Server_Exception('Handle error: ' . $e->getMessage() . ' ' . $e->getLine(), 0, $e); - } - - // Return the Amf serialized output string - return $response; - } - - /** - * Set request object - * - * @param string|Zend_Amf_Request $request - * @return Zend_Amf_Server - */ - public function setRequest($request) - { - if (is_string($request) && class_exists($request)) { - $request = new $request(); - if (!$request instanceof Zend_Amf_Request) { - #require_once 'Zend/Amf/Server/Exception.php'; - throw new Zend_Amf_Server_Exception('Invalid request class'); - } - } elseif (!$request instanceof Zend_Amf_Request) { - #require_once 'Zend/Amf/Server/Exception.php'; - throw new Zend_Amf_Server_Exception('Invalid request object'); - } - $this->_request = $request; - return $this; - } - - /** - * Return currently registered request object - * - * @return null|Zend_Amf_Request - */ - public function getRequest() - { - if (null === $this->_request) { - #require_once 'Zend/Amf/Request/Http.php'; - $this->setRequest(new Zend_Amf_Request_Http()); - } - - return $this->_request; - } - - /** - * Public access method to private Zend_Amf_Server_Response reference - * - * @param string|Zend_Amf_Server_Response $response - * @return Zend_Amf_Server - */ - public function setResponse($response) - { - if (is_string($response) && class_exists($response)) { - $response = new $response(); - if (!$response instanceof Zend_Amf_Response) { - #require_once 'Zend/Amf/Server/Exception.php'; - throw new Zend_Amf_Server_Exception('Invalid response class'); - } - } elseif (!$response instanceof Zend_Amf_Response) { - #require_once 'Zend/Amf/Server/Exception.php'; - throw new Zend_Amf_Server_Exception('Invalid response object'); - } - $this->_response = $response; - return $this; - } - - /** - * get a reference to the Zend_Amf_response instance - * - * @return Zend_Amf_Server_Response - */ - public function getResponse() - { - if (null === ($response = $this->_response)) { - #require_once 'Zend/Amf/Response/Http.php'; - $this->setResponse(new Zend_Amf_Response_Http()); - } - return $this->_response; - } - - /** - * Attach a class or object to the server - * - * Class may be either a class name or an instantiated object. Reflection - * is done on the class or object to determine the available public - * methods, and each is attached to the server as and available method. If - * a $namespace has been provided, that namespace is used to prefix - * AMF service call. - * - * @param string|object $class - * @param string $namespace Optional - * @param mixed $arg Optional arguments to pass to a method - * @return Zend_Amf_Server - * @throws Zend_Amf_Server_Exception on invalid input - */ - public function setClass($class, $namespace = '', $argv = null) - { - if (is_string($class) && !class_exists($class)){ - #require_once 'Zend/Amf/Server/Exception.php'; - throw new Zend_Amf_Server_Exception('Invalid method or class'); - } elseif (!is_string($class) && !is_object($class)) { - #require_once 'Zend/Amf/Server/Exception.php'; - throw new Zend_Amf_Server_Exception('Invalid method or class; must be a classname or object'); - } - - $args = null; - if (2 < func_num_args()) { - $args = array_slice(func_get_args(), 2); - } - - // Use the class name as the name space by default. - - if ($namespace == '') { - $namespace = is_object($class) ? get_class($class) : $class; - } - - $this->_classAllowed[is_object($class) ? get_class($class) : $class] = true; - - $this->_methods[] = Zend_Server_Reflection::reflectClass($class, $args, $namespace); - $this->_buildDispatchTable(); - - return $this; - } - - /** - * Attach a function to the server - * - * Additional arguments to pass to the function at dispatch may be passed; - * any arguments following the namespace will be aggregated and passed at - * dispatch time. - * - * @param string|array $function Valid callback - * @param string $namespace Optional namespace prefix - * @return Zend_Amf_Server - * @throws Zend_Amf_Server_Exception - */ - public function addFunction($function, $namespace = '') - { - if (!is_string($function) && !is_array($function)) { - #require_once 'Zend/Amf/Server/Exception.php'; - throw new Zend_Amf_Server_Exception('Unable to attach function'); - } - - $argv = null; - if (2 < func_num_args()) { - $argv = array_slice(func_get_args(), 2); - } - - $function = (array) $function; - foreach ($function as $func) { - if (!is_string($func) || !function_exists($func)) { - #require_once 'Zend/Amf/Server/Exception.php'; - throw new Zend_Amf_Server_Exception('Unable to attach function'); - } - $this->_methods[] = Zend_Server_Reflection::reflectFunction($func, $argv, $namespace); - } - - $this->_buildDispatchTable(); - return $this; - } - - - /** - * Creates an array of directories in which services can reside. - * TODO: add support for prefixes? - * - * @param string $dir - */ - public function addDirectory($dir) - { - $this->getLoader()->addPrefixPath("", $dir); - } - - /** - * Returns an array of directories that can hold services. - * - * @return array - */ - public function getDirectory() - { - return $this->getLoader()->getPaths(""); - } - - /** - * (Re)Build the dispatch table - * - * The dispatch table consists of a an array of method name => - * Zend_Server_Reflection_Function_Abstract pairs - * - * @return void - */ - protected function _buildDispatchTable() - { - $table = array(); - foreach ($this->_methods as $key => $dispatchable) { - if ($dispatchable instanceof Zend_Server_Reflection_Function_Abstract) { - $ns = $dispatchable->getNamespace(); - $name = $dispatchable->getName(); - $name = empty($ns) ? $name : $ns . '.' . $name; - - if (isset($table[$name])) { - #require_once 'Zend/Amf/Server/Exception.php'; - throw new Zend_Amf_Server_Exception('Duplicate method registered: ' . $name); - } - $table[$name] = $dispatchable; - continue; - } - - if ($dispatchable instanceof Zend_Server_Reflection_Class) { - foreach ($dispatchable->getMethods() as $method) { - $ns = $method->getNamespace(); - $name = $method->getName(); - $name = empty($ns) ? $name : $ns . '.' . $name; - - if (isset($table[$name])) { - #require_once 'Zend/Amf/Server/Exception.php'; - throw new Zend_Amf_Server_Exception('Duplicate method registered: ' . $name); - } - $table[$name] = $method; - continue; - } - } - } - $this->_table = $table; - } - - - - /** - * Raise a server fault - * - * Unimplemented - * - * @param string|Exception $fault - * @return void - */ - public function fault($fault = null, $code = 404) - { - } - - /** - * Returns a list of registered methods - * - * Returns an array of dispatchables (Zend_Server_Reflection_Function, - * _Method, and _Class items). - * - * @return array - */ - public function getFunctions() - { - return $this->_table; - } - - /** - * Set server persistence - * - * Unimplemented - * - * @param mixed $mode - * @return void - */ - public function setPersistence($mode) - { - } - - /** - * Load server definition - * - * Unimplemented - * - * @param array $definition - * @return void - */ - public function loadFunctions($definition) - { - } - - /** - * Map ActionScript classes to PHP classes - * - * @param string $asClass - * @param string $phpClass - * @return Zend_Amf_Server - */ - public function setClassMap($asClass, $phpClass) - { - #require_once 'Zend/Amf/Parse/TypeLoader.php'; - Zend_Amf_Parse_TypeLoader::setMapping($asClass, $phpClass); - return $this; - } - - /** - * List all available methods - * - * Returns an array of method names. - * - * @return array - */ - public function listMethods() - { - return array_keys($this->_table); - } - - /** - * Cast parameters - * - * Takes the provided parameters from the request, and attempts to cast them - * to objects, if the prototype defines any as explicit object types - * - * @param Reflection $reflectionMethod - * @param array $params - * @return array - */ - protected function _castParameters($reflectionMethod, array $params) - { - $prototypes = $reflectionMethod->getPrototypes(); - $nonObjectTypes = array( - 'null', - 'mixed', - 'void', - 'unknown', - 'bool', - 'boolean', - 'number', - 'int', - 'integer', - 'double', - 'float', - 'string', - 'array', - 'object', - 'stdclass', - ); - $types = array(); - foreach ($prototypes as $prototype) { - foreach ($prototype->getParameters() as $parameter) { - $type = $parameter->getType(); - if (in_array(strtolower($type), $nonObjectTypes)) { - continue; - } - $position = $parameter->getPosition(); - $types[$position] = $type; - } - } - - if (empty($types)) { - return $params; - } - - foreach ($params as $position => $value) { - if (!isset($types[$position])) { - // No specific type to cast to? done - continue; - } - - $type = $types[$position]; - - if (!class_exists($type)) { - // Not a class, apparently. done - continue; - } - - if ($value instanceof $type) { - // Already of the right type? done - continue; - } - - if (!is_array($value) && !is_object($value)) { - // Can't cast scalars to objects easily; done - continue; - } - - // Create instance, and loop through value to set - $object = new $type; - foreach ($value as $property => $defined) { - $object->{$property} = $defined; - } - - $params[$position] = $object; - } - - return $params; - } -} diff --git a/library/Zend/Amf/Server/Exception.php b/library/Zend/Amf/Server/Exception.php deleted file mode 100644 index 6ec77332b1..0000000000 --- a/library/Zend/Amf/Server/Exception.php +++ /dev/null @@ -1,37 +0,0 @@ -_stream = $stream; - $this->_needle = 0; - $this->_mbStringFunctionsOverloaded = function_exists('mb_strlen') && (ini_get('mbstring.func_overload') !== '') && ((int)ini_get('mbstring.func_overload') & 2); - $this->_streamLength = $this->_mbStringFunctionsOverloaded ? mb_strlen($stream, '8bit') : strlen($stream); - $this->_bigEndian = (pack('l', 1) === "\x00\x00\x00\x01"); - } - - /** - * Returns the current stream - * - * @return string - */ - public function getStream() - { - return $this->_stream; - } - - /** - * Read the number of bytes in a row for the length supplied. - * - * @todo Should check that there are enough bytes left in the stream we are about to read. - * @param int $length - * @return string - * @throws Zend_Amf_Exception for buffer underrun - */ - public function readBytes($length) - { - if (($length + $this->_needle) > $this->_streamLength) { - #require_once 'Zend/Amf/Exception.php'; - throw new Zend_Amf_Exception('Buffer underrun at needle position: ' . $this->_needle . ' while requesting length: ' . $length); - } - $bytes = $this->_mbStringFunctionsOverloaded ? mb_substr($this->_stream, $this->_needle, $length, '8bit') : substr($this->_stream, $this->_needle, $length); - $this->_needle+= $length; - return $bytes; - } - - /** - * Write any length of bytes to the stream - * - * Usually a string. - * - * @param string $bytes - * @return Zend_Amf_Util_BinaryStream - */ - public function writeBytes($bytes) - { - $this->_stream.= $bytes; - return $this; - } - - /** - * Reads a signed byte - * - * @return int Value is in the range of -128 to 127. - * @throws Zend_Amf_Exception - */ - public function readByte() - { - if (($this->_needle + 1) > $this->_streamLength) { - #require_once 'Zend/Amf/Exception.php'; - throw new Zend_Amf_Exception( - 'Buffer underrun at needle position: ' - . $this->_needle - . ' while requesting length: ' - . $this->_streamLength - ); - } - - return ord($this->_stream{$this->_needle++}); - } - - /** - * Writes the passed string into a signed byte on the stream. - * - * @param string $stream - * @return Zend_Amf_Util_BinaryStream - */ - public function writeByte($stream) - { - $this->_stream.= pack('c', $stream); - return $this; - } - - /** - * Reads a signed 32-bit integer from the data stream. - * - * @return int Value is in the range of -2147483648 to 2147483647 - */ - public function readInt() - { - return ($this->readByte() << 8) + $this->readByte(); - } - - /** - * Write an the integer to the output stream as a 32 bit signed integer - * - * @param int $stream - * @return Zend_Amf_Util_BinaryStream - */ - public function writeInt($stream) - { - $this->_stream.= pack('n', $stream); - return $this; - } - - /** - * Reads a UTF-8 string from the data stream - * - * @return string A UTF-8 string produced by the byte representation of characters - */ - public function readUtf() - { - $length = $this->readInt(); - return $this->readBytes($length); - } - - /** - * Wite a UTF-8 string to the outputstream - * - * @param string $stream - * @return Zend_Amf_Util_BinaryStream - */ - public function writeUtf($stream) - { - $this->writeInt($this->_mbStringFunctionsOverloaded ? mb_strlen($stream, '8bit') : strlen($stream)); - $this->_stream.= $stream; - return $this; - } - - - /** - * Read a long UTF string - * - * @return string - */ - public function readLongUtf() - { - $length = $this->readLong(); - return $this->readBytes($length); - } - - /** - * Write a long UTF string to the buffer - * - * @param string $stream - * @return Zend_Amf_Util_BinaryStream - */ - public function writeLongUtf($stream) - { - $this->writeLong($this->_mbStringFunctionsOverloaded ? mb_strlen($stream, '8bit') : strlen($stream)); - $this->_stream.= $stream; - } - - /** - * Read a long numeric value - * - * @return double - */ - public function readLong() - { - return ($this->readByte() << 24) + ($this->readByte() << 16) + ($this->readByte() << 8) + $this->readByte(); - } - - /** - * Write long numeric value to output stream - * - * @param int|string $stream - * @return Zend_Amf_Util_BinaryStream - */ - public function writeLong($stream) - { - $this->_stream.= pack('N', $stream); - return $this; - } - - /** - * Read a 16 bit unsigned short. - * - * @todo This could use the unpack() w/ S,n, or v - * @return double - */ - public function readUnsignedShort() - { - $byte1 = $this->readByte(); - $byte2 = $this->readByte(); - return (($byte1 << 8) | $byte2); - } - - /** - * Reads an IEEE 754 double-precision floating point number from the data stream. - * - * @return double Floating point number - */ - public function readDouble() - { - $bytes = $this->_mbStringFunctionsOverloaded ? mb_substr($this->_stream, $this->_needle, 8, '8bit') : substr($this->_stream, $this->_needle, 8); - $this->_needle+= 8; - - if (!$this->_bigEndian) { - $bytes = strrev($bytes); - } - - $double = unpack('dflt', $bytes); - return $double['flt']; - } - - /** - * Writes an IEEE 754 double-precision floating point number from the data stream. - * - * @param string|double $stream - * @return Zend_Amf_Util_BinaryStream - */ - public function writeDouble($stream) - { - $stream = pack('d', $stream); - if (!$this->_bigEndian) { - $stream = strrev($stream); - } - $this->_stream.= $stream; - return $this; - } - -} diff --git a/library/Zend/Amf/Value/ByteArray.php b/library/Zend/Amf/Value/ByteArray.php deleted file mode 100644 index 32ebf268b8..0000000000 --- a/library/Zend/Amf/Value/ByteArray.php +++ /dev/null @@ -1,58 +0,0 @@ -_data = $data; - } - - /** - * Return the byte stream - * - * @return string - */ - public function getData() - { - return $this->_data; - } -} diff --git a/library/Zend/Amf/Value/MessageBody.php b/library/Zend/Amf/Value/MessageBody.php deleted file mode 100644 index 59cacba52b..0000000000 --- a/library/Zend/Amf/Value/MessageBody.php +++ /dev/null @@ -1,182 +0,0 @@ - - * This Message structure defines how a local client would - * invoke a method/operation on a remote server. Additionally, - * the response from the Server is structured identically. - * - * @package Zend_Amf - * @subpackage Value - * @copyright Copyright (c) 2005-2015 Zend Technologies USA Inc. (http://www.zend.com) - * @license http://framework.zend.com/license/new-bsd New BSD License - */ -class Zend_Amf_Value_MessageBody -{ - /** - * A string describing which operation, function, or method - * is to be remotley invoked. - * @var string - */ - protected $_targetUri = ""; - - /** - * Universal Resource Identifier that uniquely targets the originator's - * Object that should receive the server's response. The server will - * use this path specification to target the "OnResult()" or "onStatus()" - * handlers within the client. For Flash, it specifies an ActionScript - * Object path only. The NetResponse object pointed to by the Response Uri - * contains the connection state information. Passing/specifying this - * provides a convenient mechanism for the client/server to share access - * to an object that is managing the state of the shared connection. - * - * Since the server will use this field in the event of an error, - * this field is required even if a successful server request would - * not be expected to return a value to the client. - * - * @var string - */ - protected $_responseUri = ""; - - /** - * Contains the actual data associated with the operation. It contains - * the client's parameter data that is passed to the server's operation/method. - * When serializing a root level data type or a parameter list array, no - * name field is included. That is, the data is anonomously represented - * as "Type Marker"/"Value" pairs. When serializing member data, the data is - * represented as a series of "Name"/"Type"/"Value" combinations. - * - * For server generated responses, it may contain any ActionScript - * data/objects that the server was expected to provide. - * - * @var string - */ - protected $_data; - - /** - * Constructor - * - * @param string $targetUri - * @param string $responseUri - * @param string $data - * @return void - */ - public function __construct($targetUri, $responseUri, $data) - { - $this->setTargetUri($targetUri); - $this->setResponseUri($responseUri); - $this->setData($data); - } - - /** - * Retrieve target Uri - * - * @return string - */ - public function getTargetUri() - { - return $this->_targetUri; - } - - /** - * Set target Uri - * - * @param string $targetUri - * @return Zend_Amf_Value_MessageBody - */ - public function setTargetUri($targetUri) - { - if (null === $targetUri) { - $targetUri = ''; - } - $this->_targetUri = (string) $targetUri; - return $this; - } - - /** - * Get target Uri - * - * @return string - */ - public function getResponseUri() - { - return $this->_responseUri; - } - - /** - * Set response Uri - * - * @param string $responseUri - * @return Zend_Amf_Value_MessageBody - */ - public function setResponseUri($responseUri) - { - if (null === $responseUri) { - $responseUri = ''; - } - $this->_responseUri = $responseUri; - return $this; - } - - /** - * Retrieve response data - * - * @return string - */ - public function getData() - { - return $this->_data; - } - - /** - * Set response data - * - * @param mixed $data - * @return Zend_Amf_Value_MessageBody - */ - public function setData($data) - { - $this->_data = $data; - return $this; - } - - /** - * Set reply method - * - * @param string $methodName - * @return Zend_Amf_Value_MessageBody - */ - public function setReplyMethod($methodName) - { - if (!preg_match('#^[/?]#', $methodName)) { - $this->_targetUri = rtrim($this->_targetUri, '/') . '/'; - } - $this->_targetUri = $this->_targetUri . $methodName; - return $this; - } -} diff --git a/library/Zend/Amf/Value/MessageHeader.php b/library/Zend/Amf/Value/MessageHeader.php deleted file mode 100644 index bdbbba2a7d..0000000000 --- a/library/Zend/Amf/Value/MessageHeader.php +++ /dev/null @@ -1,81 +0,0 @@ -name = $name; - $this->mustRead = (bool) $mustRead; - $this->data = $data; - if (null !== $length) { - $this->length = (int) $length; - } - } -} diff --git a/library/Zend/Amf/Value/Messaging/AbstractMessage.php b/library/Zend/Amf/Value/Messaging/AbstractMessage.php deleted file mode 100644 index acb5a0c6c8..0000000000 --- a/library/Zend/Amf/Value/Messaging/AbstractMessage.php +++ /dev/null @@ -1,92 +0,0 @@ -clientId = $this->generateId(); - $this->destination = null; - $this->messageId = $this->generateId(); - $this->timestamp = time().'00'; - $this->timeToLive = 0; - $this->headers = new STDClass(); - $this->body = null; - - // correleate the two messages - if ($message && isset($message->messageId)) { - $this->correlationId = $message->messageId; - } - } -} diff --git a/library/Zend/Amf/Value/Messaging/ArrayCollection.php b/library/Zend/Amf/Value/Messaging/ArrayCollection.php deleted file mode 100755 index a759f58e53..0000000000 --- a/library/Zend/Amf/Value/Messaging/ArrayCollection.php +++ /dev/null @@ -1,35 +0,0 @@ -body - * of the message. - */ - const LOGIN_OPERATION = 8; - - /** - * This operation is used to log the user out of the current channel, and - * will invalidate the server session if the channel is HTTP based. - */ - const LOGOUT_OPERATION = 9; - - /** - * This operation is used to indicate that the client's subscription to a - * remote destination has been invalidated. - */ - const SESSION_INVALIDATE_OPERATION = 10; - - /** - * This operation is used by the MultiTopicConsumer to subscribe/unsubscribe - * from multiple subtopics/selectors in the same message. - */ - const MULTI_SUBSCRIBE_OPERATION = 11; - - /** - * This operation is used to indicate that a channel has disconnected - */ - const DISCONNECT_OPERATION = 12; - - /** - * This is the default operation for new CommandMessage instances. - */ - const UNKNOWN_OPERATION = 10000; - - /** - * The operation to execute for messages of this type - * @var int - */ - public $operation = self::UNKNOWN_OPERATION; -} diff --git a/library/Zend/Amf/Value/Messaging/ErrorMessage.php b/library/Zend/Amf/Value/Messaging/ErrorMessage.php deleted file mode 100644 index 87b3e384bb..0000000000 --- a/library/Zend/Amf/Value/Messaging/ErrorMessage.php +++ /dev/null @@ -1,67 +0,0 @@ -clientId = $this->generateId(); - $this->destination = null; - $this->messageId = $this->generateId(); - $this->timestamp = time().'00'; - $this->timeToLive = 0; - $this->headers = new stdClass(); - $this->body = null; - } -} diff --git a/library/Zend/Amf/Value/TraitsInfo.php b/library/Zend/Amf/Value/TraitsInfo.php deleted file mode 100644 index 64d3c990ea..0000000000 --- a/library/Zend/Amf/Value/TraitsInfo.php +++ /dev/null @@ -1,154 +0,0 @@ -_className = $className; - $this->_dynamic = $dynamic; - $this->_externalizable = $externalizable; - $this->_properties = $properties; - } - - /** - * Test if the class is a dynamic class - * - * @return boolean - */ - public function isDynamic() - { - return $this->_dynamic; - } - - /** - * Test if class is externalizable - * - * @return boolean - */ - public function isExternalizable() - { - return $this->_externalizable; - } - - /** - * Return the number of properties in the class - * - * @return int - */ - public function length() - { - return count($this->_properties); - } - - /** - * Return the class name - * - * @return string - */ - public function getClassName() - { - return $this->_className; - } - - /** - * Add an additional property - * - * @param string $name - * @return Zend_Amf_Value_TraitsInfo - */ - public function addProperty($name) - { - $this->_properties[] = $name; - return $this; - } - - /** - * Add all properties of the class. - * - * @param array $props - * @return Zend_Amf_Value_TraitsInfo - */ - public function addAllProperties(array $props) - { - $this->_properties = $props; - return $this; - } - - /** - * Get the property at a given index - * - * @param int $index - * @return string - */ - public function getProperty($index) - { - return $this->_properties[(int) $index]; - } - - /** - * Return all properties of the class. - * - * @return array - */ - public function getAllProperties() - { - return $this->_properties; - } -} diff --git a/library/Zend/Application.php b/library/Zend/Application.php deleted file mode 100644 index 052a8a8f39..0000000000 --- a/library/Zend/Application.php +++ /dev/null @@ -1,440 +0,0 @@ -_environment = (string) $environment; - - #require_once 'Zend/Loader/Autoloader.php'; - $this->_autoloader = Zend_Loader_Autoloader::getInstance(); - $this->_autoloader->suppressNotFoundWarnings($suppressNotFoundWarnings); - - if (null !== $options) { - if (is_string($options)) { - $options = $this->_loadConfig($options); - } elseif ($options instanceof Zend_Config) { - $options = $options->toArray(); - } elseif (!is_array($options)) { - throw new Zend_Application_Exception( - 'Invalid options provided; must be location of config file,' - . ' a config object, or an array' - ); - } - - $this->setOptions($options); - } - } - - /** - * Retrieve current environment - * - * @return string - */ - public function getEnvironment() - { - return $this->_environment; - } - - /** - * Retrieve autoloader instance - * - * @return Zend_Loader_Autoloader - */ - public function getAutoloader() - { - return $this->_autoloader; - } - - /** - * Set application options - * - * @param array $options - * @throws Zend_Application_Exception When no bootstrap path is provided - * @throws Zend_Application_Exception When invalid bootstrap information are provided - * @return Zend_Application - */ - public function setOptions(array $options) - { - if (!empty($options['config'])) { - if (is_array($options['config'])) { - $_options = array(); - foreach ($options['config'] as $tmp) { - $_options = $this->mergeOptions( - $_options, $this->_loadConfig($tmp) - ); - } - $options = $this->mergeOptions($_options, $options); - } else { - $options = $this->mergeOptions( - $this->_loadConfig($options['config']), $options - ); - } - } - - $this->_options = $options; - - $options = array_change_key_case($options, CASE_LOWER); - - $this->_optionKeys = array_keys($options); - - if (!empty($options['phpsettings'])) { - $this->setPhpSettings($options['phpsettings']); - } - - if (!empty($options['includepaths'])) { - $this->setIncludePaths($options['includepaths']); - } - - if (!empty($options['autoloadernamespaces'])) { - $this->setAutoloaderNamespaces($options['autoloadernamespaces']); - } - - if (!empty($options['autoloaderzfpath'])) { - $autoloader = $this->getAutoloader(); - if (method_exists($autoloader, 'setZfPath')) { - $zfPath = $options['autoloaderzfpath']; - $zfVersion = !empty($options['autoloaderzfversion']) - ? $options['autoloaderzfversion'] - : 'latest'; - $autoloader->setZfPath($zfPath, $zfVersion); - } - } - - if (!empty($options['bootstrap'])) { - $bootstrap = $options['bootstrap']; - - if (is_string($bootstrap)) { - $this->setBootstrap($bootstrap); - } elseif (is_array($bootstrap)) { - if (empty($bootstrap['path'])) { - throw new Zend_Application_Exception( - 'No bootstrap path provided' - ); - } - - $path = $bootstrap['path']; - $class = null; - - if (!empty($bootstrap['class'])) { - $class = $bootstrap['class']; - } - - $this->setBootstrap($path, $class); - } else { - throw new Zend_Application_Exception( - 'Invalid bootstrap information provided' - ); - } - } - - return $this; - } - - /** - * Retrieve application options (for caching) - * - * @return array - */ - public function getOptions() - { - return $this->_options; - } - - /** - * Is an option present? - * - * @param string $key - * @return bool - */ - public function hasOption($key) - { - return in_array(strtolower($key), $this->_optionKeys); - } - - /** - * Retrieve a single option - * - * @param string $key - * @return mixed - */ - public function getOption($key) - { - if ($this->hasOption($key)) { - $options = $this->getOptions(); - $options = array_change_key_case($options, CASE_LOWER); - return $options[strtolower($key)]; - } - return null; - } - - /** - * Merge options recursively - * - * @param array $array1 - * @param mixed $array2 - * @return array - */ - public function mergeOptions(array $array1, $array2 = null) - { - if (is_array($array2)) { - foreach ($array2 as $key => $val) { - if (is_array($array2[$key])) { - $array1[$key] = (array_key_exists($key, $array1) && is_array($array1[$key])) - ? $this->mergeOptions($array1[$key], $array2[$key]) - : $array2[$key]; - } else { - $array1[$key] = $val; - } - } - } - return $array1; - } - - /** - * Set PHP configuration settings - * - * @param array $settings - * @param string $prefix Key prefix to prepend to array values (used to map . separated INI values) - * @return Zend_Application - */ - public function setPhpSettings(array $settings, $prefix = '') - { - foreach ($settings as $key => $value) { - $key = empty($prefix) ? $key : $prefix . $key; - if (is_scalar($value)) { - ini_set($key, $value); - } elseif (is_array($value)) { - $this->setPhpSettings($value, $key . '.'); - } - } - - return $this; - } - - /** - * Set include path - * - * @param array $paths - * @return Zend_Application - */ - public function setIncludePaths(array $paths) - { - $path = implode(PATH_SEPARATOR, $paths); - set_include_path($path . PATH_SEPARATOR . get_include_path()); - return $this; - } - - /** - * Set autoloader namespaces - * - * @param array $namespaces - * @return Zend_Application - */ - public function setAutoloaderNamespaces(array $namespaces) - { - $autoloader = $this->getAutoloader(); - - foreach ($namespaces as $namespace) { - $autoloader->registerNamespace($namespace); - } - - return $this; - } - - /** - * Set bootstrap path/class - * - * @param string $path - * @param string $class - * @return Zend_Application - */ - public function setBootstrap($path, $class = null) - { - // setOptions() can potentially send a null value; specify default - // here - if (null === $class) { - $class = 'Bootstrap'; - } - - if (!class_exists($class, false)) { - #require_once $path; - if (!class_exists($class, false)) { - throw new Zend_Application_Exception( - 'Bootstrap class not found' - ); - } - } - $this->_bootstrap = new $class($this); - - if (!$this->_bootstrap instanceof Zend_Application_Bootstrap_Bootstrapper) { - throw new Zend_Application_Exception( - 'Bootstrap class does not implement' - . ' Zend_Application_Bootstrap_Bootstrapper' - ); - } - - return $this; - } - - /** - * Get bootstrap object - * - * @return Zend_Application_Bootstrap_BootstrapAbstract - */ - public function getBootstrap() - { - if (null === $this->_bootstrap) { - $this->_bootstrap = new Zend_Application_Bootstrap_Bootstrap($this); - } - return $this->_bootstrap; - } - - /** - * Bootstrap application - * - * @param null|string|array $resource - * @return Zend_Application - */ - public function bootstrap($resource = null) - { - $this->getBootstrap()->bootstrap($resource); - return $this; - } - - /** - * Run the application - * - * @return void - */ - public function run() - { - $this->getBootstrap()->run(); - } - - /** - * Load configuration file of options - * - * @param string $file - * @throws Zend_Application_Exception When invalid configuration file is provided - * @return array - */ - protected function _loadConfig($file) - { - $environment = $this->getEnvironment(); - $suffix = pathinfo($file, PATHINFO_EXTENSION); - $suffix = ($suffix === 'dist') - ? pathinfo(basename($file, ".$suffix"), PATHINFO_EXTENSION) - : $suffix; - - switch (strtolower($suffix)) { - case 'ini': - $config = new Zend_Config_Ini($file, $environment); - break; - - case 'xml': - $config = new Zend_Config_Xml($file, $environment); - break; - - case 'json': - $config = new Zend_Config_Json($file, $environment); - break; - - case 'yaml': - case 'yml': - $config = new Zend_Config_Yaml($file, $environment); - break; - - case 'php': - case 'inc': - $config = include $file; - if (!is_array($config)) { - throw new Zend_Application_Exception( - 'Invalid configuration file provided; PHP file does not' - . ' return array value' - ); - } - return $config; - break; - - default: - throw new Zend_Application_Exception( - 'Invalid configuration file provided; unknown config type' - ); - } - - return $config->toArray(); - } -} diff --git a/library/Zend/Application/Bootstrap/Bootstrap.php b/library/Zend/Application/Bootstrap/Bootstrap.php deleted file mode 100644 index 6f09afbc20..0000000000 --- a/library/Zend/Application/Bootstrap/Bootstrap.php +++ /dev/null @@ -1,168 +0,0 @@ -hasOption('resourceloader')) { - $this->setOptions( - array( - 'resourceloader' => $application->getOption( - 'resourceloader' - ) - ) - ); - } - $this->getResourceLoader(); - - if (!$this->hasPluginResource('FrontController')) { - $this->registerPluginResource('FrontController'); - } - } - - /** - * Run the application - * - * Checks to see that we have a default controller directory. If not, an - * exception is thrown. - * - * If so, it registers the bootstrap with the 'bootstrap' parameter of - * the front controller, and dispatches the front controller. - * - * @return mixed - * @throws Zend_Application_Bootstrap_Exception - */ - public function run() - { - $front = $this->getResource('FrontController'); - $default = $front->getDefaultModule(); - if (null === $front->getControllerDirectory($default)) { - throw new Zend_Application_Bootstrap_Exception( - 'No default controller directory registered with front controller' - ); - } - - $front->setParam('bootstrap', $this); - $response = $front->dispatch(); - if ($front->returnResponse()) { - return $response; - } - } - - /** - * Set module resource loader - * - * @param Zend_Loader_Autoloader_Resource $loader - * @return Zend_Application_Module_Bootstrap - */ - public function setResourceLoader(Zend_Loader_Autoloader_Resource $loader) - { - $this->_resourceLoader = $loader; - return $this; - } - - /** - * Retrieve module resource loader - * - * @return Zend_Loader_Autoloader_Resource - */ - public function getResourceLoader() - { - if ((null === $this->_resourceLoader) - && (false !== ($namespace = $this->getAppNamespace())) - ) { - $r = new ReflectionClass($this); - $path = $r->getFileName(); - $this->setResourceLoader( - new Zend_Application_Module_Autoloader( - array( - 'namespace' => $namespace, - 'basePath' => dirname($path), - ) - ) - ); - } - return $this->_resourceLoader; - } - - /** - * Get application namespace (used for module autoloading) - * - * @return string - */ - public function getAppNamespace() - { - return $this->_appNamespace; - } - - /** - * Set application namespace (for module autoloading) - * - * @param string - * @return Zend_Application_Bootstrap_Bootstrap - */ - public function setAppNamespace($value) - { - $this->_appNamespace = (string) $value; - return $this; - } -} diff --git a/library/Zend/Application/Bootstrap/BootstrapAbstract.php b/library/Zend/Application/Bootstrap/BootstrapAbstract.php deleted file mode 100644 index cec7c2e3c9..0000000000 --- a/library/Zend/Application/Bootstrap/BootstrapAbstract.php +++ /dev/null @@ -1,784 +0,0 @@ -setApplication($application); - $options = $application->getOptions(); - $this->setOptions($options); - } - - /** - * Set class state - * - * @param array $options - * @return Zend_Application_Bootstrap_BootstrapAbstract - */ - public function setOptions(array $options) - { - $this->_options = $this->mergeOptions($this->_options, $options); - - $options = array_change_key_case($options, CASE_LOWER); - $this->_optionKeys = array_merge($this->_optionKeys, array_keys($options)); - - $methods = get_class_methods($this); - foreach ($methods as $key => $method) { - $methods[$key] = strtolower($method); - } - - if (array_key_exists('pluginpaths', $options)) { - $pluginLoader = $this->getPluginLoader(); - - foreach ($options['pluginpaths'] as $prefix => $path) { - $pluginLoader->addPrefixPath($prefix, $path); - } - unset($options['pluginpaths']); - } - - foreach ($options as $key => $value) { - $method = 'set' . strtolower($key); - - if (in_array($method, $methods)) { - $this->$method($value); - } elseif ('resources' == $key) { - foreach ($value as $resource => $resourceOptions) { - $this->registerPluginResource($resource, $resourceOptions); - } - } - } - return $this; - } - - /** - * Get current options from bootstrap - * - * @return array - */ - public function getOptions() - { - return $this->_options; - } - - /** - * Is an option present? - * - * @param string $key - * @return bool - */ - public function hasOption($key) - { - return in_array(strtolower($key), $this->_optionKeys); - } - - /** - * Retrieve a single option - * - * @param string $key - * @return mixed - */ - public function getOption($key) - { - if ($this->hasOption($key)) { - $options = $this->getOptions(); - $options = array_change_key_case($options, CASE_LOWER); - return $options[strtolower($key)]; - } - return null; - } - - /** - * Merge options recursively - * - * @param array $array1 - * @param mixed $array2 - * @return array - */ - public function mergeOptions(array $array1, $array2 = null) - { - if (is_array($array2)) { - foreach ($array2 as $key => $val) { - if (is_array($array2[$key])) { - $array1[$key] = (array_key_exists($key, $array1) && is_array($array1[$key])) - ? $this->mergeOptions($array1[$key], $array2[$key]) - : $array2[$key]; - } else { - $array1[$key] = $val; - } - } - } - return $array1; - } - - /** - * Get class resources (as resource/method pairs) - * - * Uses get_class_methods() by default, reflection on prior to 5.2.6, - * as a bug prevents the usage of get_class_methods() there. - * - * @return array - */ - public function getClassResources() - { - if (null === $this->_classResources) { - if (version_compare(PHP_VERSION, '5.2.6') === -1) { - $class = new ReflectionObject($this); - $classMethods = $class->getMethods(); - $methodNames = array(); - - foreach ($classMethods as $method) { - $methodNames[] = $method->getName(); - } - } else { - $methodNames = get_class_methods($this); - } - - $this->_classResources = array(); - foreach ($methodNames as $method) { - if (5 < strlen($method) && '_init' === substr($method, 0, 5)) { - $this->_classResources[strtolower(substr($method, 5))] = $method; - } - } - } - - return $this->_classResources; - } - - /** - * Get class resource names - * - * @return array - */ - public function getClassResourceNames() - { - $resources = $this->getClassResources(); - return array_keys($resources); - } - - /** - * Register a new resource plugin - * - * @param string|Zend_Application_Resource_Resource $resource - * @param mixed $options - * @return Zend_Application_Bootstrap_BootstrapAbstract - * @throws Zend_Application_Bootstrap_Exception When invalid resource is provided - */ - public function registerPluginResource($resource, $options = null) - { - if ($resource instanceof Zend_Application_Resource_Resource) { - $resource->setBootstrap($this); - $pluginName = $this->_resolvePluginResourceName($resource); - $this->_pluginResources[$pluginName] = $resource; - return $this; - } - - if (!is_string($resource)) { - throw new Zend_Application_Bootstrap_Exception('Invalid resource provided to ' . __METHOD__); - } - - $this->_pluginResources[$resource] = $options; - return $this; - } - - /** - * Unregister a resource from the bootstrap - * - * @param string|Zend_Application_Resource_Resource $resource - * @return Zend_Application_Bootstrap_BootstrapAbstract - * @throws Zend_Application_Bootstrap_Exception When unknown resource type is provided - */ - public function unregisterPluginResource($resource) - { - if ($resource instanceof Zend_Application_Resource_Resource) { - if ($index = array_search($resource, $this->_pluginResources, true)) { - unset($this->_pluginResources[$index]); - } - return $this; - } - - if (!is_string($resource)) { - throw new Zend_Application_Bootstrap_Exception('Unknown resource type provided to ' . __METHOD__); - } - - $resource = strtolower($resource); - if (array_key_exists($resource, $this->_pluginResources)) { - unset($this->_pluginResources[$resource]); - } - - return $this; - } - - /** - * Is the requested plugin resource registered? - * - * @param string $resource - * @return bool - */ - public function hasPluginResource($resource) - { - return (null !== $this->getPluginResource($resource)); - } - - /** - * Get a registered plugin resource - * - * @param string $resource - * @return Zend_Application_Resource_Resource - * @throws Zend_Application_Bootstrap_Exception - */ - public function getPluginResource($resource) - { - if (array_key_exists(strtolower($resource), $this->_pluginResources)) { - $resource = strtolower($resource); - if (!$this->_pluginResources[$resource] instanceof Zend_Application_Resource_Resource) { - $resourceName = $this->_loadPluginResource($resource, $this->_pluginResources[$resource]); - if (!$resourceName) { - throw new Zend_Application_Bootstrap_Exception(sprintf('Unable to resolve plugin "%s"; no corresponding plugin with that name', $resource)); - } - $resource = $resourceName; - } - return $this->_pluginResources[$resource]; - } - - foreach ($this->_pluginResources as $plugin => $spec) { - if ($spec instanceof Zend_Application_Resource_Resource) { - $pluginName = $this->_resolvePluginResourceName($spec); - if (0 === strcasecmp($resource, $pluginName)) { - unset($this->_pluginResources[$plugin]); - $this->_pluginResources[$pluginName] = $spec; - return $spec; - } - continue; - } - - if (false !== $pluginName = $this->_loadPluginResource($plugin, $spec)) { - if (0 === strcasecmp($resource, $pluginName)) { - return $this->_pluginResources[$pluginName]; - } - continue; - } - - if (class_exists($plugin) - && is_subclass_of($plugin, 'Zend_Application_Resource_Resource') - ) { //@SEE ZF-7550 - $spec = (array) $spec; - $spec['bootstrap'] = $this; - $instance = new $plugin($spec); - $pluginName = $this->_resolvePluginResourceName($instance); - unset($this->_pluginResources[$plugin]); - $this->_pluginResources[$pluginName] = $instance; - - if (0 === strcasecmp($resource, $pluginName)) { - return $instance; - } - } - } - - return null; - } - - /** - * Retrieve all plugin resources - * - * @return array - */ - public function getPluginResources() - { - foreach (array_keys($this->_pluginResources) as $resource) { - $this->getPluginResource($resource); - } - return $this->_pluginResources; - } - - /** - * Retrieve plugin resource names - * - * @return array - */ - public function getPluginResourceNames() - { - $this->getPluginResources(); - return array_keys($this->_pluginResources); - } - - /** - * Set plugin loader for loading resources - * - * @param Zend_Loader_PluginLoader_Interface $loader - * @return Zend_Application_Bootstrap_BootstrapAbstract - */ - public function setPluginLoader(Zend_Loader_PluginLoader_Interface $loader) - { - $this->_pluginLoader = $loader; - return $this; - } - - /** - * Get the plugin loader for resources - * - * @return Zend_Loader_PluginLoader_Interface - */ - public function getPluginLoader() - { - if ($this->_pluginLoader === null) { - $options = array( - 'Zend_Application_Resource' => 'Zend/Application/Resource', - 'ZendX_Application_Resource' => 'ZendX/Application/Resource' - ); - - $this->_pluginLoader = new Zend_Loader_PluginLoader($options); - } - - return $this->_pluginLoader; - } - - /** - * Set application/parent bootstrap - * - * @param Zend_Application|Zend_Application_Bootstrap_Bootstrapper $application - * @return Zend_Application_Bootstrap_BootstrapAbstract - * @throws Zend_Application_Bootstrap_Exception - */ - public function setApplication($application) - { - if (($application instanceof Zend_Application) - || ($application instanceof Zend_Application_Bootstrap_Bootstrapper) - ) { - if ($application === $this) { - throw new Zend_Application_Bootstrap_Exception('Cannot set application to same object; creates recursion'); - } - $this->_application = $application; - } else { - throw new Zend_Application_Bootstrap_Exception('Invalid application provided to bootstrap constructor (received "' . get_class($application) . '" instance)'); - } - return $this; - } - - /** - * Retrieve parent application instance - * - * @return Zend_Application|Zend_Application_Bootstrap_Bootstrapper - */ - public function getApplication() - { - return $this->_application; - } - - /** - * Retrieve application environment - * - * @return string - */ - public function getEnvironment() - { - if (null === $this->_environment) { - $this->_environment = $this->getApplication()->getEnvironment(); - } - return $this->_environment; - } - - /** - * Set resource container - * - * By default, if a resource callback has a non-null return value, this - * value will be stored in a container using the resource name as the - * key. - * - * Containers must be objects, and must allow setting public properties. - * - * @param object $container - * @return Zend_Application_Bootstrap_BootstrapAbstract - * @throws Zend_Application_Bootstrap_Exception - */ - public function setContainer($container) - { - if (!is_object($container)) { - throw new Zend_Application_Bootstrap_Exception('Resource containers must be objects'); - } - $this->_container = $container; - return $this; - } - - /** - * Retrieve resource container - * - * @return object - */ - public function getContainer() - { - if (null === $this->_container) { - $this->setContainer(new Zend_Registry()); - } - return $this->_container; - } - - /** - * Determine if a resource has been stored in the container - * - * During bootstrap resource initialization, you may return a value. If - * you do, it will be stored in the {@link setContainer() container}. - * You can use this method to determine if a value was stored. - * - * @param string $name - * @return bool - */ - public function hasResource($name) - { - $resource = strtolower($name); - $container = $this->getContainer(); - return isset($container->{$resource}); - } - - /** - * Retrieve a resource from the container - * - * During bootstrap resource initialization, you may return a value. If - * you do, it will be stored in the {@link setContainer() container}. - * You can use this method to retrieve that value. - * - * If no value was returned, this will return a null value. - * - * @param string $name - * @return null|mixed - */ - public function getResource($name) - { - $resource = strtolower($name); - $container = $this->getContainer(); - if ($this->hasResource($resource)) { - return $container->{$resource}; - } - return null; - } - - /** - * Implement PHP's magic to retrieve a resource - * in the bootstrap - * - * @param string $prop - * @return null|mixed - */ - public function __get($prop) - { - return $this->getResource($prop); - } - - /** - * Implement PHP's magic to ask for the - * existence of a resource in the bootstrap - * - * @param string $prop - * @return bool - */ - public function __isset($prop) - { - return $this->hasResource($prop); - } - - /** - * Bootstrap individual, all, or multiple resources - * - * Marked as final to prevent issues when subclassing and naming the - * child class 'Bootstrap' (in which case, overriding this method - * would result in it being treated as a constructor). - * - * If you need to override this functionality, override the - * {@link _bootstrap()} method. - * - * @param null|string|array $resource - * @return Zend_Application_Bootstrap_BootstrapAbstract - * @throws Zend_Application_Bootstrap_Exception When invalid argument was passed - */ - final public function bootstrap($resource = null) - { - $this->_bootstrap($resource); - return $this; - } - - /** - * Overloading: intercept calls to bootstrap() methods - * - * @param string $method - * @param array $args - * @return Zend_Application_Bootstrap_BootstrapAbstract - * @throws Zend_Application_Bootstrap_Exception On invalid method name - */ - public function __call($method, $args) - { - if (9 < strlen($method) && 'bootstrap' === substr($method, 0, 9)) { - $resource = substr($method, 9); - return $this->bootstrap($resource); - } - - throw new Zend_Application_Bootstrap_Exception('Invalid method "' . $method . '"'); - } - - /** - * Bootstrap implementation - * - * This method may be overridden to provide custom bootstrapping logic. - * It is the sole method called by {@link bootstrap()}. - * - * @param null|string|array $resource - * @return void - * @throws Zend_Application_Bootstrap_Exception When invalid argument was passed - */ - protected function _bootstrap($resource = null) - { - if (null === $resource) { - foreach ($this->getClassResourceNames() as $resource) { - $this->_executeResource($resource); - } - - foreach ($this->getPluginResourceNames() as $resource) { - $this->_executeResource($resource); - } - } elseif (is_string($resource)) { - $this->_executeResource($resource); - } elseif (is_array($resource)) { - foreach ($resource as $r) { - $this->_executeResource($r); - } - } else { - throw new Zend_Application_Bootstrap_Exception('Invalid argument passed to ' . __METHOD__); - } - } - - /** - * Execute a resource - * - * Checks to see if the resource has already been run. If not, it searches - * first to see if a local method matches the resource, and executes that. - * If not, it checks to see if a plugin resource matches, and executes that - * if found. - * - * Finally, if not found, it throws an exception. - * - * @param string $resource - * @return void - * @throws Zend_Application_Bootstrap_Exception When resource not found - */ - protected function _executeResource($resource) - { - $resourceName = strtolower($resource); - - if (in_array($resourceName, $this->_run)) { - return; - } - - if (isset($this->_started[$resourceName]) && $this->_started[$resourceName]) { - throw new Zend_Application_Bootstrap_Exception('Circular resource dependency detected'); - } - - $classResources = $this->getClassResources(); - if (array_key_exists($resourceName, $classResources)) { - $this->_started[$resourceName] = true; - $method = $classResources[$resourceName]; - $return = $this->$method(); - unset($this->_started[$resourceName]); - $this->_markRun($resourceName); - - if (null !== $return) { - $this->getContainer()->{$resourceName} = $return; - } - - return; - } - - if ($this->hasPluginResource($resource)) { - $this->_started[$resourceName] = true; - $plugin = $this->getPluginResource($resource); - $return = $plugin->init(); - unset($this->_started[$resourceName]); - $this->_markRun($resourceName); - - if (null !== $return) { - $this->getContainer()->{$resourceName} = $return; - } - - return; - } - - throw new Zend_Application_Bootstrap_Exception('Resource matching "' . $resource . '" not found'); - } - - /** - * Load a plugin resource - * - * @param string $resource - * @param array|object|null $options - * @return string|false - */ - protected function _loadPluginResource($resource, $options) - { - $options = (array) $options; - $options['bootstrap'] = $this; - $className = $this->getPluginLoader()->load(strtolower($resource), false); - - if (!$className) { - return false; - } - - $instance = new $className($options); - - unset($this->_pluginResources[$resource]); - - if (isset($instance->_explicitType)) { - $resource = $instance->_explicitType; - } - $resource = strtolower($resource); - $this->_pluginResources[$resource] = $instance; - - return $resource; - } - - /** - * Mark a resource as having run - * - * @param string $resource - * @return void - */ - protected function _markRun($resource) - { - if (!in_array($resource, $this->_run)) { - $this->_run[] = $resource; - } - } - - /** - * Resolve a plugin resource name - * - * Uses, in order of preference - * - $_explicitType property of resource - * - Short name of resource (if a matching prefix path is found) - * - class name (if none of the above are true) - * - * The name is then cast to lowercase. - * - * @param Zend_Application_Resource_Resource $resource - * @return string - */ - protected function _resolvePluginResourceName($resource) - { - if (isset($resource->_explicitType)) { - $pluginName = $resource->_explicitType; - } else { - $className = get_class($resource); - $pluginName = $className; - $loader = $this->getPluginLoader(); - foreach ($loader->getPaths() as $prefix => $paths) { - if (0 === strpos($className, $prefix)) { - $pluginName = substr($className, strlen($prefix)); - $pluginName = trim($pluginName, '_'); - break; - } - } - } - $pluginName = strtolower($pluginName); - return $pluginName; - } -} diff --git a/library/Zend/Application/Bootstrap/Bootstrapper.php b/library/Zend/Application/Bootstrap/Bootstrapper.php deleted file mode 100644 index edf56d15e2..0000000000 --- a/library/Zend/Application/Bootstrap/Bootstrapper.php +++ /dev/null @@ -1,93 +0,0 @@ -initDefaultResourceTypes(); - } - - /** - * Initialize default resource types for module resource classes - * - * @return void - */ - public function initDefaultResourceTypes() - { - $basePath = $this->getBasePath(); - $this->addResourceTypes( - array( - 'dbtable' => array( - 'namespace' => 'Model_DbTable', - 'path' => 'models/DbTable', - ), - 'mappers' => array( - 'namespace' => 'Model_Mapper', - 'path' => 'models/mappers', - ), - 'form' => array( - 'namespace' => 'Form', - 'path' => 'forms', - ), - 'model' => array( - 'namespace' => 'Model', - 'path' => 'models', - ), - 'plugin' => array( - 'namespace' => 'Plugin', - 'path' => 'plugins', - ), - 'service' => array( - 'namespace' => 'Service', - 'path' => 'services', - ), - 'viewhelper' => array( - 'namespace' => 'View_Helper', - 'path' => 'views/helpers', - ), - 'viewfilter' => array( - 'namespace' => 'View_Filter', - 'path' => 'views/filters', - ), - ) - ); - $this->setDefaultResourceType('model'); - } -} diff --git a/library/Zend/Application/Module/Bootstrap.php b/library/Zend/Application/Module/Bootstrap.php deleted file mode 100644 index bbadb95a70..0000000000 --- a/library/Zend/Application/Module/Bootstrap.php +++ /dev/null @@ -1,127 +0,0 @@ -setApplication($application); - - // Use same plugin loader as parent bootstrap - if ($application instanceof Zend_Application_Bootstrap_ResourceBootstrapper) { - $this->setPluginLoader($application->getPluginLoader()); - } - - $key = strtolower($this->getModuleName()); - if ($application->hasOption($key)) { - // Don't run via setOptions() to prevent duplicate initialization - $this->setOptions($application->getOption($key)); - } - - if ($application->hasOption('resourceloader')) { - $this->setOptions(array( - 'resourceloader' => $application->getOption('resourceloader') - )); - } - $this->initResourceLoader(); - - // ZF-6545: ensure front controller resource is loaded - if (!$this->hasPluginResource('FrontController')) { - $this->registerPluginResource('FrontController'); - } - - // ZF-6545: prevent recursive registration of modules - if ($this->hasPluginResource('modules')) { - $this->unregisterPluginResource('modules'); - } - } - - /** - * Ensure resource loader is loaded - * - * @return void - */ - public function initResourceLoader() - { - $this->getResourceLoader(); - } - - /** - * Get default application namespace - * - * Proxies to {@link getModuleName()}, and returns the current module - * name - * - * @return string - */ - public function getAppNamespace() - { - return $this->getModuleName(); - } - - /** - * Retrieve module name - * - * @return string - */ - public function getModuleName() - { - if (empty($this->_moduleName)) { - $class = get_class($this); - if (preg_match('/^([a-z][a-z0-9]*)_/i', $class, $matches)) { - $prefix = $matches[1]; - } else { - $prefix = $class; - } - $this->_moduleName = $prefix; - } - return $this->_moduleName; - } -} diff --git a/library/Zend/Application/Resource/Cachemanager.php b/library/Zend/Application/Resource/Cachemanager.php deleted file mode 100644 index aa1bdc308d..0000000000 --- a/library/Zend/Application/Resource/Cachemanager.php +++ /dev/null @@ -1,82 +0,0 @@ -getCacheManager(); - } - - /** - * Retrieve Zend_Cache_Manager instance - * - * @return Zend_Cache_Manager - */ - public function getCacheManager() - { - if (null === $this->_manager) { - $this->_manager = new Zend_Cache_Manager; - - $options = $this->getOptions(); - foreach ($options as $key => $value) { - // Logger - if (isset($value['frontend']['options']['logger'])) { - $logger = $value['frontend']['options']['logger']; - if (is_array($logger)) { - $value['frontend']['options']['logger'] = Zend_Log::factory($logger); - } - } - - // Cache templates - if ($this->_manager->hasCacheTemplate($key)) { - $this->_manager->setTemplateOptions($key, $value); - } else { - $this->_manager->setCacheTemplate($key, $value); - } - } - } - - return $this->_manager; - } -} diff --git a/library/Zend/Application/Resource/Db.php b/library/Zend/Application/Resource/Db.php deleted file mode 100644 index 2747368758..0000000000 --- a/library/Zend/Application/Resource/Db.php +++ /dev/null @@ -1,198 +0,0 @@ -_adapter = $adapter; - return $this; - } - - /** - * Adapter type to use - * - * @return string - */ - public function getAdapter() - { - return $this->_adapter; - } - - /** - * Set the adapter params - * - * @param array $params - * @return Zend_Application_Resource_Db - */ - public function setParams(array $params) - { - $this->_params = $params; - return $this; - } - - /** - * Adapter parameters - * - * @return array - */ - public function getParams() - { - return $this->_params; - } - - /** - * Set whether to use this as default table adapter - * - * @param bool $isDefaultTableAdapter - * @return Zend_Application_Resource_Db - */ - public function setIsDefaultTableAdapter($isDefaultTableAdapter) - { - $this->_isDefaultTableAdapter = $isDefaultTableAdapter; - return $this; - } - - /** - * Is this adapter the default table adapter? - * - * @return bool - */ - public function isDefaultTableAdapter() - { - return $this->_isDefaultTableAdapter; - } - - /** - * Retrieve initialized DB connection - * - * @return null|Zend_Db_Adapter_Abstract - */ - public function getDbAdapter() - { - if ((null === $this->_db) - && (null !== ($adapter = $this->getAdapter())) - ) { - $this->_db = Zend_Db::factory($adapter, $this->getParams()); - - if ($this->_db instanceof Zend_Db_Adapter_Abstract - && $this->isDefaultTableAdapter() - ) { - Zend_Db_Table::setDefaultAdapter($this->_db); - } - } - return $this->_db; - } - - /** - * Defined by Zend_Application_Resource_Resource - * - * @return Zend_Db_Adapter_Abstract|null - */ - public function init() - { - if (null !== ($db = $this->getDbAdapter())) { - return $db; - } - - return null; - } - - /** - * Set the default metadata cache - * - * @param string|Zend_Cache_Core $cache - * @return Zend_Application_Resource_Db - */ - public function setDefaultMetadataCache($cache) - { - $metadataCache = null; - - if (is_string($cache)) { - $bootstrap = $this->getBootstrap(); - if ($bootstrap instanceof Zend_Application_Bootstrap_ResourceBootstrapper - && $bootstrap->hasPluginResource('CacheManager') - ) { - $cacheManager = $bootstrap->bootstrap('CacheManager') - ->getResource('CacheManager'); - if (null !== $cacheManager && $cacheManager->hasCache($cache)) { - $metadataCache = $cacheManager->getCache($cache); - } - } - } else if ($cache instanceof Zend_Cache_Core) { - $metadataCache = $cache; - } - - if ($metadataCache instanceof Zend_Cache_Core) { - Zend_Db_Table::setDefaultMetadataCache($metadataCache); - } - - return $this; - } -} diff --git a/library/Zend/Application/Resource/Dojo.php b/library/Zend/Application/Resource/Dojo.php deleted file mode 100644 index b5437550c5..0000000000 --- a/library/Zend/Application/Resource/Dojo.php +++ /dev/null @@ -1,76 +0,0 @@ -getDojo(); - } - - /** - * Retrieve Dojo View Helper - * - * @return Zend_Dojo_View_Dojo_Container - */ - public function getDojo() - { - if (null === $this->_dojo) { - $this->getBootstrap()->bootstrap('view'); - $view = $this->getBootstrap()->view; - - Zend_Dojo::enableView($view); - $view->dojo()->setOptions($this->getOptions()); - - $this->_dojo = $view->dojo(); - } - - return $this->_dojo; - } -} diff --git a/library/Zend/Application/Resource/Exception.php b/library/Zend/Application/Resource/Exception.php deleted file mode 100644 index 0a57c78fd4..0000000000 --- a/library/Zend/Application/Resource/Exception.php +++ /dev/null @@ -1,40 +0,0 @@ -getFrontController(); - - foreach ($this->getOptions() as $key => $value) { - switch (strtolower($key)) { - case 'controllerdirectory': - if (is_string($value)) { - $front->setControllerDirectory($value); - } elseif (is_array($value)) { - foreach ($value as $module => $directory) { - $front->addControllerDirectory($directory, $module); - } - } - break; - - case 'modulecontrollerdirectoryname': - $front->setModuleControllerDirectoryName($value); - break; - - case 'moduledirectory': - if (is_string($value)) { - $front->addModuleDirectory($value); - } elseif (is_array($value)) { - foreach ($value as $moduleDir) { - $front->addModuleDirectory($moduleDir); - } - } - break; - - case 'defaultcontrollername': - $front->setDefaultControllerName($value); - break; - - case 'defaultaction': - $front->setDefaultAction($value); - break; - - case 'defaultmodule': - $front->setDefaultModule($value); - break; - - case 'baseurl': - if (!empty($value)) { - $front->setBaseUrl($value); - } - break; - - case 'params': - $front->setParams($value); - break; - - case 'plugins': - foreach ((array) $value as $pluginClass) { - $stackIndex = null; - if (is_array($pluginClass)) { - $pluginClass = array_change_key_case($pluginClass, CASE_LOWER); - if (isset($pluginClass['class'])) { - if (isset($pluginClass['stackindex'])) { - $stackIndex = $pluginClass['stackindex']; - } - - $pluginClass = $pluginClass['class']; - } - } - - $plugin = new $pluginClass(); - $front->registerPlugin($plugin, $stackIndex); - } - break; - - case 'returnresponse': - $front->returnResponse((bool) $value); - break; - - case 'throwexceptions': - $front->throwExceptions((bool) $value); - break; - - case 'actionhelperpaths': - if (is_array($value)) { - foreach ($value as $helperPrefix => $helperPath) { - Zend_Controller_Action_HelperBroker::addPath($helperPath, $helperPrefix); - } - } - break; - - case 'dispatcher': - if (!isset($value['class'])) { - #require_once 'Zend/Application/Exception.php'; - throw new Zend_Application_Exception('You must specify both '); - } - if (!isset($value['params'])) { - $value['params'] = array(); - } - - $dispatchClass = $value['class']; - if (!class_exists($dispatchClass)) { - #require_once 'Zend/Application/Exception.php'; - throw new Zend_Application_Exception('Dispatcher class not found!'); - } - $front->setDispatcher(new $dispatchClass((array)$value['params'])); - break; - default: - $front->setParam($key, $value); - break; - } - } - - if (null !== ($bootstrap = $this->getBootstrap())) { - $this->getBootstrap()->frontController = $front; - } - - return $front; - } - - /** - * Retrieve front controller instance - * - * @return Zend_Controller_Front - */ - public function getFrontController() - { - if (null === $this->_front) { - $this->_front = Zend_Controller_Front::getInstance(); - } - return $this->_front; - } -} diff --git a/library/Zend/Application/Resource/Layout.php b/library/Zend/Application/Resource/Layout.php deleted file mode 100644 index a19b2913f2..0000000000 --- a/library/Zend/Application/Resource/Layout.php +++ /dev/null @@ -1,70 +0,0 @@ -getBootstrap()->bootstrap('FrontController'); - return $this->getLayout(); - } - - /** - * Retrieve layout object - * - * @return Zend_Layout - */ - public function getLayout() - { - if (null === $this->_layout) { - $this->_layout = Zend_Layout::startMvc($this->getOptions()); - } - return $this->_layout; - } -} diff --git a/library/Zend/Application/Resource/Locale.php b/library/Zend/Application/Resource/Locale.php deleted file mode 100644 index 0e06c2ef4f..0000000000 --- a/library/Zend/Application/Resource/Locale.php +++ /dev/null @@ -1,117 +0,0 @@ -getLocale(); - } - - /** - * Retrieve locale object - * - * @return Zend_Locale - */ - public function getLocale() - { - if (null === $this->_locale) { - $options = $this->getOptions(); - - if (!isset($options['default'])) { - $this->_locale = new Zend_Locale(); - } elseif (!isset($options['force']) - || (bool)$options['force'] == false - ) { - // Don't force any locale, just go for auto detection - Zend_Locale::setDefault($options['default']); - $this->_locale = new Zend_Locale(); - } else { - $this->_locale = new Zend_Locale($options['default']); - } - - $key = (isset($options['registry_key']) && !is_numeric($options['registry_key'])) - ? $options['registry_key'] - : self::DEFAULT_REGISTRY_KEY; - Zend_Registry::set($key, $this->_locale); - } - - return $this->_locale; - } - - /** - * Set the cache - * - * @param string|Zend_Cache_Core $cache - * @return Zend_Application_Resource_Locale - */ - public function setCache($cache) - { - if (is_string($cache)) { - $bootstrap = $this->getBootstrap(); - if ($bootstrap instanceof Zend_Application_Bootstrap_ResourceBootstrapper - && $bootstrap->hasPluginResource('CacheManager') - ) { - $cacheManager = $bootstrap->bootstrap('CacheManager') - ->getResource('CacheManager'); - if (null !== $cacheManager && $cacheManager->hasCache($cache)) { - $cache = $cacheManager->getCache($cache); - } - } - } - - if ($cache instanceof Zend_Cache_Core) { - Zend_Locale::setCache($cache); - } - - return $this; - } -} diff --git a/library/Zend/Application/Resource/Log.php b/library/Zend/Application/Resource/Log.php deleted file mode 100644 index bc932ac0bb..0000000000 --- a/library/Zend/Application/Resource/Log.php +++ /dev/null @@ -1,83 +0,0 @@ -getLog(); - } - - /** - * Attach logger - * - * @param Zend_Log $log - * @return Zend_Application_Resource_Log - */ - public function setLog(Zend_Log $log) - { - $this->_log = $log; - return $this; - } - - /** - * Retrieve logger object - * - * @return Zend_Log - */ - public function getLog() - { - if (null === $this->_log) { - $options = $this->getOptions(); - $log = Zend_Log::factory($options); - $this->setLog($log); - } - return $this->_log; - } -} diff --git a/library/Zend/Application/Resource/Mail.php b/library/Zend/Application/Resource/Mail.php deleted file mode 100644 index 09d02ae5c1..0000000000 --- a/library/Zend/Application/Resource/Mail.php +++ /dev/null @@ -1,151 +0,0 @@ -getMail(); - } - - /** - * - * @return Zend_Mail_Transport_Abstract|null - */ - public function getMail() - { - if (null === $this->_transport) { - $options = $this->getOptions(); - foreach ($options as $key => $option) { - $options[strtolower($key)] = $option; - } - $this->setOptions($options); - - if (isset($options['transport']) - && !is_numeric($options['transport']) - ) { - $this->_transport = $this->_setupTransport($options['transport']); - if (!isset($options['transport']['register']) - || $options['transport']['register'] == '1' - || (isset($options['transport']['register']) - && !is_numeric($options['transport']['register']) - && (bool)$options['transport']['register'] == true) - ) { - Zend_Mail::setDefaultTransport($this->_transport); - } - } - - $this->_setDefaults('from'); - $this->_setDefaults('replyTo'); - } - - return $this->_transport; - } - - protected function _setDefaults($type) - { - $key = strtolower('default' . $type); - $options = $this->getOptions(); - - if (isset($options[$key]['email']) - && !is_numeric($options[$key]['email']) - ) { - $method = array('Zend_Mail', 'setDefault' . ucfirst($type)); - if (isset($options[$key]['name']) - && !is_numeric( - $options[$key]['name'] - ) - ) { - call_user_func( - $method, $options[$key]['email'], $options[$key]['name'] - ); - } else { - call_user_func($method, $options[$key]['email']); - } - } - } - - protected function _setupTransport($options) - { - if (!isset($options['type'])) { - $options['type'] = 'sendmail'; - } - - $transportName = $options['type']; - if (!Zend_Loader_Autoloader::autoload($transportName)) { - $transportName = ucfirst(strtolower($transportName)); - - if (!Zend_Loader_Autoloader::autoload($transportName)) { - $transportName = 'Zend_Mail_Transport_' . $transportName; - if (!Zend_Loader_Autoloader::autoload($transportName)) { - throw new Zend_Application_Resource_Exception( - "Specified Mail Transport '{$transportName}'" - . 'could not be found' - ); - } - } - } - - unset($options['type']); - unset($options['register']); //@see ZF-11022 - - switch($transportName) { - case 'Zend_Mail_Transport_Smtp': - if (!isset($options['host'])) { - throw new Zend_Application_Resource_Exception( - 'A host is necessary for smtp transport,' - . ' but none was given' - ); - } - - $transport = new $transportName($options['host'], $options); - break; - case 'Zend_Mail_Transport_Sendmail': - default: - $transport = new $transportName($options); - break; - } - - return $transport; - } -} diff --git a/library/Zend/Application/Resource/Modules.php b/library/Zend/Application/Resource/Modules.php deleted file mode 100644 index a5c2648195..0000000000 --- a/library/Zend/Application/Resource/Modules.php +++ /dev/null @@ -1,158 +0,0 @@ -_bootstraps = new ArrayObject(array(), ArrayObject::ARRAY_AS_PROPS); - parent::__construct($options); - } - - /** - * Initialize modules - * - * @return array - * @throws Zend_Application_Resource_Exception When bootstrap class was not found - */ - public function init() - { - $bootstraps = array(); - $bootstrap = $this->getBootstrap(); - $bootstrap->bootstrap('FrontController'); - $front = $bootstrap->getResource('FrontController'); - - $modules = $front->getControllerDirectory(); - $default = $front->getDefaultModule(); - $curBootstrapClass = get_class($bootstrap); - foreach ($modules as $module => $moduleDirectory) { - $bootstrapClass = $this->_formatModuleName($module) . '_Bootstrap'; - if (!class_exists($bootstrapClass, false)) { - $bootstrapPath = dirname($moduleDirectory) . '/Bootstrap.php'; - if (file_exists($bootstrapPath)) { - $eMsgTpl = 'Bootstrap file found for module "%s" but bootstrap class "%s" not found'; - include_once $bootstrapPath; - if (($default != $module) - && !class_exists($bootstrapClass, false) - ) { - throw new Zend_Application_Resource_Exception( - sprintf( - $eMsgTpl, $module, $bootstrapClass - ) - ); - } elseif ($default == $module) { - if (!class_exists($bootstrapClass, false)) { - $bootstrapClass = 'Bootstrap'; - if (!class_exists($bootstrapClass, false)) { - throw new Zend_Application_Resource_Exception( - sprintf( - $eMsgTpl, $module, $bootstrapClass - ) - ); - } - } - } - } else { - continue; - } - } - - if ($bootstrapClass == $curBootstrapClass) { - // If the found bootstrap class matches the one calling this - // resource, don't re-execute. - continue; - } - - $bootstraps[$module] = $bootstrapClass; - } - - return $this->_bootstraps = $this->bootstrapBootstraps($bootstraps); - } - - /* - * Bootstraps the bootstraps found. Allows for easy extension. - * @param array $bootstraps Array containing the bootstraps to instantiate - */ - protected function bootstrapBootstraps($bootstraps) - { - $bootstrap = $this->getBootstrap(); - $out = new ArrayObject(array(), ArrayObject::ARRAY_AS_PROPS); - - foreach ($bootstraps as $module => $bootstrapClass) { - $moduleBootstrap = new $bootstrapClass($bootstrap); - $moduleBootstrap->bootstrap(); - $out[$module] = $moduleBootstrap; - } - - return $out; - } - - /** - * Get bootstraps that have been run - * - * @return ArrayObject - */ - public function getExecutedBootstraps() - { - return $this->_bootstraps; - } - - /** - * Format a module name to the module class prefix - * - * @param string $name - * @return string - */ - protected function _formatModuleName($name) - { - $name = strtolower($name); - $name = str_replace(array('-', '.'), ' ', $name); - $name = ucwords($name); - $name = str_replace(' ', '', $name); - return $name; - } -} diff --git a/library/Zend/Application/Resource/Multidb.php b/library/Zend/Application/Resource/Multidb.php deleted file mode 100644 index 71871102dc..0000000000 --- a/library/Zend/Application/Resource/Multidb.php +++ /dev/null @@ -1,210 +0,0 @@ - - * resources.multidb.defaultMetadataCache = "database" - * - * resources.multidb.db1.adapter = "pdo_mysql" - * resources.multidb.db1.host = "localhost" - * resources.multidb.db1.username = "webuser" - * resources.multidb.db1.password = "XXXX" - * resources.multidb.db1.dbname = "db1" - * resources.multidb.db1.default = true - * - * resources.multidb.db2.adapter = "pdo_pgsql" - * resources.multidb.db2.host = "example.com" - * resources.multidb.db2.username = "dba" - * resources.multidb.db2.password = "notthatpublic" - * resources.multidb.db2.dbname = "db2" - * - * - * @category Zend - * @package Zend_Application - * @subpackage Resource - * @copyright Copyright (c) 2005-2015 Zend Technologies USA Inc. (http://www.zend.com) - * @license http://framework.zend.com/license/new-bsd New BSD License - */ -class Zend_Application_Resource_Multidb extends Zend_Application_Resource_ResourceAbstract -{ - /** - * Associative array containing all configured db's - * - * @var array - */ - protected $_dbs = array(); - - /** - * An instance of the default db, if set - * - * @var null|Zend_Db_Adapter_Abstract - */ - protected $_defaultDb; - - /** - * Initialize the Database Connections (instances of Zend_Db_Table_Abstract) - * - * @return Zend_Application_Resource_Multidb - */ - public function init() - { - $options = $this->getOptions(); - - if (isset($options['defaultMetadataCache'])) { - $this->_setDefaultMetadataCache($options['defaultMetadataCache']); - unset($options['defaultMetadataCache']); - } - - foreach ($options as $id => $params) { - $adapter = $params['adapter']; - $default = (int) ( - isset($params['isDefaultTableAdapter']) && $params['isDefaultTableAdapter'] - || isset($params['default']) && $params['default'] - ); - unset( - $params['adapter'], - $params['default'], - $params['isDefaultTableAdapter'] - ); - - $this->_dbs[$id] = Zend_Db::factory($adapter, $params); - - if ($default) { - $this->_setDefault($this->_dbs[$id]); - } - } - - return $this; - } - - /** - * Determine if the given db(identifier) is the default db. - * - * @param string|Zend_Db_Adapter_Abstract $db The db to determine whether it's set as default - * @return boolean True if the given parameter is configured as default. False otherwise - */ - public function isDefault($db) - { - if (!$db instanceof Zend_Db_Adapter_Abstract) { - $db = $this->getDb($db); - } - - return $db === $this->_defaultDb; - } - - /** - * Retrieve the specified database connection - * - * @param null|string|Zend_Db_Adapter_Abstract $db The adapter to retrieve. - * Null to retrieve the default connection - * @return Zend_Db_Adapter_Abstract - * @throws Zend_Application_Resource_Exception if the given parameter could not be found - */ - public function getDb($db = null) - { - if ($db === null) { - return $this->getDefaultDb(); - } - - if (isset($this->_dbs[$db])) { - return $this->_dbs[$db]; - } - - throw new Zend_Application_Resource_Exception( - 'A DB adapter was tried to retrieve, but was not configured' - ); - } - - /** - * Get the default db connection - * - * @param boolean $justPickOne If true, a random (the first one in the stack) - * connection is returned if no default was set. - * If false, null is returned if no default was set. - * @return null|Zend_Db_Adapter_Abstract - */ - public function getDefaultDb($justPickOne = true) - { - if ($this->_defaultDb !== null) { - return $this->_defaultDb; - } - - if ($justPickOne) { - return reset($this->_dbs); // Return first db in db pool - } - - return null; - } - - /** - * Set the default db adapter - * - * @var Zend_Db_Adapter_Abstract $adapter Adapter to set as default - */ - protected function _setDefault(Zend_Db_Adapter_Abstract $adapter) - { - Zend_Db_Table::setDefaultAdapter($adapter); - $this->_defaultDb = $adapter; - } - - /** - * Set the default metadata cache - * - * @param string|Zend_Cache_Core $cache - * @return Zend_Application_Resource_Multidb - */ - protected function _setDefaultMetadataCache($cache) - { - $metadataCache = null; - - if (is_string($cache)) { - $bootstrap = $this->getBootstrap(); - if ($bootstrap instanceof Zend_Application_Bootstrap_ResourceBootstrapper && - $bootstrap->hasPluginResource('CacheManager') - ) { - $cacheManager = $bootstrap->bootstrap('CacheManager') - ->getResource('CacheManager'); - if (null !== $cacheManager && $cacheManager->hasCache($cache)) { - $metadataCache = $cacheManager->getCache($cache); - } - } - } else if ($cache instanceof Zend_Cache_Core) { - $metadataCache = $cache; - } - - if ($metadataCache instanceof Zend_Cache_Core) { - Zend_Db_Table::setDefaultMetadataCache($metadataCache); - } - - return $this; - } -} diff --git a/library/Zend/Application/Resource/Navigation.php b/library/Zend/Application/Resource/Navigation.php deleted file mode 100644 index d6042ef646..0000000000 --- a/library/Zend/Application/Resource/Navigation.php +++ /dev/null @@ -1,131 +0,0 @@ -_container) { - $options = $this->getOptions(); - - if (isset($options['defaultPageType'])) { - Zend_Navigation_Page::setDefaultPageType( - $options['defaultPageType'] - ); - } - - $pages = isset($options['pages']) ? $options['pages'] : array(); - $this->_container = new Zend_Navigation($pages); - } - - $this->store(); - return $this->_container; - } - - /** - * Stores navigation container in registry or Navigation view helper - * - * @return void - */ - public function store() - { - $options = $this->getOptions(); - if (isset($options['storage']['registry']) && - $options['storage']['registry'] == true) { - $this->_storeRegistry(); - } else { - $this->_storeHelper(); - } - } - - /** - * Stores navigation container in the registry - * - * @return void - */ - protected function _storeRegistry() - { - $options = $this->getOptions(); - // see ZF-7461 - if (isset($options['storage']['registry']['key']) - && !is_numeric($options['storage']['registry']['key']) - ) { - $key = $options['storage']['registry']['key']; - } else { - $key = self::DEFAULT_REGISTRY_KEY; - } - - Zend_Registry::set($key, $this->getContainer()); - } - - /** - * Stores navigation container in the Navigation helper - * - * @return void - */ - protected function _storeHelper() - { - $this->getBootstrap()->bootstrap('view'); - $view = $this->getBootstrap()->view; - $view->getHelper('navigation')->navigation($this->getContainer()); - } - - /** - * Returns navigation container - * - * @return Zend_Navigation - */ - public function getContainer() - { - return $this->_container; - } -} diff --git a/library/Zend/Application/Resource/Resource.php b/library/Zend/Application/Resource/Resource.php deleted file mode 100644 index 7c73675660..0000000000 --- a/library/Zend/Application/Resource/Resource.php +++ /dev/null @@ -1,79 +0,0 @@ -setOptions($options); - } else if ($options instanceof Zend_Config) { - $this->setOptions($options->toArray()); - } - } - - /** - * Set options from array - * - * @param array $options Configuration for resource - * @return Zend_Application_Resource_ResourceAbstract - */ - public function setOptions(array $options) - { - if (array_key_exists('bootstrap', $options)) { - $this->setBootstrap($options['bootstrap']); - unset($options['bootstrap']); - } - - foreach ($options as $key => $value) { - if (in_array(strtolower($key), $this->_skipOptions)) { - continue; - } - - $method = 'set' . strtolower($key); - if (method_exists($this, $method)) { - $this->$method($value); - } - } - - $this->_options = $this->mergeOptions($this->_options, $options); - - return $this; - } - - /** - * Retrieve resource options - * - * @return array - */ - public function getOptions() - { - return $this->_options; - } - - /** - * Merge options recursively - * - * @param array $array1 - * @param mixed $array2 - * @return array - */ - public function mergeOptions(array $array1, $array2 = null) - { - if (is_array($array2)) { - foreach ($array2 as $key => $val) { - if (is_array($array2[$key])) { - $array1[$key] = (array_key_exists($key, $array1) && is_array($array1[$key])) - ? $this->mergeOptions($array1[$key], $array2[$key]) - : $array2[$key]; - } else { - $array1[$key] = $val; - } - } - } - return $array1; - } - - /** - * Set the bootstrap to which the resource is attached - * - * @param Zend_Application_Bootstrap_Bootstrapper $bootstrap - * @return Zend_Application_Resource_Resource - */ - public function setBootstrap(Zend_Application_Bootstrap_Bootstrapper $bootstrap) - { - $this->_bootstrap = $bootstrap; - return $this; - } - - /** - * Retrieve the bootstrap to which the resource is attached - * - * @return null|Zend_Application_Bootstrap_Bootstrapper - */ - public function getBootstrap() - { - return $this->_bootstrap; - } -} diff --git a/library/Zend/Application/Resource/Router.php b/library/Zend/Application/Resource/Router.php deleted file mode 100644 index 9b2066d1fd..0000000000 --- a/library/Zend/Application/Resource/Router.php +++ /dev/null @@ -1,87 +0,0 @@ -getRouter(); - } - - /** - * Retrieve router object - * - * @return Zend_Controller_Router_Rewrite - */ - public function getRouter() - { - if (null === $this->_router) { - $bootstrap = $this->getBootstrap(); - $bootstrap->bootstrap('FrontController'); - $this->_router = $bootstrap->getContainer()->frontcontroller->getRouter(); - - $options = $this->getOptions(); - if (!isset($options['routes'])) { - $options['routes'] = array(); - } - - if (isset($options['chainNameSeparator'])) { - $this->_router->setChainNameSeparator($options['chainNameSeparator']); - } - - if (isset($options['useRequestParametersAsGlobal'])) { - $this->_router->useRequestParametersAsGlobal($options['useRequestParametersAsGlobal']); - } - - $this->_router->addConfig(new Zend_Config($options['routes'])); - } - - return $this->_router; - } -} diff --git a/library/Zend/Application/Resource/Session.php b/library/Zend/Application/Resource/Session.php deleted file mode 100644 index ac9b54e6b9..0000000000 --- a/library/Zend/Application/Resource/Session.php +++ /dev/null @@ -1,119 +0,0 @@ -_saveHandler = $saveHandler; - return $this; - } - - /** - * Get session save handler - * - * @return Zend_Session_SaveHandler_Interface - * @throws Zend_Application_Resource_Exception - */ - public function getSaveHandler() - { - if (!$this->_saveHandler instanceof Zend_Session_SaveHandler_Interface) { - if (is_array($this->_saveHandler)) { - if (!array_key_exists('class', $this->_saveHandler)) { - throw new Zend_Application_Resource_Exception('Session save handler class not provided in options'); - } - $options = array(); - if (array_key_exists('options', $this->_saveHandler)) { - $options = $this->_saveHandler['options']; - } - $this->_saveHandler = $this->_saveHandler['class']; - $this->_saveHandler = new $this->_saveHandler($options); - } elseif (is_string($this->_saveHandler)) { - $this->_saveHandler = new $this->_saveHandler(); - } - - if (!$this->_saveHandler instanceof Zend_Session_SaveHandler_Interface) { - throw new Zend_Application_Resource_Exception('Invalid session save handler'); - } - } - return $this->_saveHandler; - } - - /** - * @return bool - */ - protected function _hasSaveHandler() - { - return ($this->_saveHandler !== null); - } - - /** - * Defined by Zend_Application_Resource_Resource - * - * @return void - */ - public function init() - { - $options = array_change_key_case($this->getOptions(), CASE_LOWER); - if (isset($options['savehandler'])) { - unset($options['savehandler']); - } - - if (count($options) > 0) { - Zend_Session::setOptions($options); - } - - if ($this->_hasSaveHandler()) { - Zend_Session::setSaveHandler($this->getSaveHandler()); - } - } -} diff --git a/library/Zend/Application/Resource/Translate.php b/library/Zend/Application/Resource/Translate.php deleted file mode 100644 index 02fdd65df4..0000000000 --- a/library/Zend/Application/Resource/Translate.php +++ /dev/null @@ -1,142 +0,0 @@ -getTranslate(); - } - - /** - * Retrieve translate object - * - * @return Zend_Translate - * @throws Zend_Application_Resource_Exception if registry key was used - * already but is no instance of Zend_Translate - */ - public function getTranslate() - { - if (null === $this->_translate) { - $options = $this->getOptions(); - - if (!isset($options['content']) && !isset($options['data'])) { - #require_once 'Zend/Application/Resource/Exception.php'; - throw new Zend_Application_Resource_Exception('No translation source data provided.'); - } else if (array_key_exists('content', $options) && array_key_exists('data', $options)) { - #require_once 'Zend/Application/Resource/Exception.php'; - throw new Zend_Application_Resource_Exception( - 'Conflict on translation source data: choose only one key between content and data.' - ); - } - - if (empty($options['adapter'])) { - $options['adapter'] = Zend_Translate::AN_ARRAY; - } - - if (!empty($options['data'])) { - $options['content'] = $options['data']; - unset($options['data']); - } - - if (isset($options['log'])) { - if (is_array($options['log'])) { - $options['log'] = Zend_Log::factory($options['log']); - } - } - - if (isset($options['options'])) { - foreach ($options['options'] as $key => $value) { - $options[$key] = $value; - } - } - - if (!empty($options['cache']) && is_string($options['cache'])) { - $bootstrap = $this->getBootstrap(); - if ($bootstrap instanceof Zend_Application_Bootstrap_ResourceBootstrapper && - $bootstrap->hasPluginResource('CacheManager') - ) { - $cacheManager = $bootstrap->bootstrap('CacheManager') - ->getResource('CacheManager'); - if (null !== $cacheManager && - $cacheManager->hasCache($options['cache']) - ) { - $options['cache'] = $cacheManager->getCache($options['cache']); - } - } - } - - $key = (isset($options['registry_key']) && !is_numeric($options['registry_key'])) - ? $options['registry_key'] - : self::DEFAULT_REGISTRY_KEY; - unset($options['registry_key']); - - if (Zend_Registry::isRegistered($key)) { - $translate = Zend_Registry::get($key); - if (!$translate instanceof Zend_Translate) { - #require_once 'Zend/Application/Resource/Exception.php'; - throw new Zend_Application_Resource_Exception( - $key - . ' already registered in registry but is ' - . 'no instance of Zend_Translate' - ); - } - - $translate->addTranslation($options); - $this->_translate = $translate; - } else { - $this->_translate = new Zend_Translate($options); - Zend_Registry::set($key, $this->_translate); - } - } - - return $this->_translate; - } -} diff --git a/library/Zend/Application/Resource/Useragent.php b/library/Zend/Application/Resource/Useragent.php deleted file mode 100644 index 1ac40a3256..0000000000 --- a/library/Zend/Application/Resource/Useragent.php +++ /dev/null @@ -1,72 +0,0 @@ -getUserAgent(); - - // Optionally seed the UserAgent view helper - $bootstrap = $this->getBootstrap(); - if ($bootstrap->hasResource('view') || $bootstrap->hasPluginResource('view')) { - $bootstrap->bootstrap('view'); - $view = $bootstrap->getResource('view'); - if (null !== $view) { - $view->userAgent($userAgent); - } - } - - return $userAgent; - } - - /** - * Get UserAgent instance - * - * @return Zend_Http_UserAgent - */ - public function getUserAgent() - { - if (null === $this->_userAgent) { - $options = $this->getOptions(); - $this->_userAgent = new Zend_Http_UserAgent($options); - } - - return $this->_userAgent; - } -} diff --git a/library/Zend/Application/Resource/View.php b/library/Zend/Application/Resource/View.php deleted file mode 100644 index 442bfc5c0c..0000000000 --- a/library/Zend/Application/Resource/View.php +++ /dev/null @@ -1,86 +0,0 @@ -getView(); - - $viewRenderer = Zend_Controller_Action_HelperBroker::getStaticHelper('viewRenderer'); - $viewRenderer->setView($view); - return $view; - } - - /** - * Retrieve view object - * - * @return Zend_View - */ - public function getView() - { - if (null === $this->_view) { - $options = $this->getOptions(); - $this->_view = new Zend_View($options); - - if (isset($options['doctype'])) { - $this->_view->doctype()->setDoctype(strtoupper($options['doctype'])); - if (isset($options['charset']) && $this->_view->doctype()->isHtml5()) { - $this->_view->headMeta()->setCharset($options['charset']); - } - } - if (isset($options['contentType'])) { - $this->_view->headMeta()->appendHttpEquiv('Content-Type', $options['contentType']); - } - if (isset($options['assign']) && is_array($options['assign'])) { - $this->_view->assign($options['assign']); - } - } - return $this->_view; - } -} diff --git a/library/Zend/Auth/Adapter/DbTable.php b/library/Zend/Auth/Adapter/DbTable.php deleted file mode 100644 index 5022fd5cf8..0000000000 --- a/library/Zend/Auth/Adapter/DbTable.php +++ /dev/null @@ -1,560 +0,0 @@ -_setDbAdapter($zendDb); - - if (null !== $tableName) { - $this->setTableName($tableName); - } - - if (null !== $identityColumn) { - $this->setIdentityColumn($identityColumn); - } - - if (null !== $credentialColumn) { - $this->setCredentialColumn($credentialColumn); - } - - if (null !== $credentialTreatment) { - $this->setCredentialTreatment($credentialTreatment); - } - } - - /** - * _setDbAdapter() - set the database adapter to be used for quering - * - * @param Zend_Db_Adapter_Abstract - * @throws Zend_Auth_Adapter_Exception - * @return Zend_Auth_Adapter_DbTable - */ - protected function _setDbAdapter(Zend_Db_Adapter_Abstract $zendDb = null) - { - $this->_zendDb = $zendDb; - - /** - * If no adapter is specified, fetch default database adapter. - */ - if(null === $this->_zendDb) { - #require_once 'Zend/Db/Table/Abstract.php'; - $this->_zendDb = Zend_Db_Table_Abstract::getDefaultAdapter(); - if (null === $this->_zendDb) { - #require_once 'Zend/Auth/Adapter/Exception.php'; - throw new Zend_Auth_Adapter_Exception('No database adapter present'); - } - } - - return $this; - } - - /** - * setTableName() - set the table name to be used in the select query - * - * @param string $tableName - * @return Zend_Auth_Adapter_DbTable Provides a fluent interface - */ - public function setTableName($tableName) - { - $this->_tableName = $tableName; - return $this; - } - - /** - * setIdentityColumn() - set the column name to be used as the identity column - * - * @param string $identityColumn - * @return Zend_Auth_Adapter_DbTable Provides a fluent interface - */ - public function setIdentityColumn($identityColumn) - { - $this->_identityColumn = $identityColumn; - return $this; - } - - /** - * setCredentialColumn() - set the column name to be used as the credential column - * - * @param string $credentialColumn - * @return Zend_Auth_Adapter_DbTable Provides a fluent interface - */ - public function setCredentialColumn($credentialColumn) - { - $this->_credentialColumn = $credentialColumn; - return $this; - } - - /** - * setCredentialTreatment() - allows the developer to pass a parameterized string that is - * used to transform or treat the input credential data. - * - * In many cases, passwords and other sensitive data are encrypted, hashed, encoded, - * obscured, or otherwise treated through some function or algorithm. By specifying a - * parameterized treatment string with this method, a developer may apply arbitrary SQL - * upon input credential data. - * - * Examples: - * - * 'PASSWORD(?)' - * 'MD5(?)' - * - * @param string $treatment - * @return Zend_Auth_Adapter_DbTable Provides a fluent interface - */ - public function setCredentialTreatment($treatment) - { - $this->_credentialTreatment = $treatment; - return $this; - } - - /** - * setIdentity() - set the value to be used as the identity - * - * @param string $value - * @return Zend_Auth_Adapter_DbTable Provides a fluent interface - */ - public function setIdentity($value) - { - $this->_identity = $value; - return $this; - } - - /** - * setCredential() - set the credential value to be used, optionally can specify a treatment - * to be used, should be supplied in parameterized form, such as 'MD5(?)' or 'PASSWORD(?)' - * - * @param string $credential - * @return Zend_Auth_Adapter_DbTable Provides a fluent interface - */ - public function setCredential($credential) - { - $this->_credential = $credential; - return $this; - } - - /** - * setAmbiguityIdentity() - sets a flag for usage of identical identities - * with unique credentials. It accepts integers (0, 1) or boolean (true, - * false) parameters. Default is false. - * - * @param int|bool $flag - * @return Zend_Auth_Adapter_DbTable - */ - public function setAmbiguityIdentity($flag) - { - if (is_integer($flag)) { - $this->_ambiguityIdentity = (1 === $flag ? true : false); - } elseif (is_bool($flag)) { - $this->_ambiguityIdentity = $flag; - } - return $this; - } - /** - * getAmbiguityIdentity() - returns TRUE for usage of multiple identical - * identies with different credentials, FALSE if not used. - * - * @return bool - */ - public function getAmbiguityIdentity() - { - return $this->_ambiguityIdentity; - } - - /** - * getDbSelect() - Return the preauthentication Db Select object for userland select query modification - * - * @return Zend_Db_Select - */ - public function getDbSelect() - { - if ($this->_dbSelect == null) { - $this->_dbSelect = $this->_zendDb->select(); - } - - return $this->_dbSelect; - } - - /** - * getResultRowObject() - Returns the result row as a stdClass object - * - * @param string|array $returnColumns - * @param string|array $omitColumns - * @return stdClass|boolean - */ - public function getResultRowObject($returnColumns = null, $omitColumns = null) - { - if (!$this->_resultRow) { - return false; - } - - $returnObject = new stdClass(); - - if (null !== $returnColumns) { - - $availableColumns = array_keys($this->_resultRow); - foreach ( (array) $returnColumns as $returnColumn) { - if (in_array($returnColumn, $availableColumns)) { - $returnObject->{$returnColumn} = $this->_resultRow[$returnColumn]; - } - } - return $returnObject; - - } elseif (null !== $omitColumns) { - - $omitColumns = (array) $omitColumns; - foreach ($this->_resultRow as $resultColumn => $resultValue) { - if (!in_array($resultColumn, $omitColumns)) { - $returnObject->{$resultColumn} = $resultValue; - } - } - return $returnObject; - - } else { - - foreach ($this->_resultRow as $resultColumn => $resultValue) { - $returnObject->{$resultColumn} = $resultValue; - } - return $returnObject; - - } - } - - /** - * authenticate() - defined by Zend_Auth_Adapter_Interface. This method is called to - * attempt an authentication. Previous to this call, this adapter would have already - * been configured with all necessary information to successfully connect to a database - * table and attempt to find a record matching the provided identity. - * - * @throws Zend_Auth_Adapter_Exception if answering the authentication query is impossible - * @return Zend_Auth_Result - */ - public function authenticate() - { - $this->_authenticateSetup(); - $dbSelect = $this->_authenticateCreateSelect(); - $resultIdentities = $this->_authenticateQuerySelect($dbSelect); - - if ( ($authResult = $this->_authenticateValidateResultSet($resultIdentities)) instanceof Zend_Auth_Result) { - return $authResult; - } - - if (true === $this->getAmbiguityIdentity()) { - $validIdentities = array (); - $zendAuthCredentialMatchColumn = $this->_zendDb->foldCase('zend_auth_credential_match'); - foreach ($resultIdentities as $identity) { - if (1 === (int) $identity[$zendAuthCredentialMatchColumn]) { - $validIdentities[] = $identity; - } - } - $resultIdentities = $validIdentities; - } - - $authResult = $this->_authenticateValidateResult(array_shift($resultIdentities)); - return $authResult; - } - - /** - * _authenticateSetup() - This method abstracts the steps involved with - * making sure that this adapter was indeed setup properly with all - * required pieces of information. - * - * @throws Zend_Auth_Adapter_Exception - in the event that setup was not done properly - * @return true - */ - protected function _authenticateSetup() - { - $exception = null; - - if ($this->_tableName == '') { - $exception = 'A table must be supplied for the Zend_Auth_Adapter_DbTable authentication adapter.'; - } elseif ($this->_identityColumn == '') { - $exception = 'An identity column must be supplied for the Zend_Auth_Adapter_DbTable authentication adapter.'; - } elseif ($this->_credentialColumn == '') { - $exception = 'A credential column must be supplied for the Zend_Auth_Adapter_DbTable authentication adapter.'; - } elseif ($this->_identity == '') { - $exception = 'A value for the identity was not provided prior to authentication with Zend_Auth_Adapter_DbTable.'; - } elseif ($this->_credential === null) { - $exception = 'A credential value was not provided prior to authentication with Zend_Auth_Adapter_DbTable.'; - } - - if (null !== $exception) { - /** - * @see Zend_Auth_Adapter_Exception - */ - #require_once 'Zend/Auth/Adapter/Exception.php'; - throw new Zend_Auth_Adapter_Exception($exception); - } - - $this->_authenticateResultInfo = array( - 'code' => Zend_Auth_Result::FAILURE, - 'identity' => $this->_identity, - 'messages' => array() - ); - - return true; - } - - /** - * _authenticateCreateSelect() - This method creates a Zend_Db_Select object that - * is completely configured to be queried against the database. - * - * @return Zend_Db_Select - */ - protected function _authenticateCreateSelect() - { - // build credential expression - if (empty($this->_credentialTreatment) || (strpos($this->_credentialTreatment, '?') === false)) { - $this->_credentialTreatment = '?'; - } - - $credentialExpression = new Zend_Db_Expr( - '(CASE WHEN ' . - $this->_zendDb->quoteInto( - $this->_zendDb->quoteIdentifier($this->_credentialColumn, true) - . ' = ' . $this->_credentialTreatment, $this->_credential - ) - . ' THEN 1 ELSE 0 END) AS ' - . $this->_zendDb->quoteIdentifier( - $this->_zendDb->foldCase('zend_auth_credential_match') - ) - ); - - // get select - $dbSelect = clone $this->getDbSelect(); - $dbSelect->from($this->_tableName, array('*', $credentialExpression)) - ->where($this->_zendDb->quoteIdentifier($this->_identityColumn, true) . ' = ?', $this->_identity); - - return $dbSelect; - } - - /** - * _authenticateQuerySelect() - This method accepts a Zend_Db_Select object and - * performs a query against the database with that object. - * - * @param Zend_Db_Select $dbSelect - * @throws Zend_Auth_Adapter_Exception - when an invalid select - * object is encountered - * @return array - */ - protected function _authenticateQuerySelect(Zend_Db_Select $dbSelect) - { - try { - if ($this->_zendDb->getFetchMode() != Zend_DB::FETCH_ASSOC) { - $origDbFetchMode = $this->_zendDb->getFetchMode(); - $this->_zendDb->setFetchMode(Zend_DB::FETCH_ASSOC); - } - $resultIdentities = $this->_zendDb->fetchAll($dbSelect); - if (isset($origDbFetchMode)) { - $this->_zendDb->setFetchMode($origDbFetchMode); - unset($origDbFetchMode); - } - } catch (Exception $e) { - /** - * @see Zend_Auth_Adapter_Exception - */ - #require_once 'Zend/Auth/Adapter/Exception.php'; - throw new Zend_Auth_Adapter_Exception('The supplied parameters to Zend_Auth_Adapter_DbTable failed to ' - . 'produce a valid sql statement, please check table and column names ' - . 'for validity.', 0, $e); - } - return $resultIdentities; - } - - /** - * _authenticateValidateResultSet() - This method attempts to make - * certain that only one record was returned in the resultset - * - * @param array $resultIdentities - * @return true|Zend_Auth_Result - */ - protected function _authenticateValidateResultSet(array $resultIdentities) - { - - if (count($resultIdentities) < 1) { - $this->_authenticateResultInfo['code'] = Zend_Auth_Result::FAILURE_IDENTITY_NOT_FOUND; - $this->_authenticateResultInfo['messages'][] = 'A record with the supplied identity could not be found.'; - return $this->_authenticateCreateAuthResult(); - } elseif (count($resultIdentities) > 1 && false === $this->getAmbiguityIdentity()) { - $this->_authenticateResultInfo['code'] = Zend_Auth_Result::FAILURE_IDENTITY_AMBIGUOUS; - $this->_authenticateResultInfo['messages'][] = 'More than one record matches the supplied identity.'; - return $this->_authenticateCreateAuthResult(); - } - - return true; - } - - /** - * _authenticateValidateResult() - This method attempts to validate that - * the record in the resultset is indeed a record that matched the - * identity provided to this adapter. - * - * @param array $resultIdentity - * @return Zend_Auth_Result - */ - protected function _authenticateValidateResult($resultIdentity) - { - $zendAuthCredentialMatchColumn = $this->_zendDb->foldCase('zend_auth_credential_match'); - - if ($resultIdentity[$zendAuthCredentialMatchColumn] != '1') { - $this->_authenticateResultInfo['code'] = Zend_Auth_Result::FAILURE_CREDENTIAL_INVALID; - $this->_authenticateResultInfo['messages'][] = 'Supplied credential is invalid.'; - return $this->_authenticateCreateAuthResult(); - } - - unset($resultIdentity[$zendAuthCredentialMatchColumn]); - $this->_resultRow = $resultIdentity; - - $this->_authenticateResultInfo['code'] = Zend_Auth_Result::SUCCESS; - $this->_authenticateResultInfo['messages'][] = 'Authentication successful.'; - return $this->_authenticateCreateAuthResult(); - } - - /** - * _authenticateCreateAuthResult() - Creates a Zend_Auth_Result object from - * the information that has been collected during the authenticate() attempt. - * - * @return Zend_Auth_Result - */ - protected function _authenticateCreateAuthResult() - { - return new Zend_Auth_Result( - $this->_authenticateResultInfo['code'], - $this->_authenticateResultInfo['identity'], - $this->_authenticateResultInfo['messages'] - ); - } - -} diff --git a/library/Zend/Auth/Adapter/Digest.php b/library/Zend/Auth/Adapter/Digest.php deleted file mode 100644 index 17d035b068..0000000000 --- a/library/Zend/Auth/Adapter/Digest.php +++ /dev/null @@ -1,251 +0,0 @@ -$methodName($$option); - } - } - } - - /** - * Returns the filename option value or null if it has not yet been set - * - * @return string|null - */ - public function getFilename() - { - return $this->_filename; - } - - /** - * Sets the filename option value - * - * @param mixed $filename - * @return Zend_Auth_Adapter_Digest Provides a fluent interface - */ - public function setFilename($filename) - { - $this->_filename = (string) $filename; - return $this; - } - - /** - * Returns the realm option value or null if it has not yet been set - * - * @return string|null - */ - public function getRealm() - { - return $this->_realm; - } - - /** - * Sets the realm option value - * - * @param mixed $realm - * @return Zend_Auth_Adapter_Digest Provides a fluent interface - */ - public function setRealm($realm) - { - $this->_realm = (string) $realm; - return $this; - } - - /** - * Returns the username option value or null if it has not yet been set - * - * @return string|null - */ - public function getUsername() - { - return $this->_username; - } - - /** - * Sets the username option value - * - * @param mixed $username - * @return Zend_Auth_Adapter_Digest Provides a fluent interface - */ - public function setUsername($username) - { - $this->_username = (string) $username; - return $this; - } - - /** - * Returns the password option value or null if it has not yet been set - * - * @return string|null - */ - public function getPassword() - { - return $this->_password; - } - - /** - * Sets the password option value - * - * @param mixed $password - * @return Zend_Auth_Adapter_Digest Provides a fluent interface - */ - public function setPassword($password) - { - $this->_password = (string) $password; - return $this; - } - - /** - * Defined by Zend_Auth_Adapter_Interface - * - * @throws Zend_Auth_Adapter_Exception - * @return Zend_Auth_Result - */ - public function authenticate() - { - $optionsRequired = array('filename', 'realm', 'username', 'password'); - foreach ($optionsRequired as $optionRequired) { - if (null === $this->{"_$optionRequired"}) { - /** - * @see Zend_Auth_Adapter_Exception - */ - #require_once 'Zend/Auth/Adapter/Exception.php'; - throw new Zend_Auth_Adapter_Exception("Option '$optionRequired' must be set before authentication"); - } - } - - if (false === ($fileHandle = @fopen($this->_filename, 'r'))) { - /** - * @see Zend_Auth_Adapter_Exception - */ - #require_once 'Zend/Auth/Adapter/Exception.php'; - throw new Zend_Auth_Adapter_Exception("Cannot open '$this->_filename' for reading"); - } - - $id = "$this->_username:$this->_realm"; - $idLength = strlen($id); - - $result = array( - 'code' => Zend_Auth_Result::FAILURE, - 'identity' => array( - 'realm' => $this->_realm, - 'username' => $this->_username, - ), - 'messages' => array() - ); - - while ($line = trim(fgets($fileHandle))) { - if (substr($line, 0, $idLength) === $id) { - if ($this->_secureStringCompare(substr($line, -32), md5("$this->_username:$this->_realm:$this->_password"))) { - $result['code'] = Zend_Auth_Result::SUCCESS; - } else { - $result['code'] = Zend_Auth_Result::FAILURE_CREDENTIAL_INVALID; - $result['messages'][] = 'Password incorrect'; - } - return new Zend_Auth_Result($result['code'], $result['identity'], $result['messages']); - } - } - - $result['code'] = Zend_Auth_Result::FAILURE_IDENTITY_NOT_FOUND; - $result['messages'][] = "Username '$this->_username' and realm '$this->_realm' combination not found"; - return new Zend_Auth_Result($result['code'], $result['identity'], $result['messages']); - } - - /** - * Securely compare two strings for equality while avoided C level memcmp() - * optimisations capable of leaking timing information useful to an attacker - * attempting to iteratively guess the unknown string (e.g. password) being - * compared against. - * - * @param string $a - * @param string $b - * @return bool - */ - protected function _secureStringCompare($a, $b) - { - if (strlen($a) !== strlen($b)) { - return false; - } - $result = 0; - for ($i = 0; $i < strlen($a); $i++) { - $result |= ord($a[$i]) ^ ord($b[$i]); - } - return $result == 0; - } -} diff --git a/library/Zend/Auth/Adapter/Exception.php b/library/Zend/Auth/Adapter/Exception.php deleted file mode 100644 index 8f22edc3af..0000000000 --- a/library/Zend/Auth/Adapter/Exception.php +++ /dev/null @@ -1,38 +0,0 @@ - 'basic'|'digest'|'basic digest' - * 'realm' => - * 'digest_domains' => Space-delimited list of URIs - * 'nonce_timeout' => - * 'use_opaque' => Whether to send the opaque value in the header - * 'alogrithm' => See $_supportedAlgos. Default: MD5 - * 'proxy_auth' => Whether to do authentication as a Proxy - * @throws Zend_Auth_Adapter_Exception - */ - public function __construct(array $config) - { - if (!extension_loaded('hash')) { - /** - * @see Zend_Auth_Adapter_Exception - */ - #require_once 'Zend/Auth/Adapter/Exception.php'; - throw new Zend_Auth_Adapter_Exception(__CLASS__ . ' requires the \'hash\' extension'); - } - - $this->_request = null; - $this->_response = null; - $this->_ieNoOpaque = false; - - - if (empty($config['accept_schemes'])) { - /** - * @see Zend_Auth_Adapter_Exception - */ - #require_once 'Zend/Auth/Adapter/Exception.php'; - throw new Zend_Auth_Adapter_Exception('Config key \'accept_schemes\' is required'); - } - - $schemes = explode(' ', $config['accept_schemes']); - $this->_acceptSchemes = array_intersect($schemes, $this->_supportedSchemes); - if (empty($this->_acceptSchemes)) { - /** - * @see Zend_Auth_Adapter_Exception - */ - #require_once 'Zend/Auth/Adapter/Exception.php'; - throw new Zend_Auth_Adapter_Exception('No supported schemes given in \'accept_schemes\'. Valid values: ' - . implode(', ', $this->_supportedSchemes)); - } - - // Double-quotes are used to delimit the realm string in the HTTP header, - // and colons are field delimiters in the password file. - if (empty($config['realm']) || - !ctype_print($config['realm']) || - strpos($config['realm'], ':') !== false || - strpos($config['realm'], '"') !== false) { - /** - * @see Zend_Auth_Adapter_Exception - */ - #require_once 'Zend/Auth/Adapter/Exception.php'; - throw new Zend_Auth_Adapter_Exception('Config key \'realm\' is required, and must contain only printable ' - . 'characters, excluding quotation marks and colons'); - } else { - $this->_realm = $config['realm']; - } - - if (in_array('digest', $this->_acceptSchemes)) { - if (empty($config['digest_domains']) || - !ctype_print($config['digest_domains']) || - strpos($config['digest_domains'], '"') !== false) { - /** - * @see Zend_Auth_Adapter_Exception - */ - #require_once 'Zend/Auth/Adapter/Exception.php'; - throw new Zend_Auth_Adapter_Exception('Config key \'digest_domains\' is required, and must contain ' - . 'only printable characters, excluding quotation marks'); - } else { - $this->_domains = $config['digest_domains']; - } - - if (empty($config['nonce_timeout']) || - !is_numeric($config['nonce_timeout'])) { - /** - * @see Zend_Auth_Adapter_Exception - */ - #require_once 'Zend/Auth/Adapter/Exception.php'; - throw new Zend_Auth_Adapter_Exception('Config key \'nonce_timeout\' is required, and must be an ' - . 'integer'); - } else { - $this->_nonceTimeout = (int) $config['nonce_timeout']; - } - - // We use the opaque value unless explicitly told not to - if (isset($config['use_opaque']) && false == (bool) $config['use_opaque']) { - $this->_useOpaque = false; - } else { - $this->_useOpaque = true; - } - - if (isset($config['algorithm']) && in_array($config['algorithm'], $this->_supportedAlgos)) { - $this->_algo = $config['algorithm']; - } else { - $this->_algo = 'MD5'; - } - } - - // Don't be a proxy unless explicitly told to do so - if (isset($config['proxy_auth']) && true == (bool) $config['proxy_auth']) { - $this->_imaProxy = true; // I'm a Proxy - } else { - $this->_imaProxy = false; - } - } - - /** - * Setter for the _basicResolver property - * - * @param Zend_Auth_Adapter_Http_Resolver_Interface $resolver - * @return Zend_Auth_Adapter_Http Provides a fluent interface - */ - public function setBasicResolver(Zend_Auth_Adapter_Http_Resolver_Interface $resolver) - { - $this->_basicResolver = $resolver; - - return $this; - } - - /** - * Getter for the _basicResolver property - * - * @return Zend_Auth_Adapter_Http_Resolver_Interface - */ - public function getBasicResolver() - { - return $this->_basicResolver; - } - - /** - * Setter for the _digestResolver property - * - * @param Zend_Auth_Adapter_Http_Resolver_Interface $resolver - * @return Zend_Auth_Adapter_Http Provides a fluent interface - */ - public function setDigestResolver(Zend_Auth_Adapter_Http_Resolver_Interface $resolver) - { - $this->_digestResolver = $resolver; - - return $this; - } - - /** - * Getter for the _digestResolver property - * - * @return Zend_Auth_Adapter_Http_Resolver_Interface - */ - public function getDigestResolver() - { - return $this->_digestResolver; - } - - /** - * Setter for the Request object - * - * @param Zend_Controller_Request_Http $request - * @return Zend_Auth_Adapter_Http Provides a fluent interface - */ - public function setRequest(Zend_Controller_Request_Http $request) - { - $this->_request = $request; - - return $this; - } - - /** - * Getter for the Request object - * - * @return Zend_Controller_Request_Http - */ - public function getRequest() - { - return $this->_request; - } - - /** - * Setter for the Response object - * - * @param Zend_Controller_Response_Http $response - * @return Zend_Auth_Adapter_Http Provides a fluent interface - */ - public function setResponse(Zend_Controller_Response_Http $response) - { - $this->_response = $response; - - return $this; - } - - /** - * Getter for the Response object - * - * @return Zend_Controller_Response_Http - */ - public function getResponse() - { - return $this->_response; - } - - /** - * Authenticate - * - * @throws Zend_Auth_Adapter_Exception - * @return Zend_Auth_Result - */ - public function authenticate() - { - if (empty($this->_request) || - empty($this->_response)) { - /** - * @see Zend_Auth_Adapter_Exception - */ - #require_once 'Zend/Auth/Adapter/Exception.php'; - throw new Zend_Auth_Adapter_Exception('Request and Response objects must be set before calling ' - . 'authenticate()'); - } - - if ($this->_imaProxy) { - $getHeader = 'Proxy-Authorization'; - } else { - $getHeader = 'Authorization'; - } - - $authHeader = $this->_request->getHeader($getHeader); - if (!$authHeader) { - return $this->_challengeClient(); - } - - list($clientScheme) = explode(' ', $authHeader); - $clientScheme = strtolower($clientScheme); - - // The server can issue multiple challenges, but the client should - // answer with only the selected auth scheme. - if (!in_array($clientScheme, $this->_supportedSchemes)) { - $this->_response->setHttpResponseCode(400); - return new Zend_Auth_Result( - Zend_Auth_Result::FAILURE_UNCATEGORIZED, - array(), - array('Client requested an incorrect or unsupported authentication scheme') - ); - } - - // client sent a scheme that is not the one required - if (!in_array($clientScheme, $this->_acceptSchemes)) { - // challenge again the client - return $this->_challengeClient(); - } - - switch ($clientScheme) { - case 'basic': - $result = $this->_basicAuth($authHeader); - break; - case 'digest': - $result = $this->_digestAuth($authHeader); - break; - default: - /** - * @see Zend_Auth_Adapter_Exception - */ - #require_once 'Zend/Auth/Adapter/Exception.php'; - throw new Zend_Auth_Adapter_Exception('Unsupported authentication scheme'); - } - - return $result; - } - - /** - * Challenge Client - * - * Sets a 401 or 407 Unauthorized response code, and creates the - * appropriate Authenticate header(s) to prompt for credentials. - * - * @return Zend_Auth_Result Always returns a non-identity Auth result - */ - protected function _challengeClient() - { - if ($this->_imaProxy) { - $statusCode = 407; - $headerName = 'Proxy-Authenticate'; - } else { - $statusCode = 401; - $headerName = 'WWW-Authenticate'; - } - - $this->_response->setHttpResponseCode($statusCode); - - // Send a challenge in each acceptable authentication scheme - if (in_array('basic', $this->_acceptSchemes)) { - $this->_response->setHeader($headerName, $this->_basicHeader()); - } - if (in_array('digest', $this->_acceptSchemes)) { - $this->_response->setHeader($headerName, $this->_digestHeader()); - } - return new Zend_Auth_Result( - Zend_Auth_Result::FAILURE_CREDENTIAL_INVALID, - array(), - array('Invalid or absent credentials; challenging client') - ); - } - - /** - * Basic Header - * - * Generates a Proxy- or WWW-Authenticate header value in the Basic - * authentication scheme. - * - * @return string Authenticate header value - */ - protected function _basicHeader() - { - return 'Basic realm="' . $this->_realm . '"'; - } - - /** - * Digest Header - * - * Generates a Proxy- or WWW-Authenticate header value in the Digest - * authentication scheme. - * - * @return string Authenticate header value - */ - protected function _digestHeader() - { - $wwwauth = 'Digest realm="' . $this->_realm . '", ' - . 'domain="' . $this->_domains . '", ' - . 'nonce="' . $this->_calcNonce() . '", ' - . ($this->_useOpaque ? 'opaque="' . $this->_calcOpaque() . '", ' : '') - . 'algorithm="' . $this->_algo . '", ' - . 'qop="' . implode(',', $this->_supportedQops) . '"'; - - return $wwwauth; - } - - /** - * Basic Authentication - * - * @param string $header Client's Authorization header - * @throws Zend_Auth_Adapter_Exception - * @return Zend_Auth_Result - */ - protected function _basicAuth($header) - { - if (empty($header)) { - /** - * @see Zend_Auth_Adapter_Exception - */ - #require_once 'Zend/Auth/Adapter/Exception.php'; - throw new Zend_Auth_Adapter_Exception('The value of the client Authorization header is required'); - } - if (empty($this->_basicResolver)) { - /** - * @see Zend_Auth_Adapter_Exception - */ - #require_once 'Zend/Auth/Adapter/Exception.php'; - throw new Zend_Auth_Adapter_Exception('A basicResolver object must be set before doing Basic ' - . 'authentication'); - } - - // Decode the Authorization header - $auth = substr($header, strlen('Basic ')); - $auth = base64_decode($auth); - if (!$auth) { - /** - * @see Zend_Auth_Adapter_Exception - */ - #require_once 'Zend/Auth/Adapter/Exception.php'; - throw new Zend_Auth_Adapter_Exception('Unable to base64_decode Authorization header value'); - } - - // See ZF-1253. Validate the credentials the same way the digest - // implementation does. If invalid credentials are detected, - // re-challenge the client. - if (!ctype_print($auth)) { - return $this->_challengeClient(); - } - // Fix for ZF-1515: Now re-challenges on empty username or password - $creds = array_filter(explode(':', $auth)); - if (count($creds) != 2) { - return $this->_challengeClient(); - } - - $password = $this->_basicResolver->resolve($creds[0], $this->_realm); - if ($password && $this->_secureStringCompare($password, $creds[1])) { - $identity = array('username'=>$creds[0], 'realm'=>$this->_realm); - return new Zend_Auth_Result(Zend_Auth_Result::SUCCESS, $identity); - } else { - return $this->_challengeClient(); - } - } - - /** - * Digest Authentication - * - * @param string $header Client's Authorization header - * @throws Zend_Auth_Adapter_Exception - * @return Zend_Auth_Result Valid auth result only on successful auth - */ - protected function _digestAuth($header) - { - if (empty($header)) { - /** - * @see Zend_Auth_Adapter_Exception - */ - #require_once 'Zend/Auth/Adapter/Exception.php'; - throw new Zend_Auth_Adapter_Exception('The value of the client Authorization header is required'); - } - if (empty($this->_digestResolver)) { - /** - * @see Zend_Auth_Adapter_Exception - */ - #require_once 'Zend/Auth/Adapter/Exception.php'; - throw new Zend_Auth_Adapter_Exception('A digestResolver object must be set before doing Digest authentication'); - } - - $data = $this->_parseDigestAuth($header); - if ($data === false) { - $this->_response->setHttpResponseCode(400); - return new Zend_Auth_Result( - Zend_Auth_Result::FAILURE_UNCATEGORIZED, - array(), - array('Invalid Authorization header format') - ); - } - - // See ZF-1052. This code was a bit too unforgiving of invalid - // usernames. Now, if the username is bad, we re-challenge the client. - if ('::invalid::' == $data['username']) { - return $this->_challengeClient(); - } - - // Verify that the client sent back the same nonce - if ($this->_calcNonce() != $data['nonce']) { - return $this->_challengeClient(); - } - // The opaque value is also required to match, but of course IE doesn't - // play ball. - if (!$this->_ieNoOpaque && $this->_calcOpaque() != $data['opaque']) { - return $this->_challengeClient(); - } - - // Look up the user's password hash. If not found, deny access. - // This makes no assumptions about how the password hash was - // constructed beyond that it must have been built in such a way as - // to be recreatable with the current settings of this object. - $ha1 = $this->_digestResolver->resolve($data['username'], $data['realm']); - if ($ha1 === false) { - return $this->_challengeClient(); - } - - // If MD5-sess is used, a1 value is made of the user's password - // hash with the server and client nonce appended, separated by - // colons. - if ($this->_algo == 'MD5-sess') { - $ha1 = hash('md5', $ha1 . ':' . $data['nonce'] . ':' . $data['cnonce']); - } - - // Calculate h(a2). The value of this hash depends on the qop - // option selected by the client and the supported hash functions - switch ($data['qop']) { - case 'auth': - $a2 = $this->_request->getMethod() . ':' . $data['uri']; - break; - case 'auth-int': - // Should be REQUEST_METHOD . ':' . uri . ':' . hash(entity-body), - // but this isn't supported yet, so fall through to default case - default: - /** - * @see Zend_Auth_Adapter_Exception - */ - #require_once 'Zend/Auth/Adapter/Exception.php'; - throw new Zend_Auth_Adapter_Exception('Client requested an unsupported qop option'); - } - // Using hash() should make parameterizing the hash algorithm - // easier - $ha2 = hash('md5', $a2); - - - // Calculate the server's version of the request-digest. This must - // match $data['response']. See RFC 2617, section 3.2.2.1 - $message = $data['nonce'] . ':' . $data['nc'] . ':' . $data['cnonce'] . ':' . $data['qop'] . ':' . $ha2; - $digest = hash('md5', $ha1 . ':' . $message); - - // If our digest matches the client's let them in, otherwise return - // a 401 code and exit to prevent access to the protected resource. - if ($this->_secureStringCompare($digest, $data['response'])) { - $identity = array('username'=>$data['username'], 'realm'=>$data['realm']); - return new Zend_Auth_Result(Zend_Auth_Result::SUCCESS, $identity); - } else { - return $this->_challengeClient(); - } - } - - /** - * Calculate Nonce - * - * @return string The nonce value - */ - protected function _calcNonce() - { - // Once subtle consequence of this timeout calculation is that it - // actually divides all of time into _nonceTimeout-sized sections, such - // that the value of timeout is the point in time of the next - // approaching "boundary" of a section. This allows the server to - // consistently generate the same timeout (and hence the same nonce - // value) across requests, but only as long as one of those - // "boundaries" is not crossed between requests. If that happens, the - // nonce will change on its own, and effectively log the user out. This - // would be surprising if the user just logged in. - $timeout = ceil(time() / $this->_nonceTimeout) * $this->_nonceTimeout; - - $nonce = hash('md5', $timeout . ':' . $this->_request->getServer('HTTP_USER_AGENT') . ':' . __CLASS__); - return $nonce; - } - - /** - * Calculate Opaque - * - * The opaque string can be anything; the client must return it exactly as - * it was sent. It may be useful to store data in this string in some - * applications. Ideally, a new value for this would be generated each time - * a WWW-Authenticate header is sent (in order to reduce predictability), - * but we would have to be able to create the same exact value across at - * least two separate requests from the same client. - * - * @return string The opaque value - */ - protected function _calcOpaque() - { - return hash('md5', 'Opaque Data:' . __CLASS__); - } - - /** - * Parse Digest Authorization header - * - * @param string $header Client's Authorization: HTTP header - * @return array|false Data elements from header, or false if any part of - * the header is invalid - */ - protected function _parseDigestAuth($header) - { - $temp = null; - $data = array(); - - // See ZF-1052. Detect invalid usernames instead of just returning a - // 400 code. - $ret = preg_match('/username="([^"]+)"/', $header, $temp); - if (!$ret || empty($temp[1]) - || !ctype_print($temp[1]) - || strpos($temp[1], ':') !== false) { - $data['username'] = '::invalid::'; - } else { - $data['username'] = $temp[1]; - } - $temp = null; - - $ret = preg_match('/realm="([^"]+)"/', $header, $temp); - if (!$ret || empty($temp[1])) { - return false; - } - if (!ctype_print($temp[1]) || strpos($temp[1], ':') !== false) { - return false; - } else { - $data['realm'] = $temp[1]; - } - $temp = null; - - $ret = preg_match('/nonce="([^"]+)"/', $header, $temp); - if (!$ret || empty($temp[1])) { - return false; - } - if (!ctype_xdigit($temp[1])) { - return false; - } else { - $data['nonce'] = $temp[1]; - } - $temp = null; - - $ret = preg_match('/uri="([^"]+)"/', $header, $temp); - if (!$ret || empty($temp[1])) { - return false; - } - // Section 3.2.2.5 in RFC 2617 says the authenticating server must - // verify that the URI field in the Authorization header is for the - // same resource requested in the Request Line. - $rUri = @parse_url($this->_request->getRequestUri()); - $cUri = @parse_url($temp[1]); - if (false === $rUri || false === $cUri) { - return false; - } else { - // Make sure the path portion of both URIs is the same - if ($rUri['path'] != $cUri['path']) { - return false; - } - // Section 3.2.2.5 seems to suggest that the value of the URI - // Authorization field should be made into an absolute URI if the - // Request URI is absolute, but it's vague, and that's a bunch of - // code I don't want to write right now. - $data['uri'] = $temp[1]; - } - $temp = null; - - $ret = preg_match('/response="([^"]+)"/', $header, $temp); - if (!$ret || empty($temp[1])) { - return false; - } - if (32 != strlen($temp[1]) || !ctype_xdigit($temp[1])) { - return false; - } else { - $data['response'] = $temp[1]; - } - $temp = null; - - // The spec says this should default to MD5 if omitted. OK, so how does - // that square with the algo we send out in the WWW-Authenticate header, - // if it can easily be overridden by the client? - $ret = preg_match('/algorithm="?(' . $this->_algo . ')"?/', $header, $temp); - if ($ret && !empty($temp[1]) - && in_array($temp[1], $this->_supportedAlgos)) { - $data['algorithm'] = $temp[1]; - } else { - $data['algorithm'] = 'MD5'; // = $this->_algo; ? - } - $temp = null; - - // Not optional in this implementation - $ret = preg_match('/cnonce="([^"]+)"/', $header, $temp); - if (!$ret || empty($temp[1])) { - return false; - } - if (!ctype_print($temp[1])) { - return false; - } else { - $data['cnonce'] = $temp[1]; - } - $temp = null; - - // If the server sent an opaque value, the client must send it back - if ($this->_useOpaque) { - $ret = preg_match('/opaque="([^"]+)"/', $header, $temp); - if (!$ret || empty($temp[1])) { - - // Big surprise: IE isn't RFC 2617-compliant. - if (false !== strpos($this->_request->getHeader('User-Agent'), 'MSIE')) { - $temp[1] = ''; - $this->_ieNoOpaque = true; - } else { - return false; - } - } - // This implementation only sends MD5 hex strings in the opaque value - if (!$this->_ieNoOpaque && - (32 != strlen($temp[1]) || !ctype_xdigit($temp[1]))) { - return false; - } else { - $data['opaque'] = $temp[1]; - } - $temp = null; - } - - // Not optional in this implementation, but must be one of the supported - // qop types - $ret = preg_match('/qop="?(' . implode('|', $this->_supportedQops) . ')"?/', $header, $temp); - if (!$ret || empty($temp[1])) { - return false; - } - if (!in_array($temp[1], $this->_supportedQops)) { - return false; - } else { - $data['qop'] = $temp[1]; - } - $temp = null; - - // Not optional in this implementation. The spec says this value - // shouldn't be a quoted string, but apparently some implementations - // quote it anyway. See ZF-1544. - $ret = preg_match('/nc="?([0-9A-Fa-f]{8})"?/', $header, $temp); - if (!$ret || empty($temp[1])) { - return false; - } - if (8 != strlen($temp[1]) || !ctype_xdigit($temp[1])) { - return false; - } else { - $data['nc'] = $temp[1]; - } - $temp = null; - - return $data; - } - - /** - * Securely compare two strings for equality while avoided C level memcmp() - * optimisations capable of leaking timing information useful to an attacker - * attempting to iteratively guess the unknown string (e.g. password) being - * compared against. - * - * @param string $a - * @param string $b - * @return bool - */ - protected function _secureStringCompare($a, $b) - { - if (strlen($a) !== strlen($b)) { - return false; - } - $result = 0; - for ($i = 0; $i < strlen($a); $i++) { - $result |= ord($a[$i]) ^ ord($b[$i]); - } - return $result == 0; - } -} diff --git a/library/Zend/Auth/Adapter/Http/Resolver/Exception.php b/library/Zend/Auth/Adapter/Http/Resolver/Exception.php deleted file mode 100644 index dd47800f5d..0000000000 --- a/library/Zend/Auth/Adapter/Http/Resolver/Exception.php +++ /dev/null @@ -1,40 +0,0 @@ -setFile($path); - } - } - - /** - * Set the path to the credentials file - * - * @param string $path - * @throws Zend_Auth_Adapter_Http_Resolver_Exception - * @return Zend_Auth_Adapter_Http_Resolver_File Provides a fluent interface - */ - public function setFile($path) - { - if (empty($path) || !is_readable($path)) { - /** - * @see Zend_Auth_Adapter_Http_Resolver_Exception - */ - #require_once 'Zend/Auth/Adapter/Http/Resolver/Exception.php'; - throw new Zend_Auth_Adapter_Http_Resolver_Exception('Path not readable: ' . $path); - } - $this->_file = $path; - - return $this; - } - - /** - * Returns the path to the credentials file - * - * @return string - */ - public function getFile() - { - return $this->_file; - } - - /** - * Resolve credentials - * - * Only the first matching username/realm combination in the file is - * returned. If the file contains credentials for Digest authentication, - * the returned string is the password hash, or h(a1) from RFC 2617. The - * returned string is the plain-text password for Basic authentication. - * - * The expected format of the file is: - * username:realm:sharedSecret - * - * That is, each line consists of the user's username, the applicable - * authentication realm, and the password or hash, each delimited by - * colons. - * - * @param string $username Username - * @param string $realm Authentication Realm - * @throws Zend_Auth_Adapter_Http_Resolver_Exception - * @return string|false User's shared secret, if the user is found in the - * realm, false otherwise. - */ - public function resolve($username, $realm) - { - if (empty($username)) { - /** - * @see Zend_Auth_Adapter_Http_Resolver_Exception - */ - #require_once 'Zend/Auth/Adapter/Http/Resolver/Exception.php'; - throw new Zend_Auth_Adapter_Http_Resolver_Exception('Username is required'); - } else if (!ctype_print($username) || strpos($username, ':') !== false) { - /** - * @see Zend_Auth_Adapter_Http_Resolver_Exception - */ - #require_once 'Zend/Auth/Adapter/Http/Resolver/Exception.php'; - throw new Zend_Auth_Adapter_Http_Resolver_Exception('Username must consist only of printable characters, ' - . 'excluding the colon'); - } - if (empty($realm)) { - /** - * @see Zend_Auth_Adapter_Http_Resolver_Exception - */ - #require_once 'Zend/Auth/Adapter/Http/Resolver/Exception.php'; - throw new Zend_Auth_Adapter_Http_Resolver_Exception('Realm is required'); - } else if (!ctype_print($realm) || strpos($realm, ':') !== false) { - /** - * @see Zend_Auth_Adapter_Http_Resolver_Exception - */ - #require_once 'Zend/Auth/Adapter/Http/Resolver/Exception.php'; - throw new Zend_Auth_Adapter_Http_Resolver_Exception('Realm must consist only of printable characters, ' - . 'excluding the colon.'); - } - - // Open file, read through looking for matching credentials - $fp = @fopen($this->_file, 'r'); - if (!$fp) { - /** - * @see Zend_Auth_Adapter_Http_Resolver_Exception - */ - #require_once 'Zend/Auth/Adapter/Http/Resolver/Exception.php'; - throw new Zend_Auth_Adapter_Http_Resolver_Exception('Unable to open password file: ' . $this->_file); - } - - // No real validation is done on the contents of the password file. The - // assumption is that we trust the administrators to keep it secure. - while (($line = fgetcsv($fp, 512, ':')) !== false) { - if ($line[0] == $username && $line[1] == $realm) { - $password = $line[2]; - fclose($fp); - return $password; - } - } - - fclose($fp); - return false; - } -} diff --git a/library/Zend/Auth/Adapter/Http/Resolver/Interface.php b/library/Zend/Auth/Adapter/Http/Resolver/Interface.php deleted file mode 100644 index 4326ee8202..0000000000 --- a/library/Zend/Auth/Adapter/Http/Resolver/Interface.php +++ /dev/null @@ -1,47 +0,0 @@ -setOptions($options); - if ($username !== null) { - $this->setUsername($username); - } - if ($password !== null) { - $this->setPassword($password); - } - } - - /** - * Returns the array of arrays of Zend_Ldap options of this adapter. - * - * @return array|null - */ - public function getOptions() - { - return $this->_options; - } - - /** - * Sets the array of arrays of Zend_Ldap options to be used by - * this adapter. - * - * @param array $options The array of arrays of Zend_Ldap options - * @return Zend_Auth_Adapter_Ldap Provides a fluent interface - */ - public function setOptions($options) - { - $this->_options = is_array($options) ? $options : array(); - return $this; - } - - /** - * Returns the username of the account being authenticated, or - * NULL if none is set. - * - * @return string|null - */ - public function getUsername() - { - return $this->_username; - } - - /** - * Sets the username for binding - * - * @param string $username The username for binding - * @return Zend_Auth_Adapter_Ldap Provides a fluent interface - */ - public function setUsername($username) - { - $this->_username = (string) $username; - return $this; - } - - /** - * Returns the password of the account being authenticated, or - * NULL if none is set. - * - * @return string|null - */ - public function getPassword() - { - return $this->_password; - } - - /** - * Sets the passwort for the account - * - * @param string $password The password of the account being authenticated - * @return Zend_Auth_Adapter_Ldap Provides a fluent interface - */ - public function setPassword($password) - { - $this->_password = (string) $password; - return $this; - } - - /** - * setIdentity() - set the identity (username) to be used - * - * Proxies to {@see setUsername()} - * - * Closes ZF-6813 - * - * @param string $identity - * @return Zend_Auth_Adapter_Ldap Provides a fluent interface - */ - public function setIdentity($identity) - { - return $this->setUsername($identity); - } - - /** - * setCredential() - set the credential (password) value to be used - * - * Proxies to {@see setPassword()} - * - * Closes ZF-6813 - * - * @param string $credential - * @return Zend_Auth_Adapter_Ldap Provides a fluent interface - */ - public function setCredential($credential) - { - return $this->setPassword($credential); - } - - /** - * Returns the LDAP Object - * - * @return Zend_Ldap The Zend_Ldap object used to authenticate the credentials - */ - public function getLdap() - { - if ($this->_ldap === null) { - /** - * @see Zend_Ldap - */ - #require_once 'Zend/Ldap.php'; - $this->_ldap = new Zend_Ldap(); - } - - return $this->_ldap; - } - - /** - * Set an Ldap connection - * - * @param Zend_Ldap $ldap An existing Ldap object - * @return Zend_Auth_Adapter_Ldap Provides a fluent interface - */ - public function setLdap(Zend_Ldap $ldap) - { - $this->_ldap = $ldap; - - $this->setOptions(array($ldap->getOptions())); - - return $this; - } - - /** - * Returns a domain name for the current LDAP options. This is used - * for skipping redundant operations (e.g. authentications). - * - * @return string - */ - protected function _getAuthorityName() - { - $options = $this->getLdap()->getOptions(); - $name = $options['accountDomainName']; - if (!$name) - $name = $options['accountDomainNameShort']; - return $name ? $name : ''; - } - - /** - * Authenticate the user - * - * @throws Zend_Auth_Adapter_Exception - * @return Zend_Auth_Result - */ - public function authenticate() - { - /** - * @see Zend_Ldap_Exception - */ - #require_once 'Zend/Ldap/Exception.php'; - - $messages = array(); - $messages[0] = ''; // reserved - $messages[1] = ''; // reserved - - $username = $this->_username; - $password = $this->_password; - - if (!$username) { - $code = Zend_Auth_Result::FAILURE_IDENTITY_NOT_FOUND; - $messages[0] = 'A username is required'; - return new Zend_Auth_Result($code, '', $messages); - } - if (!$password) { - /* A password is required because some servers will - * treat an empty password as an anonymous bind. - */ - $code = Zend_Auth_Result::FAILURE_CREDENTIAL_INVALID; - $messages[0] = 'A password is required'; - return new Zend_Auth_Result($code, '', $messages); - } - - $ldap = $this->getLdap(); - - $code = Zend_Auth_Result::FAILURE; - $messages[0] = "Authority not found: $username"; - $failedAuthorities = array(); - - /* Iterate through each server and try to authenticate the supplied - * credentials against it. - */ - foreach ($this->_options as $name => $options) { - - if (!is_array($options)) { - /** - * @see Zend_Auth_Adapter_Exception - */ - #require_once 'Zend/Auth/Adapter/Exception.php'; - throw new Zend_Auth_Adapter_Exception('Adapter options array not an array'); - } - $adapterOptions = $this->_prepareOptions($ldap, $options); - $dname = ''; - - try { - if ($messages[1]) - $messages[] = $messages[1]; - $messages[1] = ''; - $messages[] = $this->_optionsToString($options); - - $dname = $this->_getAuthorityName(); - if (isset($failedAuthorities[$dname])) { - /* If multiple sets of server options for the same domain - * are supplied, we want to skip redundant authentications - * where the identity or credentials where found to be - * invalid with another server for the same domain. The - * $failedAuthorities array tracks this condition (and also - * serves to supply the original error message). - * This fixes issue ZF-4093. - */ - $messages[1] = $failedAuthorities[$dname]; - $messages[] = "Skipping previously failed authority: $dname"; - continue; - } - - $canonicalName = $ldap->getCanonicalAccountName($username); - $ldap->bind($canonicalName, $password); - /* - * Fixes problem when authenticated user is not allowed to retrieve - * group-membership information or own account. - * This requires that the user specified with "username" and optionally - * "password" in the Zend_Ldap options is able to retrieve the required - * information. - */ - $requireRebind = false; - if (isset($options['username'])) { - $ldap->bind(); - $requireRebind = true; - } - $dn = $ldap->getCanonicalAccountName($canonicalName, Zend_Ldap::ACCTNAME_FORM_DN); - - $groupResult = $this->_checkGroupMembership($ldap, $canonicalName, $dn, $adapterOptions); - if ($groupResult === true) { - $this->_authenticatedDn = $dn; - $messages[0] = ''; - $messages[1] = ''; - $messages[] = "$canonicalName authentication successful"; - if ($requireRebind === true) { - // rebinding with authenticated user - $ldap->bind($dn, $password); - } - return new Zend_Auth_Result(Zend_Auth_Result::SUCCESS, $canonicalName, $messages); - } else { - $messages[0] = 'Account is not a member of the specified group'; - $messages[1] = $groupResult; - $failedAuthorities[$dname] = $groupResult; - } - } catch (Zend_Ldap_Exception $zle) { - - /* LDAP based authentication is notoriously difficult to diagnose. Therefore - * we bend over backwards to capture and record every possible bit of - * information when something goes wrong. - */ - - $err = $zle->getCode(); - - if ($err == Zend_Ldap_Exception::LDAP_X_DOMAIN_MISMATCH) { - /* This error indicates that the domain supplied in the - * username did not match the domains in the server options - * and therefore we should just skip to the next set of - * server options. - */ - continue; - } else if ($err == Zend_Ldap_Exception::LDAP_NO_SUCH_OBJECT) { - $code = Zend_Auth_Result::FAILURE_IDENTITY_NOT_FOUND; - $messages[0] = "Account not found: $username"; - $failedAuthorities[$dname] = $zle->getMessage(); - } else if ($err == Zend_Ldap_Exception::LDAP_INVALID_CREDENTIALS) { - $code = Zend_Auth_Result::FAILURE_CREDENTIAL_INVALID; - $messages[0] = 'Invalid credentials'; - $failedAuthorities[$dname] = $zle->getMessage(); - } else { - $line = $zle->getLine(); - $messages[] = $zle->getFile() . "($line): " . $zle->getMessage(); - $messages[] = preg_replace( - '/\b'.preg_quote(substr($password, 0, 15), '/').'\b/', - '*****', - $zle->getTraceAsString() - ); - $messages[0] = 'An unexpected failure occurred'; - } - $messages[1] = $zle->getMessage(); - } - } - - $msg = isset($messages[1]) ? $messages[1] : $messages[0]; - $messages[] = "$username authentication failed: $msg"; - - return new Zend_Auth_Result($code, $username, $messages); - } - - /** - * Sets the LDAP specific options on the Zend_Ldap instance - * - * @param Zend_Ldap $ldap - * @param array $options - * @return array of auth-adapter specific options - */ - protected function _prepareOptions(Zend_Ldap $ldap, array $options) - { - $adapterOptions = array( - 'group' => null, - 'groupDn' => $ldap->getBaseDn(), - 'groupScope' => Zend_Ldap::SEARCH_SCOPE_SUB, - 'groupAttr' => 'cn', - 'groupFilter' => 'objectClass=groupOfUniqueNames', - 'memberAttr' => 'uniqueMember', - 'memberIsDn' => true - ); - foreach ($adapterOptions as $key => $value) { - if (array_key_exists($key, $options)) { - $value = $options[$key]; - unset($options[$key]); - switch ($key) { - case 'groupScope': - $value = (int)$value; - if (in_array($value, array(Zend_Ldap::SEARCH_SCOPE_BASE, - Zend_Ldap::SEARCH_SCOPE_ONE, Zend_Ldap::SEARCH_SCOPE_SUB), true)) { - $adapterOptions[$key] = $value; - } - break; - case 'memberIsDn': - $adapterOptions[$key] = ($value === true || - $value === '1' || strcasecmp($value, 'true') == 0); - break; - default: - $adapterOptions[$key] = trim($value); - break; - } - } - } - $ldap->setOptions($options); - return $adapterOptions; - } - - /** - * Checks the group membership of the bound user - * - * @param Zend_Ldap $ldap - * @param string $canonicalName - * @param string $dn - * @param array $adapterOptions - * @return string|true - */ - protected function _checkGroupMembership(Zend_Ldap $ldap, $canonicalName, $dn, array $adapterOptions) - { - if ($adapterOptions['group'] === null) { - return true; - } - - if ($adapterOptions['memberIsDn'] === false) { - $user = $canonicalName; - } else { - $user = $dn; - } - - /** - * @see Zend_Ldap_Filter - */ - #require_once 'Zend/Ldap/Filter.php'; - $groupName = Zend_Ldap_Filter::equals($adapterOptions['groupAttr'], $adapterOptions['group']); - $membership = Zend_Ldap_Filter::equals($adapterOptions['memberAttr'], $user); - $group = Zend_Ldap_Filter::andFilter($groupName, $membership); - $groupFilter = $adapterOptions['groupFilter']; - if (!empty($groupFilter)) { - $group = $group->addAnd($groupFilter); - } - - $result = $ldap->count($group, $adapterOptions['groupDn'], $adapterOptions['groupScope']); - - if ($result === 1) { - return true; - } else { - return 'Failed to verify group membership with ' . $group->toString(); - } - } - - /** - * getAccountObject() - Returns the result entry as a stdClass object - * - * This resembles the feature {@see Zend_Auth_Adapter_DbTable::getResultRowObject()}. - * Closes ZF-6813 - * - * @param array $returnAttribs - * @param array $omitAttribs - * @return stdClass|boolean - */ - public function getAccountObject(array $returnAttribs = array(), array $omitAttribs = array()) - { - if (!$this->_authenticatedDn) { - return false; - } - - $returnObject = new stdClass(); - - $returnAttribs = array_map('strtolower', $returnAttribs); - $omitAttribs = array_map('strtolower', $omitAttribs); - $returnAttribs = array_diff($returnAttribs, $omitAttribs); - - $entry = $this->getLdap()->getEntry($this->_authenticatedDn, $returnAttribs, true); - foreach ($entry as $attr => $value) { - if (in_array($attr, $omitAttribs)) { - // skip attributes marked to be omitted - continue; - } - if (is_array($value)) { - $returnObject->$attr = (count($value) > 1) ? $value : $value[0]; - } else { - $returnObject->$attr = $value; - } - } - return $returnObject; - } - - /** - * Converts options to string - * - * @param array $options - * @return string - */ - private function _optionsToString(array $options) - { - $str = ''; - foreach ($options as $key => $val) { - if ($key === 'password') - $val = '*****'; - if ($str) - $str .= ','; - $str .= $key . '=' . $val; - } - return $str; - } -} diff --git a/library/Zend/Auth/Adapter/OpenId.php b/library/Zend/Auth/Adapter/OpenId.php deleted file mode 100644 index 0a68bc20ec..0000000000 --- a/library/Zend/Auth/Adapter/OpenId.php +++ /dev/null @@ -1,283 +0,0 @@ -_id = $id; - $this->_storage = $storage; - $this->_returnTo = $returnTo; - $this->_root = $root; - $this->_extensions = $extensions; - $this->_response = $response; - } - - /** - * Sets the value to be used as the identity - * - * @param string $id the identity value - * @return Zend_Auth_Adapter_OpenId Provides a fluent interface - */ - public function setIdentity($id) - { - $this->_id = $id; - return $this; - } - - /** - * Sets the storage implementation which will be use by OpenId - * - * @param Zend_OpenId_Consumer_Storage $storage - * @return Zend_Auth_Adapter_OpenId Provides a fluent interface - */ - public function setStorage(Zend_OpenId_Consumer_Storage $storage) - { - $this->_storage = $storage; - return $this; - } - - /** - * Sets the HTTP URL to redirect response from server to - * - * @param string $returnTo - * @return Zend_Auth_Adapter_OpenId Provides a fluent interface - */ - public function setReturnTo($returnTo) - { - $this->_returnTo = $returnTo; - return $this; - } - - /** - * Sets HTTP URL to identify consumer on server - * - * @param string $root - * @return Zend_Auth_Adapter_OpenId Provides a fluent interface - */ - public function setRoot($root) - { - $this->_root = $root; - return $this; - } - - /** - * Sets OpenID extension(s) - * - * @param mixed $extensions - * @return Zend_Auth_Adapter_OpenId Provides a fluent interface - */ - public function setExtensions($extensions) - { - $this->_extensions = $extensions; - return $this; - } - - /** - * Sets an optional response object to perform HTTP or HTML form redirection - * - * @param string $response - * @return Zend_Auth_Adapter_OpenId Provides a fluent interface - */ - public function setResponse($response) - { - $this->_response = $response; - return $this; - } - - /** - * Enables or disables interaction with user during authentication on - * OpenID provider. - * - * @param bool $check_immediate - * @return Zend_Auth_Adapter_OpenId Provides a fluent interface - */ - public function setCheckImmediate($check_immediate) - { - $this->_check_immediate = $check_immediate; - return $this; - } - - /** - * Sets HTTP client object to make HTTP requests - * - * @param Zend_Http_Client $client HTTP client object to be used - */ - public function setHttpClient($client) { - $this->_httpClient = $client; - } - - /** - * Authenticates the given OpenId identity. - * Defined by Zend_Auth_Adapter_Interface. - * - * @throws Zend_Auth_Adapter_Exception If answering the authentication query is impossible - * @return Zend_Auth_Result - */ - public function authenticate() { - $id = $this->_id; - if (!empty($id)) { - $consumer = new Zend_OpenId_Consumer($this->_storage); - $consumer->setHttpClient($this->_httpClient); - /* login() is never returns on success */ - if (!$this->_check_immediate) { - if (!$consumer->login($id, - $this->_returnTo, - $this->_root, - $this->_extensions, - $this->_response)) { - return new Zend_Auth_Result( - Zend_Auth_Result::FAILURE, - $id, - array("Authentication failed", $consumer->getError())); - } - } else { - if (!$consumer->check($id, - $this->_returnTo, - $this->_root, - $this->_extensions, - $this->_response)) { - return new Zend_Auth_Result( - Zend_Auth_Result::FAILURE, - $id, - array("Authentication failed", $consumer->getError())); - } - } - } else { - $params = (isset($_SERVER['REQUEST_METHOD']) && - $_SERVER['REQUEST_METHOD']=='POST') ? $_POST: $_GET; - $consumer = new Zend_OpenId_Consumer($this->_storage); - $consumer->setHttpClient($this->_httpClient); - if ($consumer->verify( - $params, - $id, - $this->_extensions)) { - return new Zend_Auth_Result( - Zend_Auth_Result::SUCCESS, - $id, - array("Authentication successful")); - } else { - return new Zend_Auth_Result( - Zend_Auth_Result::FAILURE, - $id, - array("Authentication failed", $consumer->getError())); - } - } - } - -} diff --git a/library/Zend/Auth/Exception.php b/library/Zend/Auth/Exception.php deleted file mode 100644 index 753f037552..0000000000 --- a/library/Zend/Auth/Exception.php +++ /dev/null @@ -1,36 +0,0 @@ - self::SUCCESS ) { - $code = 1; - } - - $this->_code = $code; - $this->_identity = $identity; - $this->_messages = $messages; - } - - /** - * Returns whether the result represents a successful authentication attempt - * - * @return boolean - */ - public function isValid() - { - return ($this->_code > 0) ? true : false; - } - - /** - * getCode() - Get the result code for this authentication attempt - * - * @return int - */ - public function getCode() - { - return $this->_code; - } - - /** - * Returns the identity used in the authentication attempt - * - * @return mixed - */ - public function getIdentity() - { - return $this->_identity; - } - - /** - * Returns an array of string reasons why the authentication attempt was unsuccessful - * - * If authentication was successful, this method returns an empty array. - * - * @return array - */ - public function getMessages() - { - return $this->_messages; - } -} diff --git a/library/Zend/Auth/Storage/Exception.php b/library/Zend/Auth/Storage/Exception.php deleted file mode 100644 index 7ab89718a0..0000000000 --- a/library/Zend/Auth/Storage/Exception.php +++ /dev/null @@ -1,38 +0,0 @@ -_data); - } - - /** - * Returns the contents of storage - * Behavior is undefined when storage is empty. - * - * @throws Zend_Auth_Storage_Exception If reading contents from storage is impossible - * @return mixed - */ - public function read() - { - return $this->_data; - } - - /** - * Writes $contents to storage - * - * @param mixed $contents - * @throws Zend_Auth_Storage_Exception If writing $contents to storage is impossible - * @return void - */ - public function write($contents) - { - $this->_data = $contents; - } - - /** - * Clears contents from storage - * - * @throws Zend_Auth_Storage_Exception If clearing contents from storage is impossible - * @return void - */ - public function clear() - { - $this->_data = null; - } -} diff --git a/library/Zend/Auth/Storage/Session.php b/library/Zend/Auth/Storage/Session.php deleted file mode 100644 index 8d179fb950..0000000000 --- a/library/Zend/Auth/Storage/Session.php +++ /dev/null @@ -1,149 +0,0 @@ -_namespace = $namespace; - $this->_member = $member; - $this->_session = new Zend_Session_Namespace($this->_namespace); - } - - /** - * Returns the session namespace - * - * @return string - */ - public function getNamespace() - { - return $this->_namespace; - } - - /** - * Returns the name of the session object member - * - * @return string - */ - public function getMember() - { - return $this->_member; - } - - /** - * Defined by Zend_Auth_Storage_Interface - * - * @return boolean - */ - public function isEmpty() - { - return !isset($this->_session->{$this->_member}); - } - - /** - * Defined by Zend_Auth_Storage_Interface - * - * @return mixed - */ - public function read() - { - return $this->_session->{$this->_member}; - } - - /** - * Defined by Zend_Auth_Storage_Interface - * - * @param mixed $contents - * @return void - */ - public function write($contents) - { - $this->_session->{$this->_member} = $contents; - } - - /** - * Defined by Zend_Auth_Storage_Interface - * - * @return void - */ - public function clear() - { - unset($this->_session->{$this->_member}); - } -} diff --git a/library/Zend/Barcode.php b/library/Zend/Barcode.php deleted file mode 100644 index 7338cbf0f9..0000000000 --- a/library/Zend/Barcode.php +++ /dev/null @@ -1,352 +0,0 @@ -rendererParams)) { - $rendererConfig = $barcode->rendererParams->toArray(); - } - if (isset($barcode->renderer)) { - $renderer = (string) $barcode->renderer; - } - if (isset($barcode->barcodeParams)) { - $barcodeConfig = $barcode->barcodeParams->toArray(); - } - if (isset($barcode->barcode)) { - $barcode = (string) $barcode->barcode; - } else { - $barcode = null; - } - } - - try { - $barcode = self::makeBarcode($barcode, $barcodeConfig); - $renderer = self::makeRenderer($renderer, $rendererConfig); - } catch (Zend_Exception $e) { - $renderable = ($e instanceof Zend_Barcode_Exception) ? $e->isRenderable() : false; - if ($automaticRenderError && $renderable) { - $barcode = self::makeBarcode('error', array( - 'text' => $e->getMessage() - )); - $renderer = self::makeRenderer($renderer, array()); - } else { - throw $e; - } - } - - $renderer->setAutomaticRenderError($automaticRenderError); - return $renderer->setBarcode($barcode); - } - - /** - * Barcode Constructor - * - * @param mixed $barcode String name of barcode class, or Zend_Config object. - * @param mixed $barcodeConfig OPTIONAL; an array or Zend_Config object with barcode parameters. - * @return Zend_Barcode_Object - */ - public static function makeBarcode($barcode, $barcodeConfig = array()) - { - if ($barcode instanceof Zend_Barcode_Object_ObjectAbstract) { - return $barcode; - } - - /* - * Convert Zend_Config argument to plain string - * barcode name and separate config object. - */ - if ($barcode instanceof Zend_Config) { - if (isset($barcode->barcodeParams) && $barcode->barcodeParams instanceof Zend_Config) { - $barcodeConfig = $barcode->barcodeParams->toArray(); - } - if (isset($barcode->barcode)) { - $barcode = (string) $barcode->barcode; - } else { - $barcode = null; - } - } - if ($barcodeConfig instanceof Zend_Config) { - $barcodeConfig = $barcodeConfig->toArray(); - } - - /* - * Verify that barcode parameters are in an array. - */ - if (!is_array($barcodeConfig)) { - /** - * @see Zend_Barcode_Exception - */ - #require_once 'Zend/Barcode/Exception.php'; - throw new Zend_Barcode_Exception( - 'Barcode parameters must be in an array or a Zend_Config object' - ); - } - - /* - * Verify that an barcode name has been specified. - */ - if (!is_string($barcode) || empty($barcode)) { - /** - * @see Zend_Barcode_Exception - */ - #require_once 'Zend/Barcode/Exception.php'; - throw new Zend_Barcode_Exception( - 'Barcode name must be specified in a string' - ); - } - /* - * Form full barcode class name - */ - $barcodeNamespace = 'Zend_Barcode_Object'; - if (isset($barcodeConfig['barcodeNamespace'])) { - $barcodeNamespace = $barcodeConfig['barcodeNamespace']; - } - - $barcodeName = strtolower($barcodeNamespace . '_' . $barcode); - $barcodeName = str_replace(' ', '_', ucwords( - str_replace( '_', ' ', $barcodeName) - )); - - /* - * Load the barcode class. This throws an exception - * if the specified class cannot be loaded. - */ - if (!class_exists($barcodeName)) { - #require_once 'Zend/Loader.php'; - Zend_Loader::loadClass($barcodeName); - } - - /* - * Create an instance of the barcode class. - * Pass the config to the barcode class constructor. - */ - $bcAdapter = new $barcodeName($barcodeConfig); - - /* - * Verify that the object created is a descendent of the abstract barcode type. - */ - if (!$bcAdapter instanceof Zend_Barcode_Object_ObjectAbstract) { - /** - * @see Zend_Barcode_Exception - */ - #require_once 'Zend/Barcode/Exception.php'; - throw new Zend_Barcode_Exception( - "Barcode class '$barcodeName' does not extend Zend_Barcode_Object_ObjectAbstract" - ); - } - return $bcAdapter; - } - - /** - * Renderer Constructor - * - * @param mixed $renderer String name of renderer class, or Zend_Config object. - * @param mixed $rendererConfig OPTIONAL; an array or Zend_Config object with renderer parameters. - * @return Zend_Barcode_Renderer - */ - public static function makeRenderer($renderer = 'image', $rendererConfig = array()) - { - if ($renderer instanceof Zend_Barcode_Renderer_RendererAbstract) { - return $renderer; - } - - /* - * Convert Zend_Config argument to plain string - * barcode name and separate config object. - */ - if ($renderer instanceof Zend_Config) { - if (isset($renderer->rendererParams)) { - $rendererConfig = $renderer->rendererParams->toArray(); - } - if (isset($renderer->renderer)) { - $renderer = (string) $renderer->renderer; - } - } - if ($rendererConfig instanceof Zend_Config) { - $rendererConfig = $rendererConfig->toArray(); - } - - /* - * Verify that barcode parameters are in an array. - */ - if (!is_array($rendererConfig)) { - /** - * @see Zend_Barcode_Exception - */ - #require_once 'Zend/Barcode/Exception.php'; - $e = new Zend_Barcode_Exception( - 'Barcode parameters must be in an array or a Zend_Config object' - ); - $e->setIsRenderable(false); - throw $e; - } - - /* - * Verify that an barcode name has been specified. - */ - if (!is_string($renderer) || empty($renderer)) { - /** - * @see Zend_Barcode_Exception - */ - #require_once 'Zend/Barcode/Exception.php'; - $e = new Zend_Barcode_Exception( - 'Renderer name must be specified in a string' - ); - $e->setIsRenderable(false); - throw $e; - } - - /* - * Form full barcode class name - */ - $rendererNamespace = 'Zend_Barcode_Renderer'; - if (isset($rendererConfig['rendererNamespace'])) { - $rendererNamespace = $rendererConfig['rendererNamespace']; - } - - $rendererName = strtolower($rendererNamespace . '_' . $renderer); - $rendererName = str_replace(' ', '_', ucwords( - str_replace( '_', ' ', $rendererName) - )); - - /* - * Load the barcode class. This throws an exception - * if the specified class cannot be loaded. - */ - if (!class_exists($rendererName)) { - #require_once 'Zend/Loader.php'; - Zend_Loader::loadClass($rendererName); - } - - /* - * Create an instance of the barcode class. - * Pass the config to the barcode class constructor. - */ - $rdrAdapter = new $rendererName($rendererConfig); - - /* - * Verify that the object created is a descendent of the abstract barcode type. - */ - if (!$rdrAdapter instanceof Zend_Barcode_Renderer_RendererAbstract) { - /** - * @see Zend_Barcode_Exception - */ - #require_once 'Zend/Barcode/Exception.php'; - $e = new Zend_Barcode_Exception( - "Renderer class '$rendererName' does not extend Zend_Barcode_Renderer_RendererAbstract" - ); - $e->setIsRenderable(false); - throw $e; - } - return $rdrAdapter; - } - - /** - * Proxy to renderer render() method - * - * @param string | Zend_Barcode_Object | array | Zend_Config $barcode - * @param string | Zend_Barcode_Renderer $renderer - * @param array | Zend_Config $barcodeConfig - * @param array | Zend_Config $rendererConfig - */ - public static function render( - $barcode, - $renderer, - $barcodeConfig = array(), - $rendererConfig = array() - ) { - self::factory($barcode, $renderer, $barcodeConfig, $rendererConfig)->render(); - } - - /** - * Proxy to renderer draw() method - * - * @param string | Zend_Barcode_Object | array | Zend_Config $barcode - * @param string | Zend_Barcode_Renderer $renderer - * @param array | Zend_Config $barcodeConfig - * @param array | Zend_Config $rendererConfig - * @return mixed - */ - public static function draw( - $barcode, - $renderer, - $barcodeConfig = array(), - $rendererConfig = array() - ) { - return self::factory($barcode, $renderer, $barcodeConfig, $rendererConfig)->draw(); - } - - /** - * Proxy for setBarcodeFont of Zend_Barcode_Object - * @param string $font - * @eturn void - */ - public static function setBarcodeFont($font) - { - #require_once 'Zend/Barcode/Object/ObjectAbstract.php'; - Zend_Barcode_Object_ObjectAbstract::setBarcodeFont($font); - } -} diff --git a/library/Zend/Barcode/Exception.php b/library/Zend/Barcode/Exception.php deleted file mode 100644 index 703b0c4f6e..0000000000 --- a/library/Zend/Barcode/Exception.php +++ /dev/null @@ -1,63 +0,0 @@ -_isRenderable = (bool) $flag; - return $this; - } - - /** - * Retrieve renderable flag - * - * @return bool - */ - public function isRenderable() - { - return $this->_isRenderable; - } -} diff --git a/library/Zend/Barcode/Object/Code128.php b/library/Zend/Barcode/Object/Code128.php deleted file mode 100644 index 0d5eabc12a..0000000000 --- a/library/Zend/Barcode/Object/Code128.php +++ /dev/null @@ -1,395 +0,0 @@ - "11011001100", 1 => "11001101100", 2 => "11001100110", - 3 => "10010011000", 4 => "10010001100", 5 => "10001001100", - 6 => "10011001000", 7 => "10011000100", 8 => "10001100100", - 9 => "11001001000", 10 => "11001000100", 11 => "11000100100", - 12 => "10110011100", 13 => "10011011100", 14 => "10011001110", - 15 => "10111001100", 16 => "10011101100", 17 => "10011100110", - 18 => "11001110010", 19 => "11001011100", 20 => "11001001110", - 21 => "11011100100", 22 => "11001110100", 23 => "11101101110", - 24 => "11101001100", 25 => "11100101100", 26 => "11100100110", - 27 => "11101100100", 28 => "11100110100", 29 => "11100110010", - 30 => "11011011000", 31 => "11011000110", 32 => "11000110110", - 33 => "10100011000", 34 => "10001011000", 35 => "10001000110", - 36 => "10110001000", 37 => "10001101000", 38 => "10001100010", - 39 => "11010001000", 40 => "11000101000", 41 => "11000100010", - 42 => "10110111000", 43 => "10110001110", 44 => "10001101110", - 45 => "10111011000", 46 => "10111000110", 47 => "10001110110", - 48 => "11101110110", 49 => "11010001110", 50 => "11000101110", - 51 => "11011101000", 52 => "11011100010", 53 => "11011101110", - 54 => "11101011000", 55 => "11101000110", 56 => "11100010110", - 57 => "11101101000", 58 => "11101100010", 59 => "11100011010", - 60 => "11101111010", 61 => "11001000010", 62 => "11110001010", - 63 => "10100110000", 64 => "10100001100", 65 => "10010110000", - 66 => "10010000110", 67 => "10000101100", 68 => "10000100110", - 69 => "10110010000", 70 => "10110000100", 71 => "10011010000", - 72 => "10011000010", 73 => "10000110100", 74 => "10000110010", - 75 => "11000010010", 76 => "11001010000", 77 => "11110111010", - 78 => "11000010100", 79 => "10001111010", 80 => "10100111100", - 81 => "10010111100", 82 => "10010011110", 83 => "10111100100", - 84 => "10011110100", 85 => "10011110010", 86 => "11110100100", - 87 => "11110010100", 88 => "11110010010", 89 => "11011011110", - 90 => "11011110110", 91 => "11110110110", 92 => "10101111000", - 93 => "10100011110", 94 => "10001011110", 95 => "10111101000", - 96 => "10111100010", 97 => "11110101000", 98 => "11110100010", - 99 => "10111011110", 100 => "10111101110", 101 => "11101011110", - 102 => "11110101110", - 103 => "11010000100", 104 => "11010010000", 105 => "11010011100", - 106 => "1100011101011"); - - /** - * Character sets ABC - * @var array - */ - protected $_charSets = array( - 'A' => array( - ' ', '!', '"', '#', '$', '%', '&', "'", - '(', ')', '*', '+', ',', '-', '.', '/', - '0', '1', '2', '3', '4', '5', '6', '7', - '8', '9', ':', ';', '<', '=', '>', '?', - '@', 'A', 'B', 'C', 'D', 'E', 'F', 'G', - 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', - 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', - 'X', 'Y', 'Z', '[', '\\', ']', '^', '_', - 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, - 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F, - 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, - 0x18, 0x19, 0x1A, 0x1B, 0x1C, 0x1D, 0x1E, 0x1F, - 'FNC3', 'FNC2', 'SHIFT', 'Code C', 'Code B', 'FNC4', 'FNC1', - 'START A', 'START B', 'START C', 'STOP'), - 'B' => array( - ' ', '!', '"', '#', '$', '%', '&', "'", - '(', ')', '*', '+', ',', '-', '.', '/', - '0', '1', '2', '3', '4', '5', '6', '7', - '8', '9', ':', ';', '<', '=', '>', '?', - '@', 'A', 'B', 'C', 'D', 'E', 'F', 'G', - 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', - 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', - 'X', 'Y', 'Z', '[', '\\', ']', '^', '_', - '`', 'a', 'b', 'c', 'd', 'e', 'f', 'g', - 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', - 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', - 'x', 'y', 'z', '{', '|', '}', '~', 0x7F, - 'FNC3', 'FNC2', 'SHIFT', 'Code C', 'FNC4', 'Code A', 'FNC1', - 'START A', 'START B', 'START C', 'STOP',), - 'C' => array( - '00', '01', '02', '03', '04', '05', '06', '07', '08', '09', - '10', '11', '12', '13', '14', '15', '16', '17', '18', '19', - '20', '21', '22', '23', '24', '25', '26', '27', '28', '29', - '30', '31', '32', '33', '34', '35', '36', '37', '38', '39', - '40', '41', '42', '43', '44', '45', '46', '47', '48', '49', - '50', '51', '52', '53', '54', '55', '56', '57', '58', '59', - '60', '61', '62', '63', '64', '65', '66', '67', '68', '69', - '70', '71', '72', '73', '74', '75', '76', '77', '78', '79', - '80', '81', '82', '83', '84', '85', '86', '87', '88', '89', - '90', '91', '92', '93', '94', '95', '96', '97', '98', '99', - 'Code B', 'Code A', 'FNC1', 'START A', 'START B', 'START C', 'STOP')); - /*'A' => array( - ' '=>0, '!'=>1, '"'=>2, '#'=>3, '$'=>4, '%'=>5, '&'=>6, "'"=>7, - '('=>8, ')'=>9, '*'=>10, '+'=>11, ','=>12, '-'=>13, '.'=>14, '/'=>15, - '0'=>16, '1'=>17, '2'=>18, '3'=>19, '4'=>20, '5'=>21, '6'=>22, '7'=>23, - '8'=>24, '9'=>25, ':'=>26, ';'=>27, '<'=>28, '='=>29, '>'=>30, '?'=>31, - '@'=>32, 'A'=>33, 'B'=>34, 'C'=>35, 'D'=>36, 'E'=>37, 'F'=>38, 'G'=>39, - 'H'=>40, 'I'=>41, 'J'=>42, 'K'=>43, 'L'=>44, 'M'=>45, 'N'=>46, 'O'=>47, - 'P'=>48, 'Q'=>49, 'R'=>50, 'S'=>51, 'T'=>52, 'U'=>53, 'V'=>54, 'W'=>55, - 'X'=>56, 'Y'=>57, 'Z'=>58, '['=>59, '\\'=>60, ']'=>61, '^'=>62, '_'=>63, - 0x00=>64, 0x01=>65, 0x02=>66, 0x03=>67, 0x04=>68, 0x05=>69, 0x06=>70, 0x07=>71, - 0x08=>72, 0x09=>73, 0x0A=>74, 0x0B=>75, 0x0C=>76, 0x0D=>77, 0x0E=>78, 0x0F=>79, - 0x10=>80, 0x11=>81, 0x12=>82, 0x13=>83, 0x14=>84, 0x15=>85, 0x16=>86, 0x17=>87, - 0x18=>88, 0x19=>89, 0x1A=>90, 0x1B=>91, 0x1C=>92, 0x1D=>93, 0x1E=>94, 0x1F=>95, - 'FNC3'=>96, 'FNC2'=>97, 'SHIFT'=>98, 'Code C'=>99, 'Code B'=>100, 'FNC4'=>101, 'FNC1'=>102, 'START A'=>103, - 'START B'=>104, 'START C'=>105, 'STOP'=>106), - 'B' => array( - ' '=>0, '!'=>1, '"'=>2, '#'=>3, '$'=>4, '%'=>5, '&'=>6, "'"=>7, - '('=>8, ')'=>9, '*'=>10, '+'=>11, ','=>12, '-'=>13, '.'=>14, '/'=>15, - '0'=>16, '1'=>17, '2'=>18, '3'=>19, '4'=>20, '5'=>21, '6'=>22, '7'=>23, - '8'=>24, '9'=>25, ':'=>26, ';'=>27, '<'=>28, '='=>29, '>'=>30, '?'=>31, - '@'=>32, 'A'=>33, 'B'=>34, 'C'=>35, 'D'=>36, 'E'=>37, 'F'=>38, 'G'=>39, - 'H'=>40, 'I'=>41, 'J'=>42, 'K'=>43, 'L'=>44, 'M'=>45, 'N'=>46, 'O'=>47, - 'P'=>48, 'Q'=>49, 'R'=>50, 'S'=>51, 'T'=>52, 'U'=>53, 'V'=>54, 'W'=>55, - 'X'=>56, 'Y'=>57, 'Z'=>58, '['=>59, '\\'=>60, ']'=>61, '^'=>62, '_'=>63, - '`' =>64, 'a'=>65, 'b'=>66, 'c'=>67, 'd'=>68, 'e'=>69, 'f'=>70, 'g'=>71, - 'h'=>72, 'i'=>73, 'j'=>74, 'k'=>75, 'l'=>76, 'm'=>77, 'n'=>78, 'o'=>79, - 'p'=>80, 'q'=>81, 'r'=>82, 's'=>83, 't'=>84, 'u'=>85, 'v'=>86, 'w'=>87, - 'x'=>88, 'y'=>89, 'z'=>90, '{'=>91, '|'=>92, '}'=>93, '~'=>94, 0x7F=>95, - 'FNC3'=>96, 'FNC2'=>97, 'SHIFT'=>98, 'Code C'=>99, 'FNC4'=>100, 'Code A'=>101, 'FNC1'=>102, 'START A'=>103, - 'START B'=>104, 'START C'=>105, 'STOP'=>106,), - 'C' => array( - '00'=>0, '01'=>1, '02'=>2, '03'=>3, '04'=>4, '05'=>5, '06'=>6, '07'=>7, '08'=>8, '09'=>9, - '10'=>10, '11'=>11, '12'=>12, '13'=>13, '14'=>14, '15'=>15, '16'=>16, '17'=>17, '18'=>18, '19'=>19, - '20'=>20, '21'=>21, '22'=>22, '23'=>23, '24'=>24, '25'=>25, '26'=>26, '27'=>27, '28'=>28, '29'=>29, - '30'=>30, '31'=>31, '32'=>32, '33'=>33, '34'=>34, '35'=>35, '36'=>36, '37'=>37, '38'=>38, '39'=>39, - '40'=>40, '41'=>41, '42'=>42, '43'=>43, '44'=>44, '45'=>45, '46'=>46, '47'=>47, '48'=>48, '49'=>49, - '50'=>50, '51'=>51, '52'=>52, '53'=>53, '54'=>54, '55'=>55, '56'=>56, '57'=>57, '58'=>58, '59'=>59, - '60'=>60, '61'=>61, '62'=>62, '63'=>63, '64'=>64, '65'=>65, '66'=>66, '67'=>67, '68'=>68, '69'=>69, - '70'=>70, '71'=>71, '72'=>72, '73'=>73, '74'=>74, '75'=>75, '76'=>76, '77'=>77, '78'=>78, '79'=>79, - '80'=>80, '81'=>81, '82'=>82, '83'=>83, '84'=>84, '85'=>85, '86'=>86, '87'=>87, '88'=>88, '89'=>89, - '90'=>90, '91'=>91, '92'=>92, '93'=>93, '94'=>94, '95'=>95, '96'=>96, '97'=>97, '98'=>98, '99'=>99, - 'Code B'=>100, 'Code A'=>101, 'FNC1'=>102, 'START A'=>103, 'START B'=>104, 'START C'=>105, 'STOP'=>106));*/ - - /** - * Width of the barcode (in pixels) - * @return integer - */ - protected function _calculateBarcodeWidth() - { - $quietZone = $this->getQuietZone(); - // Each characters contain 11 bars... - $characterLength = 11 * $this->_barThinWidth * $this->_factor; - $convertedChars = count($this->_convertToBarcodeChars($this->getText())); - if ($this->_withChecksum) { - $convertedChars++; - } - $encodedData = $convertedChars * $characterLength; - // ...except the STOP character (13) - $encodedData += $characterLength + 2 * $this->_barThinWidth * $this->_factor; - $width = $quietZone + $encodedData + $quietZone; - return $width; - } - - /** - * Partial check of code128 barcode - * @return void - */ - protected function _checkParams() - { - } - - /** - * Prepare array to draw barcode - * @return array - */ - protected function _prepareBarcode() - { - $barcodeTable = array(); - - $convertedChars = $this->_convertToBarcodeChars($this->getText()); - - if ($this->_withChecksum) { - $convertedChars[] = $this->getChecksum($this->getText()); - } - - // STOP CHARACTER - $convertedChars[] = 106; - - foreach ($convertedChars as $barcodeChar) { - $barcodePattern = $this->_codingMap[$barcodeChar]; - foreach (str_split($barcodePattern) as $c) { - $barcodeTable[] = array($c, $this->_barThinWidth, 0, 1); - } - } - return $barcodeTable; - } - - /** - * Checks if the next $length chars of $string starting at $pos are numeric. - * Returns false if the end of the string is reached. - * @param string $string String to search - * @param int $pos Starting position - * @param int $length Length to search - * @return bool - */ - protected static function _isDigit($string, $pos, $length = 2) - { - if ($pos + $length > strlen($string)) { - return false; - } - - for ($i = $pos; $i < $pos + $length; $i++) { - if (!is_numeric($string[$i])) { - return false; - } - } - return true; - } - - /** - * Convert string to barcode string - * - * @param $string - * @return array - */ - protected function _convertToBarcodeChars($string) - { - $string = (string) $string; - if (!strlen($string)) { - return array(); - } - - if (isset($this->_convertedText[md5($string)])) { - return $this->_convertedText[md5($string)]; - } - - $currentCharset = null; - $sum = 0; - $fak = 0; - $result = array(); - - for ($pos = 0; $pos < strlen($string); $pos++) { - $char = $string[$pos]; - $code = null; - - if (self::_isDigit($string, $pos, 4) && $currentCharset != 'C' - || self::_isDigit($string, $pos, 2) && $currentCharset == 'C') { - /** - * Switch to C if the next 4 chars are numeric or stay C if the next 2 - * chars are numeric - */ - if ($currentCharset != 'C') { - if ($pos == 0) { - $code = array_search("START C", $this->_charSets['C']); - } else { - $code = array_search("Code C", $this->_charSets[$currentCharset]); - } - $result[] = $code; - $currentCharset = 'C'; - } - } else if (in_array($char, $this->_charSets['B']) && $currentCharset != 'B' - && !(in_array($char, $this->_charSets['A']) && $currentCharset == 'A')) { - /** - * Switch to B as B contains the char and B is not the current charset. - */ - if ($pos == 0) { - $code = array_search("START B", $this->_charSets['B']); - } else { - $code = array_search("Code B", $this->_charSets[$currentCharset]); - } - $result[] = $code; - $currentCharset = 'B'; - } else if (array_key_exists($char, $this->_charSets['A']) && $currentCharset != 'A' - && !(array_key_exists($char, $this->_charSets['B']) && $currentCharset == 'B')) { - /** - * Switch to C as C contains the char and C is not the current charset. - */ - if ($pos == 0) { - $code = array_search("START A", $this->_charSets['A']); - } else { - $code =array_search("Code A", $this->_charSets[$currentCharset]); - } - $result[] = $code; - $currentCharset = 'A'; - } - - if ($currentCharset == 'C') { - $code = array_search(substr($string, $pos, 2), $this->_charSets['C']); - $pos++; //Two chars from input - } else { - $code = array_search($string[$pos], $this->_charSets[$currentCharset]); - } - $result[] = $code; - } - - $this->_convertedText[md5($string)] = $result; - return $result; - } - - /** - * Set text to encode - * @param string $value - * @return Zend_Barcode_Object - */ - public function setText($value) - { - $this->_text = $value; - return $this; - } - - /** - * Retrieve text to encode - * @return string - */ - public function getText() - { - return $this->_text; - } - - /** - * Get barcode checksum - * - * @param string $text - * @return int - */ - public function getChecksum($text) - { - $tableOfChars = $this->_convertToBarcodeChars($text); - - $sum = $tableOfChars[0]; - unset($tableOfChars[0]); - - $k = 1; - foreach ($tableOfChars as $char) { - $sum += ($k++) * $char; - } - - $checksum = $sum % 103; - - return $checksum; - } - - /** - * Standard validation for most of barcode objects - * - * @param string $value - * @param array $options - * @return bool - */ - protected function _validateText($value, $options = array()) - { - // @TODO: add code128 validator - return true; - } -} diff --git a/library/Zend/Barcode/Object/Code25.php b/library/Zend/Barcode/Object/Code25.php deleted file mode 100644 index 0fb577e811..0000000000 --- a/library/Zend/Barcode/Object/Code25.php +++ /dev/null @@ -1,143 +0,0 @@ - '00110', - '1' => '10001', - '2' => '01001', - '3' => '11000', - '4' => '00101', - '5' => '10100', - '6' => '01100', - '7' => '00011', - '8' => '10010', - '9' => '01010', - ); - - /** - * Width of the barcode (in pixels) - * @return integer - */ - protected function _calculateBarcodeWidth() - { - $quietZone = $this->getQuietZone(); - $startCharacter = (2 * $this->_barThickWidth + 4 * $this->_barThinWidth) * $this->_factor; - $characterLength = (3 * $this->_barThinWidth + 2 * $this->_barThickWidth + 5 * $this->_barThinWidth) - * $this->_factor; - $encodedData = strlen($this->getText()) * $characterLength; - $stopCharacter = (2 * $this->_barThickWidth + 4 * $this->_barThinWidth) * $this->_factor; - return $quietZone + $startCharacter + $encodedData + $stopCharacter + $quietZone; - } - - /** - * Partial check of interleaved 2 of 5 barcode - * @return void - */ - protected function _checkParams() - { - $this->_checkRatio(); - } - - /** - * Prepare array to draw barcode - * @return array - */ - protected function _prepareBarcode() - { - $barcodeTable = array(); - - // Start character (30301) - $barcodeTable[] = array(1 , $this->_barThickWidth , 0 , 1); - $barcodeTable[] = array(0 , $this->_barThinWidth , 0 , 1); - $barcodeTable[] = array(1 , $this->_barThickWidth , 0 , 1); - $barcodeTable[] = array(0 , $this->_barThinWidth , 0 , 1); - $barcodeTable[] = array(1 , $this->_barThinWidth , 0 , 1); - $barcodeTable[] = array(0 , $this->_barThinWidth); - - $text = str_split($this->getText()); - foreach ($text as $char) { - $barcodeChar = str_split($this->_codingMap[$char]); - foreach ($barcodeChar as $c) { - /* visible, width, top, length */ - $width = $c ? $this->_barThickWidth : $this->_barThinWidth; - $barcodeTable[] = array(1 , $width , 0 , 1); - $barcodeTable[] = array(0 , $this->_barThinWidth); - } - } - - // Stop character (30103) - $barcodeTable[] = array(1 , $this->_barThickWidth , 0 , 1); - $barcodeTable[] = array(0 , $this->_barThinWidth , 0 , 1); - $barcodeTable[] = array(1 , $this->_barThinWidth , 0 , 1); - $barcodeTable[] = array(0 , $this->_barThinWidth , 0 , 1); - $barcodeTable[] = array(1 , $this->_barThickWidth , 0 , 1); - return $barcodeTable; - } - - /** - * Get barcode checksum - * - * @param string $text - * @return int - */ - public function getChecksum($text) - { - $this->_checkText($text); - $factor = 3; - $checksum = 0; - - for ($i = strlen($text); $i > 0; $i --) { - $checksum += intval($text{$i - 1}) * $factor; - $factor = 4 - $factor; - } - - $checksum = (10 - ($checksum % 10)) % 10; - - return $checksum; - } -} diff --git a/library/Zend/Barcode/Object/Code25interleaved.php b/library/Zend/Barcode/Object/Code25interleaved.php deleted file mode 100644 index 19b6853650..0000000000 --- a/library/Zend/Barcode/Object/Code25interleaved.php +++ /dev/null @@ -1,179 +0,0 @@ -_barcodeLength = 'even'; - } - - /** - * Activate/deactivate drawing of bearer bars - * @param boolean $value - * @return Zend_Barcode_Object_Int25 - */ - public function setWithBearerBars($value) - { - $this->_withBearerBars = (bool) $value; - return $this; - } - - /** - * Retrieve if bearer bars are enabled - * @return boolean - */ - public function getWithBearerBars() - { - return $this->_withBearerBars; - } - - /** - * Width of the barcode (in pixels) - * @return integer - */ - protected function _calculateBarcodeWidth() - { - $quietZone = $this->getQuietZone(); - $startCharacter = (4 * $this->_barThinWidth) * $this->_factor; - $characterLength = (3 * $this->_barThinWidth + 2 * $this->_barThickWidth) * $this->_factor; - $encodedData = strlen($this->getText()) * $characterLength; - $stopCharacter = ($this->_barThickWidth + 2 * $this->_barThinWidth) * $this->_factor; - return $quietZone + $startCharacter + $encodedData + $stopCharacter + $quietZone; - } - - /** - * Prepare array to draw barcode - * @return array - */ - protected function _prepareBarcode() - { - if ($this->_withBearerBars) { - $this->_withBorder = false; - } - - // Start character (0000) - $barcodeTable[] = array(1, $this->_barThinWidth, 0, 1); - $barcodeTable[] = array(0, $this->_barThinWidth, 0, 1); - $barcodeTable[] = array(1, $this->_barThinWidth, 0, 1); - $barcodeTable[] = array(0, $this->_barThinWidth, 0, 1); - - // Encoded $text - $text = $this->getText(); - for ($i = 0; $i < strlen($text); $i += 2) { // Draw 2 chars at a time - $char1 = substr($text, $i, 1); - $char2 = substr($text, $i + 1, 1); - - // Interleave - for ($ibar = 0; $ibar < 5; $ibar ++) { - // Draws char1 bar (fore color) - $barWidth = (substr($this->_codingMap[$char1], $ibar, 1)) - ? $this->_barThickWidth - : $this->_barThinWidth; - - $barcodeTable[] = array(1, $barWidth, 0, 1); - - // Left space corresponding to char2 (background color) - $barWidth = (substr($this->_codingMap[$char2], $ibar, 1)) - ? $this->_barThickWidth - : $this->_barThinWidth; - $barcodeTable[] = array(0, $barWidth, 0 , 1); - } - } - - // Stop character (100) - $barcodeTable[] = array(1 , $this->_barThickWidth, 0, 1); - $barcodeTable[] = array(0 , $this->_barThinWidth, 0, 1); - $barcodeTable[] = array(1 , $this->_barThinWidth, 0, 1); - return $barcodeTable; - } - - /** - * Drawing of bearer bars (if enabled) - * - * @return void - */ - protected function _postDrawBarcode() - { - if (!$this->_withBearerBars) { - return; - } - - $width = $this->_barThickWidth * $this->_factor; - $point1 = $this->_rotate(-1, -1); - $point2 = $this->_rotate($this->_calculateWidth() - 1, -1); - $point3 = $this->_rotate($this->_calculateWidth() - 1, $width - 1); - $point4 = $this->_rotate(-1, $width - 1); - $this->_addPolygon(array( - $point1, - $point2, - $point3, - $point4, - )); - $point1 = $this->_rotate( - 0, - 0 + $this->_barHeight * $this->_factor - 1 - ); - $point2 = $this->_rotate( - $this->_calculateWidth() - 1, - 0 + $this->_barHeight * $this->_factor - 1 - ); - $point3 = $this->_rotate( - $this->_calculateWidth() - 1, - 0 + $this->_barHeight * $this->_factor - $width - ); - $point4 = $this->_rotate( - 0, - 0 + $this->_barHeight * $this->_factor - $width - ); - $this->_addPolygon(array( - $point1, - $point2, - $point3, - $point4, - )); - } -} diff --git a/library/Zend/Barcode/Object/Code39.php b/library/Zend/Barcode/Object/Code39.php deleted file mode 100644 index 637f9e11c2..0000000000 --- a/library/Zend/Barcode/Object/Code39.php +++ /dev/null @@ -1,188 +0,0 @@ - '000110100', - '1' => '100100001', - '2' => '001100001', - '3' => '101100000', - '4' => '000110001', - '5' => '100110000', - '6' => '001110000', - '7' => '000100101', - '8' => '100100100', - '9' => '001100100', - 'A' => '100001001', - 'B' => '001001001', - 'C' => '101001000', - 'D' => '000011001', - 'E' => '100011000', - 'F' => '001011000', - 'G' => '000001101', - 'H' => '100001100', - 'I' => '001001100', - 'J' => '000011100', - 'K' => '100000011', - 'L' => '001000011', - 'M' => '101000010', - 'N' => '000010011', - 'O' => '100010010', - 'P' => '001010010', - 'Q' => '000000111', - 'R' => '100000110', - 'S' => '001000110', - 'T' => '000010110', - 'U' => '110000001', - 'V' => '011000001', - 'W' => '111000000', - 'X' => '010010001', - 'Y' => '110010000', - 'Z' => '011010000', - '-' => '010000101', - '.' => '110000100', - ' ' => '011000100', - '$' => '010101000', - '/' => '010100010', - '+' => '010001010', - '%' => '000101010', - '*' => '010010100', - ); - - /** - * Partial check of Code39 barcode - * @return void - */ - protected function _checkParams() - { - $this->_checkRatio(); - } - - /** - * Width of the barcode (in pixels) - * @return int - */ - protected function _calculateBarcodeWidth() - { - $quietZone = $this->getQuietZone(); - $characterLength = (6 * $this->_barThinWidth + 3 * $this->_barThickWidth + 1) * $this->_factor; - $encodedData = strlen($this->getText()) * $characterLength - $this->_factor; - return $quietZone + $encodedData + $quietZone; - } - - /** - * Set text to encode - * @param string $value - * @return Zend_Barcode_Object - */ - public function setText($value) - { - $this->_text = $value; - return $this; - } - - /** - * Retrieve text to display - * @return string - */ - public function getText() - { - return '*' . parent::getText() . '*'; - } - - /** - * Retrieve text to display - * @return string - */ - public function getTextToDisplay() - { - $text = parent::getTextToDisplay(); - if (substr($text, 0, 1) != '*' && substr($text, -1) != '*') { - return '*' . $text . '*'; - } else { - return $text; - } - } - - /** - * Prepare array to draw barcode - * @return array - */ - protected function _prepareBarcode() - { - $text = str_split($this->getText()); - $barcodeTable = array(); - foreach ($text as $char) { - $barcodeChar = str_split($this->_codingMap[$char]); - $visible = true; - foreach ($barcodeChar as $c) { - /* visible, width, top, length */ - $width = $c ? $this->_barThickWidth : $this->_barThinWidth; - $barcodeTable[] = array((int) $visible, $width, 0, 1); - $visible = ! $visible; - } - $barcodeTable[] = array(0 , $this->_barThinWidth); - } - return $barcodeTable; - } - - /** - * Get barcode checksum - * - * @param string $text - * @return int - */ - public function getChecksum($text) - { - $this->_checkText($text); - $text = str_split($text); - $charset = array_flip(array_keys($this->_codingMap)); - $checksum = 0; - foreach ($text as $character) { - $checksum += $charset[$character]; - } - return array_search(($checksum % 43), $charset); - } -} diff --git a/library/Zend/Barcode/Object/Ean13.php b/library/Zend/Barcode/Object/Ean13.php deleted file mode 100644 index d0cd4fecf4..0000000000 --- a/library/Zend/Barcode/Object/Ean13.php +++ /dev/null @@ -1,225 +0,0 @@ - array( - 0 => "0001101", 1 => "0011001", 2 => "0010011", 3 => "0111101", 4 => "0100011", - 5 => "0110001", 6 => "0101111", 7 => "0111011", 8 => "0110111", 9 => "0001011" - ), - 'B' => array( - 0 => "0100111", 1 => "0110011", 2 => "0011011", 3 => "0100001", 4 => "0011101", - 5 => "0111001", 6 => "0000101", 7 => "0010001", 8 => "0001001", 9 => "0010111" - ), - 'C' => array( - 0 => "1110010", 1 => "1100110", 2 => "1101100", 3 => "1000010", 4 => "1011100", - 5 => "1001110", 6 => "1010000", 7 => "1000100", 8 => "1001000", 9 => "1110100" - )); - - protected $_parities = array( - 0 => array('A','A','A','A','A','A'), - 1 => array('A','A','B','A','B','B'), - 2 => array('A','A','B','B','A','B'), - 3 => array('A','A','B','B','B','A'), - 4 => array('A','B','A','A','B','B'), - 5 => array('A','B','B','A','A','B'), - 6 => array('A','B','B','B','A','A'), - 7 => array('A','B','A','B','A','B'), - 8 => array('A','B','A','B','B','A'), - 9 => array('A','B','B','A','B','A') - ); - - /** - * Default options for Postnet barcode - * @return void - */ - protected function _getDefaultOptions() - { - $this->_barcodeLength = 13; - $this->_mandatoryChecksum = true; - $this->_mandatoryQuietZones = true; - } - - /** - * Width of the barcode (in pixels) - * @return integer - */ - protected function _calculateBarcodeWidth() - { - $quietZone = $this->getQuietZone(); - $startCharacter = (3 * $this->_barThinWidth) * $this->_factor; - $middleCharacter = (5 * $this->_barThinWidth) * $this->_factor; - $stopCharacter = (3 * $this->_barThinWidth) * $this->_factor; - $encodedData = (7 * $this->_barThinWidth) * $this->_factor * 12; - return $quietZone + $startCharacter + $middleCharacter + $encodedData + $stopCharacter + $quietZone; - } - - /** - * Partial check of interleaved EAN/UPC barcode - * @return void - */ - protected function _checkParams() - {} - - /** - * Prepare array to draw barcode - * @return array - */ - protected function _prepareBarcode() - { - $barcodeTable = array(); - $height = ($this->_drawText) ? 1.1 : 1; - - // Start character (101) - $barcodeTable[] = array(1 , $this->_barThinWidth , 0 , $height); - $barcodeTable[] = array(0 , $this->_barThinWidth , 0 , $height); - $barcodeTable[] = array(1 , $this->_barThinWidth , 0 , $height); - - $textTable = str_split($this->getText()); - $parity = $this->_parities[$textTable[0]]; - - // First part - for ($i = 1; $i < 7; $i++) { - $bars = str_split($this->_codingMap[$parity[$i - 1]][$textTable[$i]]); - foreach ($bars as $b) { - $barcodeTable[] = array($b , $this->_barThinWidth , 0 , 1); - } - } - - // Middle character (01010) - $barcodeTable[] = array(0 , $this->_barThinWidth , 0 , $height); - $barcodeTable[] = array(1 , $this->_barThinWidth , 0 , $height); - $barcodeTable[] = array(0 , $this->_barThinWidth , 0 , $height); - $barcodeTable[] = array(1 , $this->_barThinWidth , 0 , $height); - $barcodeTable[] = array(0 , $this->_barThinWidth , 0 , $height); - - // Second part - for ($i = 7; $i < 13; $i++) { - $bars = str_split($this->_codingMap['C'][$textTable[$i]]); - foreach ($bars as $b) { - $barcodeTable[] = array($b , $this->_barThinWidth , 0 , 1); - } - } - - // Stop character (101) - $barcodeTable[] = array(1 , $this->_barThinWidth , 0 , $height); - $barcodeTable[] = array(0 , $this->_barThinWidth , 0 , $height); - $barcodeTable[] = array(1 , $this->_barThinWidth , 0 , $height); - return $barcodeTable; - } - - /** - * Get barcode checksum - * - * @param string $text - * @return int - */ - public function getChecksum($text) - { - $this->_checkText($text); - $factor = 3; - $checksum = 0; - - for ($i = strlen($text); $i > 0; $i --) { - $checksum += intval($text{$i - 1}) * $factor; - $factor = 4 - $factor; - } - - $checksum = (10 - ($checksum % 10)) % 10; - - return $checksum; - } - - /** - * Partial function to draw text - * @return void - */ - protected function _drawText() - { - if (get_class($this) == 'Zend_Barcode_Object_Ean13') { - $this->_drawEan13Text(); - } else { - parent::_drawText(); - } - } - - protected function _drawEan13Text() - { - if ($this->_drawText) { - $text = $this->getTextToDisplay(); - $characterWidth = (7 * $this->_barThinWidth) * $this->_factor; - $leftPosition = $this->getQuietZone() - $characterWidth; - for ($i = 0; $i < $this->_barcodeLength; $i ++) { - $this->_addText( - $text{$i}, - $this->_fontSize * $this->_factor, - $this->_rotate( - $leftPosition, - (int) $this->_withBorder * 2 - + $this->_factor * ($this->_barHeight + $this->_fontSize) + 1 - ), - $this->_font, - $this->_foreColor, - 'left', - - $this->_orientation - ); - switch ($i) { - case 0: - $factor = 3; - break; - case 6: - $factor = 4; - break; - default: - $factor = 0; - } - $leftPosition = $leftPosition + $characterWidth + ($factor * $this->_barThinWidth * $this->_factor); - } - } - } -} diff --git a/library/Zend/Barcode/Object/Ean2.php b/library/Zend/Barcode/Object/Ean2.php deleted file mode 100644 index 94d332b885..0000000000 --- a/library/Zend/Barcode/Object/Ean2.php +++ /dev/null @@ -1,65 +0,0 @@ - array('A','A'), - 1 => array('A','B'), - 2 => array('B','A'), - 3 => array('B','B') - ); - - /** - * Default options for Ean2 barcode - * @return void - */ - protected function _getDefaultOptions() - { - $this->_barcodeLength = 2; - } - - protected function _getParity($i) - { - $modulo = $this->getText() % 4; - return $this->_parities[$modulo][$i]; - } -} diff --git a/library/Zend/Barcode/Object/Ean5.php b/library/Zend/Barcode/Object/Ean5.php deleted file mode 100644 index 23b86834fa..0000000000 --- a/library/Zend/Barcode/Object/Ean5.php +++ /dev/null @@ -1,147 +0,0 @@ - array('B','B','A','A','A'), - 1 => array('B','A','B','A','A'), - 2 => array('B','A','A','B','A'), - 3 => array('B','A','A','A','B'), - 4 => array('A','B','B','A','A'), - 5 => array('A','A','B','B','A'), - 6 => array('A','A','A','B','B'), - 7 => array('A','B','A','B','A'), - 8 => array('A','B','A','A','B'), - 9 => array('A','A','B','A','B') - ); - - /** - * Default options for Ean5 barcode - * @return void - */ - protected function _getDefaultOptions() - { - $this->_barcodeLength = 5; - } - - /** - * Width of the barcode (in pixels) - * @return integer - */ - protected function _calculateBarcodeWidth() - { - $quietZone = $this->getQuietZone(); - $startCharacter = (5 * $this->_barThinWidth) * $this->_factor; - $middleCharacter = (2 * $this->_barThinWidth) * $this->_factor; - $encodedData = (7 * $this->_barThinWidth) * $this->_factor; - return $quietZone + $startCharacter + ($this->_barcodeLength - 1) * $middleCharacter + $this->_barcodeLength * $encodedData + $quietZone; - } - - /** - * Prepare array to draw barcode - * @return array - */ - protected function _prepareBarcode() - { - $barcodeTable = array(); - - // Start character (01011) - $barcodeTable[] = array(0 , $this->_barThinWidth , 0 , 1); - $barcodeTable[] = array(1 , $this->_barThinWidth , 0 , 1); - $barcodeTable[] = array(0 , $this->_barThinWidth , 0 , 1); - $barcodeTable[] = array(1 , $this->_barThinWidth , 0 , 1); - $barcodeTable[] = array(1 , $this->_barThinWidth , 0 , 1); - - $firstCharacter = true; - $textTable = str_split($this->getText()); - - // Characters - for ($i = 0; $i < $this->_barcodeLength; $i++) { - if ($firstCharacter) { - $firstCharacter = false; - } else { - // Intermediate character (01) - $barcodeTable[] = array(0 , $this->_barThinWidth , 0 , 1); - $barcodeTable[] = array(1 , $this->_barThinWidth , 0 , 1); - } - $bars = str_split($this->_codingMap[$this->_getParity($i)][$textTable[$i]]); - foreach ($bars as $b) { - $barcodeTable[] = array($b , $this->_barThinWidth , 0 , 1); - } - } - - return $barcodeTable; - } - - /** - * Get barcode checksum - * - * @param string $text - * @return int - */ - public function getChecksum($text) - { - $this->_checkText($text); - $checksum = 0; - - for ($i = 0 ; $i < $this->_barcodeLength; $i ++) { - $checksum += intval($text{$i}) * ($i % 2 ? 9 : 3); - } - - return ($checksum % 10); - } - - protected function _getParity($i) - { - $checksum = $this->getChecksum($this->getText()); - return $this->_parities[$checksum][$i]; - } - - /** - * Retrieve text to encode - * @return string - */ - public function getText() - { - return $this->_addLeadingZeros($this->_text); - } -} diff --git a/library/Zend/Barcode/Object/Ean8.php b/library/Zend/Barcode/Object/Ean8.php deleted file mode 100644 index 250deb618e..0000000000 --- a/library/Zend/Barcode/Object/Ean8.php +++ /dev/null @@ -1,177 +0,0 @@ -_barcodeLength = 8; - $this->_mandatoryChecksum = true; - } - - /** - * Width of the barcode (in pixels) - * @return integer - */ - protected function _calculateBarcodeWidth() - { - $quietZone = $this->getQuietZone(); - $startCharacter = (3 * $this->_barThinWidth) * $this->_factor; - $middleCharacter = (5 * $this->_barThinWidth) * $this->_factor; - $stopCharacter = (3 * $this->_barThinWidth) * $this->_factor; - $encodedData = (7 * $this->_barThinWidth) * $this->_factor * 8; - return $quietZone + $startCharacter + $middleCharacter + $encodedData + $stopCharacter + $quietZone; - } - - /** - * Prepare array to draw barcode - * @return array - */ - protected function _prepareBarcode() - { - $barcodeTable = array(); - $height = ($this->_drawText) ? 1.1 : 1; - - // Start character (101) - $barcodeTable[] = array(1 , $this->_barThinWidth , 0 , $height); - $barcodeTable[] = array(0 , $this->_barThinWidth , 0 , $height); - $barcodeTable[] = array(1 , $this->_barThinWidth , 0 , $height); - - $textTable = str_split($this->getText()); - - // First part - for ($i = 0; $i < 4; $i++) { - $bars = str_split($this->_codingMap['A'][$textTable[$i]]); - foreach ($bars as $b) { - $barcodeTable[] = array($b , $this->_barThinWidth , 0 , 1); - } - } - - // Middle character (01010) - $barcodeTable[] = array(0 , $this->_barThinWidth , 0 , $height); - $barcodeTable[] = array(1 , $this->_barThinWidth , 0 , $height); - $barcodeTable[] = array(0 , $this->_barThinWidth , 0 , $height); - $barcodeTable[] = array(1 , $this->_barThinWidth , 0 , $height); - $barcodeTable[] = array(0 , $this->_barThinWidth , 0 , $height); - - // Second part - for ($i = 4; $i < 8; $i++) { - $bars = str_split($this->_codingMap['C'][$textTable[$i]]); - foreach ($bars as $b) { - $barcodeTable[] = array($b , $this->_barThinWidth , 0 , 1); - } - } - - // Stop character (101) - $barcodeTable[] = array(1 , $this->_barThinWidth , 0 , $height); - $barcodeTable[] = array(0 , $this->_barThinWidth , 0 , $height); - $barcodeTable[] = array(1 , $this->_barThinWidth , 0 , $height); - return $barcodeTable; - } - - /** - * Partial function to draw text - * @return void - */ - protected function _drawText() - { - if ($this->_drawText) { - $text = $this->getTextToDisplay(); - $characterWidth = (7 * $this->_barThinWidth) * $this->_factor; - $leftPosition = $this->getQuietZone() + (3 * $this->_barThinWidth) * $this->_factor; - for ($i = 0; $i < $this->_barcodeLength; $i ++) { - $this->_addText( - $text{$i}, - $this->_fontSize * $this->_factor, - $this->_rotate( - $leftPosition, - (int) $this->_withBorder * 2 - + $this->_factor * ($this->_barHeight + $this->_fontSize) + 1 - ), - $this->_font, - $this->_foreColor, - 'left', - - $this->_orientation - ); - switch ($i) { - case 3: - $factor = 4; - break; - default: - $factor = 0; - } - $leftPosition = $leftPosition + $characterWidth + ($factor * $this->_barThinWidth * $this->_factor); - } - } - } - - /** - * Particular validation for Ean8 barcode objects - * (to suppress checksum character substitution) - * - * @param string $value - * @param array $options - * @throws Zend_Barcode_Object_Exception - */ - protected function _validateText($value, $options = array()) - { - $validator = new Zend_Validate_Barcode(array( - 'adapter' => 'ean8', - 'checksum' => false, - )); - - $value = $this->_addLeadingZeros($value, true); - - if (!$validator->isValid($value)) { - $message = implode("\n", $validator->getMessages()); - - /** - * @see Zend_Barcode_Object_Exception - */ - #require_once 'Zend/Barcode/Object/Exception.php'; - throw new Zend_Barcode_Object_Exception($message); - } - } -} diff --git a/library/Zend/Barcode/Object/Error.php b/library/Zend/Barcode/Object/Error.php deleted file mode 100644 index 7b2c70e449..0000000000 --- a/library/Zend/Barcode/Object/Error.php +++ /dev/null @@ -1,104 +0,0 @@ -_instructions = array(); - $this->_addText('ERROR:', 10, array(5 , 18), $this->_font, 0, 'left'); - $this->_addText($this->_text, 10, array(5 , 32), $this->_font, 0, 'left'); - return $this->_instructions; - } - - /** - * For compatibility reason - * @return void - */ - protected function _prepareBarcode() - { - } - - /** - * For compatibility reason - * @return void - */ - protected function _checkParams() - { - } - - /** - * For compatibility reason - * @return void - */ - protected function _calculateBarcodeWidth() - { - } -} diff --git a/library/Zend/Barcode/Object/Exception.php b/library/Zend/Barcode/Object/Exception.php deleted file mode 100644 index 356016feff..0000000000 --- a/library/Zend/Barcode/Object/Exception.php +++ /dev/null @@ -1,35 +0,0 @@ -_barcodeLength = 12; - $this->_mandatoryChecksum = true; - } - - /** - * Retrieve text to display - * @return string - */ - public function getTextToDisplay() - { - return preg_replace('/([0-9]{2})([0-9]{3})([0-9]{3})([0-9]{3})([0-9])/', - '$1.$2 $3.$4 $5', - $this->getText()); - } - - /** - * Check allowed characters - * @param string $value - * @return string - * @throws Zend_Barcode_Object_Exception - */ - public function validateText($value) - { - $this->_validateText($value, array('validator' => $this->getType())); - } - - /** - * Get barcode checksum - * - * @param string $text - * @return int - */ - public function getChecksum($text) - { - $this->_checkText($text); - $checksum = 0; - - for ($i = strlen($text); $i > 0; $i --) { - $checksum += intval($text{$i - 1}) * (($i % 2) ? 4 : 9); - } - - $checksum = (10 - ($checksum % 10)) % 10; - - return $checksum; - } -} diff --git a/library/Zend/Barcode/Object/Itf14.php b/library/Zend/Barcode/Object/Itf14.php deleted file mode 100644 index e42b1dd129..0000000000 --- a/library/Zend/Barcode/Object/Itf14.php +++ /dev/null @@ -1,49 +0,0 @@ -_barcodeLength = 14; - $this->_mandatoryChecksum = true; - } -} diff --git a/library/Zend/Barcode/Object/Leitcode.php b/library/Zend/Barcode/Object/Leitcode.php deleted file mode 100644 index e0b802a2e9..0000000000 --- a/library/Zend/Barcode/Object/Leitcode.php +++ /dev/null @@ -1,64 +0,0 @@ -_barcodeLength = 14; - $this->_mandatoryChecksum = true; - } - - /** - * Retrieve text to display - * @return string - */ - public function getTextToDisplay() - { - return preg_replace('/([0-9]{5})([0-9]{3})([0-9]{3})([0-9]{2})([0-9])/', - '$1.$2.$3.$4 $5', - $this->getText()); - } -} diff --git a/library/Zend/Barcode/Object/ObjectAbstract.php b/library/Zend/Barcode/Object/ObjectAbstract.php deleted file mode 100644 index ff6e771203..0000000000 --- a/library/Zend/Barcode/Object/ObjectAbstract.php +++ /dev/null @@ -1,1440 +0,0 @@ -_getDefaultOptions(); - if (self::$_staticFont !== null) { - $this->_font = self::$_staticFont; - } - if ($options instanceof Zend_Config) { - $options = $options->toArray(); - } - if (is_array($options)) { - $this->setOptions($options); - } - $this->_type = strtolower( - substr(get_class($this), strlen($this->_barcodeNamespace) + 1) - ); - if ($this->_mandatoryChecksum) { - $this->_withChecksum = true; - $this->_withChecksumInText = true; - } - } - - /** - * Set default options for particular object - */ - protected function _getDefaultOptions() - { - } - - /** - * Set barcode state from options array - * - * @param array $options - * @return $this - */ - public function setOptions($options) - { - foreach ($options as $key => $value) { - $method = 'set' . $key; - if (method_exists($this, $method)) { - $this->$method($value); - } - } - return $this; - } - - /** - * Set barcode state from config object - * - * @param Zend_Config $config - * @return $this - */ - public function setConfig(Zend_Config $config) - { - return $this->setOptions($config->toArray()); - } - - /** - * Set barcode namespace for autoloading - * - * @param string $namespace - * @return $this - */ - public function setBarcodeNamespace($namespace) - { - $this->_barcodeNamespace = $namespace; - return $this; - } - - /** - * Retrieve barcode namespace - * - * @return string - */ - public function getBarcodeNamespace() - { - return $this->_barcodeNamespace; - } - - /** - * Retrieve type of barcode - * - * @return string - */ - public function getType() - { - return $this->_type; - } - - /** - * Set height of the barcode bar - * - * @param integer $value - * @return $this - * @throws Zend_Barcode_Object_Exception - */ - public function setBarHeight($value) - { - if (intval($value) <= 0) { - #require_once 'Zend/Barcode/Object/Exception.php'; - throw new Zend_Barcode_Object_Exception( - 'Bar height must be greater than 0' - ); - } - $this->_barHeight = intval($value); - return $this; - } - - /** - * Get height of the barcode bar - * - * @return integer - */ - public function getBarHeight() - { - return $this->_barHeight; - } - - /** - * Set thickness of thin bar - * - * @param integer $value - * @return $this - * @throws Zend_Barcode_Object_Exception - */ - public function setBarThinWidth($value) - { - if (intval($value) <= 0) { - #require_once 'Zend/Barcode/Object/Exception.php'; - throw new Zend_Barcode_Object_Exception( - 'Bar width must be greater than 0' - ); - } - $this->_barThinWidth = intval($value); - return $this; - } - - /** - * Get thickness of thin bar - * - * @return integer - */ - public function getBarThinWidth() - { - return $this->_barThinWidth; - } - - /** - * Set thickness of thick bar - * - * @param integer $value - * @return $this - * @throws Zend_Barcode_Object_Exception - */ - public function setBarThickWidth($value) - { - if (intval($value) <= 0) { - #require_once 'Zend/Barcode/Object/Exception.php'; - throw new Zend_Barcode_Object_Exception( - 'Bar width must be greater than 0' - ); - } - $this->_barThickWidth = intval($value); - return $this; - } - - /** - * Get thickness of thick bar - * - * @return integer - */ - public function getBarThickWidth() - { - return $this->_barThickWidth; - } - - /** - * Set factor applying to - * thinBarWidth - thickBarWidth - barHeight - fontSize - * - * @param int|float|string|bool $value - * @return $this - * @throws Zend_Barcode_Object_Exception - */ - public function setFactor($value) - { - if (floatval($value) <= 0) { - #require_once 'Zend/Barcode/Object/Exception.php'; - throw new Zend_Barcode_Object_Exception( - 'Factor must be greater than 0' - ); - } - $this->_factor = floatval($value); - return $this; - } - - /** - * Get factor applying to - * thinBarWidth - thickBarWidth - barHeight - fontSize - * - * @return integer - */ - public function getFactor() - { - return $this->_factor; - } - - /** - * Set color of the barcode and text - * - * @param string $value - * @return $this - * @throws Zend_Barcode_Object_Exception - */ - public function setForeColor($value) - { - if (preg_match('`\#[0-9A-F]{6}`', $value)) { - $this->_foreColor = hexdec($value); - } elseif (is_numeric($value) && $value >= 0 && $value <= 16777125) { - $this->_foreColor = intval($value); - } else { - #require_once 'Zend/Barcode/Object/Exception.php'; - throw new Zend_Barcode_Object_Exception( - 'Text color must be set as #[0-9A-F]{6}' - ); - } - return $this; - } - - /** - * Retrieve color of the barcode and text - * - * @return unknown - */ - public function getForeColor() - { - return $this->_foreColor; - } - - /** - * Set the color of the background - * - * @param integer $value - * @return $this - * @throws Zend_Barcode_Object_Exception - */ - public function setBackgroundColor($value) - { - if (preg_match('`\#[0-9A-F]{6}`', $value)) { - $this->_backgroundColor = hexdec($value); - } elseif (is_numeric($value) && $value >= 0 && $value <= 16777125) { - $this->_backgroundColor = intval($value); - } else { - #require_once 'Zend/Barcode/Object/Exception.php'; - throw new Zend_Barcode_Object_Exception( - 'Background color must be set as #[0-9A-F]{6}' - ); - } - return $this; - } - - /** - * Retrieve background color of the image - * - * @return integer - */ - public function getBackgroundColor() - { - return $this->_backgroundColor; - } - - /** - * Activate/deactivate drawing of the bar - * - * @param boolean $value - * @return $this - */ - public function setWithBorder($value) - { - $this->_withBorder = (bool) $value; - return $this; - } - - /** - * Retrieve if border are draw or not - * - * @return boolean - */ - public function getWithBorder() - { - return $this->_withBorder; - } - - /** - * Activate/deactivate drawing of the quiet zones - * - * @param boolean $value - * @return $this - */ - public function setWithQuietZones($value) - { - $this->_withQuietZones = (bool) $value; - return $this; - } - - /** - * Retrieve if quiet zones are draw or not - * - * @return boolean - */ - public function getWithQuietZones() - { - return $this->_withQuietZones; - } - - /** - * Allow fast inversion of font/bars color and background color - * - * @return $this - */ - public function setReverseColor() - { - $tmp = $this->_foreColor; - $this->_foreColor = $this->_backgroundColor; - $this->_backgroundColor = $tmp; - - return $this; - } - - /** - * Set orientation of barcode and text - * - * @param int|float|string|bool $value - * @return $this - * @throws Zend_Barcode_Object_Exception - */ - public function setOrientation($value) - { - $value = floatval($value); - $this->_orientation = $value - floor($value / 360) * 360; - return $this; - } - - /** - * Retrieve orientation of barcode and text - * - * @return float - */ - public function getOrientation() - { - return $this->_orientation; - } - - /** - * Set text to encode - * - * @param string $value - * @return $this - */ - public function setText($value) - { - $this->_text = trim($value); - return $this; - } - - /** - * Retrieve text to encode - * - * @return string - */ - public function getText() - { - $text = $this->_text; - if ($this->_withChecksum) { - $text .= $this->getChecksum($this->_text); - } - return $this->_addLeadingZeros($text); - } - - /** - * Automatically add leading zeros if barcode length is fixed - * - * @param string $text - * @param boolean $withoutChecksum - * @return string - */ - protected function _addLeadingZeros($text, $withoutChecksum = false) - { - if ($this->_barcodeLength && $this->_addLeadingZeros) { - $omitChecksum = (int) ($this->_withChecksum && $withoutChecksum); - if (is_int($this->_barcodeLength)) { - $length = $this->_barcodeLength - $omitChecksum; - if (strlen($text) < $length) { - $text = str_repeat('0', $length - strlen($text)) . $text; - } - } else { - if ($this->_barcodeLength == 'even') { - $text = ((strlen($text) - $omitChecksum) % 2 ? '0' . $text : $text); - } - } - } - return $text; - } - - /** - * Retrieve text to encode - * - * @return string - */ - public function getRawText() - { - return $this->_text; - } - - /** - * Retrieve text to display - * - * @return string - */ - public function getTextToDisplay() - { - if ($this->_withChecksumInText) { - return $this->getText(); - } else { - return $this->_addLeadingZeros($this->_text, true); - } - } - - /** - * Activate/deactivate drawing of text to encode - * - * @param boolean $value - * @return $this - */ - public function setDrawText($value) - { - $this->_drawText = (bool) $value; - return $this; - } - - /** - * Retrieve if drawing of text to encode is enabled - * - * @return boolean - */ - public function getDrawText() - { - return $this->_drawText; - } - - /** - * Activate/deactivate the adjustment of the position - * of the characters to the position of the bars - * - * @param boolean $value - * @return $this - * @throws Zend_Barcode_Object_Exception - */ - public function setStretchText($value) - { - $this->_stretchText = (bool) $value; - return $this; - } - - /** - * Retrieve if the adjustment of the position of the characters - * to the position of the bars is enabled - * - * @return boolean - */ - public function getStretchText() - { - return $this->_stretchText; - } - - /** - * Activate/deactivate the automatic generation - * of the checksum character - * added to the barcode text - * - * @param boolean $value - * @return $this - */ - public function setWithChecksum($value) - { - if (!$this->_mandatoryChecksum) { - $this->_withChecksum = (bool) $value; - } - return $this; - } - - /** - * Retrieve if the checksum character is automatically - * added to the barcode text - * - * @return boolean - */ - public function getWithChecksum() - { - return $this->_withChecksum; - } - - /** - * Activate/deactivate the automatic generation - * of the checksum character - * added to the barcode text - * - * @param boolean $value - * @return $this - * @throws Zend_Barcode_Object_Exception - */ - public function setWithChecksumInText($value) - { - if (!$this->_mandatoryChecksum) { - $this->_withChecksumInText = (bool) $value; - } - - return $this; - } - - /** - * Retrieve if the checksum character is automatically - * added to the barcode text - * - * @return boolean - */ - public function getWithChecksumInText() - { - return $this->_withChecksumInText; - } - - /** - * Set the font for all instances of barcode - * - * @param string $font - */ - public static function setBarcodeFont($font) - { - if (is_string($font) || (is_int($font) && $font >= 1 && $font <= 5)) { - self::$_staticFont = $font; - } - } - - /** - * Set the font: - * - if integer between 1 and 5, use gd built-in fonts - * - if string, $value is assumed to be the path to a TTF font - * - * @param integer|string $value - * @return $this - * @throws Zend_Barcode_Object_Exception - */ - public function setFont($value) - { - if (is_int($value) && $value >= 1 && $value <= 5) { - if (!extension_loaded('gd')) { - #require_once 'Zend/Barcode/Object/Exception.php'; - throw new Zend_Barcode_Object_Exception( - 'GD extension is required to use numeric font' - ); - } - - // Case of numeric font with GD - $this->_font = $value; - - // In this case font size is given by: - $this->_fontSize = imagefontheight($value); - } elseif (is_string($value)) { - $this->_font = $value; - } else { - #require_once 'Zend/Barcode/Object/Exception.php'; - throw new Zend_Barcode_Object_Exception( - sprintf( - 'Invalid font "%s" provided to setFont()', - $value - ) - ); - } - return $this; - } - - /** - * Retrieve the font - * - * @return integer|string - */ - public function getFont() - { - return $this->_font; - } - - /** - * Set the size of the font in case of TTF - * - * @param float $value - * @return $this - * @throws Zend_Barcode_Object_Exception - */ - public function setFontSize($value) - { - if (is_numeric($this->_font)) { - // Case of numeric font with GD - return $this; - } - - if (!is_numeric($value)) { - #require_once 'Zend/Barcode/Object/Exception.php'; - throw new Zend_Barcode_Object_Exception( - 'Font size must be a numeric value' - ); - } - - $this->_fontSize = $value; - return $this; - } - - /** - * Retrieve the size of the font in case of TTF - * - * @return float - */ - public function getFontSize() - { - return $this->_fontSize; - } - - /** - * Quiet zone before first bar - * and after the last bar - * - * @return integer - */ - public function getQuietZone() - { - if ($this->_withQuietZones || $this->_mandatoryQuietZones) { - return 10 * $this->_barThinWidth * $this->_factor; - } else { - return 0; - } - } - - /** - * Add an instruction in the array of instructions - * - * @param array $instruction - */ - protected function _addInstruction(array $instruction) - { - $this->_instructions[] = $instruction; - } - - /** - * Retrieve the set of drawing instructions - * - * @return array - */ - public function getInstructions() - { - return $this->_instructions; - } - - /** - * Add a polygon drawing instruction in the set of instructions - * - * @param array $points - * @param integer $color - * @param boolean $filled - */ - protected function _addPolygon(array $points, $color = null, $filled = true) - { - if ($color === null) { - $color = $this->_foreColor; - } - $this->_addInstruction( - array( - 'type' => 'polygon', - 'points' => $points, - 'color' => $color, - 'filled' => $filled, - ) - ); - } - - /** - * Add a text drawing instruction in the set of instructions - * - * @param string $text - * @param float $size - * @param array $position - * @param string $font - * @param integer $color - * @param string $alignment - * @param float|int $orientation - */ - protected function _addText( - $text, - $size, - $position, - $font, - $color, - $alignment = 'center', - $orientation = 0 - ) { - if ($color === null) { - $color = $this->_foreColor; - } - $this->_addInstruction( - array( - 'type' => 'text', - 'text' => $text, - 'size' => $size, - 'position' => $position, - 'font' => $font, - 'color' => $color, - 'alignment' => $alignment, - 'orientation' => $orientation, - ) - ); - } - - /** - * Checking of parameters after all settings - * - * @return bool - */ - public function checkParams() - { - $this->_checkText(); - $this->_checkFontAndOrientation(); - $this->_checkParams(); - return true; - } - - /** - * Check if a text is really provided to barcode - * - * @param string|null $value - * @throws Zend_Barcode_Object_Exception - */ - protected function _checkText($value = null) - { - if ($value === null) { - $value = $this->_text; - } - if (!strlen($value)) { - #require_once 'Zend/Barcode/Object/Exception.php'; - throw new Zend_Barcode_Object_Exception( - 'A text must be provide to Barcode before drawing' - ); - } - $this->validateText($value); - } - - /** - * Check the ratio between the thick and the thin bar - * - * @param int $min - * @param int $max - * @throws Zend_Barcode_Object_Exception - */ - protected function _checkRatio($min = 2, $max = 3) - { - $ratio = $this->_barThickWidth / $this->_barThinWidth; - if (!($ratio >= $min && $ratio <= $max)) { - #require_once 'Zend/Barcode/Object/Exception.php'; - throw new Zend_Barcode_Object_Exception( - sprintf( - 'Ratio thick/thin bar must be between %0.1f and %0.1f (actual %0.3f)', - $min, - $max, - $ratio - ) - ); - } - } - - /** - * Drawing with an angle is just allow TTF font - * - * @throws Zend_Barcode_Object_Exception - */ - protected function _checkFontAndOrientation() - { - if (is_numeric($this->_font) && $this->_orientation != 0) { - #require_once 'Zend/Barcode/Object/Exception.php'; - throw new Zend_Barcode_Object_Exception( - 'Only drawing with TTF font allow orientation of the barcode.' - ); - } - } - - /** - * Width of the result image (before any rotation) - * - * @return integer - */ - protected function _calculateWidth() - { - return (int) $this->_withBorder - + $this->_calculateBarcodeWidth() - + (int) $this->_withBorder; - } - - /** - * Calculate the width of the barcode - * - * @return integer - */ - abstract protected function _calculateBarcodeWidth(); - - /** - * Height of the result object - * - * @return int - */ - protected function _calculateHeight() - { - return (int) $this->_withBorder * 2 - + $this->_calculateBarcodeHeight() - + (int) $this->_withBorder * 2; - } - - /** - * Height of the barcode - * - * @return int - */ - protected function _calculateBarcodeHeight() - { - $textHeight = 0; - $extraHeight = 0; - if ($this->_drawText) { - $textHeight += $this->_fontSize; - $extraHeight = 2; - } - - return ($this->_barHeight + $textHeight) * $this->_factor - + $extraHeight; - } - - /** - * Get height of the result object - * - * @param bool $recalculate - * @return int - */ - public function getHeight($recalculate = false) - { - if ($this->_height === null || $recalculate) { - $this->_height = - abs( - $this->_calculateHeight() * cos( - $this->_orientation / 180 * pi() - ) - ) - + abs( - $this->_calculateWidth() * sin( - $this->_orientation / 180 * pi() - ) - ); - } - return $this->_height; - } - - /** - * Get width of the result object - * - * @param bool $recalculate - * @return int - */ - public function getWidth($recalculate = false) - { - if ($this->_width === null || $recalculate) { - $this->_width = - abs( - $this->_calculateWidth() * cos( - $this->_orientation / 180 * pi() - ) - ) - + abs( - $this->_calculateHeight() * sin( - $this->_orientation / 180 * pi() - ) - ); - } - return $this->_width; - } - - /** - * Calculate the offset from the left of the object - * if an orientation is activated - * - * @param bool $recalculate - * @return float - */ - public function getOffsetLeft($recalculate = false) - { - if ($this->_offsetLeft === null || $recalculate) { - $this->_offsetLeft = - min(array( - 0 * cos( - $this->_orientation / 180 * pi()) - 0 * sin( - $this->_orientation / 180 * pi()), - 0 * cos( - $this->_orientation / 180 * pi()) - $this->_calculateBarcodeHeight() * sin( - $this->_orientation / 180 * pi()), - $this->_calculateBarcodeWidth() * cos( - $this->_orientation / 180 * pi()) - $this->_calculateBarcodeHeight() * sin( - $this->_orientation / 180 * pi()), - $this->_calculateBarcodeWidth() * cos( - $this->_orientation / 180 * pi()) - 0 * sin( - $this->_orientation / 180 * pi()), - )); - } - return $this->_offsetLeft; - } - - /** - * Calculate the offset from the top of the object - * if an orientation is activated - * - * @param bool $recalculate - * @return float - */ - public function getOffsetTop($recalculate = false) - { - if ($this->_offsetTop === null || $recalculate) { - $this->_offsetTop = - min(array( - 0 * cos( - $this->_orientation / 180 * pi()) + 0 * sin( - $this->_orientation / 180 * pi()), - $this->_calculateBarcodeHeight() * cos( - $this->_orientation / 180 * pi()) + 0 * sin( - $this->_orientation / 180 * pi()), - $this->_calculateBarcodeHeight() * cos( - $this->_orientation / 180 * pi()) + $this->_calculateBarcodeWidth() * sin( - $this->_orientation / 180 * pi()), - 0 * cos( - $this->_orientation / 180 * pi()) + $this->_calculateBarcodeWidth() * sin( - $this->_orientation / 180 * pi()), - )); - } - return $this->_offsetTop; - } - - /** - * Apply rotation on a point in X/Y dimensions - * - * @param float $x1 x-position before rotation - * @param float $y1 y-position before rotation - * @return array Array of two elements corresponding to the new XY point - */ - protected function _rotate($x1, $y1) - { - $x2 = $x1 * cos($this->_orientation / 180 * pi()) - - $y1 * sin($this->_orientation / 180 * pi()) - + $this->getOffsetLeft(); - $y2 = $y1 * cos($this->_orientation / 180 * pi()) - + $x1 * sin($this->_orientation / 180 * pi()) - + $this->getOffsetTop(); - - return array( - intval($x2), - intval($y2) - ); - } - - /** - * Complete drawing of the barcode - * - * @return array Table of instructions - */ - public function draw() - { - $this->checkParams(); - $this->_drawBarcode(); - $this->_drawBorder(); - $this->_drawText(); - return $this->getInstructions(); - } - - /** - * Draw the barcode - */ - protected function _drawBarcode() - { - $barcodeTable = $this->_prepareBarcode(); - - $this->_preDrawBarcode(); - - $xpos = (int) $this->_withBorder; - $ypos = (int) $this->_withBorder; - - $point1 = $this->_rotate(0, 0); - $point2 = $this->_rotate(0, $this->_calculateHeight() - 1); - $point3 = $this->_rotate( - $this->_calculateWidth() - 1, - $this->_calculateHeight() - 1 - ); - $point4 = $this->_rotate($this->_calculateWidth() - 1, 0); - - $this->_addPolygon( - array( - $point1, - $point2, - $point3, - $point4 - ), $this->_backgroundColor - ); - - $xpos += $this->getQuietZone(); - $barLength = $this->_barHeight * $this->_factor; - - foreach ($barcodeTable as $bar) { - $width = $bar[1] * $this->_factor; - if ($bar[0]) { - $point1 = $this->_rotate($xpos, $ypos + $bar[2] * $barLength); - $point2 = $this->_rotate($xpos, $ypos + $bar[3] * $barLength); - $point3 = $this->_rotate( - $xpos + $width - 1, - $ypos + $bar[3] * $barLength - ); - $point4 = $this->_rotate( - $xpos + $width - 1, - $ypos + $bar[2] * $barLength - ); - $this->_addPolygon( - array( - $point1, - $point2, - $point3, - $point4, - ) - ); - } - $xpos += $width; - } - - $this->_postDrawBarcode(); - } - - /** - * Partial function to draw border - */ - protected function _drawBorder() - { - if ($this->_withBorder) { - $point1 = $this->_rotate(0, 0); - $point2 = $this->_rotate($this->_calculateWidth() - 1, 0); - $point3 = $this->_rotate( - $this->_calculateWidth() - 1, - $this->_calculateHeight() - 1 - ); - $point4 = $this->_rotate(0, $this->_calculateHeight() - 1); - $this->_addPolygon( - array( - $point1, - $point2, - $point3, - $point4, - $point1, - ), $this->_foreColor, false - ); - } - } - - /** - * Partial function to draw text - */ - protected function _drawText() - { - if ($this->_drawText) { - $text = $this->getTextToDisplay(); - if ($this->_stretchText) { - $textLength = strlen($text); - $space = ($this->_calculateWidth() - 2 * $this->getQuietZone()) / $textLength; - for ($i = 0; $i < $textLength; $i ++) { - $leftPosition = $this->getQuietZone() + $space * ($i + 0.5); - $this->_addText( - $text{$i}, - $this->_fontSize * $this->_factor, - $this->_rotate( - $leftPosition, - (int) $this->_withBorder * 2 - + $this->_factor * ($this->_barHeight + $this->_fontSize) + 1 - ), - $this->_font, - $this->_foreColor, - 'center', - - $this->_orientation - ); - } - } else { - $this->_addText( - $text, - $this->_fontSize * $this->_factor, - $this->_rotate( - $this->_calculateWidth() / 2, - (int) $this->_withBorder * 2 - + $this->_factor * ($this->_barHeight + $this->_fontSize) + 1 - ), - $this->_font, - $this->_foreColor, - 'center', - - $this->_orientation - ); - } - } - } - - /** - * Check for invalid characters - * - * @param string $value Text to be ckecked - */ - public function validateText($value) - { - $this->_validateText($value); - } - - /** - * Standard validation for most of barcode objects - * - * @param string $value - * @param array $options - * @throws Zend_Barcode_Object_Exception - */ - protected function _validateText($value, $options = array()) - { - $validatorName = (isset($options['validator'])) ? $options['validator'] : $this->getType(); - - $validator = new Zend_Validate_Barcode( - array( - 'adapter' => $validatorName, - 'checksum' => false, - ) - ); - - $checksumCharacter = ''; - $withChecksum = false; - if ($this->_mandatoryChecksum) { - $checksumCharacter = $this->_substituteChecksumCharacter; - $withChecksum = true; - } - - $value = $this->_addLeadingZeros($value, $withChecksum) - . $checksumCharacter; - - if (!$validator->isValid($value)) { - $message = implode("\n", $validator->getMessages()); - - /** - * @see Zend_Barcode_Object_Exception - */ - #require_once 'Zend/Barcode/Object/Exception.php'; - throw new Zend_Barcode_Object_Exception($message); - } - } - - /** - * Each child must prepare the barcode and return - * a table like array( - * 0 => array( - * 0 => int (visible(black) or not(white)) - * 1 => int (width of the bar) - * 2 => float (0->1 position from the top of the beginning of the bar in %) - * 3 => float (0->1 position from the top of the end of the bar in %) - * ), - * 1 => ... - * ) - * - * @return array - */ - abstract protected function _prepareBarcode(); - - /** - * Checking of parameters after all settings - */ - abstract protected function _checkParams(); - - /** - * Allow each child to draw something else - */ - protected function _preDrawBarcode() - { - } - - /** - * Allow each child to draw something else - * (ex: bearer bars in interleaved 2 of 5 code) - */ - protected function _postDrawBarcode() - { - } -} diff --git a/library/Zend/Barcode/Object/Planet.php b/library/Zend/Barcode/Object/Planet.php deleted file mode 100644 index 780932887a..0000000000 --- a/library/Zend/Barcode/Object/Planet.php +++ /dev/null @@ -1,62 +0,0 @@ - "00111", - 1 => "11100", - 2 => "11010", - 3 => "11001", - 4 => "10110", - 5 => "10101", - 6 => "10011", - 7 => "01110", - 8 => "01101", - 9 => "01011" - ); -} diff --git a/library/Zend/Barcode/Object/Postnet.php b/library/Zend/Barcode/Object/Postnet.php deleted file mode 100644 index cf4c218d54..0000000000 --- a/library/Zend/Barcode/Object/Postnet.php +++ /dev/null @@ -1,136 +0,0 @@ - "11000", - 1 => "00011", - 2 => "00101", - 3 => "00110", - 4 => "01001", - 5 => "01010", - 6 => "01100", - 7 => "10001", - 8 => "10010", - 9 => "10100" - ); - - /** - * Default options for Postnet barcode - * @return void - */ - protected function _getDefaultOptions() - { - $this->_barThinWidth = 2; - $this->_barHeight = 20; - $this->_drawText = false; - $this->_stretchText = true; - $this->_mandatoryChecksum = true; - } - - /** - * Width of the barcode (in pixels) - * @return integer - */ - protected function _calculateBarcodeWidth() - { - $quietZone = $this->getQuietZone(); - $startCharacter = (2 * $this->_barThinWidth) * $this->_factor; - $stopCharacter = (1 * $this->_barThinWidth) * $this->_factor; - $encodedData = (10 * $this->_barThinWidth) * $this->_factor * strlen($this->getText()); - return $quietZone + $startCharacter + $encodedData + $stopCharacter + $quietZone; - } - - /** - * Partial check of interleaved Postnet barcode - * @return void - */ - protected function _checkParams() - {} - - /** - * Prepare array to draw barcode - * @return array - */ - protected function _prepareBarcode() - { - $barcodeTable = array(); - - // Start character (1) - $barcodeTable[] = array(1 , $this->_barThinWidth , 0 , 1); - $barcodeTable[] = array(0 , $this->_barThinWidth , 0 , 1); - - // Text to encode - $textTable = str_split($this->getText()); - foreach ($textTable as $char) { - $bars = str_split($this->_codingMap[$char]); - foreach ($bars as $b) { - $barcodeTable[] = array(1 , $this->_barThinWidth , 0.5 - $b * 0.5 , 1); - $barcodeTable[] = array(0 , $this->_barThinWidth , 0 , 1); - } - } - - // Stop character (1) - $barcodeTable[] = array(1 , $this->_barThinWidth , 0 , 1); - return $barcodeTable; - } - - /** - * Get barcode checksum - * - * @param string $text - * @return int - */ - public function getChecksum($text) - { - $this->_checkText($text); - $sum = array_sum(str_split($text)); - $checksum = (10 - ($sum % 10)) % 10; - return $checksum; - } -} diff --git a/library/Zend/Barcode/Object/Royalmail.php b/library/Zend/Barcode/Object/Royalmail.php deleted file mode 100644 index 40590f0593..0000000000 --- a/library/Zend/Barcode/Object/Royalmail.php +++ /dev/null @@ -1,163 +0,0 @@ - '3300', '1' => '3210', '2' => '3201', '3' => '2310', '4' => '2301', '5' => '2211', - '6' => '3120', '7' => '3030', '8' => '3021', '9' => '2130', 'A' => '2121', 'B' => '2031', - 'C' => '3102', 'D' => '3012', 'E' => '3003', 'F' => '2112', 'G' => '2103', 'H' => '2013', - 'I' => '1320', 'J' => '1230', 'K' => '1221', 'L' => '0330', 'M' => '0321', 'N' => '0231', - 'O' => '1302', 'P' => '1212', 'Q' => '1203', 'R' => '0312', 'S' => '0303', 'T' => '0213', - 'U' => '1122', 'V' => '1032', 'W' => '1023', 'X' => '0132', 'Y' => '0123', 'Z' => '0033' - ); - - protected $_rows = array( - '0' => 1, '1' => 1, '2' => 1, '3' => 1, '4' => 1, '5' => 1, - '6' => 2, '7' => 2, '8' => 2, '9' => 2, 'A' => 2, 'B' => 2, - 'C' => 3, 'D' => 3, 'E' => 3, 'F' => 3, 'G' => 3, 'H' => 3, - 'I' => 4, 'J' => 4, 'K' => 4, 'L' => 4, 'M' => 4, 'N' => 4, - 'O' => 5, 'P' => 5, 'Q' => 5, 'R' => 5, 'S' => 5, 'T' => 5, - 'U' => 0, 'V' => 0, 'W' => 0, 'X' => 0, 'Y' => 0, 'Z' => 0, - ); - - protected $_columns = array( - '0' => 1, '1' => 2, '2' => 3, '3' => 4, '4' => 5, '5' => 0, - '6' => 1, '7' => 2, '8' => 3, '9' => 4, 'A' => 5, 'B' => 0, - 'C' => 1, 'D' => 2, 'E' => 3, 'F' => 4, 'G' => 5, 'H' => 0, - 'I' => 1, 'J' => 2, 'K' => 3, 'L' => 4, 'M' => 5, 'N' => 0, - 'O' => 1, 'P' => 2, 'Q' => 3, 'R' => 4, 'S' => 5, 'T' => 0, - 'U' => 1, 'V' => 2, 'W' => 3, 'X' => 4, 'Y' => 5, 'Z' => 0, - ); - - /** - * Default options for Postnet barcode - * @return void - */ - protected function _getDefaultOptions() - { - $this->_barThinWidth = 2; - $this->_barHeight = 20; - $this->_drawText = false; - $this->_stretchText = true; - $this->_mandatoryChecksum = true; - } - - /** - * Width of the barcode (in pixels) - * @return integer - */ - protected function _calculateBarcodeWidth() - { - $quietZone = $this->getQuietZone(); - $startCharacter = (2 * $this->_barThinWidth) * $this->_factor; - $stopCharacter = (1 * $this->_barThinWidth) * $this->_factor; - $encodedData = (8 * $this->_barThinWidth) * $this->_factor * strlen($this->getText()); - return $quietZone + $startCharacter + $encodedData + $stopCharacter + $quietZone; - } - - /** - * Partial check of interleaved Postnet barcode - * @return void - */ - protected function _checkParams() - {} - - /** - * Prepare array to draw barcode - * @return array - */ - protected function _prepareBarcode() - { - $barcodeTable = array(); - - // Start character (1) - $barcodeTable[] = array(1 , $this->_barThinWidth , 0 , 5/8); - $barcodeTable[] = array(0 , $this->_barThinWidth , 0 , 1); - - // Text to encode - $textTable = str_split($this->getText()); - foreach ($textTable as $char) { - $bars = str_split($this->_codingMap[$char]); - foreach ($bars as $b) { - $barcodeTable[] = array(1 , $this->_barThinWidth , ($b > 1 ? 3/8 : 0) , ($b % 2 ? 5/8 : 1)); - $barcodeTable[] = array(0 , $this->_barThinWidth , 0 , 1); - } - } - - // Stop character (1) - $barcodeTable[] = array(1 , $this->_barThinWidth , 0 , 1); - return $barcodeTable; - } - - /** - * Get barcode checksum - * - * @param string $text - * @return int - */ - public function getChecksum($text) - { - $this->_checkText($text); - $values = str_split($text); - $rowvalue = 0; - $colvalue = 0; - foreach($values as $row) { - $rowvalue += $this->_rows[$row]; - $colvalue += $this->_columns[$row]; - } - - $rowvalue %= 6; - $colvalue %= 6; - - $rowchkvalue = array_keys($this->_rows, $rowvalue); - $colchkvalue = array_keys($this->_columns, $colvalue); - return current(array_intersect($rowchkvalue, $colchkvalue)); - } -} diff --git a/library/Zend/Barcode/Object/Upca.php b/library/Zend/Barcode/Object/Upca.php deleted file mode 100644 index 49cc54da8c..0000000000 --- a/library/Zend/Barcode/Object/Upca.php +++ /dev/null @@ -1,172 +0,0 @@ -_barcodeLength = 12; - $this->_mandatoryChecksum = true; - $this->_mandatoryQuietZones = true; - } - - /** - * Width of the barcode (in pixels) - * @return integer - */ - protected function _calculateBarcodeWidth() - { - $quietZone = $this->getQuietZone(); - $startCharacter = (3 * $this->_barThinWidth) * $this->_factor; - $middleCharacter = (5 * $this->_barThinWidth) * $this->_factor; - $stopCharacter = (3 * $this->_barThinWidth) * $this->_factor; - $encodedData = (7 * $this->_barThinWidth) * $this->_factor * 12; - return $quietZone + $startCharacter + $middleCharacter + $encodedData + $stopCharacter + $quietZone; - } - - /** - * Prepare array to draw barcode - * @return array - */ - protected function _prepareBarcode() - { - $barcodeTable = array(); - $height = ($this->_drawText) ? 1.1 : 1; - - // Start character (101) - $barcodeTable[] = array(1 , $this->_barThinWidth , 0 , $height); - $barcodeTable[] = array(0 , $this->_barThinWidth , 0 , $height); - $barcodeTable[] = array(1 , $this->_barThinWidth , 0 , $height); - - $textTable = str_split($this->getText()); - - // First character - $bars = str_split($this->_codingMap['A'][$textTable[0]]); - foreach ($bars as $b) { - $barcodeTable[] = array($b , $this->_barThinWidth , 0 , $height); - } - - // First part - for ($i = 1; $i < 6; $i++) { - $bars = str_split($this->_codingMap['A'][$textTable[$i]]); - foreach ($bars as $b) { - $barcodeTable[] = array($b , $this->_barThinWidth , 0 , 1); - } - } - - // Middle character (01010) - $barcodeTable[] = array(0 , $this->_barThinWidth , 0 , $height); - $barcodeTable[] = array(1 , $this->_barThinWidth , 0 , $height); - $barcodeTable[] = array(0 , $this->_barThinWidth , 0 , $height); - $barcodeTable[] = array(1 , $this->_barThinWidth , 0 , $height); - $barcodeTable[] = array(0 , $this->_barThinWidth , 0 , $height); - - // Second part - for ($i = 6; $i < 11; $i++) { - $bars = str_split($this->_codingMap['C'][$textTable[$i]]); - foreach ($bars as $b) { - $barcodeTable[] = array($b , $this->_barThinWidth , 0 , 1); - } - } - - // Last character - $bars = str_split($this->_codingMap['C'][$textTable[11]]); - foreach ($bars as $b) { - $barcodeTable[] = array($b , $this->_barThinWidth , 0 , $height); - } - - // Stop character (101) - $barcodeTable[] = array(1 , $this->_barThinWidth , 0 , $height); - $barcodeTable[] = array(0 , $this->_barThinWidth , 0 , $height); - $barcodeTable[] = array(1 , $this->_barThinWidth , 0 , $height); - return $barcodeTable; - } - - /** - * Partial function to draw text - * @return void - */ - protected function _drawText() - { - if ($this->_drawText) { - $text = $this->getTextToDisplay(); - $characterWidth = (7 * $this->_barThinWidth) * $this->_factor; - $leftPosition = $this->getQuietZone() - $characterWidth; - for ($i = 0; $i < $this->_barcodeLength; $i ++) { - $fontSize = $this->_fontSize; - if ($i == 0 || $i == 11) { - $fontSize *= 0.8; - } - $this->_addText( - $text{$i}, - $fontSize * $this->_factor, - $this->_rotate( - $leftPosition, - (int) $this->_withBorder * 2 - + $this->_factor * ($this->_barHeight + $fontSize) + 1 - ), - $this->_font, - $this->_foreColor, - 'left', - - $this->_orientation - ); - switch ($i) { - case 0: - $factor = 10; - break; - case 5: - $factor = 4; - break; - case 10: - $factor = 11; - break; - default: - $factor = 0; - } - $leftPosition = $leftPosition + $characterWidth + ($factor * $this->_barThinWidth * $this->_factor); - } - } - } -} diff --git a/library/Zend/Barcode/Object/Upce.php b/library/Zend/Barcode/Object/Upce.php deleted file mode 100644 index 726c8de8e6..0000000000 --- a/library/Zend/Barcode/Object/Upce.php +++ /dev/null @@ -1,230 +0,0 @@ - array( - 0 => array('B','B','B','A','A','A'), - 1 => array('B','B','A','B','A','A'), - 2 => array('B','B','A','A','B','A'), - 3 => array('B','B','A','A','A','B'), - 4 => array('B','A','B','B','A','A'), - 5 => array('B','A','A','B','B','A'), - 6 => array('B','A','A','A','B','B'), - 7 => array('B','A','B','A','B','A'), - 8 => array('B','A','B','A','A','B'), - 9 => array('B','A','A','B','A','B')), - 1 => array( - 0 => array('A','A','A','B','B','B'), - 1 => array('A','A','B','A','B','B'), - 2 => array('A','A','B','B','A','B'), - 3 => array('A','A','B','B','B','A'), - 4 => array('A','B','A','A','B','B'), - 5 => array('A','B','B','A','A','B'), - 6 => array('A','B','B','B','A','A'), - 7 => array('A','B','A','B','A','B'), - 8 => array('A','B','A','B','B','A'), - 9 => array('A','B','B','A','B','A')) - ); - - /** - * Default options for Postnet barcode - * @return void - */ - protected function _getDefaultOptions() - { - $this->_barcodeLength = 8; - $this->_mandatoryChecksum = true; - $this->_mandatoryQuietZones = true; - } - - /** - * Retrieve text to encode - * @return string - */ - public function getText() - { - $text = parent::getText(); - if ($text{0} != 1) { - $text{0} = 0; - } - return $text; - } - - /** - * Width of the barcode (in pixels) - * @return integer - */ - protected function _calculateBarcodeWidth() - { - $quietZone = $this->getQuietZone(); - $startCharacter = (3 * $this->_barThinWidth) * $this->_factor; - $stopCharacter = (6 * $this->_barThinWidth) * $this->_factor; - $encodedData = (7 * $this->_barThinWidth) * $this->_factor * 6; - return $quietZone + $startCharacter + $encodedData + $stopCharacter + $quietZone; - } - - /** - * Prepare array to draw barcode - * @return array - */ - protected function _prepareBarcode() - { - $barcodeTable = array(); - $height = ($this->_drawText) ? 1.1 : 1; - - // Start character (101) - $barcodeTable[] = array(1 , $this->_barThinWidth , 0 , $height); - $barcodeTable[] = array(0 , $this->_barThinWidth , 0 , $height); - $barcodeTable[] = array(1 , $this->_barThinWidth , 0 , $height); - - $textTable = str_split($this->getText()); - $system = 0; - if ($textTable[0] == 1) { - $system = 1; - } - $checksum = $textTable[7]; - $parity = $this->_parities[$system][$checksum]; - - for ($i = 1; $i < 7; $i++) { - $bars = str_split($this->_codingMap[$parity[$i - 1]][$textTable[$i]]); - foreach ($bars as $b) { - $barcodeTable[] = array($b , $this->_barThinWidth , 0 , 1); - } - } - - // Stop character (10101) - $barcodeTable[] = array(0 , $this->_barThinWidth , 0 , $height); - $barcodeTable[] = array(1 , $this->_barThinWidth , 0 , $height); - $barcodeTable[] = array(0 , $this->_barThinWidth , 0 , $height); - $barcodeTable[] = array(1 , $this->_barThinWidth , 0 , $height); - $barcodeTable[] = array(0 , $this->_barThinWidth , 0 , $height); - $barcodeTable[] = array(1 , $this->_barThinWidth , 0 , $height); - return $barcodeTable; - } - - /** - * Partial function to draw text - * @return void - */ - protected function _drawText() - { - if ($this->_drawText) { - $text = $this->getTextToDisplay(); - $characterWidth = (7 * $this->_barThinWidth) * $this->_factor; - $leftPosition = $this->getQuietZone() - $characterWidth; - for ($i = 0; $i < $this->_barcodeLength; $i ++) { - $fontSize = $this->_fontSize; - if ($i == 0 || $i == 7) { - $fontSize *= 0.8; - } - $this->_addText( - $text{$i}, - $fontSize * $this->_factor, - $this->_rotate( - $leftPosition, - (int) $this->_withBorder * 2 - + $this->_factor * ($this->_barHeight + $fontSize) + 1 - ), - $this->_font, - $this->_foreColor, - 'left', - - $this->_orientation - ); - switch ($i) { - case 0: - $factor = 3; - break; - case 6: - $factor = 5; - break; - default: - $factor = 0; - } - $leftPosition = $leftPosition + $characterWidth + ($factor * $this->_barThinWidth * $this->_factor); - } - } - } - - /** - * Particular validation for Upce barcode objects - * (to suppress checksum character substitution) - * - * @param string $value - * @param array $options - * @throws Zend_Barcode_Object_Exception - */ - protected function _validateText($value, $options = array()) - { - $validator = new Zend_Validate_Barcode(array( - 'adapter' => 'upce', - 'checksum' => false, - )); - - $value = $this->_addLeadingZeros($value, true); - - if (!$validator->isValid($value)) { - $message = implode("\n", $validator->getMessages()); - - /** - * @see Zend_Barcode_Object_Exception - */ - #require_once 'Zend/Barcode/Object/Exception.php'; - throw new Zend_Barcode_Object_Exception($message); - } - } - - /** - * Get barcode checksum - * - * @param string $text - * @return int - */ - public function getChecksum($text) - { - $text = $this->_addLeadingZeros($text, true); - if ($text{0} != 1) { - $text{0} = 0; - } - return parent::getChecksum($text); - } -} diff --git a/library/Zend/Barcode/Renderer/Exception.php b/library/Zend/Barcode/Renderer/Exception.php deleted file mode 100644 index 8a110c5d50..0000000000 --- a/library/Zend/Barcode/Renderer/Exception.php +++ /dev/null @@ -1,35 +0,0 @@ -_userHeight = intval($value); - return $this; - } - - /** - * Get barcode height - * - * @return int - */ - public function getHeight() - { - return $this->_userHeight; - } - - /** - * Set barcode width - * - * @param mixed $value - * @return self - * @throws Zend_Barcode_Renderer_Exception - */ - public function setWidth($value) - { - if (!is_numeric($value) || intval($value) < 0) { - #require_once 'Zend/Barcode/Renderer/Exception.php'; - throw new Zend_Barcode_Renderer_Exception( - 'Image width must be greater than or equals 0' - ); - } - $this->_userWidth = intval($value); - return $this; - } - - /** - * Get barcode width - * - * @return int - */ - public function getWidth() - { - return $this->_userWidth; - } - - /** - * Set an image resource to draw the barcode inside - * - * @param $image - * @return Zend_Barcode_Renderer - * @throws Zend_Barcode_Renderer_Exception - */ - public function setResource($image) - { - if (gettype($image) != 'resource' || get_resource_type($image) != 'gd') { - #require_once 'Zend/Barcode/Renderer/Exception.php'; - throw new Zend_Barcode_Renderer_Exception( - 'Invalid image resource provided to setResource()' - ); - } - $this->_resource = $image; - return $this; - } - - /** - * Set the image type to produce (png, jpeg, gif) - * - * @param string $value - * @return Zend_Barcode_RendererAbstract - * @throws Zend_Barcode_Renderer_Exception - */ - public function setImageType($value) - { - if ($value == 'jpg') { - $value = 'jpeg'; - } - - if (!in_array($value, $this->_allowedImageType)) { - #require_once 'Zend/Barcode/Renderer/Exception.php'; - throw new Zend_Barcode_Renderer_Exception(sprintf( - 'Invalid type "%s" provided to setImageType()', - $value - )); - } - - $this->_imageType = $value; - return $this; - } - - /** - * Retrieve the image type to produce - * - * @return string - */ - public function getImageType() - { - return $this->_imageType; - } - - /** - * Initialize the image resource - * - * @return void - * @throws Zend_Barcode_Exception - */ - protected function _initRenderer() - { - if (!extension_loaded('gd')) { - #require_once 'Zend/Barcode/Exception.php'; - $e = new Zend_Barcode_Exception( - 'Gd extension must be loaded to render barcode as image' - ); - $e->setIsRenderable(false); - throw $e; - } - - $barcodeWidth = $this->_barcode->getWidth(true); - $barcodeHeight = $this->_barcode->getHeight(true); - - if ($this->_resource !== null) { - $foreColor = $this->_barcode->getForeColor(); - $backgroundColor = $this->_barcode->getBackgroundColor(); - $this->_imageBackgroundColor = imagecolorallocate( - $this->_resource, - ($backgroundColor & 0xFF0000) >> 16, - ($backgroundColor & 0x00FF00) >> 8, - $backgroundColor & 0x0000FF - ); - $this->_imageForeColor = imagecolorallocate( - $this->_resource, - ($foreColor & 0xFF0000) >> 16, - ($foreColor & 0x00FF00) >> 8, - $foreColor & 0x0000FF - ); - } else { - $width = $barcodeWidth; - $height = $barcodeHeight; - if ($this->_userWidth && $this->_barcode->getType() != 'error') { - $width = $this->_userWidth; - } - if ($this->_userHeight && $this->_barcode->getType() != 'error') { - $height = $this->_userHeight; - } - - $foreColor = $this->_barcode->getForeColor(); - $backgroundColor = $this->_barcode->getBackgroundColor(); - $this->_resource = imagecreatetruecolor($width, $height); - - $this->_imageBackgroundColor = imagecolorallocate( - $this->_resource, - ($backgroundColor & 0xFF0000) >> 16, - ($backgroundColor & 0x00FF00) >> 8, - $backgroundColor & 0x0000FF - ); - $this->_imageForeColor = imagecolorallocate( - $this->_resource, - ($foreColor & 0xFF0000) >> 16, - ($foreColor & 0x00FF00) >> 8, - $foreColor & 0x0000FF - ); - $white = imagecolorallocate($this->_resource, 255, 255, 255); - imagefilledrectangle($this->_resource, 0, 0, $width - 1, $height - 1, $white); - } - $this->_adjustPosition(imagesy($this->_resource), imagesx($this->_resource)); - imagefilledrectangle( - $this->_resource, - $this->_leftOffset, - $this->_topOffset, - $this->_leftOffset + $barcodeWidth - 1, - $this->_topOffset + $barcodeHeight - 1, - $this->_imageBackgroundColor - ); - } - - /** - * Check barcode parameters - * - * @return void - */ - protected function _checkParams() - { - $this->_checkDimensions(); - } - - /** - * Check barcode dimensions - * - * @return void - * @throws Zend_Barcode_Renderer_Exception - */ - protected function _checkDimensions() - { - if ($this->_resource !== null) { - if (imagesy($this->_resource) < $this->_barcode->getHeight(true)) { - #require_once 'Zend/Barcode/Renderer/Exception.php'; - throw new Zend_Barcode_Renderer_Exception( - 'Barcode is define outside the image (height)' - ); - } - } else { - if ($this->_userHeight) { - $height = $this->_barcode->getHeight(true); - if ($this->_userHeight < $height) { - #require_once 'Zend/Barcode/Renderer/Exception.php'; - throw new Zend_Barcode_Renderer_Exception(sprintf( - "Barcode is define outside the image (calculated: '%d', provided: '%d')", - $height, - $this->_userHeight - )); - } - } - } - if ($this->_resource !== null) { - if (imagesx($this->_resource) < $this->_barcode->getWidth(true)) { - #require_once 'Zend/Barcode/Renderer/Exception.php'; - throw new Zend_Barcode_Renderer_Exception( - 'Barcode is define outside the image (width)' - ); - } - } else { - if ($this->_userWidth) { - $width = $this->_barcode->getWidth(true); - if ($this->_userWidth < $width) { - #require_once 'Zend/Barcode/Renderer/Exception.php'; - throw new Zend_Barcode_Renderer_Exception(sprintf( - "Barcode is define outside the image (calculated: '%d', provided: '%d')", - $width, - $this->_userWidth - )); - } - } - } - } - - /** - * Draw and render the barcode with correct headers - * - * @return mixed - */ - public function render() - { - $this->draw(); - header("Content-Type: image/" . $this->_imageType); - $functionName = 'image' . $this->_imageType; - call_user_func($functionName, $this->_resource); - @imagedestroy($this->_resource); - } - - /** - * Draw a polygon in the image resource - * - * @param array $points - * @param integer $color - * @param boolean $filled - */ - protected function _drawPolygon($points, $color, $filled = true) - { - $newPoints = array( - $points[0][0] + $this->_leftOffset, - $points[0][1] + $this->_topOffset, - $points[1][0] + $this->_leftOffset, - $points[1][1] + $this->_topOffset, - $points[2][0] + $this->_leftOffset, - $points[2][1] + $this->_topOffset, - $points[3][0] + $this->_leftOffset, - $points[3][1] + $this->_topOffset, - ); - - $allocatedColor = imagecolorallocate( - $this->_resource, - ($color & 0xFF0000) >> 16, - ($color & 0x00FF00) >> 8, - $color & 0x0000FF - ); - - if ($filled) { - imagefilledpolygon($this->_resource, $newPoints, 4, $allocatedColor); - } else { - imagepolygon($this->_resource, $newPoints, 4, $allocatedColor); - } - } - - /** - * Draw a polygon in the image resource - * - * @param string $text - * @param float $size - * @param array $position - * @param string $font - * @param integer $color - * @param string $alignment - * @param float|int $orientation - * @throws Zend_Barcode_Renderer_Exception - */ - protected function _drawText($text, $size, $position, $font, $color, $alignment = 'center', $orientation = 0) - { - $allocatedColor = imagecolorallocate( - $this->_resource, - ($color & 0xFF0000) >> 16, - ($color & 0x00FF00) >> 8, - $color & 0x0000FF - ); - - if ($font == null) { - $font = 3; - } - $position[0] += $this->_leftOffset; - $position[1] += $this->_topOffset; - - if (is_numeric($font)) { - if ($orientation) { - /** - * imagestring() doesn't allow orientation, if orientation - * needed: a TTF font is required. - * Throwing an exception here, allow to use automaticRenderError - * to informe user of the problem instead of simply not drawing - * the text - */ - #require_once 'Zend/Barcode/Renderer/Exception.php'; - throw new Zend_Barcode_Renderer_Exception( - 'No orientation possible with GD internal font' - ); - } - $fontWidth = imagefontwidth($font); - $positionY = $position[1] - imagefontheight($font) + 1; - switch ($alignment) { - case 'left': - $positionX = $position[0]; - break; - case 'center': - $positionX = $position[0] - ceil(($fontWidth * strlen($text)) / 2); - break; - case 'right': - $positionX = $position[0] - ($fontWidth * strlen($text)); - break; - } - imagestring($this->_resource, $font, $positionX, $positionY, $text, $color); - } else { - - if (!function_exists('imagettfbbox')) { - #require_once 'Zend/Barcode/Renderer/Exception.php'; - throw new Zend_Barcode_Renderer_Exception( - 'A font was provided, but this instance of PHP does not have TTF (FreeType) support' - ); - } - - $box = imagettfbbox($size, 0, $font, $text); - switch ($alignment) { - case 'left': - $width = 0; - break; - case 'center': - $width = ($box[2] - $box[0]) / 2; - break; - case 'right': - $width = ($box[2] - $box[0]); - break; - } - imagettftext( - $this->_resource, - $size, - $orientation, - $position[0] - ($width * cos(pi() * $orientation / 180)), - $position[1] + ($width * sin(pi() * $orientation / 180)), - $allocatedColor, - $font, - $text - ); - } - } -} diff --git a/library/Zend/Barcode/Renderer/Pdf.php b/library/Zend/Barcode/Renderer/Pdf.php deleted file mode 100644 index 0aa87b606f..0000000000 --- a/library/Zend/Barcode/Renderer/Pdf.php +++ /dev/null @@ -1,245 +0,0 @@ -_resource = $pdf; - $this->_page = intval($page); - - if (!count($this->_resource->pages)) { - $this->_page = 0; - $this->_resource->pages[] = new Zend_Pdf_Page( - Zend_Pdf_Page::SIZE_A4 - ); - } - return $this; - } - - /** - * Check renderer parameters - * - * @return void - */ - protected function _checkParams() - { - } - - /** - * Draw the barcode in the PDF, send headers and the PDF - * @return mixed - */ - public function render() - { - $this->draw(); - header("Content-Type: application/pdf"); - echo $this->_resource->render(); - } - - /** - * Initialize the PDF resource - * @return void - */ - protected function _initRenderer() - { - if ($this->_resource === null) { - $this->_resource = new Zend_Pdf(); - $this->_resource->pages[] = new Zend_Pdf_Page( - Zend_Pdf_Page::SIZE_A4 - ); - } - - $pdfPage = $this->_resource->pages[$this->_page]; - $this->_adjustPosition($pdfPage->getHeight(), $pdfPage->getWidth()); - } - - /** - * Draw a polygon in the rendering resource - * @param array $points - * @param integer $color - * @param boolean $filled - */ - protected function _drawPolygon($points, $color, $filled = true) - { - $page = $this->_resource->pages[$this->_page]; - foreach ($points as $point) { - $x[] = $point[0] * $this->_moduleSize + $this->_leftOffset; - $y[] = $page->getHeight() - $point[1] * $this->_moduleSize - $this->_topOffset; - } - if (count($y) == 4) { - if ($x[0] != $x[3] && $y[0] == $y[3]) { - $y[0] -= ($this->_moduleSize / 2); - $y[3] -= ($this->_moduleSize / 2); - } - if ($x[1] != $x[2] && $y[1] == $y[2]) { - $y[1] += ($this->_moduleSize / 2); - $y[2] += ($this->_moduleSize / 2); - } - } - - $color = new Zend_Pdf_Color_Rgb( - (($color & 0xFF0000) >> 16) / 255.0, - (($color & 0x00FF00) >> 8) / 255.0, - ($color & 0x0000FF) / 255.0 - ); - - $page->setLineColor($color); - $page->setFillColor($color); - $page->setLineWidth($this->_moduleSize); - - $fillType = ($filled) - ? Zend_Pdf_Page::SHAPE_DRAW_FILL_AND_STROKE - : Zend_Pdf_Page::SHAPE_DRAW_STROKE; - - $page->drawPolygon($x, $y, $fillType); - } - - /** - * Draw a text in the rendering resource - * - * @param string $text - * @param float $size - * @param array $position - * @param string $font - * @param integer $color - * @param string $alignment - * @param float|int $orientation - */ - protected function _drawText( - $text, - $size, - $position, - $font, - $color, - $alignment = 'center', - $orientation = 0 - ) { - $page = $this->_resource->pages[$this->_page]; - $color = new Zend_Pdf_Color_Rgb( - (($color & 0xFF0000) >> 16) / 255.0, - (($color & 0x00FF00) >> 8) / 255.0, - ($color & 0x0000FF) / 255.0 - ); - - $page->setLineColor($color); - $page->setFillColor($color); - $page->setFont(Zend_Pdf_Font::fontWithPath($font), $size * $this->_moduleSize * 1.2); - - $width = $this->widthForStringUsingFontSize( - $text, - Zend_Pdf_Font::fontWithPath($font), - $size * $this->_moduleSize - ); - - $angle = pi() * $orientation / 180; - $left = $position[0] * $this->_moduleSize + $this->_leftOffset; - $top = $page->getHeight() - $position[1] * $this->_moduleSize - $this->_topOffset; - - switch ($alignment) { - case 'center': - $left -= ($width / 2) * cos($angle); - $top -= ($width / 2) * sin($angle); - break; - case 'right': - $left -= $width; - break; - } - $page->rotate($left, $top, $angle); - $page->drawText($text, $left, $top); - $page->rotate($left, $top, - $angle); - } - - /** - * Calculate the width of a string: - * in case of using alignment parameter in drawText - * @param string $text - * @param Zend_Pdf_Font $font - * @param float $fontSize - * @return float - */ - public function widthForStringUsingFontSize($text, $font, $fontSize) - { - $drawingString = iconv('UTF-8', 'UTF-16BE//IGNORE', $text); - $characters = array(); - for ($i = 0; $i < strlen($drawingString); $i ++) { - $characters[] = (ord($drawingString[$i ++]) << 8) | ord($drawingString[$i]); - } - $glyphs = $font->glyphNumbersForCharacters($characters); - $widths = $font->widthsForGlyphs($glyphs); - $stringWidth = (array_sum($widths) / $font->getUnitsPerEm()) * $fontSize; - return $stringWidth; - } -} diff --git a/library/Zend/Barcode/Renderer/RendererAbstract.php b/library/Zend/Barcode/Renderer/RendererAbstract.php deleted file mode 100644 index bfccaca723..0000000000 --- a/library/Zend/Barcode/Renderer/RendererAbstract.php +++ /dev/null @@ -1,551 +0,0 @@ -toArray(); - } - if (is_array($options)) { - $this->setOptions($options); - } - $this->_type = strtolower(substr( - get_class($this), - strlen($this->_rendererNamespace) + 1 - )); - } - - /** - * Set renderer state from options array - * @param array $options - * @return Zend_Renderer_Object - */ - public function setOptions($options) - { - foreach ($options as $key => $value) { - $method = 'set' . $key; - if (method_exists($this, $method)) { - $this->$method($value); - } - } - return $this; - } - - /** - * Set renderer state from config object - * @param Zend_Config $config - * @return Zend_Renderer_Object - */ - public function setConfig(Zend_Config $config) - { - return $this->setOptions($config->toArray()); - } - - /** - * Set renderer namespace for autoloading - * - * @param string $namespace - * @return Zend_Renderer_Object - */ - public function setRendererNamespace($namespace) - { - $this->_rendererNamespace = $namespace; - return $this; - } - - /** - * Retrieve renderer namespace - * - * @return string - */ - public function getRendererNamespace() - { - return $this->_rendererNamespace; - } - - /** - * Retrieve renderer type - * @return string - */ - public function getType() - { - return $this->_type; - } - - /** - * Manually adjust top position - * @param integer $value - * @return Zend_Barcode_Renderer - * @throws Zend_Barcode_Renderer_Exception - */ - public function setTopOffset($value) - { - if (!is_numeric($value) || intval($value) < 0) { - #require_once 'Zend/Barcode/Renderer/Exception.php'; - throw new Zend_Barcode_Renderer_Exception( - 'Vertical position must be greater than or equals 0' - ); - } - $this->_topOffset = intval($value); - return $this; - } - - /** - * Retrieve vertical adjustment - * @return integer - */ - public function getTopOffset() - { - return $this->_topOffset; - } - - /** - * Manually adjust left position - * @param integer $value - * @return Zend_Barcode_Renderer - * @throws Zend_Barcode_Renderer_Exception - */ - public function setLeftOffset($value) - { - if (!is_numeric($value) || intval($value) < 0) { - #require_once 'Zend/Barcode/Renderer/Exception.php'; - throw new Zend_Barcode_Renderer_Exception( - 'Horizontal position must be greater than or equals 0' - ); - } - $this->_leftOffset = intval($value); - return $this; - } - - /** - * Retrieve vertical adjustment - * @return integer - */ - public function getLeftOffset() - { - return $this->_leftOffset; - } - - /** - * Activate/Deactivate the automatic rendering of exception - * - * @param boolean $value - * @return $this - */ - public function setAutomaticRenderError($value) - { - $this->_automaticRenderError = (bool) $value; - return $this; - } - - /** - * Horizontal position of the barcode in the rendering resource - * - * @param string $value - * @return Zend_Barcode_Renderer - * @throws Zend_Barcode_Renderer_Exception - */ - public function setHorizontalPosition($value) - { - if (!in_array($value, array('left' , 'center' , 'right'))) { - #require_once 'Zend/Barcode/Renderer/Exception.php'; - throw new Zend_Barcode_Renderer_Exception( - "Invalid barcode position provided must be 'left', 'center' or 'right'" - ); - } - $this->_horizontalPosition = $value; - return $this; - } - - /** - * Horizontal position of the barcode in the rendering resource - * @return string - */ - public function getHorizontalPosition() - { - return $this->_horizontalPosition; - } - - /** - * Vertical position of the barcode in the rendering resource - * - * @param string $value - * @return self - * @throws Zend_Barcode_Renderer_Exception - */ - public function setVerticalPosition($value) - { - if (!in_array($value, array('top' , 'middle' , 'bottom'))) { - #require_once 'Zend/Barcode/Renderer/Exception.php'; - throw new Zend_Barcode_Renderer_Exception( - "Invalid barcode position provided must be 'top', 'middle' or 'bottom'" - ); - } - $this->_verticalPosition = $value; - return $this; - } - - /** - * Vertical position of the barcode in the rendering resource - * @return string - */ - public function getVerticalPosition() - { - return $this->_verticalPosition; - } - - /** - * Set the size of a module - * @param float $value - * @return Zend_Barcode_Renderer - * @throws Zend_Barcode_Renderer_Exception - */ - public function setModuleSize($value) - { - if (!is_numeric($value) || floatval($value) <= 0) { - #require_once 'Zend/Barcode/Renderer/Exception.php'; - throw new Zend_Barcode_Renderer_Exception( - 'Float size must be greater than 0' - ); - } - $this->_moduleSize = floatval($value); - return $this; - } - - - /** - * Set the size of a module - * @return float - */ - public function getModuleSize() - { - return $this->_moduleSize; - } - - /** - * Retrieve the automatic rendering of exception - * @return boolean - */ - public function getAutomaticRenderError() - { - return $this->_automaticRenderError; - } - - /** - * Set the barcode object - * - * @param Zend_Barcode_Object $barcode - * @return Zend_Barcode_Renderer - * @throws Zend_Barcode_Renderer_Exception - */ - public function setBarcode($barcode) - { - if (!$barcode instanceof Zend_Barcode_Object_ObjectAbstract) { - #require_once 'Zend/Barcode/Renderer/Exception.php'; - throw new Zend_Barcode_Renderer_Exception( - 'Invalid barcode object provided to setBarcode()' - ); - } - $this->_barcode = $barcode; - return $this; - } - - /** - * Retrieve the barcode object - * @return Zend_Barcode_Object - */ - public function getBarcode() - { - return $this->_barcode; - } - - /** - * Checking of parameters after all settings - * @return boolean - */ - public function checkParams() - { - $this->_checkBarcodeObject(); - $this->_checkParams(); - return true; - } - - /** - * Check if a barcode object is correctly provided - * @return void - * @throws Zend_Barcode_Renderer_Exception - */ - protected function _checkBarcodeObject() - { - if ($this->_barcode === null) { - /** - * @see Zend_Barcode_Renderer_Exception - */ - #require_once 'Zend/Barcode/Renderer/Exception.php'; - throw new Zend_Barcode_Renderer_Exception( - 'No barcode object provided' - ); - } - } - - /** - * Calculate the left and top offset of the barcode in the - * rendering support - * - * @param float $supportHeight - * @param float $supportWidth - * @return void - */ - protected function _adjustPosition($supportHeight, $supportWidth) - { - $barcodeHeight = $this->_barcode->getHeight(true) * $this->_moduleSize; - if ($barcodeHeight != $supportHeight && $this->_topOffset == 0) { - switch ($this->_verticalPosition) { - case 'middle': - $this->_topOffset = floor( - ($supportHeight - $barcodeHeight) / 2); - break; - case 'bottom': - $this->_topOffset = $supportHeight - $barcodeHeight; - break; - case 'top': - default: - $this->_topOffset = 0; - break; - } - } - $barcodeWidth = $this->_barcode->getWidth(true) * $this->_moduleSize; - if ($barcodeWidth != $supportWidth && $this->_leftOffset == 0) { - switch ($this->_horizontalPosition) { - case 'center': - $this->_leftOffset = floor( - ($supportWidth - $barcodeWidth) / 2); - break; - case 'right': - $this->_leftOffset = $supportWidth - $barcodeWidth; - break; - case 'left': - default: - $this->_leftOffset = 0; - break; - } - } - } - - /** - * Draw the barcode in the rendering resource - * - * @return mixed - * @throws Zend_Exception - * @throws Zend_Barcode_Exception - */ - public function draw() - { - try { - $this->checkParams(); - $this->_initRenderer(); - $this->_drawInstructionList(); - } catch (Zend_Exception $e) { - $renderable = false; - if ($e instanceof Zend_Barcode_Exception) { - $renderable = $e->isRenderable(); - } - if ($this->_automaticRenderError && $renderable) { - $barcode = Zend_Barcode::makeBarcode( - 'error', - array('text' => $e->getMessage()) - ); - $this->setBarcode($barcode); - $this->_resource = null; - $this->_initRenderer(); - $this->_drawInstructionList(); - } else { - if ($e instanceof Zend_Barcode_Exception) { - $e->setIsRenderable(false); - } - throw $e; - } - } - return $this->_resource; - } - - /** - * Sub process to draw the barcode instructions - * Needed by the automatic error rendering - */ - private function _drawInstructionList() - { - $instructionList = $this->_barcode->draw(); - foreach ($instructionList as $instruction) { - switch ($instruction['type']) { - case 'polygon': - $this->_drawPolygon( - $instruction['points'], - $instruction['color'], - $instruction['filled'] - ); - break; - case 'text': //$text, $size, $position, $font, $color, $alignment = 'center', $orientation = 0) - $this->_drawText( - $instruction['text'], - $instruction['size'], - $instruction['position'], - $instruction['font'], - $instruction['color'], - $instruction['alignment'], - $instruction['orientation'] - ); - break; - default: - /** - * @see Zend_Barcode_Renderer_Exception - */ - #require_once 'Zend/Barcode/Renderer/Exception.php'; - throw new Zend_Barcode_Renderer_Exception( - 'Unknown drawing command' - ); - } - } - } - - /** - * Checking of parameters after all settings - * @return void - */ - abstract protected function _checkParams(); - - /** - * Render the resource by sending headers and drawed resource - * @return mixed - */ - abstract public function render(); - - /** - * Initialize the rendering resource - * @return void - */ - abstract protected function _initRenderer(); - - /** - * Draw a polygon in the rendering resource - * @param array $points - * @param integer $color - * @param boolean $filled - */ - abstract protected function _drawPolygon($points, $color, $filled = true); - - /** - * Draw a polygon in the rendering resource - * - * @param string $text - * @param float $size - * @param array $position - * @param string $font - * @param integer $color - * @param string $alignment - * @param float|int $orientation - */ - abstract protected function _drawText( - $text, - $size, - $position, - $font, - $color, - $alignment = 'center', - $orientation = 0 - ); -} diff --git a/library/Zend/Barcode/Renderer/Svg.php b/library/Zend/Barcode/Renderer/Svg.php deleted file mode 100644 index 76b274d1ec..0000000000 --- a/library/Zend/Barcode/Renderer/Svg.php +++ /dev/null @@ -1,385 +0,0 @@ -_userHeight = intval($value); - return $this; - } - - /** - * Get barcode height - * - * @return int - */ - public function getHeight() - { - return $this->_userHeight; - } - - /** - * Set barcode width - * - * @param mixed $value - * @return self - * @throws Zend_Barcode_Renderer_Exception - */ - public function setWidth($value) - { - if (!is_numeric($value) || intval($value) < 0) { - #require_once 'Zend/Barcode/Renderer/Exception.php'; - throw new Zend_Barcode_Renderer_Exception( - 'Svg width must be greater than or equals 0' - ); - } - $this->_userWidth = intval($value); - return $this; - } - - /** - * Get barcode width - * - * @return int - */ - public function getWidth() - { - return $this->_userWidth; - } - - /** - * Set an image resource to draw the barcode inside - * - * @param $svg - * @return Zend_Barcode_Renderer - * @throws Zend_Barcode_Renderer_Exception - */ - public function setResource($svg) - { - if (!$svg instanceof DOMDocument) { - #require_once 'Zend/Barcode/Renderer/Exception.php'; - throw new Zend_Barcode_Renderer_Exception( - 'Invalid DOMDocument resource provided to setResource()' - ); - } - $this->_resource = $svg; - return $this; - } - - /** - * Initialize the image resource - * - * @return void - */ - protected function _initRenderer() - { - $barcodeWidth = $this->_barcode->getWidth(true); - $barcodeHeight = $this->_barcode->getHeight(true); - - $backgroundColor = $this->_barcode->getBackgroundColor(); - $imageBackgroundColor = 'rgb(' . implode(', ', array(($backgroundColor & 0xFF0000) >> 16, - ($backgroundColor & 0x00FF00) >> 8, - ($backgroundColor & 0x0000FF))) . ')'; - - $width = $barcodeWidth; - $height = $barcodeHeight; - if ($this->_userWidth && $this->_barcode->getType() != 'error') { - $width = $this->_userWidth; - } - if ($this->_userHeight && $this->_barcode->getType() != 'error') { - $height = $this->_userHeight; - } - if ($this->_resource === null) { - $this->_resource = new DOMDocument('1.0', 'utf-8'); - $this->_resource->formatOutput = true; - $this->_rootElement = $this->_resource->createElement('svg'); - $this->_rootElement->setAttribute('xmlns', "http://www.w3.org/2000/svg"); - $this->_rootElement->setAttribute('version', '1.1'); - $this->_rootElement->setAttribute('width', $width); - $this->_rootElement->setAttribute('height', $height); - - $this->_appendRootElement('title', - array(), - "Barcode " . strtoupper($this->_barcode->getType()) . " " . $this->_barcode->getText()); - } else { - $this->_readRootElement(); - $width = $this->_rootElement->getAttribute('width'); - $height = $this->_rootElement->getAttribute('height'); - } - $this->_adjustPosition($height, $width); - - $this->_appendRootElement('rect', - array('x' => $this->_leftOffset, - 'y' => $this->_topOffset, - 'width' => ($this->_leftOffset + $barcodeWidth - 1), - 'height' => ($this->_topOffset + $barcodeHeight - 1), - 'fill' => $imageBackgroundColor)); - } - - protected function _readRootElement() - { - if ($this->_resource !== null) { - $this->_rootElement = $this->_resource->documentElement; - } - } - - /** - * Append a new DOMElement to the root element - * - * @param string $tagName - * @param array $attributes - * @param string $textContent - */ - protected function _appendRootElement($tagName, $attributes = array(), $textContent = null) - { - $newElement = $this->_createElement($tagName, $attributes, $textContent); - $this->_rootElement->appendChild($newElement); - } - - /** - * Create DOMElement - * - * @param string $tagName - * @param array $attributes - * @param string $textContent - * @return DOMElement - */ - protected function _createElement($tagName, $attributes = array(), $textContent = null) - { - $element = $this->_resource->createElement($tagName); - foreach ($attributes as $k =>$v) { - $element->setAttribute($k, $v); - } - if ($textContent !== null) { - $element->appendChild(new DOMText((string) $textContent)); - } - return $element; - } - - /** - * Check barcode parameters - * - * @return void - */ - protected function _checkParams() - { - $this->_checkDimensions(); - } - - /** - * Check barcode dimensions - * - * @return void - * @throws Zend_Barcode_Renderer_Exception - */ - protected function _checkDimensions() - { - if ($this->_resource !== null) { - $this->_readRootElement(); - $height = (float) $this->_rootElement->getAttribute('height'); - if ($height < $this->_barcode->getHeight(true)) { - #require_once 'Zend/Barcode/Renderer/Exception.php'; - throw new Zend_Barcode_Renderer_Exception( - 'Barcode is define outside the image (height)' - ); - } - } else { - if ($this->_userHeight) { - $height = $this->_barcode->getHeight(true); - if ($this->_userHeight < $height) { - #require_once 'Zend/Barcode/Renderer/Exception.php'; - throw new Zend_Barcode_Renderer_Exception(sprintf( - "Barcode is define outside the image (calculated: '%d', provided: '%d')", - $height, - $this->_userHeight - )); - } - } - } - if ($this->_resource !== null) { - $this->_readRootElement(); - $width = $this->_rootElement->getAttribute('width'); - if ($width < $this->_barcode->getWidth(true)) { - #require_once 'Zend/Barcode/Renderer/Exception.php'; - throw new Zend_Barcode_Renderer_Exception( - 'Barcode is define outside the image (width)' - ); - } - } else { - if ($this->_userWidth) { - $width = (float) $this->_barcode->getWidth(true); - if ($this->_userWidth < $width) { - #require_once 'Zend/Barcode/Renderer/Exception.php'; - throw new Zend_Barcode_Renderer_Exception(sprintf( - "Barcode is define outside the image (calculated: '%d', provided: '%d')", - $width, - $this->_userWidth - )); - } - } - } - } - - /** - * Draw the barcode in the rendering resource - * @return mixed - */ - public function draw() - { - parent::draw(); - $this->_resource->appendChild($this->_rootElement); - return $this->_resource; - } - - /** - * Draw and render the barcode with correct headers - * - * @return mixed - */ - public function render() - { - $this->draw(); - header("Content-Type: image/svg+xml"); - echo $this->_resource->saveXML(); - } - - /** - * Draw a polygon in the svg resource - * - * @param array $points - * @param integer $color - * @param boolean $filled - */ - protected function _drawPolygon($points, $color, $filled = true) - { - $color = 'rgb(' . implode(', ', array(($color & 0xFF0000) >> 16, - ($color & 0x00FF00) >> 8, - ($color & 0x0000FF))) . ')'; - $orientation = $this->getBarcode()->getOrientation(); - $newPoints = array( - $points[0][0] + $this->_leftOffset, - $points[0][1] + $this->_topOffset, - $points[1][0] + $this->_leftOffset, - $points[1][1] + $this->_topOffset, - $points[2][0] + $this->_leftOffset + cos(-$orientation), - $points[2][1] + $this->_topOffset - sin($orientation), - $points[3][0] + $this->_leftOffset + cos(-$orientation), - $points[3][1] + $this->_topOffset - sin($orientation), - ); - $newPoints = implode(' ', $newPoints); - $attributes['points'] = $newPoints; - $attributes['fill'] = $color; - $this->_appendRootElement('polygon', $attributes); - } - - /** - * Draw a polygon in the svg resource - * - * @param string $text - * @param float $size - * @param array $position - * @param string $font - * @param integer $color - * @param string $alignment - * @param float|int $orientation - */ - protected function _drawText($text, $size, $position, $font, $color, $alignment = 'center', $orientation = 0) - { - $color = 'rgb(' . implode(', ', array(($color & 0xFF0000) >> 16, - ($color & 0x00FF00) >> 8, - ($color & 0x0000FF))) . ')'; - $attributes['x'] = $position[0] + $this->_leftOffset; - $attributes['y'] = $position[1] + $this->_topOffset; - //$attributes['font-family'] = $font; - $attributes['color'] = $color; - $attributes['font-size'] = $size * 1.2; - switch ($alignment) { - case 'left': - $textAnchor = 'start'; - break; - case 'right': - $textAnchor = 'end'; - break; - case 'center': - default: - $textAnchor = 'middle'; - } - $attributes['style'] = 'text-anchor: ' . $textAnchor; - $attributes['transform'] = 'rotate(' - . (- $orientation) - . ', ' - . ($position[0] + $this->_leftOffset) - . ', ' . ($position[1] + $this->_topOffset) - . ')'; - $this->_appendRootElement('text', $attributes, $text); - } -} diff --git a/library/Zend/Cloud/AbstractFactory.php b/library/Zend/Cloud/AbstractFactory.php deleted file mode 100755 index 031c6ac487..0000000000 --- a/library/Zend/Cloud/AbstractFactory.php +++ /dev/null @@ -1,65 +0,0 @@ -toArray(); - } - - if (!isset($options[$adapterOption])) { - return null; - } - - $classname = $options[$adapterOption]; - unset($options[$adapterOption]); - if (!class_exists($classname)) { - #require_once 'Zend/Loader.php'; - Zend_Loader::loadClass($classname); - } - - return new $classname($options); - } -} diff --git a/library/Zend/Cloud/DocumentService/Adapter.php b/library/Zend/Cloud/DocumentService/Adapter.php deleted file mode 100644 index a60767fa44..0000000000 --- a/library/Zend/Cloud/DocumentService/Adapter.php +++ /dev/null @@ -1,155 +0,0 @@ -_documentClass = (string) $class; - return $this; - } - - /** - * Get the class for document objects - * - * @return string - */ - public function getDocumentClass() - { - return $this->_documentClass; - } - - /** - * Set the class for document set objects - * - * @param string $class - * @return Zend_Cloud_DocumentService_Adapter_AbstractAdapter - */ - public function setDocumentSetClass($class) - { - $this->_documentSetClass = (string) $class; - return $this; - } - - /** - * Get the class for document set objects - * - * @return string - */ - public function getDocumentSetClass() - { - return $this->_documentSetClass; - } - - /** - * Set the query class for query objects - * - * @param string $class - * @return Zend_Cloud_DocumentService_Adapter_AbstractAdapter - */ - public function setQueryClass($class) - { - $this->_queryClass = (string) $class; - return $this; - } - - /** - * Get the class for query objects - * - * @return string - */ - public function getQueryClass() - { - return $this->_queryClass; - } -} diff --git a/library/Zend/Cloud/DocumentService/Adapter/SimpleDb.php b/library/Zend/Cloud/DocumentService/Adapter/SimpleDb.php deleted file mode 100644 index 35a61d7524..0000000000 --- a/library/Zend/Cloud/DocumentService/Adapter/SimpleDb.php +++ /dev/null @@ -1,468 +0,0 @@ -toArray(); - } - - if (!is_array($options)) { - throw new Zend_Cloud_DocumentService_Exception('Invalid options provided to constructor'); - } - - $this->_simpleDb = new Zend_Service_Amazon_SimpleDb( - $options[self::AWS_ACCESS_KEY], $options[self::AWS_SECRET_KEY] - ); - - if (isset($options[self::HTTP_ADAPTER])) { - $this->_simpleDb->getHttpClient()->setAdapter($options[self::HTTP_ADAPTER]); - } - - if (isset($options[self::DOCUMENT_CLASS])) { - $this->setDocumentClass($options[self::DOCUMENT_CLASS]); - } - - if (isset($options[self::DOCUMENTSET_CLASS])) { - $this->setDocumentSetClass($options[self::DOCUMENTSET_CLASS]); - } - - if (isset($options[self::QUERY_CLASS])) { - $this->setQueryClass($options[self::QUERY_CLASS]); - } - } - - /** - * Create collection. - * - * @param string $name - * @param array $options - * @return void - */ - public function createCollection($name, $options = null) - { - try { - $this->_simpleDb->createDomain($name); - } catch(Zend_Service_Amazon_Exception $e) { - throw new Zend_Cloud_DocumentService_Exception('Error on domain creation: '.$e->getMessage(), $e->getCode(), $e); - } - } - - /** - * Delete collection. - * - * @param string $name - * @param array $options - * @return void - */ - public function deleteCollection($name, $options = null) - { - try { - $this->_simpleDb->deleteDomain($name); - } catch(Zend_Service_Amazon_Exception $e) { - throw new Zend_Cloud_DocumentService_Exception('Error on collection deletion: '.$e->getMessage(), $e->getCode(), $e); - } - } - - /** - * List collections. - * - * @param array $options - * @return array - */ - public function listCollections($options = null) - { - try { - // TODO package this in Pages - $domains = $this->_simpleDb->listDomains()->getData(); - } catch(Zend_Service_Amazon_Exception $e) { - throw new Zend_Cloud_DocumentService_Exception('Error on collection deletion: '.$e->getMessage(), $e->getCode(), $e); - } - - return $domains; - } - - /** - * List documents - * - * Returns a key/value array of document names to document objects. - * - * @param string $collectionName Name of collection for which to list documents - * @param array|null $options - * @return Zend_Cloud_DocumentService_DocumentSet - */ - public function listDocuments($collectionName, array $options = null) - { - $query = $this->select('*')->from($collectionName); - $items = $this->query($collectionName, $query, $options); - return $items; - } - - /** - * Insert document - * - * @param string $collectionName Collection into which to insert document - * @param array|Zend_Cloud_DocumentService_Document $document - * @param array $options - * @return void - */ - public function insertDocument($collectionName, $document, $options = null) - { - if (is_array($document)) { - $document = $this->_getDocumentFromArray($document); - } - - if (!$document instanceof Zend_Cloud_DocumentService_Document) { - throw new Zend_Cloud_DocumentService_Exception('Invalid document supplied'); - } - - try { - $this->_simpleDb->putAttributes( - $collectionName, - $document->getID(), - $this->_makeAttributes($document->getID(), $document->getFields()) - ); - } catch(Zend_Service_Amazon_Exception $e) { - throw new Zend_Cloud_DocumentService_Exception('Error on document insertion: '.$e->getMessage(), $e->getCode(), $e); - } - } - - /** - * Replace an existing document with a new version - * - * @param string $collectionName - * @param array|Zend_Cloud_DocumentService_Document $document - * @param array $options - * @return void - */ - public function replaceDocument($collectionName, $document, $options = null) - { - if (is_array($document)) { - $document = $this->_getDocumentFromArray($document); - } - - if (!$document instanceof Zend_Cloud_DocumentService_Document) { - throw new Zend_Cloud_DocumentService_Exception('Invalid document supplied'); - } - - // Delete document first, then insert. PutAttributes always keeps any - // fields not referenced in the payload, but present in the document - $documentId = $document->getId(); - $fields = $document->getFields(); - $docClass = get_class($document); - $this->deleteDocument($collectionName, $document, $options); - - $document = new $docClass($fields, $documentId); - $this->insertDocument($collectionName, $document); - } - - /** - * Update document. The new document replaces the existing document. - * - * Option 'merge' specifies to add all attributes (if true) or - * specific attributes ("attr" => true) instead of replacing them. - * By default, attributes are replaced. - * - * @param string $collectionName - * @param mixed|Zend_Cloud_DocumentService_Document $documentId Document ID, adapter-dependent - * @param array|Zend_Cloud_DocumentService_Document $fieldset Set of fields to update - * @param array $options - * @return boolean - */ - public function updateDocument($collectionName, $documentId, $fieldset = null, $options = null) - { - if (null === $fieldset && $documentId instanceof Zend_Cloud_DocumentService_Document) { - $fieldset = $documentId->getFields(); - if (empty($documentId)) { - $documentId = $documentId->getId(); - } - } elseif ($fieldset instanceof Zend_Cloud_DocumentService_Document) { - if (empty($documentId)) { - $documentId = $fieldset->getId(); - } - $fieldset = $fieldset->getFields(); - } - - $replace = array(); - if (empty($options[self::MERGE_OPTION])) { - // no merge option - we replace all - foreach ($fieldset as $key => $value) { - $replace[$key] = true; - } - } elseif (is_array($options[self::MERGE_OPTION])) { - foreach ($fieldset as $key => $value) { - if (empty($options[self::MERGE_OPTION][$key])) { - // if there's merge key, we add it, otherwise we replace it - $replace[$key] = true; - } - } - } // otherwise $replace is empty - all is merged - - try { - $this->_simpleDb->putAttributes( - $collectionName, - $documentId, - $this->_makeAttributes($documentId, $fieldset), - $replace - ); - } catch(Zend_Service_Amazon_Exception $e) { - throw new Zend_Cloud_DocumentService_Exception('Error on document update: '.$e->getMessage(), $e->getCode(), $e); - } - return true; - } - - /** - * Delete document. - * - * @param string $collectionName Collection from which to delete document - * @param mixed $document Document ID or Document object. - * @param array $options - * @return boolean - */ - public function deleteDocument($collectionName, $document, $options = null) - { - if ($document instanceof Zend_Cloud_DocumentService_Document) { - $document = $document->getId(); - } - try { - $this->_simpleDb->deleteAttributes($collectionName, $document); - } catch(Zend_Service_Amazon_Exception $e) { - throw new Zend_Cloud_DocumentService_Exception('Error on document deletion: '.$e->getMessage(), $e->getCode(), $e); - } - return true; - } - - /** - * Fetch single document by ID - * - * @param string $collectionName Collection name - * @param mixed $documentId Document ID, adapter-dependent - * @param array $options - * @return Zend_Cloud_DocumentService_Document - */ - public function fetchDocument($collectionName, $documentId, $options = null) - { - try { - $attributes = $this->_simpleDb->getAttributes($collectionName, $documentId); - if ($attributes == false || count($attributes) == 0) { - return false; - } - return $this->_resolveAttributes($attributes, true); - } catch(Zend_Service_Amazon_Exception $e) { - throw new Zend_Cloud_DocumentService_Exception('Error on fetching document: '.$e->getMessage(), $e->getCode(), $e); - } - } - - /** - * Query for documents stored in the document service. If a string is passed in - * $query, the query string will be passed directly to the service. - * - * @param string $collectionName Collection name - * @param string $query - * @param array $options - * @return array Zend_Cloud_DocumentService_DocumentSet - */ - public function query($collectionName, $query, $options = null) - { - $returnDocs = isset($options[self::RETURN_DOCUMENTS]) - ? (bool) $options[self::RETURN_DOCUMENTS] - : true; - - try { - if ($query instanceof Zend_Cloud_DocumentService_Adapter_SimpleDb_Query) { - $query = $query->assemble($collectionName); - } - $result = $this->_simpleDb->select($query); - } catch(Zend_Service_Amazon_Exception $e) { - throw new Zend_Cloud_DocumentService_Exception('Error on document query: '.$e->getMessage(), $e->getCode(), $e); - } - - return $this->_getDocumentSetFromResultSet($result, $returnDocs); - } - - /** - * Create query statement - * - * @param string $fields - * @return Zend_Cloud_DocumentService_Adapter_SimpleDb_Query - */ - public function select($fields = null) - { - $queryClass = $this->getQueryClass(); - if (!class_exists($queryClass)) { - #require_once 'Zend/Loader.php'; - Zend_Loader::loadClass($queryClass); - } - - $query = new $queryClass($this); - $defaultClass = self::DEFAULT_QUERY_CLASS; - if (!$query instanceof $defaultClass) { - throw new Zend_Cloud_DocumentService_Exception('Query class must extend ' . self::DEFAULT_QUERY_CLASS); - } - - $query->select($fields); - return $query; - } - - /** - * Get the concrete service client - * - * @return Zend_Service_Amazon_SimpleDb - */ - public function getClient() - { - return $this->_simpleDb; - } - - /** - * Convert array of key-value pairs to array of Amazon attributes - * - * @param string $name - * @param array $attributes - * @return array - */ - protected function _makeAttributes($name, $attributes) - { - $result = array(); - foreach ($attributes as $key => $attr) { - $result[] = new Zend_Service_Amazon_SimpleDb_Attribute($name, $key, $attr); - } - return $result; - } - - /** - * Convert array of Amazon attributes to array of key-value pairs - * - * @param array $attributes - * @return array - */ - protected function _resolveAttributes($attributes, $returnDocument = false) - { - $result = array(); - foreach ($attributes as $attr) { - $value = $attr->getValues(); - if (count($value) == 0) { - $value = null; - } elseif (count($value) == 1) { - $value = $value[0]; - } - $result[$attr->getName()] = $value; - } - - // Return as document object? - if ($returnDocument) { - $documentClass = $this->getDocumentClass(); - return new $documentClass($result, $attr->getItemName()); - } - - return $result; - } - - /** - * Create suitable document from array of fields - * - * @param array $document - * @return Zend_Cloud_DocumentService_Document - */ - protected function _getDocumentFromArray($document) - { - if (!isset($document[Zend_Cloud_DocumentService_Document::KEY_FIELD])) { - if (isset($document[self::ITEM_NAME])) { - $key = $document[self::ITEM_NAME]; - unset($document[self::ITEM_NAME]); - } else { - throw new Zend_Cloud_DocumentService_Exception('Fields array should contain the key field '.Zend_Cloud_DocumentService_Document::KEY_FIELD); - } - } else { - $key = $document[Zend_Cloud_DocumentService_Document::KEY_FIELD]; - unset($document[Zend_Cloud_DocumentService_Document::KEY_FIELD]); - } - - $documentClass = $this->getDocumentClass(); - return new $documentClass($document, $key); - } - - /** - * Create a DocumentSet from a SimpleDb resultset - * - * @param Zend_Service_Amazon_SimpleDb_Page $resultSet - * @param bool $returnDocs - * @return Zend_Cloud_DocumentService_DocumentSet - */ - protected function _getDocumentSetFromResultSet(Zend_Service_Amazon_SimpleDb_Page $resultSet, $returnDocs = true) - { - $docs = array(); - foreach ($resultSet->getData() as $item) { - $docs[] = $this->_resolveAttributes($item, $returnDocs); - } - - $setClass = $this->getDocumentSetClass(); - return new $setClass($docs); - } -} diff --git a/library/Zend/Cloud/DocumentService/Adapter/SimpleDb/Query.php b/library/Zend/Cloud/DocumentService/Adapter/SimpleDb/Query.php deleted file mode 100644 index 1477e0ea8a..0000000000 --- a/library/Zend/Cloud/DocumentService/Adapter/SimpleDb/Query.php +++ /dev/null @@ -1,175 +0,0 @@ -_adapter = $adapter; - if (null !== $collectionName) { - $this->from($collectionName); - } - } - - /** - * Get adapter - * - * @return Zend_Cloud_DocumentService_Adapter_SimpleDb - */ - public function getAdapter() - { - return $this->_adapter; - } - - /** - * Assemble the query into a format the adapter can utilize - * - * @var string $collectionName Name of collection from which to select - * @return string - */ - public function assemble($collectionName = null) - { - $adapter = $this->getAdapter()->getClient(); - $select = null; - $from = null; - $where = null; - $order = null; - $limit = null; - foreach ($this->getClauses() as $clause) { - list($name, $args) = $clause; - - switch ($name) { - case self::QUERY_SELECT: - $select = $args[0]; - break; - case self::QUERY_FROM: - if (null === $from) { - // Only allow setting FROM clause once - $from = $adapter->quoteName($args); - } - break; - case self::QUERY_WHERE: - $statement = $this->_parseWhere($args[0], $args[1]); - if (null === $where) { - $where = $statement; - } else { - $operator = empty($args[2]) ? 'AND' : $args[2]; - $where .= ' ' . $operator . ' ' . $statement; - } - break; - case self::QUERY_WHEREID: - $statement = $this->_parseWhere('ItemName() = ?', array($args)); - if (null === $where) { - $where = $statement; - } else { - $operator = empty($args[2]) ? 'AND' : $args[2]; - $where .= ' ' . $operator . ' ' . $statement; - } - break; - case self::QUERY_ORDER: - $order = $adapter->quoteName($args[0]); - if (isset($args[1])) { - $order .= ' ' . $args[1]; - } - break; - case self::QUERY_LIMIT: - $limit = $args; - break; - default: - // Ignore unknown clauses - break; - } - } - - if (empty($select)) { - $select = "*"; - } - if (empty($from)) { - if (null === $collectionName) { - #require_once 'Zend/Cloud/DocumentService/Exception.php'; - throw new Zend_Cloud_DocumentService_Exception("Query requires a FROM clause"); - } - $from = $adapter->quoteName($collectionName); - } - $query = "select $select from $from"; - if (!empty($where)) { - $query .= " where $where"; - } - if (!empty($order)) { - $query .= " order by $order"; - } - if (!empty($limit)) { - $query .= " limit $limit"; - } - return $query; - } - - /** - * Parse a where statement into service-specific language - * - * @todo Ensure this fulfills the entire SimpleDB query specification for WHERE - * @param string $where - * @param array $args - * @return string - */ - protected function _parseWhere($where, $args) - { - if (!is_array($args)) { - $args = (array) $args; - } - $adapter = $this->getAdapter()->getClient(); - $i = 0; - while (false !== ($pos = strpos($where, '?'))) { - $where = substr_replace($where, $adapter->quote($args[$i]), $pos); - ++$i; - } - if (('(' != $where[0]) || (')' != $where[strlen($where) - 1])) { - $where = '(' . $where . ')'; - } - return $where; - } - } diff --git a/library/Zend/Cloud/DocumentService/Adapter/WindowsAzure.php b/library/Zend/Cloud/DocumentService/Adapter/WindowsAzure.php deleted file mode 100755 index ffc0229754..0000000000 --- a/library/Zend/Cloud/DocumentService/Adapter/WindowsAzure.php +++ /dev/null @@ -1,628 +0,0 @@ -toArray(); - } - - if (empty($options)) { - $options = array(); - } - - if (!is_array($options)) { - throw new Zend_Cloud_DocumentService_Exception('Invalid options provided'); - } - - if (isset($options[self::DOCUMENT_CLASS])) { - $this->setDocumentClass($options[self::DOCUMENT_CLASS]); - } - - if (isset($options[self::DOCUMENTSET_CLASS])) { - $this->setDocumentSetClass($options[self::DOCUMENTSET_CLASS]); - } - - if (isset($options[self::QUERY_CLASS])) { - $this->setQueryClass($options[self::QUERY_CLASS]); - } - - // Build Zend_Service_WindowsAzure_Storage_Blob instance - if (!isset($options[self::HOST])) { - $host = self::DEFAULT_HOST; - } else { - $host = $options[self::HOST]; - } - - if (! isset($options[self::ACCOUNT_NAME])) { - throw new Zend_Cloud_DocumentService_Exception('No Windows Azure account name provided.'); - } - - if (! isset($options[self::ACCOUNT_KEY])) { - throw new Zend_Cloud_DocumentService_Exception('No Windows Azure account key provided.'); - } - - // TODO: support $usePathStyleUri and $retryPolicy - try { - $this->_storageClient = new Zend_Service_WindowsAzure_Storage_Table( - $host, $options[self::ACCOUNT_NAME], $options[self::ACCOUNT_KEY]); - // Parse other options - if (! empty($options[self::PROXY_HOST])) { - $proxyHost = $options[self::PROXY_HOST]; - $proxyPort = isset($options[self::PROXY_PORT]) ? $options[self::PROXY_PORT] : 8080; - $proxyCredentials = isset($options[self::PROXY_CREDENTIALS]) ? $options[self::PROXY_CREDENTIALS] : ''; - $this->_storageClient->setProxy(true, $proxyHost, $proxyPort, $proxyCredentials); - } - if (isset($options[self::HTTP_ADAPTER])) { - $this->_storageClient->setHttpClientChannel($options[self::HTTP_ADAPTER]); - } - } catch(Zend_Service_WindowsAzure_Exception $e) { - throw new Zend_Cloud_DocumentService_Exception('Error on document service creation: '.$e->getMessage(), $e->getCode(), $e); - } - } - - /** - * Set the default partition key - * - * @param string $key - * @return Zend_Cloud_DocumentService_Adapter_WindowsAzure - */ - public function setDefaultPartitionKey($key) - { - $this->_validateKey($key); - $this->_defaultPartitionKey = $key; - return $this; - } - - /** - * Retrieve default partition key - * - * @return null|string - */ - public function getDefaultPartitionKey() - { - return $this->_defaultPartitionKey; - } - - /** - * Create collection. - * - * @param string $name - * @param array $options - * @return boolean - */ - public function createCollection($name, $options = null) - { - if (!preg_match('/^[A-Za-z][A-Za-z0-9]{2,}$/', $name)) { - throw new Zend_Cloud_DocumentService_Exception('Invalid collection name; Windows Azure collection names must consist of alphanumeric characters only, and be at least 3 characters long'); - } - try { - $this->_storageClient->createTable($name); - } catch(Zend_Service_WindowsAzure_Exception $e) { - if (strpos($e->getMessage(), "table specified already exists") === false) { - throw new Zend_Cloud_DocumentService_Exception('Error on collection creation: '.$e->getMessage(), $e->getCode(), $e); - } - } - return true; - } - - /** - * Delete collection. - * - * @param string $name - * @param array $options - * @return boolean - */ - public function deleteCollection($name, $options = null) - { - try { - $this->_storageClient->deleteTable($name); - } catch(Zend_Service_WindowsAzure_Exception $e) { - if (strpos($e->getMessage(), "does not exist") === false) { - throw new Zend_Cloud_DocumentService_Exception('Error on collection deletion: '.$e->getMessage(), $e->getCode(), $e); - } - } - return true; - } - - /** - * List collections. - * - * @param array $options - * @return array - */ - public function listCollections($options = null) - { - try { - $tables = $this->_storageClient->listTables(); - $restables = array(); - foreach ($tables as $table) { - $restables[] = $table->name; - } - return $restables; - } catch(Zend_Service_WindowsAzure_Exception $e) { - throw new Zend_Cloud_DocumentService_Exception('Error on collection list: '.$e->getMessage(), $e->getCode(), $e); - } - - return $tables; - } - - /** - * Create suitable document from array of fields - * - * @param array $document - * @param null|string $collectionName Collection to which this document belongs - * @return Zend_Cloud_DocumentService_Document - */ - protected function _getDocumentFromArray($document, $collectionName = null) - { - $key = null; - if (!isset($document[Zend_Cloud_DocumentService_Document::KEY_FIELD])) { - if (isset($document[self::ROW_KEY])) { - $rowKey = $document[self::ROW_KEY]; - unset($document[self::ROW_KEY]); - if (isset($document[self::PARTITION_KEY])) { - $key = array($document[self::PARTITION_KEY], $rowKey); - unset($document[self::PARTITION_KEY]); - } elseif (null !== ($partitionKey = $this->getDefaultPartitionKey())) { - $key = array($partitionKey, $rowKey); - } elseif (null !== $collectionName) { - $key = array($collectionName, $rowKey); - } - } - } else { - $key = $document[Zend_Cloud_DocumentService_Document::KEY_FIELD]; - unset($document[Zend_Cloud_DocumentService_Document::KEY_FIELD]); - } - - $documentClass = $this->getDocumentClass(); - return new $documentClass($document, $key); - } - - /** - * List all documents in a collection - * - * @param string $collectionName - * @param null|array $options - * @return Zend_Cloud_DocumentService_DocumentSet - */ - public function listDocuments($collectionName, array $options = null) - { - $select = $this->select()->from($collectionName); - return $this->query($collectionName, $select); - } - - /** - * Insert document - * - * @param array|Zend_Cloud_DocumentService_Document $document - * @param array $options - * @return boolean - */ - public function insertDocument($collectionName, $document, $options = null) - { - if (is_array($document)) { - $document = $this->_getDocumentFromArray($document, $collectionName); - } - - if (!$document instanceof Zend_Cloud_DocumentService_Document) { - throw new Zend_Cloud_DocumentService_Exception('Invalid document supplied'); - } - - $key = $this->_validateDocumentId($document->getId(), $collectionName); - $document->setId($key); - - $this->_validateCompositeKey($key); - $this->_validateFields($document); - try { - - $entity = new Zend_Service_WindowsAzure_Storage_DynamicTableEntity($key[0], $key[1]); - $entity->setAzureValues($document->getFields(), true); - $this->_storageClient->insertEntity($collectionName, $entity); - } catch(Zend_Service_WindowsAzure_Exception $e) { - throw new Zend_Cloud_DocumentService_Exception('Error on document insertion: '.$e->getMessage(), $e->getCode(), $e); - } - } - - /** - * Replace document. - * - * The new document replaces the existing document. - * - * @param Zend_Cloud_DocumentService_Document $document - * @param array $options - * @return boolean - */ - public function replaceDocument($collectionName, $document, $options = null) - { - if (is_array($document)) { - $document = $this->_getDocumentFromArray($document, $collectionName); - } - - if (!$document instanceof Zend_Cloud_DocumentService_Document) { - throw new Zend_Cloud_DocumentService_Exception('Invalid document supplied'); - } - - $key = $this->_validateDocumentId($document->getId(), $collectionName); - $this->_validateFields($document); - try { - $entity = new Zend_Service_WindowsAzure_Storage_DynamicTableEntity($key[0], $key[1]); - $entity->setAzureValues($document->getFields(), true); - if (isset($options[self::VERIFY_ETAG])) { - $entity->setEtag($options[self::VERIFY_ETAG]); - } - - $this->_storageClient->updateEntity($collectionName, $entity, isset($options[self::VERIFY_ETAG])); - } catch(Zend_Service_WindowsAzure_Exception $e) { - throw new Zend_Cloud_DocumentService_Exception('Error on document replace: '.$e->getMessage(), $e->getCode(), $e); - } - } - - /** - * Update document. - * - * The new document is merged the existing document. - * - * @param string $collectionName - * @param mixed|Zend_Cloud_DocumentService_Document $documentId Document identifier or document contaiing updates - * @param null|array|Zend_Cloud_DocumentService_Document Fields to update (or new fields)) - * @param array $options - * @return boolean - */ - public function updateDocument($collectionName, $documentId, $fieldset = null, $options = null) - { - if (null === $fieldset && $documentId instanceof Zend_Cloud_DocumentService_Document) { - $fieldset = $documentId->getFields(); - $documentId = $documentId->getId(); - } elseif ($fieldset instanceof Zend_Cloud_DocumentService_Document) { - if ($documentId == null) { - $documentId = $fieldset->getId(); - } - $fieldset = $fieldset->getFields(); - } - - $this->_validateCompositeKey($documentId, $collectionName); - $this->_validateFields($fieldset); - try { - $entity = new Zend_Service_WindowsAzure_Storage_DynamicTableEntity($documentId[0], $documentId[1]); - - // Ensure timestamp is set correctly - if (isset($fieldset[self::TIMESTAMP_KEY])) { - $entity->setTimestamp($fieldset[self::TIMESTAMP_KEY]); - unset($fieldset[self::TIMESTAMP_KEY]); - } - - $entity->setAzureValues($fieldset, true); - if (isset($options[self::VERIFY_ETAG])) { - $entity->setEtag($options[self::VERIFY_ETAG]); - } - - $this->_storageClient->mergeEntity($collectionName, $entity, isset($options[self::VERIFY_ETAG])); - } catch(Zend_Service_WindowsAzure_Exception $e) { - throw new Zend_Cloud_DocumentService_Exception('Error on document update: '.$e->getMessage(), $e->getCode(), $e); - } - } - - /** - * Delete document. - * - * @param mixed $document Document ID or Document object. - * @param array $options - * @return void - */ - public function deleteDocument($collectionName, $documentId, $options = null) - { - if ($documentId instanceof Zend_Cloud_DocumentService_Document) { - $documentId = $documentId->getId(); - } - - $documentId = $this->_validateDocumentId($documentId, $collectionName); - - try { - $entity = new Zend_Service_WindowsAzure_Storage_DynamicTableEntity($documentId[0], $documentId[1]); - if (isset($options[self::VERIFY_ETAG])) { - $entity->setEtag($options[self::VERIFY_ETAG]); - } - $this->_storageClient->deleteEntity($collectionName, $entity, isset($options[self::VERIFY_ETAG])); - } catch(Zend_Service_WindowsAzure_Exception $e) { - if (strpos($e->getMessage(), "does not exist") === false) { - throw new Zend_Cloud_DocumentService_Exception('Error on document deletion: '.$e->getMessage(), $e->getCode(), $e); - } - } - } - - /** - * Fetch single document by ID - * - * @param string $collectionName Collection name - * @param mixed $documentId Document ID, adapter-dependent - * @param array $options - * @return Zend_Cloud_DocumentService_Document - */ - public function fetchDocument($collectionName, $documentId, $options = null) - { - $documentId = $this->_validateDocumentId($documentId, $collectionName); - try { - $entity = $this->_storageClient->retrieveEntityById($collectionName, $documentId[0], $documentId[1]); - $documentClass = $this->getDocumentClass(); - return new $documentClass($this->_resolveAttributes($entity), array($entity->getPartitionKey(), $entity->getRowKey())); - } catch (Zend_Service_WindowsAzure_Exception $e) { - if (strpos($e->getMessage(), "does not exist") !== false) { - return false; - } - throw new Zend_Cloud_DocumentService_Exception('Error on document fetch: '.$e->getMessage(), $e->getCode(), $e); - } - } - - /** - * Query for documents stored in the document service. If a string is passed in - * $query, the query string will be passed directly to the service. - * - * @param string $collectionName Collection name - * @param string|Zend_Cloud_DocumentService_Adapter_WindowsAzure_Query $query - * @param array $options - * @return array Zend_Cloud_DocumentService_DocumentSet - */ - public function query($collectionName, $query, $options = null) - { - try { - if ($query instanceof Zend_Cloud_DocumentService_Adapter_WindowsAzure_Query) { - $entities = $this->_storageClient->retrieveEntities($query->assemble()); - } else { - $entities = $this->_storageClient->retrieveEntities($collectionName, $query); - } - - $documentClass = $this->getDocumentClass(); - $resultSet = array(); - foreach ($entities as $entity) { - $resultSet[] = new $documentClass( - $this->_resolveAttributes($entity), - array($entity->getPartitionKey(), $entity->getRowKey()) - ); - } - } catch(Zend_Service_WindowsAzure_Exception $e) { - throw new Zend_Cloud_DocumentService_Exception('Error on document query: '.$e->getMessage(), $e->getCode(), $e); - } - - $setClass = $this->getDocumentSetClass(); - return new $setClass($resultSet); - } - - /** - * Create query statement - * - * @return Zend_Cloud_DocumentService_Query - */ - public function select($fields = null) - { - $queryClass = $this->getQueryClass(); - if (!class_exists($queryClass)) { - #require_once 'Zend/Loader.php'; - Zend_Loader::loadClass($queryClass); - } - - $query = new $queryClass(); - $defaultClass = self::DEFAULT_QUERY_CLASS; - if (!$query instanceof $defaultClass) { - throw new Zend_Cloud_DocumentService_Exception('Query class must extend ' . self::DEFAULT_QUERY_CLASS); - } - - $query->select($fields); - return $query; - } - - /** - * Get the concrete service client - * - * @return Zend_Service_WindowsAzure_Storage_Table - */ - public function getClient() - { - return $this->_storageClient; - } - - /** - * Resolve table values to attributes - * - * @param Zend_Service_WindowsAzure_Storage_TableEntity $entity - * @return array - */ - protected function _resolveAttributes(Zend_Service_WindowsAzure_Storage_TableEntity $entity) - { - $result = array(); - foreach ($entity->getAzureValues() as $attr) { - $result[$attr->Name] = $attr->Value; - } - return $result; - } - - - /** - * Validate a partition or row key - * - * @param string $key - * @return void - * @throws Zend_Cloud_DocumentService_Exception - */ - protected function _validateKey($key) - { - if (preg_match('@[/#?' . preg_quote('\\') . ']@', $key)) { - throw new Zend_Cloud_DocumentService_Exception('Invalid partition or row key provided; must not contain /, \\, #, or ? characters'); - } - } - - /** - * Validate a composite key - * - * @param array $key - * @return throws Zend_Cloud_DocumentService_Exception - */ - protected function _validateCompositeKey(array $key) - { - if (2 != count($key)) { - throw new Zend_Cloud_DocumentService_Exception('Invalid document key provided; must contain exactly two elements: a PartitionKey and a RowKey'); - } - foreach ($key as $k) { - $this->_validateKey($k); - } - } - - /** - * Validate a document identifier - * - * If the identifier is an array containing a valid partition and row key, - * returns it. If the identifier is a string: - * - if a default partition key is present, it creates an identifier using - * that and the provided document ID - * - if a collection name is provided, it will use that for the partition key - * - otherwise, it's invalid - * - * @param array|string $documentId - * @param null|string $collectionName - * @return array - * @throws Zend_Cloud_DocumentService_Exception - */ - protected function _validateDocumentId($documentId, $collectionName = false) - { - if (is_array($documentId)) { - $this->_validateCompositeKey($documentId); - return $documentId; - } - if (!is_string($documentId)) { - throw new Zend_Cloud_DocumentService_Exception('Invalid document identifier; must be a string or an array'); - } - - $this->_validateKey($documentId); - - if (null !== ($partitionKey = $this->getDefaultPartitionKey())) { - return array($partitionKey, $documentId); - } - if (null !== $collectionName) { - return array($collectionName, $documentId); - } - throw new Zend_Cloud_DocumentService_Exception('Cannot determine partition name; invalid document identifier'); - } - - /** - * Validate a document's fields for well-formedness - * - * Since Azure uses Atom, and fieldnames are included as part of XML - * element tag names, the field names must be valid XML names. - * - * @param Zend_Cloud_DocumentService_Document|array $document - * @return void - * @throws Zend_Cloud_DocumentService_Exception - */ - public function _validateFields($document) - { - if ($document instanceof Zend_Cloud_DocumentService_Document) { - $document = $document->getFields(); - } elseif (!is_array($document)) { - throw new Zend_Cloud_DocumentService_Exception('Cannot inspect fields; invalid type provided'); - } - - foreach (array_keys($document) as $key) { - $this->_validateFieldKey($key); - } - } - - /** - * Validate an individual field name for well-formedness - * - * Since Azure uses Atom, and fieldnames are included as part of XML - * element tag names, the field names must be valid XML names. - * - * While we could potentially normalize names, this could also lead to - * conflict with other field names -- which we should avoid. As such, - * invalid field names will raise an exception. - * - * @param string $key - * @return void - * @throws Zend_Cloud_DocumentService_Exception - */ - public function _validateFieldKey($key) - { - if (!preg_match('/^[_A-Za-z][-._A-Za-z0-9]*$/', $key)) { - throw new Zend_Cloud_DocumentService_Exception('Field keys must conform to XML names (^[_A-Za-z][-._A-Za-z0-9]*$); key "' . $key . '" does not match'); - } - } -} diff --git a/library/Zend/Cloud/DocumentService/Adapter/WindowsAzure/Query.php b/library/Zend/Cloud/DocumentService/Adapter/WindowsAzure/Query.php deleted file mode 100755 index 21eb039da0..0000000000 --- a/library/Zend/Cloud/DocumentService/Adapter/WindowsAzure/Query.php +++ /dev/null @@ -1,171 +0,0 @@ -_azureSelect = $select; - } - - /** - * SELECT clause (fields to be selected) - * - * Does nothing for Azure. - * - * @param string $select - * @return Zend_Cloud_DocumentService_Adapter_WindowsAzure_Query - */ - public function select($select) - { - return $this; - } - - /** - * FROM clause (table name) - * - * @param string $from - * @return Zend_Cloud_DocumentService_Adapter_WindowsAzure_Query - */ - public function from($from) - { - $this->_azureSelect->from($from); - return $this; - } - - /** - * WHERE clause (conditions to be used) - * - * @param string $where - * @param mixed $value Value or array of values to be inserted instead of ? - * @param string $op Operation to use to join where clauses (AND/OR) - * @return Zend_Cloud_DocumentService_Adapter_WindowsAzure_Query - */ - public function where($where, $value = null, $op = 'and') - { - if (!empty($value) && !is_array($value)) { - // fix buglet in Azure - numeric values are quoted unless passed as an array - $value = array($value); - } - $this->_azureSelect->where($where, $value, $op); - return $this; - } - - /** - * WHERE clause for item ID - * - * This one should be used when fetching specific rows since some adapters - * have special syntax for primary keys - * - * @param array $value Row ID for the document (PartitionKey, RowKey) - * @return Zend_Cloud_DocumentService_Adapter_WindowsAzure_Query - */ - public function whereId($value) - { - if (!is_array($value)) { - #require_once 'Zend/Cloud/DocumentService/Exception.php'; - throw new Zend_Cloud_DocumentService_Exception('Invalid document key'); - } - $this->_azureSelect->wherePartitionKey($value[0])->whereRowKey($value[1]); - return $this; - } - - /** - * LIMIT clause (how many rows to return) - * - * @param int $limit - * @return Zend_Cloud_DocumentService_Adapter_WindowsAzure_Query - */ - public function limit($limit) - { - $this->_azureSelect->top($limit); - return $this; - } - - /** - * ORDER BY clause (sorting) - * - * @todo Azure service doesn't seem to support this yet; emulate? - * @param string $sort Column to sort by - * @param string $direction Direction - asc/desc - * @return Zend_Cloud_DocumentService_Adapter_WindowsAzure_Query - * @throws Zend_Cloud_OperationNotAvailableException - */ - public function order($sort, $direction = 'asc') - { - #require_once 'Zend/Cloud/OperationNotAvailableException.php'; - throw new Zend_Cloud_OperationNotAvailableException('No support for sorting for Azure yet'); - } - - /** - * Get Azure select query - * - * @return Zend_Service_WindowsAzure_Storage_TableEntityQuery - */ - public function getAzureSelect() - { - return $this->_azureSelect; - } - - /** - * Assemble query - * - * Simply return the WindowsAzure table entity query object - * - * @return Zend_Service_WindowsAzure_Storage_TableEntityQuery - */ - public function assemble() - { - return $this->getAzureSelect(); - } -} diff --git a/library/Zend/Cloud/DocumentService/Document.php b/library/Zend/Cloud/DocumentService/Document.php deleted file mode 100644 index 46aade2c41..0000000000 --- a/library/Zend/Cloud/DocumentService/Document.php +++ /dev/null @@ -1,248 +0,0 @@ -_fields = $fields; - $this->setId($id); - } - - /** - * Set document identifier - * - * @param mixed $id - * @return Zend_Cloud_DocumentService_Document - */ - public function setId($id) - { - $this->_id = $id; - return $this; - } - - /** - * Get ID name. - * - * @return string - */ - public function getId() - { - return $this->_id; - } - - /** - * Get fields as array. - * - * @return array - */ - public function getFields() - { - return $this->_fields; - } - - /** - * Get field by name. - * - * @param string $name - * @return mixed - */ - public function getField($name) - { - if (isset($this->_fields[$name])) { - return $this->_fields[$name]; - } - return null; - } - - /** - * Set field by name. - * - * @param string $name - * @param mixed $value - * @return Zend_Cloud_DocumentService_Document - */ - public function setField($name, $value) - { - $this->_fields[$name] = $value; - return $this; - } - - /** - * Overloading: get value - * - * @param string $name - * @return mixed - */ - public function __get($name) - { - return $this->getField($name); - } - - /** - * Overloading: set field - * - * @param string $name - * @param mixed $value - * @return void - */ - public function __set($name, $value) - { - $this->setField($name, $value); - } - - /** - * ArrayAccess: does field exist? - * - * @param string $name - * @return bool - */ - public function offsetExists($name) - { - return isset($this->_fields[$name]); - } - - /** - * ArrayAccess: get field by name - * - * @param string $name - * @return mixed - */ - public function offsetGet($name) - { - return $this->getField($name); - } - - /** - * ArrayAccess: set field to value - * - * @param string $name - * @param mixed $value - * @return void - */ - public function offsetSet($name, $value) - { - $this->setField($name, $value); - } - - /** - * ArrayAccess: remove field from document - * - * @param string $name - * @return void - */ - public function offsetUnset($name) - { - if ($this->offsetExists($name)) { - unset($this->_fields[$name]); - } - } - - /** - * Overloading: retrieve and set fields by name - * - * @param string $name - * @param mixed $args - * @return mixed - */ - public function __call($name, $args) - { - $prefix = substr($name, 0, 3); - if ($prefix == 'get') { - // Get value - $option = substr($name, 3); - return $this->getField($option); - } elseif ($prefix == 'set') { - // set value - $option = substr($name, 3); - return $this->setField($option, $args[0]); - } - - #require_once 'Zend/Cloud/OperationNotAvailableException.php'; - throw new Zend_Cloud_OperationNotAvailableException("Unknown operation $name"); - } - - /** - * Countable: return count of fields in document - * - * @return int - */ - public function count() - { - return count($this->_fields); - } - - /** - * IteratorAggregate: return iterator for iterating over fields - * - * @return Iterator - */ - public function getIterator() - { - return new ArrayIterator($this->_fields); - } -} diff --git a/library/Zend/Cloud/DocumentService/DocumentSet.php b/library/Zend/Cloud/DocumentService/DocumentSet.php deleted file mode 100644 index 3c8b541176..0000000000 --- a/library/Zend/Cloud/DocumentService/DocumentSet.php +++ /dev/null @@ -1,68 +0,0 @@ -_documentCount = count($documents); - $this->_documents = new ArrayIterator($documents); - } - - /** - * Countable: number of documents in set - * - * @return int - */ - public function count() - { - return $this->_documentCount; - } - - /** - * IteratorAggregate: retrieve iterator - * - * @return Traversable - */ - public function getIterator() - { - return $this->_documents; - } -} diff --git a/library/Zend/Cloud/DocumentService/Exception.php b/library/Zend/Cloud/DocumentService/Exception.php deleted file mode 100644 index c77c698f18..0000000000 --- a/library/Zend/Cloud/DocumentService/Exception.php +++ /dev/null @@ -1,38 +0,0 @@ -foo('bar') - * but concrete adapters should be able to recognise it - * - * The call will be iterpreted as clause 'foo' with argument 'bar' - * - * @param string $name Clause/method name - * @param mixed $args - * @return Zend_Cloud_DocumentService_Query - */ - public function __call($name, $args) - { - $this->_clauses[] = array(strtolower($name), $args); - return $this; - } - - /** - * SELECT clause (fields to be selected) - * - * @param null|string|array $select - * @return Zend_Cloud_DocumentService_Query - */ - public function select($select) - { - if (empty($select)) { - return $this; - } - if (!is_string($select) && !is_array($select)) { - #require_once 'Zend/Cloud/DocumentService/Exception.php'; - throw new Zend_Cloud_DocumentService_Exception("SELECT argument must be a string or an array of strings"); - } - $this->_clauses[] = array(self::QUERY_SELECT, $select); - return $this; - } - - /** - * FROM clause - * - * @param string $name Field names - * @return Zend_Cloud_DocumentService_Query - */ - public function from($name) - { - if(!is_string($name)) { - #require_once 'Zend/Cloud/DocumentService/Exception.php'; - throw new Zend_Cloud_DocumentService_Exception("FROM argument must be a string"); - } - $this->_clauses[] = array(self::QUERY_FROM, $name); - return $this; - } - - /** - * WHERE query - * - * @param string $cond Condition - * @param array $args Arguments to substitute instead of ?'s in condition - * @param string $op relation to other clauses - and/or - * @return Zend_Cloud_DocumentService_Query - */ - public function where($cond, $value = null, $op = 'and') - { - if (!is_string($cond)) { - #require_once 'Zend/Cloud/DocumentService/Exception.php'; - throw new Zend_Cloud_DocumentService_Exception("WHERE argument must be a string"); - } - $this->_clauses[] = array(self::QUERY_WHERE, array($cond, $value, $op)); - return $this; - } - - /** - * Select record or fields by ID - * - * @param string|int $value Identifier to select by - * @return Zend_Cloud_DocumentService_Query - */ - public function whereId($value) - { - if (!is_scalar($value)) { - #require_once 'Zend/Cloud/DocumentService/Exception.php'; - throw new Zend_Cloud_DocumentService_Exception("WHEREID argument must be a scalar"); - } - $this->_clauses[] = array(self::QUERY_WHEREID, $value); - return $this; - } - - /** - * LIMIT clause (how many items to return) - * - * @param int $limit - * @return Zend_Cloud_DocumentService_Query - */ - public function limit($limit) - { - if ($limit != (int) $limit) { - #require_once 'Zend/Cloud/DocumentService/Exception.php'; - throw new Zend_Cloud_DocumentService_Exception("LIMIT argument must be an integer"); - } - $this->_clauses[] = array(self::QUERY_LIMIT, $limit); - return $this; - } - - /** - * ORDER clause; field or fields to sort by, and direction to sort - * - * @param string|int|array $sort - * @param string $direction - * @return Zend_Cloud_DocumentService_Query - */ - public function order($sort, $direction = 'asc') - { - $this->_clauses[] = array(self::QUERY_ORDER, array($sort, $direction)); - return $this; - } - - /** - * "Assemble" the query - * - * Simply returns the clauses present. - * - * @return array - */ - public function assemble() - { - return $this->getClauses(); - } - - /** - * Return query clauses as an array - * - * @return array Clauses in the query - */ - public function getClauses() - { - return $this->_clauses; - } -} diff --git a/library/Zend/Cloud/DocumentService/QueryAdapter.php b/library/Zend/Cloud/DocumentService/QueryAdapter.php deleted file mode 100644 index b4216c3e39..0000000000 --- a/library/Zend/Cloud/DocumentService/QueryAdapter.php +++ /dev/null @@ -1,102 +0,0 @@ -_clientException = $clientException; - parent::__construct($message, $code, $clientException); - } - - public function getClientException() { - return $this->_getPrevious(); - } -} - diff --git a/library/Zend/Cloud/Infrastructure/Adapter.php b/library/Zend/Cloud/Infrastructure/Adapter.php deleted file mode 100644 index 1192127aa6..0000000000 --- a/library/Zend/Cloud/Infrastructure/Adapter.php +++ /dev/null @@ -1,167 +0,0 @@ -adapterResult; - } - - /** - * Wait for status $status with a timeout of $timeout seconds - * - * @param string $id - * @param string $status - * @param integer $timeout - * @return boolean - */ - public function waitStatusInstance($id, $status, $timeout = self::TIMEOUT_STATUS_CHANGE) - { - if (empty($id) || empty($status)) { - return false; - } - - $num = 0; - while (($num<$timeout) && ($this->statusInstance($id) != $status)) { - sleep(self::TIME_STEP_STATUS_CHANGE); - $num += self::TIME_STEP_STATUS_CHANGE; - } - return ($num < $timeout); - } - - /** - * Run arbitrary shell script on an instance - * - * @param string $id - * @param array $param - * @param string|array $cmd - * @return string|array - */ - public function deployInstance($id, $params, $cmd) - { - if (!function_exists("ssh2_connect")) { - #require_once 'Zend/Cloud/Infrastructure/Exception.php'; - throw new Zend_Cloud_Infrastructure_Exception('Deployment requires the PHP "SSH" extension (ext/ssh2)'); - } - - if (empty($id)) { - #require_once 'Zend/Cloud/Infrastructure/Exception.php'; - throw new Zend_Cloud_Infrastructure_Exception('You must specify the instance where to deploy'); - } - - if (empty($cmd)) { - #require_once 'Zend/Cloud/Infrastructure/Exception.php'; - throw new Zend_Cloud_Infrastructure_Exception('You must specify the shell commands to run on the instance'); - } - - if (empty($params) - || empty($params[Zend_Cloud_Infrastructure_Instance::SSH_USERNAME]) - || (empty($params[Zend_Cloud_Infrastructure_Instance::SSH_PASSWORD]) - && empty($params[Zend_Cloud_Infrastructure_Instance::SSH_KEY])) - ) { - #require_once 'Zend/Cloud/Infrastructure/Exception.php'; - throw new Zend_Cloud_Infrastructure_Exception('You must specify the params for the SSH connection'); - } - - $host = $this->publicDnsInstance($id); - if (empty($host)) { - #require_once 'Zend/Cloud/Infrastructure/Exception.php'; - throw new Zend_Cloud_Infrastructure_Exception(sprintf( - 'The instance identified by "%s" does not exist', - $id - )); - } - - $conn = ssh2_connect($host); - if (!ssh2_auth_password($conn, $params[Zend_Cloud_Infrastructure_Instance::SSH_USERNAME], - $params[Zend_Cloud_Infrastructure_Instance::SSH_PASSWORD])) { - #require_once 'Zend/Cloud/Infrastructure/Exception.php'; - throw new Zend_Cloud_Infrastructure_Exception('SSH authentication failed'); - } - - if (is_array($cmd)) { - $result = array(); - foreach ($cmd as $command) { - $stream = ssh2_exec($conn, $command); - $errorStream = ssh2_fetch_stream($stream, SSH2_STREAM_STDERR); - - stream_set_blocking($errorStream, true); - stream_set_blocking($stream, true); - - $output = stream_get_contents($stream); - $error = stream_get_contents($errorStream); - - if (empty($error)) { - $result[$command] = $output; - } else { - $result[$command] = $error; - } - } - } else { - $stream = ssh2_exec($conn, $cmd); - $result = stream_set_blocking($stream, true); - $errorStream = ssh2_fetch_stream($stream, SSH2_STREAM_STDERR); - - stream_set_blocking($errorStream, true); - stream_set_blocking($stream, true); - - $output = stream_get_contents($stream); - $error = stream_get_contents($errorStream); - - if (empty($error)) { - $result = $output; - } else { - $result = $error; - } - } - return $result; - } -} diff --git a/library/Zend/Cloud/Infrastructure/Adapter/Ec2.php b/library/Zend/Cloud/Infrastructure/Adapter/Ec2.php deleted file mode 100644 index defb5633c7..0000000000 --- a/library/Zend/Cloud/Infrastructure/Adapter/Ec2.php +++ /dev/null @@ -1,496 +0,0 @@ - Zend_Cloud_Infrastructure_Instance::STATUS_RUNNING, - 'terminated' => Zend_Cloud_Infrastructure_Instance::STATUS_TERMINATED, - 'pending' => Zend_Cloud_Infrastructure_Instance::STATUS_PENDING, - 'shutting-down' => Zend_Cloud_Infrastructure_Instance::STATUS_SHUTTING_DOWN, - 'stopping' => Zend_Cloud_Infrastructure_Instance::STATUS_PENDING, - 'stopped' => Zend_Cloud_Infrastructure_Instance::STATUS_STOPPED, - 'rebooting' => Zend_Cloud_Infrastructure_Instance::STATUS_REBOOTING, - ); - - /** - * Map monitor metrics between Infrastructure and EC2 - * - * @var array - */ - protected $mapMetrics= array ( - Zend_Cloud_Infrastructure_Instance::MONITOR_CPU => 'CPUUtilization', - Zend_Cloud_Infrastructure_Instance::MONITOR_DISK_READ => 'DiskReadBytes', - Zend_Cloud_Infrastructure_Instance::MONITOR_DISK_WRITE => 'DiskWriteBytes', - Zend_Cloud_Infrastructure_Instance::MONITOR_NETWORK_IN => 'NetworkIn', - Zend_Cloud_Infrastructure_Instance::MONITOR_NETWORK_OUT => 'NetworkOut', - ); - - /** - * Constructor - * - * @param array|Zend_Config $options - * @return void - */ - public function __construct($options = array()) - { - if (is_object($options)) { - if (method_exists($options, 'toArray')) { - $options= $options->toArray(); - } elseif ($options instanceof Traversable) { - $options = iterator_to_array($options); - } - } - - if (empty($options) || !is_array($options)) { - #require_once 'Zend/Cloud/Infrastructure/Exception.php'; - throw new Zend_Cloud_Infrastructure_Exception('Invalid options provided'); - } - - if (!isset($options[self::AWS_ACCESS_KEY]) - || !isset($options[self::AWS_SECRET_KEY]) - ) { - #require_once 'Zend/Cloud/Infrastructure/Exception.php'; - throw new Zend_Cloud_Infrastructure_Exception('AWS keys not specified!'); - } - - $this->accessKey = $options[self::AWS_ACCESS_KEY]; - $this->accessSecret = $options[self::AWS_SECRET_KEY]; - $this->region = ''; - - if (isset($options[self::AWS_REGION])) { - $this->region= $options[self::AWS_REGION]; - } - - try { - $this->ec2 = new Zend_Service_Amazon_Ec2_Instance($options[self::AWS_ACCESS_KEY], $options[self::AWS_SECRET_KEY], $this->region); - } catch (Exception $e) { - #require_once 'Zend/Cloud/Infrastructure/Exception.php'; - throw new Zend_Cloud_Infrastructure_Exception('Error on create: ' . $e->getMessage(), $e->getCode(), $e); - } - - if (isset($options[self::HTTP_ADAPTER])) { - $this->ec2->getHttpClient()->setAdapter($options[self::HTTP_ADAPTER]); - } - } - - /** - * Convert the attributes of EC2 into attributes of Infrastructure - * - * @param array $attr - * @return array|boolean - */ - private function convertAttributes($attr) - { - $result = array(); - if (!empty($attr) && is_array($attr)) { - $result[Zend_Cloud_Infrastructure_Instance::INSTANCE_ID] = $attr['instanceId']; - $result[Zend_Cloud_Infrastructure_Instance::INSTANCE_STATUS] = $this->mapStatus[$attr['instanceState']['name']]; - $result[Zend_Cloud_Infrastructure_Instance::INSTANCE_IMAGEID] = $attr['imageId']; - $result[Zend_Cloud_Infrastructure_Instance::INSTANCE_ZONE] = $attr['availabilityZone']; - $result[Zend_Cloud_Infrastructure_Instance::INSTANCE_LAUNCHTIME] = $attr['launchTime']; - - switch ($attr['instanceType']) { - case Zend_Service_Amazon_Ec2_Instance::MICRO: - $result[Zend_Cloud_Infrastructure_Instance::INSTANCE_CPU] = '1 virtual core'; - $result[Zend_Cloud_Infrastructure_Instance::INSTANCE_RAM] = '613MB'; - $result[Zend_Cloud_Infrastructure_Instance::INSTANCE_STORAGE] = '0GB'; - break; - case Zend_Service_Amazon_Ec2_Instance::SMALL: - $result[Zend_Cloud_Infrastructure_Instance::INSTANCE_CPU] = '1 virtual core'; - $result[Zend_Cloud_Infrastructure_Instance::INSTANCE_RAM] = '1.7GB'; - $result[Zend_Cloud_Infrastructure_Instance::INSTANCE_STORAGE] = '160GB'; - break; - case Zend_Service_Amazon_Ec2_Instance::LARGE: - $result[Zend_Cloud_Infrastructure_Instance::INSTANCE_CPU] = '2 virtual core'; - $result[Zend_Cloud_Infrastructure_Instance::INSTANCE_RAM] = '7.5GB'; - $result[Zend_Cloud_Infrastructure_Instance::INSTANCE_STORAGE] = '850GB'; - break; - case Zend_Service_Amazon_Ec2_Instance::XLARGE: - $result[Zend_Cloud_Infrastructure_Instance::INSTANCE_CPU] = '4 virtual core'; - $result[Zend_Cloud_Infrastructure_Instance::INSTANCE_RAM] = '15GB'; - $result[Zend_Cloud_Infrastructure_Instance::INSTANCE_STORAGE] = '1690GB'; - break; - case Zend_Service_Amazon_Ec2_Instance::HCPU_MEDIUM: - $result[Zend_Cloud_Infrastructure_Instance::INSTANCE_CPU] = '2 virtual core'; - $result[Zend_Cloud_Infrastructure_Instance::INSTANCE_RAM] = '1.7GB'; - $result[Zend_Cloud_Infrastructure_Instance::INSTANCE_STORAGE] = '350GB'; - break; - case Zend_Service_Amazon_Ec2_Instance::HCPU_XLARGE: - $result[Zend_Cloud_Infrastructure_Instance::INSTANCE_CPU] = '8 virtual core'; - $result[Zend_Cloud_Infrastructure_Instance::INSTANCE_RAM] = '7GB'; - $result[Zend_Cloud_Infrastructure_Instance::INSTANCE_STORAGE] = '1690GB'; - break; - } - } - return $result; - } - - /** - * Return a list of the available instancies - * - * @return Zend_Cloud_Infrastructure_InstanceList - */ - public function listInstances() - { - $this->adapterResult = $this->ec2->describe(); - - $result = array(); - foreach ($this->adapterResult['instances'] as $instance) { - $result[]= $this->convertAttributes($instance); - } - return new Zend_Cloud_Infrastructure_InstanceList($this, $result); - } - - /** - * Return the status of an instance - * - * @param string - * @return string|boolean - */ - public function statusInstance($id) - { - $this->adapterResult = $this->ec2->describe($id); - if (empty($this->adapterResult['instances'])) { - return false; - } - $result = $this->adapterResult['instances'][0]; - return $this->mapStatus[$result['instanceState']['name']]; - } - - /** - * Return the public DNS name of the instance - * - * @param string $id - * @return string|boolean - */ - public function publicDnsInstance($id) - { - $this->adapterResult = $this->ec2->describe($id); - if (empty($this->adapterResult['instances'])) { - return false; - } - $result = $this->adapterResult['instances'][0]; - return $result['dnsName']; - } - - /** - * Reboot an instance - * - * @param string $id - * @return boolean - */ - public function rebootInstance($id) - { - $this->adapterResult= $this->ec2->reboot($id); - return $this->adapterResult; - } - - /** - * Create a new instance - * - * @param string $name - * @param array $options - * @return Instance|boolean - */ - public function createInstance($name, $options) - { - // @todo instance's name management? - $this->adapterResult = $this->ec2->run($options); - if (empty($this->adapterResult['instances'])) { - return false; - } - $this->error= false; - return new Zend_Cloud_Infrastructure_Instance($this, $this->convertAttributes($this->adapterResult['instances'][0])); - } - - /** - * Stop an instance - * - * @param string $id - * @return boolean - */ - public function stopInstance($id) - { - #require_once 'Zend/Cloud/Infrastructure/Exception.php'; - throw new Zend_Cloud_Infrastructure_Exception('The stopInstance method is not implemented in the adapter'); - } - - /** - * Start an instance - * - * @param string $id - * @return boolean - */ - public function startInstance($id) - { - #require_once 'Zend/Cloud/Infrastructure/Exception.php'; - throw new Zend_Cloud_Infrastructure_Exception('The startInstance method is not implemented in the adapter'); - } - - /** - * Destroy an instance - * - * @param string $id - * @return boolean - */ - public function destroyInstance($id) - { - $this->adapterResult = $this->ec2->terminate($id); - return (!empty($this->adapterResult)); - } - - /** - * Return a list of all the available instance images - * - * @return ImageList - */ - public function imagesInstance() - { - if (!isset($this->ec2Image)) { - $this->ec2Image = new Zend_Service_Amazon_Ec2_Image($this->accessKey, $this->accessSecret, $this->region); - } - - $this->adapterResult = $this->ec2Image->describe(); - - $images = array(); - - foreach ($this->adapterResult as $result) { - switch (strtolower($result['platform'])) { - case 'windows' : - $platform = Zend_Cloud_Infrastructure_Image::IMAGE_WINDOWS; - break; - default: - $platform = Zend_Cloud_Infrastructure_Image::IMAGE_LINUX; - break; - } - - $images[]= array ( - Zend_Cloud_Infrastructure_Image::IMAGE_ID => $result['imageId'], - Zend_Cloud_Infrastructure_Image::IMAGE_NAME => '', - Zend_Cloud_Infrastructure_Image::IMAGE_DESCRIPTION => $result['imageLocation'], - Zend_Cloud_Infrastructure_Image::IMAGE_OWNERID => $result['imageOwnerId'], - Zend_Cloud_Infrastructure_Image::IMAGE_ARCHITECTURE => $result['architecture'], - Zend_Cloud_Infrastructure_Image::IMAGE_PLATFORM => $platform, - ); - } - return new Zend_Cloud_Infrastructure_ImageList($images,$this->ec2Image); - } - - /** - * Return all the available zones - * - * @return array - */ - public function zonesInstance() - { - if (!isset($this->ec2Zone)) { - $this->ec2Zone = new Zend_Service_Amazon_Ec2_AvailabilityZones($this->accessKey,$this->accessSecret,$this->region); - } - $this->adapterResult = $this->ec2Zone->describe(); - - $zones = array(); - foreach ($this->adapterResult as $zone) { - if (strtolower($zone['zoneState']) === 'available') { - $zones[] = array ( - Zend_Cloud_Infrastructure_Instance::INSTANCE_ZONE => $zone['zoneName'], - ); - } - } - return $zones; - } - - /** - * Return the system information about the $metric of an instance - * - * @param string $id - * @param string $metric - * @param null|array $options - * @return array - */ - public function monitorInstance($id, $metric, $options = null) - { - if (empty($id) || empty($metric)) { - return false; - } - - if (!in_array($metric,$this->validMetrics)) { - #require_once 'Zend/Cloud/Infrastructure/Exception.php'; - throw new Zend_Cloud_Infrastructure_Exception(sprintf( - 'The metric "%s" is not valid', - $metric - )); - } - - if (!empty($options) && !is_array($options)) { - #require_once 'Zend/Cloud/Infrastructure/Exception.php'; - throw new Zend_Cloud_Infrastructure_Exception('The options must be an array'); - } - - if (!empty($options) - && (empty($options[Zend_Cloud_Infrastructure_Instance::MONITOR_START_TIME]) - || empty($options[Zend_Cloud_Infrastructure_Instance::MONITOR_END_TIME])) - ) { - #require_once 'Zend/Cloud/Infrastructure/Exception.php'; - throw new Zend_Cloud_Infrastructure_Exception(sprintf( - 'The options array must contain: "%s" and "%s"', - $options[Zend_Cloud_Infrastructure_Instance::MONITOR_START_TIME], - $options[Zend_Cloud_Infrastructure_Instance::MONITOR_END_TIME] - )); - } - - if (!isset($this->ec2Monitor)) { - $this->ec2Monitor = new Zend_Service_Amazon_Ec2_CloudWatch($this->accessKey, $this->accessSecret, $this->region); - } - - $param = array( - 'MeasureName' => $this->mapMetrics[$metric], - 'Statistics' => array('Average'), - 'Dimensions' => array('InstanceId' => $id), - ); - - if (!empty($options)) { - $param['StartTime'] = $options[Zend_Cloud_Infrastructure_Instance::MONITOR_START_TIME]; - $param['EndTime'] = $options[Zend_Cloud_Infrastructure_Instance::MONITOR_END_TIME]; - } - - $this->adapterResult = $this->ec2Monitor->getMetricStatistics($param); - - $monitor = array(); - $num = 0; - $average = 0; - - if (!empty($this->adapterResult['datapoints'])) { - foreach ($this->adapterResult['datapoints'] as $result) { - $monitor['series'][] = array ( - 'timestamp' => $result['Timestamp'], - 'value' => $result['Average'], - ); - $average += $result['Average']; - $num++; - } - } - - if ($num > 0) { - $monitor['average'] = $average / $num; - } - - return $monitor; - } - - /** - * Get the adapter - * - * @return Zend_Service_Amazon_Ec2_Instance - */ - public function getAdapter() - { - return $this->ec2; - } - - /** - * Get last HTTP request - * - * @return string - */ - public function getLastHttpRequest() - { - return $this->ec2->getHttpClient()->getLastRequest(); - } - - /** - * Get the last HTTP response - * - * @return Zend_Http_Response - */ - public function getLastHttpResponse() - { - return $this->ec2->getHttpClient()->getLastResponse(); - } -} diff --git a/library/Zend/Cloud/Infrastructure/Adapter/Rackspace.php b/library/Zend/Cloud/Infrastructure/Adapter/Rackspace.php deleted file mode 100644 index c23f627e76..0000000000 --- a/library/Zend/Cloud/Infrastructure/Adapter/Rackspace.php +++ /dev/null @@ -1,483 +0,0 @@ - Zend_Cloud_Infrastructure_Instance::STATUS_RUNNING, - 'SUSPENDED' => Zend_Cloud_Infrastructure_Instance::STATUS_STOPPED, - 'BUILD' => Zend_Cloud_Infrastructure_Instance::STATUS_REBUILD, - 'REBUILD' => Zend_Cloud_Infrastructure_Instance::STATUS_REBUILD, - 'QUEUE_RESIZE' => Zend_Cloud_Infrastructure_Instance::STATUS_PENDING, - 'PREP_RESIZE' => Zend_Cloud_Infrastructure_Instance::STATUS_PENDING, - 'RESIZE' => Zend_Cloud_Infrastructure_Instance::STATUS_REBUILD, - 'VERIFY_RESIZE' => Zend_Cloud_Infrastructure_Instance::STATUS_REBUILD, - 'PASSWORD' => Zend_Cloud_Infrastructure_Instance::STATUS_PENDING, - 'RESCUE' => Zend_Cloud_Infrastructure_Instance::STATUS_PENDING, - 'REBOOT' => Zend_Cloud_Infrastructure_Instance::STATUS_REBOOTING, - 'HARD_REBOOT' => Zend_Cloud_Infrastructure_Instance::STATUS_REBOOTING, - 'SHARE_IP' => Zend_Cloud_Infrastructure_Instance::STATUS_PENDING, - 'SHARE_IP_NO_CONFIG' => Zend_Cloud_Infrastructure_Instance::STATUS_PENDING, - 'DELETE_IP' => Zend_Cloud_Infrastructure_Instance::STATUS_PENDING, - 'UNKNOWN' => Zend_Cloud_Infrastructure_Instance::STATUS_PENDING - ); - /** - * Constructor - * - * @param array|Zend_Config $options - * @return void - */ - public function __construct($options = array()) - { - if (is_object($options)) { - if (method_exists($options, 'toArray')) { - $options= $options->toArray(); - } elseif ($options instanceof Traversable) { - $options = iterator_to_array($options); - } - } - - if (empty($options) || !is_array($options)) { - #require_once 'Zend/Cloud/Infrastructure/Exception.php'; - throw new Zend_Cloud_Infrastructure_Exception('Invalid options provided'); - } - - if (!isset($options[self::RACKSPACE_USER])) { - #require_once 'Zend/Cloud/Infrastructure/Exception.php'; - throw new Zend_Cloud_Infrastructure_Exception('Rackspace access user not specified!'); - } - - if (!isset($options[self::RACKSPACE_KEY])) { - #require_once 'Zend/Cloud/Infrastructure/Exception.php'; - throw new Zend_Cloud_Infrastructure_Exception('Rackspace access key not specified!'); - } - - $this->accessUser = $options[self::RACKSPACE_USER]; - $this->accessKey = $options[self::RACKSPACE_KEY]; - - if (isset($options[self::RACKSPACE_REGION])) { - switch ($options[self::RACKSPACE_REGION]) { - case self::RACKSPACE_ZONE_UK: - $this->region= Zend_Service_Rackspace_Servers::UK_AUTH_URL; - break; - case self::RACKSPACE_ZONE_USA: - $this->region = Zend_Service_Rackspace_Servers::US_AUTH_URL; - break; - default: - #require_once 'Zend/Cloud/Infrastructure/Exception.php'; - throw new Zend_Cloud_Infrastructure_Exception('The region is not valid'); - } - } else { - $this->region = Zend_Service_Rackspace_Servers::US_AUTH_URL; - } - - try { - $this->rackspace = new Zend_Service_Rackspace_Servers($this->accessUser,$this->accessKey, $this->region); - } catch (Exception $e) { - #require_once 'Zend/Cloud/Infrastructure/Exception.php'; - throw new Zend_Cloud_Infrastructure_Exception('Error on create: ' . $e->getMessage(), $e->getCode(), $e); - } - - if (isset($options[self::HTTP_ADAPTER])) { - $this->rackspace->getHttpClient()->setAdapter($options[self::HTTP_ADAPTER]); - } - - } - /** - * Convert the attributes of Rackspace server into attributes of Infrastructure - * - * @param array $attr - * @return array|boolean - */ - protected function convertAttributes($attr) - { - $result = array(); - if (!empty($attr) && is_array($attr)) { - $result[Zend_Cloud_Infrastructure_Instance::INSTANCE_ID] = $attr['id']; - $result[Zend_Cloud_Infrastructure_Instance::INSTANCE_NAME] = $attr['name']; - $result[Zend_Cloud_Infrastructure_Instance::INSTANCE_STATUS] = $this->mapStatus[$attr['status']]; - $result[Zend_Cloud_Infrastructure_Instance::INSTANCE_IMAGEID] = $attr['imageId']; - if ($this->region==Zend_Service_Rackspace_Servers::US_AUTH_URL) { - $result[Zend_Cloud_Infrastructure_Instance::INSTANCE_ZONE] = self::RACKSPACE_ZONE_USA; - } else { - $result[Zend_Cloud_Infrastructure_Instance::INSTANCE_ZONE] = self::RACKSPACE_ZONE_UK; - } - $result[Zend_Cloud_Infrastructure_Instance::INSTANCE_RAM] = $this->flavors[$attr['flavorId']]['ram']; - $result[Zend_Cloud_Infrastructure_Instance::INSTANCE_STORAGE] = $this->flavors[$attr['flavorId']]['disk']; - } - return $result; - } - /** - * Return a list of the available instancies - * - * @return InstanceList|boolean - */ - public function listInstances() - { - $this->adapterResult = $this->rackspace->listServers(true); - if ($this->adapterResult===false) { - return false; - } - $array= $this->adapterResult->toArray(); - $result = array(); - foreach ($array as $instance) { - $result[]= $this->convertAttributes($instance); - } - return new Zend_Cloud_Infrastructure_InstanceList($this, $result); - } - /** - * Return the status of an instance - * - * @param string - * @return string|boolean - */ - public function statusInstance($id) - { - $this->adapterResult = $this->rackspace->getServer($id); - if ($this->adapterResult===false) { - return false; - } - $array= $this->adapterResult->toArray(); - return $this->mapStatus[$array['status']]; - } - /** - * Return the public DNS name/Ip address of the instance - * - * @param string $id - * @return string|boolean - */ - public function publicDnsInstance($id) - { - $this->adapterResult = $this->rackspace->getServerPublicIp($id); - if (empty($this->adapterResult)) { - return false; - } - return $this->adapterResult[0]; - } - /** - * Reboot an instance - * - * @param string $id - * @return boolean - */ - public function rebootInstance($id) - { - return $this->rackspace->rebootServer($id,true); - } - /** - * Create a new instance - * - * @param string $name - * @param array $options - * @return Instance|boolean - */ - public function createInstance($name, $options) - { - if (empty($name)) { - #require_once 'Zend/Cloud/Infrastructure/Exception.php'; - throw new Zend_Cloud_Infrastructure_Exception('You must specify the name of the instance'); - } - if (empty($options) || !is_array($options)) { - #require_once 'Zend/Cloud/Infrastructure/Exception.php'; - throw new Zend_Cloud_Infrastructure_Exception('The options must be an array'); - } - // @todo create an generic abstract definition for an instance? - $metadata= array(); - if (isset($options['metadata'])) { - $metadata= $options['metadata']; - unset($options['metadata']); - } - $files= array(); - if (isset($options['files'])) { - $files= $options['files']; - unset($options['files']); - } - $options['name']= $name; - $this->adapterResult = $this->rackspace->createServer($options,$metadata,$files); - if ($this->adapterResult===false) { - return false; - } - return new Zend_Cloud_Infrastructure_Instance($this, $this->convertAttributes($this->adapterResult->toArray())); - } - /** - * Stop an instance - * - * @param string $id - * @return boolean - */ - public function stopInstance($id) - { - #require_once 'Zend/Cloud/Infrastructure/Exception.php'; - throw new Zend_Cloud_Infrastructure_Exception('The stopInstance method is not implemented in the adapter'); - } - - /** - * Start an instance - * - * @param string $id - * @return boolean - */ - public function startInstance($id) - { - #require_once 'Zend/Cloud/Infrastructure/Exception.php'; - throw new Zend_Cloud_Infrastructure_Exception('The startInstance method is not implemented in the adapter'); - } - - /** - * Destroy an instance - * - * @param string $id - * @return boolean - */ - public function destroyInstance($id) - { - $this->adapterResult= $this->rackspace->deleteServer($id); - return $this->adapterResult; - } - /** - * Return a list of all the available instance images - * - * @return ImageList|boolean - */ - public function imagesInstance() - { - $this->adapterResult = $this->rackspace->listImages(true); - if ($this->adapterResult===false) { - return false; - } - - $images= $this->adapterResult->toArray(); - $result= array(); - - foreach ($images as $image) { - if (strtolower($image['status'])==='active') { - if (strpos($image['name'],'Windows')!==false) { - $platform = Zend_Cloud_Infrastructure_Image::IMAGE_WINDOWS; - } else { - $platform = Zend_Cloud_Infrastructure_Image::IMAGE_LINUX; - } - if (strpos($image['name'],'x64')!==false) { - $arch = Zend_Cloud_Infrastructure_Image::ARCH_64BIT; - } else { - $arch = Zend_Cloud_Infrastructure_Image::ARCH_32BIT; - } - $result[]= array ( - Zend_Cloud_Infrastructure_Image::IMAGE_ID => $image['id'], - Zend_Cloud_Infrastructure_Image::IMAGE_NAME => $image['name'], - Zend_Cloud_Infrastructure_Image::IMAGE_DESCRIPTION => $image['name'], - Zend_Cloud_Infrastructure_Image::IMAGE_ARCHITECTURE => $arch, - Zend_Cloud_Infrastructure_Image::IMAGE_PLATFORM => $platform, - ); - } - } - return new Zend_Cloud_Infrastructure_ImageList($result,$this->adapterResult); - } - /** - * Return all the available zones - * - * @return array - */ - public function zonesInstance() - { - return array(self::RACKSPACE_ZONE_USA,self::RACKSPACE_ZONE_UK); - } - /** - * Return the system information about the $metric of an instance - * NOTE: it works only for Linux servers - * - * @param string $id - * @param string $metric - * @param null|array $options - * @return array|boolean - */ - public function monitorInstance($id, $metric, $options = null) - { - if (!function_exists("ssh2_connect")) { - #require_once 'Zend/Cloud/Infrastructure/Exception.php'; - throw new Zend_Cloud_Infrastructure_Exception('Monitor requires the PHP "SSH" extension (ext/ssh2)'); - } - if (empty($id)) { - #require_once 'Zend/Cloud/Infrastructure/Exception.php'; - throw new Zend_Cloud_Infrastructure_Exception('You must specify the id of the instance to monitor'); - } - if (empty($metric)) { - #require_once 'Zend/Cloud/Infrastructure/Exception.php'; - throw new Zend_Cloud_Infrastructure_Exception('You must specify the metric to monitor'); - } - if (!in_array($metric,$this->validMetrics)) { - #require_once 'Zend/Cloud/Infrastructure/Exception.php'; - throw new Zend_Cloud_Infrastructure_Exception(sprintf('The metric "%s" is not valid', $metric)); - } - if (!empty($options) && !is_array($options)) { - #require_once 'Zend/Cloud/Infrastructure/Exception.php'; - throw new Zend_Cloud_Infrastructure_Exception('The options must be an array'); - } - - switch ($metric) { - case Zend_Cloud_Infrastructure_Instance::MONITOR_CPU: - $cmd= 'top -b -n '.self::MONITOR_CPU_SAMPLES.' | grep \'Cpu\''; - break; - case Zend_Cloud_Infrastructure_Instance::MONITOR_RAM: - $cmd= 'top -b -n 1 | grep \'Mem\''; - break; - case Zend_Cloud_Infrastructure_Instance::MONITOR_DISK: - $cmd= 'df --total | grep total'; - break; - } - if (empty($cmd)) { - #require_once 'Zend/Cloud/Infrastructure/Exception.php'; - throw new Zend_Cloud_Infrastructure_Exception('The metric specified is not supported by the adapter'); - } - - $params= array( - Zend_Cloud_Infrastructure_Instance::SSH_USERNAME => $options['username'], - Zend_Cloud_Infrastructure_Instance::SSH_PASSWORD => $options['password'] - ); - $exec_time= time(); - $result= $this->deployInstance($id,$params,$cmd); - - if (empty($result)) { - return false; - } - - $monitor = array(); - $num = 0; - $average = 0; - - $outputs= explode("\n",$result); - foreach ($outputs as $output) { - if (!empty($output)) { - switch ($metric) { - case Zend_Cloud_Infrastructure_Instance::MONITOR_CPU: - if (preg_match('/(\d+\.\d)%us/', $output,$match)) { - $usage = (float) $match[1]; - } - break; - case Zend_Cloud_Infrastructure_Instance::MONITOR_RAM: - if (preg_match('/(\d+)k total/', $output,$match)) { - $total = (integer) $match[1]; - } - if (preg_match('/(\d+)k used/', $output,$match)) { - $used = (integer) $match[1]; - } - if ($total>0) { - $usage= (float) $used/$total; - } - break; - case Zend_Cloud_Infrastructure_Instance::MONITOR_DISK: - if (preg_match('/(\d+)%/', $output,$match)) { - $usage = (float) $match[1]; - } - break; - } - - $monitor['series'][] = array ( - 'timestamp' => $exec_time, - 'value' => number_format($usage,2).'%' - ); - - $average += $usage; - $exec_time+= 60; // seconds - $num++; - } - } - - if ($num>0) { - $monitor['average'] = number_format($average/$num,2).'%'; - } - return $monitor; - } - /** - * Get the adapter - * - * @return Zend_Service_Rackspace_Servers - */ - public function getAdapter() - { - return $this->rackspace; - } - /** - * Get last HTTP request - * - * @return string - */ - public function getLastHttpRequest() - { - return $this->rackspace->getHttpClient()->getLastRequest(); - } - /** - * Get the last HTTP response - * - * @return Zend_Http_Response - */ - public function getLastHttpResponse() - { - return $this->rackspace->getHttpClient()->getLastResponse(); - } -} diff --git a/library/Zend/Cloud/Infrastructure/Exception.php b/library/Zend/Cloud/Infrastructure/Exception.php deleted file mode 100644 index 0f1a070049..0000000000 --- a/library/Zend/Cloud/Infrastructure/Exception.php +++ /dev/null @@ -1,25 +0,0 @@ -toArray(); - } elseif ($data instanceof Traversable) { - $data = iterator_to_array($data); - } - } - - if (empty($data) || !is_array($data)) { - #require_once 'Zend/Cloud/Infrastructure/Exception.php'; - throw new Zend_Cloud_Infrastructure_Exception('You must pass an array of parameters'); - } - - foreach ($this->attributeRequired as $key) { - if (empty($data[$key])) { - #require_once 'Zend/Cloud/Infrastructure/Exception.php'; - throw new Zend_Cloud_Infrastructure_Exception(sprintf( - 'The param "%s" is a required parameter for class %s', - $key, - __CLASS__ - )); - } - } - - $this->attributes = $data; - $this->adapter = $adapter; - } - - /** - * Get Attribute with a specific key - * - * @param array $data - * @return misc|boolean - */ - public function getAttribute($key) - { - if (!empty($this->attributes[$key])) { - return $this->attributes[$key]; - } - return false; - } - - /** - * Get all the attributes - * - * @return array - */ - public function getAttributes() - { - return $this->attributes; - } - - /** - * Get the image ID - * - * @return string - */ - public function getId() - { - return $this->attributes[self::IMAGE_ID]; - } - - /** - * Get the Owner ID - * - * @return string - */ - public function getOwnerId() - { - return $this->attributes[self::IMAGE_OWNERID]; - } - - /** - * Get the name - * - * @return string - */ - public function getName() - { - return $this->attributes[self::IMAGE_NAME]; - } - - /** - * Get the description - * - * @return string - */ - public function getDescription() - { - return $this->attributes[self::IMAGE_DESCRIPTION]; - } - - /** - * Get the platform - * - * @return string - */ - public function getPlatform() - { - return $this->attributes[self::IMAGE_PLATFORM]; - } - - /** - * Get the architecture - * - * @return string - */ - public function getArchitecture() - { - return $this->attributes[self::IMAGE_ARCHITECTURE]; - } -} diff --git a/library/Zend/Cloud/Infrastructure/ImageList.php b/library/Zend/Cloud/Infrastructure/ImageList.php deleted file mode 100644 index 7fea82495e..0000000000 --- a/library/Zend/Cloud/Infrastructure/ImageList.php +++ /dev/null @@ -1,218 +0,0 @@ -adapter = $adapter; - $this->constructFromArray($images); - } - - /** - * Transforms the Array to array of Instances - * - * @param array $list - * @return void - */ - protected function constructFromArray(array $list) - { - foreach ($list as $image) { - $this->addImage(new Zend_Cloud_Infrastructure_Image($image, $this->adapter)); - } - } - - /** - * Add an image - * - * @param Image - * @return ImageList - */ - protected function addImage(Zend_Cloud_Infrastructure_Image $image) - { - $this->images[] = $image; - return $this; - } - - /** - * Return number of images - * - * Implement Countable::count() - * - * @return int - */ - public function count() - { - return count($this->images); - } - - /** - * Return the current element - * - * Implement Iterator::current() - * - * @return Image - */ - public function current() - { - return $this->images[$this->iteratorKey]; - } - - /** - * Return the key of the current element - * - * Implement Iterator::key() - * - * @return int - */ - public function key() - { - return $this->iteratorKey; - } - - /** - * Move forward to next element - * - * Implement Iterator::next() - * - * @return void - */ - public function next() - { - $this->iteratorKey++; - } - - /** - * Rewind the Iterator to the first element - * - * Implement Iterator::rewind() - * - * @return void - */ - public function rewind() - { - $this->iteratorKey = 0; - } - - /** - * Check if there is a current element after calls to rewind() or next() - * - * Implement Iterator::valid() - * - * @return bool - */ - public function valid() - { - $numItems = $this->count(); - if ($numItems > 0 && $this->iteratorKey < $numItems) { - return true; - } - return false; - } - - /** - * Whether the offset exists - * - * Implement ArrayAccess::offsetExists() - * - * @param int $offset - * @return bool - */ - public function offsetExists($offset) - { - return ($offset < $this->count()); - } - - /** - * Return value at given offset - * - * Implement ArrayAccess::offsetGet() - * - * @param int $offset - * @throws Zend_Cloud_Infrastructure_Exception - * @return Image - */ - public function offsetGet($offset) - { - if (!$this->offsetExists($offset)) { - #require_once 'Zend/Cloud/Infrastructure/Exception.php'; - throw new Zend_Cloud_Infrastructure_Exception('Illegal index'); - } - return $this->images[$offset]; - } - - /** - * Throws exception because all values are read-only - * - * Implement ArrayAccess::offsetSet() - * - * @param int $offset - * @param string $value - * @throws Zend_Cloud_Infrastructure_Exception - */ - public function offsetSet($offset, $value) - { - #require_once 'Zend/Cloud/Infrastructure/Exception.php'; - throw new Zend_Cloud_Infrastructure_Exception('You are trying to set read-only property'); - } - - /** - * Throws exception because all values are read-only - * - * Implement ArrayAccess::offsetUnset() - * - * @param int $offset - * @throws Zend_Cloud_Infrastructure_Exception - */ - public function offsetUnset($offset) - { - #require_once 'Zend/Cloud/Infrastructure/Exception.php'; - throw new Zend_Cloud_Infrastructure_Exception('You are trying to unset read-only property'); - } -} diff --git a/library/Zend/Cloud/Infrastructure/Instance.php b/library/Zend/Cloud/Infrastructure/Instance.php deleted file mode 100644 index 77f7064869..0000000000 --- a/library/Zend/Cloud/Infrastructure/Instance.php +++ /dev/null @@ -1,320 +0,0 @@ -toArray(); - } elseif ($data instanceof Traversable) { - $data = iterator_to_array($data); - } - } - - if (empty($data) || !is_array($data)) { - #require_once 'Zend/Cloud/Infrastructure/Exception.php'; - throw new Zend_Cloud_Infrastructure_Exception("You must pass an array of parameters"); - } - - foreach ($this->attributeRequired as $key) { - if (empty($data[$key])) { - #require_once 'Zend/Cloud/Infrastructure/Exception.php'; - throw new Zend_Cloud_Infrastructure_Exception(sprintf( - 'The param "%s" is a required param for %s', - $key, - __CLASS__ - )); - } - } - - $this->adapter = $adapter; - $this->attributes = $data; - } - - /** - * Get Attribute with a specific key - * - * @param array $data - * @return misc|false - */ - public function getAttribute($key) - { - if (!empty($this->attributes[$key])) { - return $this->attributes[$key]; - } - return false; - } - - /** - * Get all the attributes - * - * @return array - */ - public function getAttributes() - { - return $this->attributes; - } - - /** - * Get the instance's id - * - * @return string - */ - public function getId() - { - return $this->attributes[self::INSTANCE_ID]; - } - - /** - * Get the instance's image id - * - * @return string - */ - public function getImageId() - { - return $this->attributes[self::INSTANCE_IMAGEID]; - } - - /** - * Get the instance's name - * - * @return string - */ - public function getName() - { - return $this->attributes[self::INSTANCE_NAME]; - } - - /** - * Get the status of the instance - * - * @return string|boolean - */ - public function getStatus() - { - return $this->adapter->statusInstance($this->attributes[self::INSTANCE_ID]); - } - - /** - * Wait for status $status with a timeout of $timeout seconds - * - * @param string $status - * @param integer $timeout - * @return boolean - */ - public function waitStatus($status, $timeout = Adapter::TIMEOUT_STATUS_CHANGE) - { - return $this->adapter->waitStatusInstance($this->attributes[self::INSTANCE_ID], $status, $timeout); - } - - /** - * Get the public DNS of the instance - * - * @return string - */ - public function getPublicDns() - { - if (!isset($this->attributes[self::INSTANCE_PUBLICDNS])) { - $this->attributes[self::INSTANCE_PUBLICDNS] = $this->adapter->publicDnsInstance($this->attributes[self::INSTANCE_ID]); - } - return $this->attributes[self::INSTANCE_PUBLICDNS]; - } - - /** - * Get the instance's CPU - * - * @return string - */ - public function getCpu() - { - return $this->attributes[self::INSTANCE_CPU]; - } - - /** - * Get the instance's RAM size - * - * @return string - */ - public function getRamSize() - { - return $this->attributes[self::INSTANCE_RAM]; - } - - /** - * Get the instance's storage size - * - * @return string - */ - public function getStorageSize() - { - return $this->attributes[self::INSTANCE_STORAGE]; - } - - /** - * Get the instance's zone - * - * @return string - */ - public function getZone() - { - return $this->attributes[self::INSTANCE_ZONE]; - } - - /** - * Get the instance's launch time - * - * @return string - */ - public function getLaunchTime() - { - return $this->attributes[self::INSTANCE_LAUNCHTIME]; - } - - /** - * Reboot the instance - * - * @return boolean - */ - public function reboot() - { - return $this->adapter->rebootInstance($this->attributes[self::INSTANCE_ID]); - } - - /** - * Stop the instance - * - * @return boolean - */ - public function stop() - { - return $this->adapter->stopInstance($this->attributes[self::INSTANCE_ID]); - } - - /** - * Start the instance - * - * @return boolean - */ - public function start() - { - return $this->adapter->startInstance($this->attributes[self::INSTANCE_ID]); - } - - /** - * Destroy the instance - * - * @return boolean - */ - public function destroy() - { - return $this->adapter->destroyInstance($this->attributes[self::INSTANCE_ID]); - } - - /** - * Return the system informations about the $metric of an instance - * - * @param string $metric - * @param null|array $options - * @return array|boolean - */ - public function monitor($metric, $options = null) - { - return $this->adapter->monitorInstance($this->attributes[self::INSTANCE_ID], $metric, $options); - } - - /** - * Run arbitrary shell script on the instance - * - * @param array $param - * @param string|array $cmd - * @return string|array - */ - public function deploy($params, $cmd) - { - return $this->adapter->deployInstance($this->attributes[self::INSTANCE_ID], $params, $cmd); - } -} diff --git a/library/Zend/Cloud/Infrastructure/InstanceList.php b/library/Zend/Cloud/Infrastructure/InstanceList.php deleted file mode 100644 index 46fe895da3..0000000000 --- a/library/Zend/Cloud/Infrastructure/InstanceList.php +++ /dev/null @@ -1,219 +0,0 @@ -adapter = $adapter; - $this->constructFromArray($instances); - } - - /** - * Transforms the Array to array of Instances - * - * @param array $list - * @return void - */ - protected function constructFromArray(array $list) - { - foreach ($list as $instance) { - $this->addInstance(new Zend_Cloud_Infrastructure_Instance($this->adapter,$instance)); - } - } - - /** - * Add an instance - * - * @param Instance - * @return InstanceList - */ - protected function addInstance(Zend_Cloud_Infrastructure_Instance $instance) - { - $this->instances[] = $instance; - return $this; - } - - /** - * Return number of instances - * - * Implement Countable::count() - * - * @return int - */ - public function count() - { - return count($this->instances); - } - - /** - * Return the current element - * - * Implement Iterator::current() - * - * @return Instance - */ - public function current() - { - return $this->instances[$this->iteratorKey]; - } - - /** - * Return the key of the current element - * - * Implement Iterator::key() - * - * @return int - */ - public function key() - { - return $this->iteratorKey; - } - - /** - * Move forward to next element - * - * Implement Iterator::next() - * - * @return void - */ - public function next() - { - $this->iteratorKey++; - } - - /** - * Rewind the Iterator to the first element - * - * Implement Iterator::rewind() - * - * @return void - */ - public function rewind() - { - $this->iteratorKey = 0; - } - - /** - * Check if there is a current element after calls to rewind() or next() - * - * Implement Iterator::valid() - * - * @return bool - */ - public function valid() - { - $numItems = $this->count(); - if ($numItems > 0 && $this->iteratorKey < $numItems) { - return true; - } - return false; - } - - /** - * Whether the offset exists - * - * Implement ArrayAccess::offsetExists() - * - * @param int $offset - * @return bool - */ - public function offsetExists($offset) - { - return ($offset < $this->count()); - } - - /** - * Return value at given offset - * - * Implement ArrayAccess::offsetGet() - * - * @param int $offset - * @return Instance - * @throws Zend_Cloud_Infrastructure_Exception - */ - public function offsetGet($offset) - { - if (!$this->offsetExists($offset)) { - #require_once 'Zend/Cloud/Infrastructure/Exception.php'; - throw new Zend_Cloud_Infrastructure_Exception('Illegal index'); - } - return $this->instances[$offset]; - } - - /** - * Throws exception because all values are read-only - * - * Implement ArrayAccess::offsetSet() - * - * @param int $offset - * @param string $value - * @throws Zend_Cloud_Infrastructure_Exception - */ - public function offsetSet($offset, $value) - { - #require_once 'Zend/Cloud/Infrastructure/Exception.php'; - throw new Zend_Cloud_Infrastructure_Exception('You are trying to set read-only property'); - } - - /** - * Throws exception because all values are read-only - * - * Implement ArrayAccess::offsetUnset() - * - * @param int $offset - * @throws Zend_Cloud_Infrastructure_Exception - */ - public function offsetUnset($offset) - { - #require_once 'Zend/Cloud/Infrastructure/Exception.php'; - throw new Zend_Cloud_Infrastructure_Exception('You are trying to unset read-only property'); - } -} diff --git a/library/Zend/Cloud/OperationNotAvailableException.php b/library/Zend/Cloud/OperationNotAvailableException.php deleted file mode 100644 index b447b0d859..0000000000 --- a/library/Zend/Cloud/OperationNotAvailableException.php +++ /dev/null @@ -1,34 +0,0 @@ -_messageClass = (string) $class; - return $this; - } - - /** - * Get class to use for message objects - * - * @return string - */ - public function getMessageClass() - { - return $this->_messageClass; - } - - /** - * Set class to use for message collection objects - * - * @param string $class - * @return Zend_Cloud_QueueService_Adapter_AbstractAdapter - */ - public function setMessageSetClass($class) - { - $this->_messageSetClass = (string) $class; - return $this; - } - - /** - * Get class to use for message collection objects - * - * @return string - */ - public function getMessageSetClass() - { - return $this->_messageSetClass; - } -} diff --git a/library/Zend/Cloud/QueueService/Adapter/Sqs.php b/library/Zend/Cloud/QueueService/Adapter/Sqs.php deleted file mode 100644 index 4457c49762..0000000000 --- a/library/Zend/Cloud/QueueService/Adapter/Sqs.php +++ /dev/null @@ -1,278 +0,0 @@ -toArray(); - } - - if (!is_array($options)) { - throw new Zend_Cloud_QueueService_Exception('Invalid options provided'); - } - - if (isset($options[self::MESSAGE_CLASS])) { - $this->setMessageClass($options[self::MESSAGE_CLASS]); - } - - if (isset($options[self::MESSAGESET_CLASS])) { - $this->setMessageSetClass($options[self::MESSAGESET_CLASS]); - } - - try { - $this->_sqs = new Zend_Service_Amazon_Sqs( - $options[self::AWS_ACCESS_KEY], $options[self::AWS_SECRET_KEY] - ); - } catch(Zend_Service_Amazon_Exception $e) { - throw new Zend_Cloud_QueueService_Exception('Error on create: '.$e->getMessage(), $e->getCode(), $e); - } - - if(isset($options[self::HTTP_ADAPTER])) { - $this->_sqs->getHttpClient()->setAdapter($options[self::HTTP_ADAPTER]); - } - } - - /** - * Create a queue. Returns the ID of the created queue (typically the URL). - * It may take some time to create the queue. Check your vendor's - * documentation for details. - * - * @param string $name - * @param array $options - * @return string Queue ID (typically URL) - */ - public function createQueue($name, $options = null) - { - try { - return $this->_sqs->create($name, $options[self::CREATE_TIMEOUT]); - } catch(Zend_Service_Amazon_Exception $e) { - throw new Zend_Cloud_QueueService_Exception('Error on queue creation: '.$e->getMessage(), $e->getCode(), $e); - } - } - - /** - * Delete a queue. All messages in the queue will also be deleted. - * - * @param string $queueId - * @param array $options - * @return boolean true if successful, false otherwise - */ - public function deleteQueue($queueId, $options = null) -{ - try { - return $this->_sqs->delete($queueId); - } catch(Zend_Service_Amazon_Exception $e) { - throw new Zend_Cloud_QueueService_Exception('Error on queue deletion: '.$e->getMessage(), $e->getCode(), $e); - } - } - - /** - * List all queues. - * - * @param array $options - * @return array Queue IDs - */ - public function listQueues($options = null) - { - try { - return $this->_sqs->getQueues(); - } catch(Zend_Service_Amazon_Exception $e) { - throw new Zend_Cloud_QueueService_Exception('Error on listing queues: '.$e->getMessage(), $e->getCode(), $e); - } - } - - /** - * Get a key/value array of metadata for the given queue. - * - * @param string $queueId - * @param array $options - * @return array - */ - public function fetchQueueMetadata($queueId, $options = null) - { - try { - // TODO: ZF-9050 Fix the SQS client library in trunk to return all attribute values - $attributes = $this->_sqs->getAttribute($queueId, 'All'); - if(is_array($attributes)) { - return $attributes; - } else { - return array('All' => $this->_sqs->getAttribute($queueId, 'All')); - } - } catch(Zend_Service_Amazon_Exception $e) { - throw new Zend_Cloud_QueueService_Exception('Error on fetching queue metadata: '.$e->getMessage(), $e->getCode(), $e); - } - } - - /** - * Store a key/value array of metadata for the specified queue. - * WARNING: This operation overwrites any metadata that is located at - * $destinationPath. Some adapters may not support this method. - * - * @param array $metadata - * @param string $queueId - * @param array $options - * @return void - */ - public function storeQueueMetadata($queueId, $metadata, $options = null) - { - // TODO Add support for SetQueueAttributes to client library - #require_once 'Zend/Cloud/OperationNotAvailableException.php'; - throw new Zend_Cloud_OperationNotAvailableException('Amazon SQS doesn\'t currently support storing metadata'); - } - - /** - * Send a message to the specified queue. - * - * @param string $message - * @param string $queueId - * @param array $options - * @return string Message ID - */ - public function sendMessage($queueId, $message, $options = null) - { - try { - return $this->_sqs->send($queueId, $message); - } catch(Zend_Service_Amazon_Exception $e) { - throw new Zend_Cloud_QueueService_Exception('Error on sending message: '.$e->getMessage(), $e->getCode(), $e); - } - } - - /** - * Recieve at most $max messages from the specified queue and return the - * message IDs for messages recieved. - * - * @param string $queueId - * @param int $max - * @param array $options - * @return array - */ - public function receiveMessages($queueId, $max = 1, $options = null) - { - try { - return $this->_makeMessages($this->_sqs->receive($queueId, $max, $options[self::VISIBILITY_TIMEOUT])); - } catch(Zend_Service_Amazon_Exception $e) { - throw new Zend_Cloud_QueueService_Exception('Error on recieving messages: '.$e->getMessage(), $e->getCode(), $e); - } - } - - /** - * Create Zend_Cloud_QueueService_Message array for - * Sqs messages. - * - * @param array $messages - * @return Zend_Cloud_QueueService_Message[] - */ - protected function _makeMessages($messages) - { - $messageClass = $this->getMessageClass(); - $setClass = $this->getMessageSetClass(); - $result = array(); - foreach($messages as $message) { - $result[] = new $messageClass($message['body'], $message); - } - return new $setClass($result); - } - - /** - * Delete the specified message from the specified queue. - * - * @param string $queueId - * @param Zend_Cloud_QueueService_Message $message - * @param array $options - * @return void - */ - public function deleteMessage($queueId, $message, $options = null) - { - try { - if($message instanceof Zend_Cloud_QueueService_Message) { - $message = $message->getMessage(); - } - $messageId = $message['handle']; - return $this->_sqs->deleteMessage($queueId, $messageId); - } catch(Zend_Service_Amazon_Exception $e) { - throw new Zend_Cloud_QueueService_Exception('Error on deleting a message: '.$e->getMessage(), $e->getCode(), $e); - } - } - - /** - * Peek at the messages from the specified queue without removing them. - * - * @param string $queueId - * @param int $num How many messages - * @param array $options - * @return Zend_Cloud_QueueService_Message[] - */ - public function peekMessages($queueId, $num = 1, $options = null) - { - try { - return $this->_makeMessages($this->_sqs->receive($queueId, $num, 0)); - } catch(Zend_Service_Amazon_Exception $e) { - throw new Zend_Cloud_QueueService_Exception('Error on peeking messages: '.$e->getMessage(), $e->getCode(), $e); - } - } - - /** - * Get SQS implementation - * @return Zend_Service_Amazon_Sqs - */ - public function getClient() - { - return $this->_sqs; - } -} diff --git a/library/Zend/Cloud/QueueService/Adapter/WindowsAzure.php b/library/Zend/Cloud/QueueService/Adapter/WindowsAzure.php deleted file mode 100755 index cd7eef2010..0000000000 --- a/library/Zend/Cloud/QueueService/Adapter/WindowsAzure.php +++ /dev/null @@ -1,343 +0,0 @@ -toArray(); - } - - if (!is_array($options)) { - throw new Zend_Cloud_QueueService_Exception('Invalid options provided'); - } - - if (isset($options[self::MESSAGE_CLASS])) { - $this->setMessageClass($options[self::MESSAGE_CLASS]); - } - - if (isset($options[self::MESSAGESET_CLASS])) { - $this->setMessageSetClass($options[self::MESSAGESET_CLASS]); - } - - // Build Zend_Service_WindowsAzure_Storage_Blob instance - if (!isset($options[self::HOST])) { - $host = self::DEFAULT_HOST; - } else { - $host = $options[self::HOST]; - } - if (! isset($options[self::ACCOUNT_NAME])) { - throw new Zend_Cloud_Storage_Exception('No Windows Azure account name provided.'); - } - if (! isset($options[self::ACCOUNT_KEY])) { - throw new Zend_Cloud_Storage_Exception('No Windows Azure account key provided.'); - } - try { - // TODO: support $usePathStyleUri and $retryPolicy - $this->_storageClient = new Zend_Service_WindowsAzure_Storage_Queue( - $host, $options[self::ACCOUNT_NAME], $options[self::ACCOUNT_KEY]); - // Parse other options - if (! empty($options[self::PROXY_HOST])) { - $proxyHost = $options[self::PROXY_HOST]; - $proxyPort = isset($options[self::PROXY_PORT]) ? $options[self::PROXY_PORT] : 8080; - $proxyCredentials = isset($options[self::PROXY_CREDENTIALS]) ? $options[self::PROXY_CREDENTIALS] : ''; - $this->_storageClient->setProxy(true, $proxyHost, $proxyPort, $proxyCredentials); - } - if (isset($options[self::HTTP_ADAPTER])) { - $this->_storageClient->setHttpClientChannel($httpAdapter); - } - } catch(Zend_Service_WindowsAzure_Exception $e) { - throw new Zend_Cloud_QueueService_Exception('Error on create: '.$e->getMessage(), $e->getCode(), $e); - } - - } - - /** - * Create a queue. Returns the ID of the created queue (typically the URL). - * It may take some time to create the queue. Check your vendor's - * documentation for details. - * - * @param string $name - * @param array $options - * @return string Queue ID (typically URL) - */ - public function createQueue($name, $options = null) - { - try { - $queue = $this->_storageClient->createQueue($name, $options); - return $queue->Name; - } catch (Zend_Service_WindowsAzure_Exception $e) { - throw new Zend_Cloud_QueueService_Exception('Error on queue creation: '.$e->getMessage(), $e->getCode(), $e); - } - } - - /** - * Delete a queue. All messages in the queue will also be deleted. - * - * @param string $queueId - * @param array $options - * @return boolean true if successful, false otherwise - */ - public function deleteQueue($queueId, $options = null) - { - try { - if ($queueId instanceof Zend_Service_WindowsAzure_Storage_QueueInstance) { - $queueId = $queueId->Name; - } - return $this->_storageClient->deleteQueue($queueId); - } catch (Zend_Service_WindowsAzure_Exception $e) { - throw new Zend_Cloud_QueueService_Exception('Error on queue deletion: '.$e->getMessage(), $e->getCode(), $e); - } - } - - /** - * List all queues. - * - * @param array $options - * @return array Queue IDs - */ - public function listQueues($options = null) - { - $prefix = $maxResults = null; - if (is_array($options)) { - isset($options[self::LIST_PREFIX]) ? $prefix = $options[self::LIST_PREFIX] : null; - isset($options[self::LIST_MAX_RESULTS]) ? $maxResults = $options[self::LIST_MAX_RESULTS] : null; - } - try { - $queues = $this->_storageClient->listQueues($prefix, $maxResults); - $result = array(); - foreach ($queues as $queue) { - $result[] = $queue->Name; - } - return $result; - } catch (Zend_Service_WindowsAzure_Exception $e) { - throw new Zend_Cloud_QueueService_Exception('Error on listing queues: '.$e->getMessage(), $e->getCode(), $e); - } - } - - /** - * Get a key/value array of metadata for the given queue. - * - * @param string $queueId - * @param array $options - * @return array - */ - public function fetchQueueMetadata($queueId, $options = null) - { - try { - if ($queueId instanceof Zend_Service_WindowsAzure_Storage_QueueInstance) { - $queueId = $queueId->Name; - } - return $this->_storageClient->getQueueMetadata($queueId); - } catch (Zend_Service_WindowsAzure_Exception $e) { - throw new Zend_Cloud_QueueService_Exception('Error on fetching queue metadata: '.$e->getMessage(), $e->getCode(), $e); - } - } - - /** - * Store a key/value array of metadata for the specified queue. - * WARNING: This operation overwrites any metadata that is located at - * $destinationPath. Some adapters may not support this method. - * - * @param string $queueId - * @param array $metadata - * @param array $options - * @return void - */ - public function storeQueueMetadata($queueId, $metadata, $options = null) - { - try { - if ($queueId instanceof Zend_Service_WindowsAzure_Storage_QueueInstance) { - $queueId = $queueId->Name; - } - return $this->_storageClient->setQueueMetadata($queueId, $metadata); - } catch (Zend_Service_WindowsAzure_Exception $e) { - throw new Zend_Cloud_QueueService_Exception('Error on setting queue metadata: '.$e->getMessage(), $e->getCode(), $e); - } - } - - /** - * Send a message to the specified queue. - * - * @param string $queueId - * @param string $message - * @param array $options - * @return string Message ID - */ - public function sendMessage($queueId, $message, $options = null) - { - try { - if ($queueId instanceof Zend_Service_WindowsAzure_Storage_QueueInstance) { - $queueId = $queueId->Name; - } - return $this->_storageClient->putMessage( - $queueId, $message, $options[self::MESSAGE_TTL] - ); - } catch (Zend_Service_WindowsAzure_Exception $e) { - throw new Zend_Cloud_QueueService_Exception('Error on sending message: '.$e->getMessage(), $e->getCode(), $e); - } - } - - /** - * Recieve at most $max messages from the specified queue and return the - * message IDs for messages recieved. - * - * @param string $queueId - * @param int $max - * @param array $options - * @return Zend_Cloud_QueueService_Message[] - */ - public function receiveMessages($queueId, $max = 1, $options = null) - { - try { - if ($queueId instanceof Zend_Service_WindowsAzure_Storage_QueueInstance) { - $queueId = $queueId->Name; - } - if (isset($options[self::VISIBILITY_TIMEOUT])) { - $visibility = $options[self::VISIBILITY_TIMEOUT]; - } else { - $visibility = self::DEFAULT_TIMEOUT; - } - return $this->_makeMessages($this->_storageClient->getMessages($queueId, $max, $visibility, false)); - } catch (Zend_Service_WindowsAzure_Exception $e) { - throw new Zend_Cloud_QueueService_Exception('Error on recieving messages: '.$e->getMessage(), $e->getCode(), $e); - } - } - - /** - * Create Zend_Cloud_QueueService_Message array for - * Azure messages. - * - * @param array $messages - * @return Zend_Cloud_QueueService_Message[] - */ - protected function _makeMessages($messages) - { - $messageClass = $this->getMessageClass(); - $setClass = $this->getMessageSetClass(); - $result = array(); - foreach ($messages as $message) { - $result[] = new $messageClass($message->MessageText, $message); - } - return new $setClass($result); - } - - /** - * Delete the specified message from the specified queue. - * - * @param string $queueId - * @param Zend_Cloud_QueueService_Message $message Message ID or message - * @param array $options - * @return void - */ - public function deleteMessage($queueId, $message, $options = null) - { - try { - if ($queueId instanceof Zend_Service_WindowsAzure_Storage_QueueInstance) { - $queueId = $queueId->Name; - } - if ($message instanceof Zend_Cloud_QueueService_Message) { - $message = $message->getMessage(); - } - if ($message instanceof Zend_Service_WindowsAzure_Storage_QueueMessage) { - return $this->_storageClient->deleteMessage($queueId, $message); - } else { - throw new Zend_Cloud_QueueService_Exception('Cannot delete the message: message object required'); - } - } catch (Zend_Service_WindowsAzure_Exception $e) { - throw new Zend_Cloud_QueueService_Exception('Error on deleting a message: '.$e->getMessage(), $e->getCode(), $e); - } - } - - /** - * Peek at the messages from the specified queue without removing them. - * - * @param string $queueId - * @param int $num How many messages - * @param array $options - * @return Zend_Cloud_QueueService_Message[] - */ - public function peekMessages($queueId, $num = 1, $options = null) - { - try { - if ($queueId instanceof Zend_Service_WindowsAzure_Storage_QueueInstance) { - $queueId = $queueId->Name; - } - return $this->_makeMessages($this->_storageClient->peekMessages($queueId, $num)); - } catch (Zend_Service_WindowsAzure_Exception $e) { - throw new Zend_Cloud_QueueService_Exception('Error on peeking messages: '.$e->getMessage(), $e->getCode(), $e); - } - } - - /** - * Get Azure implementation - * @return Zend_Service_Azure_Storage_Queue - */ - public function getClient() - { - return $this->_storageClient; - } -} diff --git a/library/Zend/Cloud/QueueService/Adapter/ZendQueue.php b/library/Zend/Cloud/QueueService/Adapter/ZendQueue.php deleted file mode 100755 index 0672695e12..0000000000 --- a/library/Zend/Cloud/QueueService/Adapter/ZendQueue.php +++ /dev/null @@ -1,301 +0,0 @@ -toArray(); - } - - if (!is_array($options)) { - throw new Zend_Cloud_QueueService_Exception('Invalid options provided'); - } - - if (isset($options[self::MESSAGE_CLASS])) { - $this->setMessageClass($options[self::MESSAGE_CLASS]); - } - - if (isset($options[self::MESSAGESET_CLASS])) { - $this->setMessageSetClass($options[self::MESSAGESET_CLASS]); - } - - // Build Zend_Service_WindowsAzure_Storage_Blob instance - if (!isset($options[self::ADAPTER])) { - throw new Zend_Cloud_QueueService_Exception('No Zend_Queue adapter provided'); - } else { - $adapter = $options[self::ADAPTER]; - unset($options[self::ADAPTER]); - } - try { - $this->_queue = new Zend_Queue($adapter, $options); - } catch (Zend_Queue_Exception $e) { - throw new Zend_Cloud_QueueService_Exception('Error on create: '.$e->getMessage(), $e->getCode(), $e); - } - } - - /** - * Create a queue. Returns the ID of the created queue (typically the URL). - * It may take some time to create the queue. Check your vendor's - * documentation for details. - * - * @param string $name - * @param array $options - * @return string Queue ID (typically URL) - */ - public function createQueue($name, $options = null) - { - try { - $this->_queues[$name] = $this->_queue->createQueue($name, isset($options[Zend_Queue::TIMEOUT])?$options[Zend_Queue::TIMEOUT]:null); - return $name; - } catch (Zend_Queue_Exception $e) { - throw new Zend_Cloud_QueueService_Exception('Error on queue creation: '.$e->getMessage(), $e->getCode(), $e); - } - } - - /** - * Delete a queue. All messages in the queue will also be deleted. - * - * @param string $queueId - * @param array $options - * @return boolean true if successful, false otherwise - */ - public function deleteQueue($queueId, $options = null) - { - if (!isset($this->_queues[$queueId])) { - return false; - } - try { - if ($this->_queues[$queueId]->deleteQueue()) { - unset($this->_queues[$queueId]); - return true; - } - } catch (Zend_Queue_Exception $e) { - throw new Zend_Cloud_QueueService_Exception('Error on queue deletion: '.$e->getMessage(), $e->getCode(), $e); - } - } - - /** - * List all queues. - * - * @param array $options - * @return array Queue IDs - */ - public function listQueues($options = null) - { - try { - return $this->_queue->getQueues(); - } catch (Zend_Queue_Exception $e) { - throw new Zend_Cloud_QueueService_Exception('Error on listing queues: '.$e->getMessage(), $e->getCode(), $e); - } - } - - /** - * Get a key/value array of metadata for the given queue. - * - * @param string $queueId - * @param array $options - * @return array - */ - public function fetchQueueMetadata($queueId, $options = null) - { - if (!isset($this->_queues[$queueId])) { - return false; - } - try { - return $this->_queues[$queueId]->getOptions(); - } catch (Zend_Queue_Exception $e) { - throw new Zend_Cloud_QueueService_Exception('Error on fetching queue metadata: '.$e->getMessage(), $e->getCode(), $e); - } - } - - /** - * Store a key/value array of metadata for the specified queue. - * WARNING: This operation overwrites any metadata that is located at - * $destinationPath. Some adapters may not support this method. - * - * @param string $queueId - * @param array $metadata - * @param array $options - * @return void - */ - public function storeQueueMetadata($queueId, $metadata, $options = null) - { - if (!isset($this->_queues[$queueId])) { - throw new Zend_Cloud_QueueService_Exception("No such queue: $queueId"); - } - try { - return $this->_queues[$queueId]->setOptions($metadata); - } catch (Zend_Queue_Exception $e) { - throw new Zend_Cloud_QueueService_Exception('Error on setting queue metadata: '.$e->getMessage(), $e->getCode(), $e); - } - } - - /** - * Send a message to the specified queue. - * - * @param string $queueId - * @param string $message - * @param array $options - * @return string Message ID - */ - public function sendMessage($queueId, $message, $options = null) - { - if (!isset($this->_queues[$queueId])) { - throw new Zend_Cloud_QueueService_Exception("No such queue: $queueId"); - } - try { - return $this->_queues[$queueId]->send($message); - } catch (Zend_Queue_Exception $e) { - throw new Zend_Cloud_QueueService_Exception('Error on sending message: '.$e->getMessage(), $e->getCode(), $e); - } - } - - /** - * Recieve at most $max messages from the specified queue and return the - * message IDs for messages recieved. - * - * @param string $queueId - * @param int $max - * @param array $options - * @return array - */ - public function receiveMessages($queueId, $max = 1, $options = null) - { - if (!isset($this->_queues[$queueId])) { - throw new Zend_Cloud_QueueService_Exception("No such queue: $queueId"); - } - try { - $res = $this->_queues[$queueId]->receive($max, isset($options[Zend_Queue::TIMEOUT])?$options[Zend_Queue::TIMEOUT]:null); - if ($res instanceof Iterator) { - return $this->_makeMessages($res); - } else { - return $this->_makeMessages(array($res)); - } - } catch (Zend_Queue_Exception $e) { - throw new Zend_Cloud_QueueService_Exception('Error on recieving messages: '.$e->getMessage(), $e->getCode(), $e); - } - } - - /** - * Create Zend_Cloud_QueueService_Message array for - * Azure messages. - * - * @param array $messages - * @return Zend_Cloud_QueueService_Message[] - */ - protected function _makeMessages($messages) - { - $messageClass = $this->getMessageClass(); - $setClass = $this->getMessageSetClass(); - $result = array(); - foreach ($messages as $message) { - $result[] = new $messageClass($message->body, $message); - } - return new $setClass($result); - } - - /** - * Delete the specified message from the specified queue. - * - * @param string $queueId - * @param Zend_Cloud_QueueService_Message $message Message ID or message - * @param array $options - * @return void - */ - public function deleteMessage($queueId, $message, $options = null) - { - if (!isset($this->_queues[$queueId])) { - throw new Zend_Cloud_QueueService_Exception("No such queue: $queueId"); - } - try { - if ($message instanceof Zend_Cloud_QueueService_Message) { - $message = $message->getMessage(); - } - if (!($message instanceof Zend_Queue_Message)) { - throw new Zend_Cloud_QueueService_Exception('Cannot delete the message: Zend_Queue_Message object required'); - } - - return $this->_queues[$queueId]->deleteMessage($message); - } catch (Zend_Queue_Exception $e) { - throw new Zend_Cloud_QueueService_Exception('Error on deleting a message: '.$e->getMessage(), $e->getCode(), $e); - } - } - - /** - * Peek at the messages from the specified queue without removing them. - * - * @param string $queueId - * @param int $num How many messages - * @param array $options - * @return Zend_Cloud_QueueService_Message[] - */ - public function peekMessages($queueId, $num = 1, $options = null) - { - #require_once 'Zend/Cloud/OperationNotAvailableException.php'; - throw new Zend_Cloud_OperationNotAvailableException('ZendQueue doesn\'t currently support message peeking'); - } - - /** - * Get Azure implementation - * @return Zend_Queue - */ - public function getClient() - { - return $this->_queue; - } -} diff --git a/library/Zend/Cloud/QueueService/Exception.php b/library/Zend/Cloud/QueueService/Exception.php deleted file mode 100644 index 54882cad29..0000000000 --- a/library/Zend/Cloud/QueueService/Exception.php +++ /dev/null @@ -1,37 +0,0 @@ -_body = $body; - $this->_clientMessage = $message; - } - - /** - * Get the message body - * @return string - */ - public function getBody() - { - return $this->_body; - } - - /** - * Get the original adapter-specific message - */ - public function getMessage() - { - return $this->_clientMessage; - } -} diff --git a/library/Zend/Cloud/QueueService/MessageSet.php b/library/Zend/Cloud/QueueService/MessageSet.php deleted file mode 100644 index d80e935ed2..0000000000 --- a/library/Zend/Cloud/QueueService/MessageSet.php +++ /dev/null @@ -1,68 +0,0 @@ -_messageCount = count($messages); - $this->_messages = new ArrayIterator($messages); - } - - /** - * Countable: number of messages in collection - * - * @return int - */ - public function count() - { - return $this->_messageCount; - } - - /** - * IteratorAggregate: return iterable object - * - * @return Traversable - */ - public function getIterator() - { - return $this->_messages; - } -} diff --git a/library/Zend/Cloud/StorageService/Adapter.php b/library/Zend/Cloud/StorageService/Adapter.php deleted file mode 100644 index d494ca0524..0000000000 --- a/library/Zend/Cloud/StorageService/Adapter.php +++ /dev/null @@ -1,145 +0,0 @@ -toArray(); - } - - if (!is_array($options)) { - throw new Zend_Cloud_StorageService_Exception('Invalid options provided'); - } - - if (isset($options[self::LOCAL_DIRECTORY])) { - $this->_directory = $options[self::LOCAL_DIRECTORY]; - } else { - $this->_directory = realpath(sys_get_temp_dir()); - } - } - - /** - * Get an item from the storage service. - * - * TODO: Support streaming - * - * @param string $path - * @param array $options - * @return false|string - */ - public function fetchItem($path, $options = array()) - { - $filepath = $this->_getFullPath($path); - $path = realpath($filepath); - - if (!$path || !file_exists($path)) { - return false; - } - - return file_get_contents($path); - } - - /** - * Store an item in the storage service. - * - * WARNING: This operation overwrites any item that is located at - * $destinationPath. - * - * @TODO Support streams - * - * @param string $destinationPath - * @param mixed $data - * @param array $options - * @return void - */ - public function storeItem($destinationPath, $data, $options = array()) - { - $path = $this->_getFullPath($destinationPath); - file_put_contents($path, $data); - chmod($path, 0775); - } - - /** - * Delete an item in the storage service. - * - * @param string $path - * @param array $options - * @return void - */ - public function deleteItem($path, $options = array()) - { - if (!isset($path)) { - return; - } - - $filepath = $this->_getFullPath($path); - if (file_exists($filepath)) { - unlink($filepath); - } - } - - /** - * Copy an item in the storage service to a given path. - * - * WARNING: This operation is *very* expensive for services that do not - * support copying an item natively. - * - * @TODO Support streams for those services that don't support natively - * - * @param string $sourcePath - * @param string $destination path - * @param array $options - * @return void - */ - public function copyItem($sourcePath, $destinationPath, $options = array()) - { - copy($this->_getFullPath($sourcePath), $this->_getFullPath($destinationPath)); - } - - /** - * Move an item in the storage service to a given path. - * - * WARNING: This operation is *very* expensive for services that do not - * support moving an item natively. - * - * @TODO Support streams for those services that don't support natively - * - * @param string $sourcePath - * @param string $destination path - * @param array $options - * @return void - */ - public function moveItem($sourcePath, $destinationPath, $options = array()) - { - rename($this->_getFullPath($sourcePath), $this->_getFullPath($destinationPath)); - } - - /** - * Rename an item in the storage service to a given name. - * - * - * @param string $path - * @param string $name - * @param array $options - * @return void - */ - public function renameItem($path, $name, $options = null) - { - rename( - $this->_getFullPath($path), - dirname($this->_getFullPath($path)) . DIRECTORY_SEPARATOR . $name - ); - } - - /** - * List items in the given directory in the storage service - * - * The $path must be a directory - * - * - * @param string $path Must be a directory - * @param array $options - * @return array A list of item names - */ - public function listItems($path, $options = null) - { - $listing = scandir($this->_getFullPath($path)); - - // Remove the hidden navigation directories - $listing = array_diff($listing, array('.', '..')); - - return $listing; - } - - /** - * Get a key/value array of metadata for the given path. - * - * @param string $path - * @param array $options - * @return array - */ - public function fetchMetadata($path, $options = array()) - { - $fullPath = $this->_getFullPath($path); - $metadata = null; - if (file_exists($fullPath)) { - $metadata = stat(realpath($fullPath)); - } - - return isset($metadata) ? $metadata : false; - } - - /** - * Store a key/value array of metadata at the given path. - * WARNING: This operation overwrites any metadata that is located at - * $destinationPath. - * - * @param string $destinationPath - * @param array $options - * @return void - */ - public function storeMetadata($destinationPath, $metadata, $options = array()) - { - #require_once 'Zend/Cloud/OperationNotAvailableException.php'; - throw new Zend_Cloud_OperationNotAvailableException('Storing metadata not implemented'); - } - - /** - * Delete a key/value array of metadata at the given path. - * - * @param string $path - * @param array $options - * @return void - */ - public function deleteMetadata($path) - { - #require_once 'Zend/Cloud/OperationNotAvailableException.php'; - throw new Zend_Cloud_OperationNotAvailableException('Deleting metadata not implemented'); - } - - /** - * Return the full path for the file. - * - * @param string $path - * @return string - */ - private function _getFullPath($path) - { - return $this->_directory . DIRECTORY_SEPARATOR . $path; - } - - /** - * Get the concrete client. - * @return strings - */ - public function getClient() - { - return $this->_directory; - } -} diff --git a/library/Zend/Cloud/StorageService/Adapter/Rackspace.php b/library/Zend/Cloud/StorageService/Adapter/Rackspace.php deleted file mode 100644 index bdc69c2557..0000000000 --- a/library/Zend/Cloud/StorageService/Adapter/Rackspace.php +++ /dev/null @@ -1,332 +0,0 @@ -toArray(); - } - - if (!is_array($options) || empty($options)) { - throw new Zend_Cloud_StorageService_Exception('Invalid options provided'); - } - - try { - $this->_rackspace = new Zend_Service_Rackspace_Files($options[self::USER], $options[self::API_KEY]); - } catch (Zend_Service_Rackspace_Exception $e) { - throw new Zend_Cloud_StorageService_Exception('Error on create: '.$e->getMessage(), $e->getCode(), $e); - } - - if (isset($options[self::HTTP_ADAPTER])) { - $this->_rackspace->getHttpClient()->setAdapter($options[self::HTTP_ADAPTER]); - } - if (!empty($options[self::REMOTE_CONTAINER])) { - $this->_container = $options[self::REMOTE_CONTAINER]; - } - } - - /** - * Get an item from the storage service. - * - * @param string $path - * @param array $options - * @return mixed - */ - public function fetchItem($path, $options = null) - { - $item = $this->_rackspace->getObject($this->_container,$path, $options); - if (!$this->_rackspace->isSuccessful() && ($this->_rackspace->getErrorCode()!='404')) { - throw new Zend_Cloud_StorageService_Exception('Error on fetch: '.$this->_rackspace->getErrorMsg()); - } - if (!empty($item)) { - return $item->getContent(); - } else { - return false; - } - } - - /** - * Store an item in the storage service. - * - * @param string $destinationPath - * @param mixed $data - * @param array $options - * @return void - */ - public function storeItem($destinationPath, $data, $options = null) - { - $this->_rackspace->storeObject($this->_container,$destinationPath,$data,$options); - if (!$this->_rackspace->isSuccessful()) { - throw new Zend_Cloud_StorageService_Exception('Error on store: '.$this->_rackspace->getErrorMsg()); - } - } - - /** - * Delete an item in the storage service. - * - * @param string $path - * @param array $options - * @return void - */ - public function deleteItem($path, $options = null) - { - $this->_rackspace->deleteObject($this->_container,$path); - if (!$this->_rackspace->isSuccessful()) { - throw new Zend_Cloud_StorageService_Exception('Error on delete: '.$this->_rackspace->getErrorMsg()); - } - } - - /** - * Copy an item in the storage service to a given path. - * - * @param string $sourcePath - * @param string $destination path - * @param array $options - * @return void - */ - public function copyItem($sourcePath, $destinationPath, $options = null) - { - $this->_rackspace->copyObject($this->_container,$sourcePath,$this->_container,$destinationPath,$options); - if (!$this->_rackspace->isSuccessful()) { - throw new Zend_Cloud_StorageService_Exception('Error on copy: '.$this->_rackspace->getErrorMsg()); - } - } - - /** - * Move an item in the storage service to a given path. - * WARNING: This operation is *very* expensive for services that do not - * support moving an item natively. - * - * @param string $sourcePath - * @param string $destination path - * @param array $options - * @return void - */ - public function moveItem($sourcePath, $destinationPath, $options = null) - { - try { - $this->copyItem($sourcePath, $destinationPath, $options); - } catch (Zend_Service_Rackspace_Exception $e) { - throw new Zend_Cloud_StorageService_Exception('Error on move: '.$e->getMessage()); - } - try { - $this->deleteItem($sourcePath); - } catch (Zend_Service_Rackspace_Exception $e) { - $this->deleteItem($destinationPath); - throw new Zend_Cloud_StorageService_Exception('Error on move: '.$e->getMessage()); - } - } - - /** - * Rename an item in the storage service to a given name. - * - * @param string $path - * @param string $name - * @param array $options - * @return void - */ - public function renameItem($path, $name, $options = null) - { - #require_once 'Zend/Cloud/OperationNotAvailableException.php'; - throw new Zend_Cloud_OperationNotAvailableException('Renaming not implemented'); - } - - /** - * Get a key/value array of metadata for the given path. - * - * @param string $path - * @param array $options - * @return array An associative array of key/value pairs specifying the metadata for this object. - * If no metadata exists, an empty array is returned. - */ - public function fetchMetadata($path, $options = null) - { - $result = $this->_rackspace->getMetadataObject($this->_container,$path); - if (!$this->_rackspace->isSuccessful()) { - throw new Zend_Cloud_StorageService_Exception('Error on fetch metadata: '.$this->_rackspace->getErrorMsg()); - } - $metadata = array(); - if (isset($result['metadata'])) { - $metadata = $result['metadata']; - } - // delete the self::DELETE_METADATA_KEY - this is a trick to remove all - // the metadata information of an object (see deleteMetadata). - // Rackspace doesn't have an API to remove the metadata of an object - unset($metadata[self::DELETE_METADATA_KEY]); - return $metadata; - } - - /** - * Store a key/value array of metadata at the given path. - * WARNING: This operation overwrites any metadata that is located at - * $destinationPath. - * - * @param string $destinationPath - * @param array $metadata associative array specifying the key/value pairs for the metadata. - * @param array $options - * @return void - */ - public function storeMetadata($destinationPath, $metadata, $options = null) - { - $this->_rackspace->setMetadataObject($this->_container, $destinationPath, $metadata); - if (!$this->_rackspace->isSuccessful()) { - throw new Zend_Cloud_StorageService_Exception('Error on store metadata: '.$this->_rackspace->getErrorMsg()); - } - } - - /** - * Delete a key/value array of metadata at the given path. - * - * @param string $path - * @param array $metadata - An associative array specifying the key/value pairs for the metadata - * to be deleted. If null, all metadata associated with the object will - * be deleted. - * @param array $options - * @return void - */ - public function deleteMetadata($path, $metadata = null, $options = null) - { - if (empty($metadata)) { - $newMetadata = array(self::DELETE_METADATA_KEY => true); - try { - $this->storeMetadata($path, $newMetadata); - } catch (Zend_Service_Rackspace_Exception $e) { - throw new Zend_Cloud_StorageService_Exception('Error on delete metadata: '.$e->getMessage()); - } - } else { - try { - $oldMetadata = $this->fetchMetadata($path); - } catch (Zend_Service_Rackspace_Exception $e) { - throw new Zend_Cloud_StorageService_Exception('Error on delete metadata: '.$e->getMessage()); - } - $newMetadata = array_diff_assoc($oldMetadata, $metadata); - try { - $this->storeMetadata($path, $newMetadata); - } catch (Zend_Service_Rackspace_Exception $e) { - throw new Zend_Cloud_StorageService_Exception('Error on delete metadata: '.$e->getMessage()); - } - } - } - - /* - * Recursively traverse all the folders and build an array that contains - * the path names for each folder. - * - * @param string $path folder path to get the list of folders from. - * @param array& $resultArray reference to the array that contains the path names - * for each folder. - * @return void - */ - private function getAllFolders($path, &$resultArray) - { - if (!empty($path)) { - $options = array ( - 'prefix' => $path - ); - } - $files = $this->_rackspace->getObjects($this->_container,$options); - if (!$this->_rackspace->isSuccessful()) { - throw new Zend_Cloud_StorageService_Exception('Error on get all folders: '.$this->_rackspace->getErrorMsg()); - } - $resultArray = array(); - foreach ($files as $file) { - $resultArray[dirname($file->getName())] = true; - } - $resultArray = array_keys($resultArray); - } - - /** - * Return an array of the items contained in the given path. The items - * returned are the files or objects that in the specified path. - * - * @param string $path - * @param array $options - * @return array - */ - public function listItems($path, $options = null) - { - if (!empty($path)) { - $options = array ( - 'prefix' => $path - ); - } - - $files = $this->_rackspace->getObjects($this->_container,$options); - if (!$this->_rackspace->isSuccessful()) { - throw new Zend_Cloud_StorageService_Exception('Error on list items: '.$this->_rackspace->getErrorMsg()); - } - $resultArray = array(); - if (!empty($files)) { - foreach ($files as $file) { - $resultArray[] = $file->getName(); - } - } - return $resultArray; - } - - /** - * Get the concrete client. - * - * @return Zend_Service_Rackspace_File - */ - public function getClient() - { - return $this->_rackspace; - } -} diff --git a/library/Zend/Cloud/StorageService/Adapter/S3.php b/library/Zend/Cloud/StorageService/Adapter/S3.php deleted file mode 100644 index 32f474d55a..0000000000 --- a/library/Zend/Cloud/StorageService/Adapter/S3.php +++ /dev/null @@ -1,332 +0,0 @@ -toArray(); - } - - if (!is_array($options)) { - throw new Zend_Cloud_StorageService_Exception('Invalid options provided'); - } - - if (!isset($options[self::AWS_ACCESS_KEY]) || !isset($options[self::AWS_SECRET_KEY])) { - throw new Zend_Cloud_StorageService_Exception('AWS keys not specified!'); - } - - try { - $this->_s3 = new Zend_Service_Amazon_S3($options[self::AWS_ACCESS_KEY], - $options[self::AWS_SECRET_KEY]); - } catch (Zend_Service_Amazon_S3_Exception $e) { - throw new Zend_Cloud_StorageService_Exception('Error on create: '.$e->getMessage(), $e->getCode(), $e); - } - - if (isset($options[self::HTTP_ADAPTER])) { - $this->_s3->getHttpClient()->setAdapter($options[self::HTTP_ADAPTER]); - } - - if (isset($options[self::BUCKET_NAME])) { - $this->_defaultBucketName = $options[self::BUCKET_NAME]; - } - - if (isset($options[self::BUCKET_AS_DOMAIN])) { - $this->_defaultBucketAsDomain = $options[self::BUCKET_AS_DOMAIN]; - } - } - - /** - * Get an item from the storage service. - * - * @TODO Support streams - * - * @param string $path - * @param array $options - * @return string - */ - public function fetchItem($path, $options = array()) - { - $fullPath = $this->_getFullPath($path, $options); - try { - if (!empty($options[self::FETCH_STREAM])) { - return $this->_s3->getObjectStream($fullPath, $options[self::FETCH_STREAM]); - } else { - return $this->_s3->getObject($fullPath); - } - } catch (Zend_Service_Amazon_S3_Exception $e) { - throw new Zend_Cloud_StorageService_Exception('Error on fetch: '.$e->getMessage(), $e->getCode(), $e); - } - } - - /** - * Store an item in the storage service. - * - * WARNING: This operation overwrites any item that is located at - * $destinationPath. - * - * @TODO Support streams - * - * @param string $destinationPath - * @param string|resource $data - * @param array $options - * @return void - */ - public function storeItem($destinationPath, $data, $options = array()) - { - try { - $fullPath = $this->_getFullPath($destinationPath, $options); - return $this->_s3->putObject( - $fullPath, - $data, - empty($options[self::METADATA]) ? null : $options[self::METADATA] - ); - } catch (Zend_Service_Amazon_S3_Exception $e) { - throw new Zend_Cloud_StorageService_Exception('Error on store: '.$e->getMessage(), $e->getCode(), $e); - } - } - - /** - * Delete an item in the storage service. - * - * @param string $path - * @param array $options - * @return void - */ - public function deleteItem($path, $options = array()) - { - try { - $this->_s3->removeObject($this->_getFullPath($path, $options)); - } catch (Zend_Service_Amazon_S3_Exception $e) { - throw new Zend_Cloud_StorageService_Exception('Error on delete: '.$e->getMessage(), $e->getCode(), $e); - } - } - - /** - * Copy an item in the storage service to a given path. - * - * WARNING: This operation is *very* expensive for services that do not - * support copying an item natively. - * - * @TODO Support streams for those services that don't support natively - * - * @param string $sourcePath - * @param string $destination path - * @param array $options - * @return void - */ - public function copyItem($sourcePath, $destinationPath, $options = array()) - { - try { - $fullSourcePath = $this->_getFullPath($sourcePath, $options); - $fullDestPath = $this->_getFullPath($destinationPath, $options); - return $this->_s3->copyObject( - $fullSourcePath, - $fullDestPath, - empty($options[self::METADATA]) ? null : $options[self::METADATA] - ); - - } catch (Zend_Service_Amazon_S3_Exception $e) { - throw new Zend_Cloud_StorageService_Exception('Error on copy: '.$e->getMessage(), $e->getCode(), $e); - } - } - - /** - * Move an item in the storage service to a given path. - * - * @TODO Support streams for those services that don't support natively - * - * @param string $sourcePath - * @param string $destination path - * @param array $options - * @return void - */ - public function moveItem($sourcePath, $destinationPath, $options = array()) - { - try { - $fullSourcePath = $this->_getFullPath($sourcePath, $options); - $fullDestPath = $this->_getFullPath($destinationPath, $options); - return $this->_s3->moveObject( - $fullSourcePath, - $fullDestPath, - empty($options[self::METADATA]) ? null : $options[self::METADATA] - ); - } catch (Zend_Service_Amazon_S3_Exception $e) { - throw new Zend_Cloud_StorageService_Exception('Error on move: '.$e->getMessage(), $e->getCode(), $e); - } - } - - /** - * Rename an item in the storage service to a given name. - * - * - * @param string $path - * @param string $name - * @param array $options - * @return void - */ - public function renameItem($path, $name, $options = null) - { - #require_once 'Zend/Cloud/OperationNotAvailableException.php'; - throw new Zend_Cloud_OperationNotAvailableException('Rename not implemented'); - } - - /** - * List items in the given directory in the storage service - * - * The $path must be a directory - * - * - * @param string $path Must be a directory - * @param array $options - * @return array A list of item names - */ - public function listItems($path, $options = null) - { - try { - // TODO Support 'prefix' parameter for Zend_Service_Amazon_S3::getObjectsByBucket() - return $this->_s3->getObjectsByBucket($this->_defaultBucketName); - } catch (Zend_Service_Amazon_S3_Exception $e) { - throw new Zend_Cloud_StorageService_Exception('Error on list: '.$e->getMessage(), $e->getCode(), $e); - } - } - - /** - * Get a key/value array of metadata for the given path. - * - * @param string $path - * @param array $options - * @return array - */ - public function fetchMetadata($path, $options = array()) - { - try { - return $this->_s3->getInfo($this->_getFullPath($path, $options)); - } catch (Zend_Service_Amazon_S3_Exception $e) { - throw new Zend_Cloud_StorageService_Exception('Error on fetch: '.$e->getMessage(), $e->getCode(), $e); - } - } - - /** - * Store a key/value array of metadata at the given path. - * WARNING: This operation overwrites any metadata that is located at - * $destinationPath. - * - * @param string $destinationPath - * @param array $options - * @return void - */ - public function storeMetadata($destinationPath, $metadata, $options = array()) - { - #require_once 'Zend/Cloud/OperationNotAvailableException.php'; - throw new Zend_Cloud_OperationNotAvailableException('Storing separate metadata is not supported, use storeItem() with \'metadata\' option key'); - } - - /** - * Delete a key/value array of metadata at the given path. - * - * @param string $path - * @param array $options - * @return void - */ - public function deleteMetadata($path) - { - #require_once 'Zend/Cloud/OperationNotAvailableException.php'; - throw new Zend_Cloud_OperationNotAvailableException('Deleting metadata not supported'); - } - - /** - * Get full path, including bucket, for an object - * - * @param string $path - * @param array $options - * @return void - */ - protected function _getFullPath($path, $options) - { - if (isset($options[self::BUCKET_NAME])) { - $bucket = $options[self::BUCKET_NAME]; - } else if (isset($this->_defaultBucketName)) { - $bucket = $this->_defaultBucketName; - } else { - #require_once 'Zend/Cloud/StorageService/Exception.php'; - throw new Zend_Cloud_StorageService_Exception('Bucket name must be specified for S3 adapter.'); - } - - if (isset($options[self::BUCKET_AS_DOMAIN])) { - // TODO: support bucket domain names - #require_once 'Zend/Cloud/StorageService/Exception.php'; - throw new Zend_Cloud_StorageService_Exception('The S3 adapter does not currently support buckets in domain names.'); - } - - return trim($bucket) . '/' . trim($path); - } - - /** - * Get the concrete client. - * @return Zend_Service_Amazon_S3 - */ - public function getClient() - { - return $this->_s3; - } -} diff --git a/library/Zend/Cloud/StorageService/Adapter/WindowsAzure.php b/library/Zend/Cloud/StorageService/Adapter/WindowsAzure.php deleted file mode 100644 index 6df6603c26..0000000000 --- a/library/Zend/Cloud/StorageService/Adapter/WindowsAzure.php +++ /dev/null @@ -1,443 +0,0 @@ -toArray(); - } - - if (!is_array($options)) { - throw new Zend_Cloud_StorageService_Exception('Invalid options provided'); - } - - // Build Zend_Service_WindowsAzure_Storage_Blob instance - if (!isset($options[self::HOST])) { - $host = self::DEFAULT_HOST; - } else { - $host = $options[self::HOST]; - } - - if (!isset($options[self::ACCOUNT_NAME])) { - throw new Zend_Cloud_StorageService_Exception('No Windows Azure account name provided.'); - } - if (!isset($options[self::ACCOUNT_KEY])) { - throw new Zend_Cloud_StorageService_Exception('No Windows Azure account key provided.'); - } - - $this->_storageClient = new Zend_Service_WindowsAzure_Storage_Blob($host, - $options[self::ACCOUNT_NAME], $options[self::ACCOUNT_KEY]); - - // Parse other options - if (!empty($options[self::PROXY_HOST])) { - $proxyHost = $options[self::PROXY_HOST]; - $proxyPort = isset($options[self::PROXY_PORT]) ? $options[self::PROXY_PORT] : 8080; - $proxyCredentials = isset($options[self::PROXY_CREDENTIALS]) ? $options[self::PROXY_CREDENTIALS] : ''; - - $this->_storageClient->setProxy(true, $proxyHost, $proxyPort, $proxyCredentials); - } - - if (isset($options[self::HTTP_ADAPTER])) { - $this->_storageClient->setHttpClientChannel($options[self::HTTP_ADAPTER]); - } - - // Set container - $this->_container = $options[self::CONTAINER]; - - // Make sure the container exists - if (!$this->_storageClient->containerExists($this->_container)) { - $this->_storageClient->createContainer($this->_container); - } - } - - /** - * Get an item from the storage service. - * - * @param string $path - * @param array $options - * @return mixed - */ - public function fetchItem($path, $options = null) - { - // Options - $returnType = self::RETURN_STRING; - $returnPath = tempnam('', 'azr'); - $openMode = 'r'; - - // Parse options - if (is_array($options)) { - if (isset($options[self::RETURN_TYPE])) { - $returnType = $options[self::RETURN_TYPE]; - } - - if (isset($options[self::RETURN_PATHNAME])) { - $returnPath = $options[self::RETURN_PATHNAME]; - } - - if (isset($options[self::RETURN_OPENMODE])) { - $openMode = $options[self::RETURN_OPENMODE]; - } - } - - // Fetch the blob - try { - $this->_storageClient->getBlob( - $this->_container, - $path, - $returnPath - ); - } catch (Zend_Service_WindowsAzure_Exception $e) { - if (strpos($e->getMessage(), "does not exist") !== false) { - return false; - } - throw new Zend_Cloud_StorageService_Exception('Error on fetch: '.$e->getMessage(), $e->getCode(), $e); - } - - // Return value - if ($returnType == self::RETURN_PATH) { - return $returnPath; - } - if ($returnType == self::RETURN_STRING) { - return file_get_contents($returnPath); - } - if ($returnType == self::RETURN_STREAM) { - return fopen($returnPath, $openMode); - } - } - - /** - * Store an item in the storage service. - * WARNING: This operation overwrites any item that is located at - * $destinationPath. - * @param string $destinationPath - * @param mixed $data - * @param array $options - * @return boolean - */ - public function storeItem($destinationPath, $data, $options = null) - { - // Create a temporary file that will be uploaded - $temporaryFilePath = ''; - $removeTemporaryFilePath = false; - - if (is_resource($data)) { - $temporaryFilePath = tempnam('', 'azr'); - $fpDestination = fopen($temporaryFilePath, 'w'); - - $fpSource = $data; - rewind($fpSource); - while (!feof($fpSource)) { - fwrite($fpDestination, fread($fpSource, 8192)); - } - - fclose($fpDestination); - - $removeTemporaryFilePath = true; - } elseif (file_exists($data)) { - $temporaryFilePath = $data; - $removeTemporaryFilePath = false; - } else { - $temporaryFilePath = tempnam('', 'azr'); - file_put_contents($temporaryFilePath, $data); - $removeTemporaryFilePath = true; - } - - try { - // Upload data - $this->_storageClient->putBlob( - $this->_container, - $destinationPath, - $temporaryFilePath - ); - } catch(Zend_Service_WindowsAzure_Exception $e) { - @unlink($temporaryFilePath); - throw new Zend_Cloud_StorageService_Exception('Error on store: '.$e->getMessage(), $e->getCode(), $e); - } - if ($removeTemporaryFilePath) { - @unlink($temporaryFilePath); - } - } - - /** - * Delete an item in the storage service. - * - * @param string $path - * @param array $options - * @return void - */ - public function deleteItem($path, $options = null) - { - try { - $this->_storageClient->deleteBlob( - $this->_container, - $path - ); - } catch (Zend_Service_WindowsAzure_Exception $e) { - throw new Zend_Cloud_StorageService_Exception('Error on delete: '.$e->getMessage(), $e->getCode(), $e); - } - } - - /** - * Copy an item in the storage service to a given path. - * - * @param string $sourcePath - * @param string $destinationPath - * @param array $options - * @return void - */ - public function copyItem($sourcePath, $destinationPath, $options = null) - { - try { - $this->_storageClient->copyBlob( - $this->_container, - $sourcePath, - $this->_container, - $destinationPath - ); - } catch (Zend_Service_WindowsAzure_Exception $e) { - throw new Zend_Cloud_StorageService_Exception('Error on copy: '.$e->getMessage(), $e->getCode(), $e); - } - } - - /** - * Move an item in the storage service to a given path. - * - * @param string $sourcePath - * @param string $destinationPath - * @param array $options - * @return void - */ - public function moveItem($sourcePath, $destinationPath, $options = null) - { - try { - $this->_storageClient->copyBlob( - $this->_container, - $sourcePath, - $this->_container, - $destinationPath - ); - - $this->_storageClient->deleteBlob( - $this->_container, - $sourcePath - ); - } catch (Zend_Service_WindowsAzure_Exception $e) { - throw new Zend_Cloud_StorageService_Exception('Error on move: '.$e->getMessage(), $e->getCode(), $e); - } - - } - - /** - * Rename an item in the storage service to a given name. - * - * - * @param string $path - * @param string $name - * @param array $options - * @return void - */ - public function renameItem($path, $name, $options = null) - { - return $this->moveItem($path, $name, $options); - } - - /** - * List items in the given directory in the storage service - * - * The $path must be a directory - * - * - * @param string $path Must be a directory - * @param array $options - * @return array A list of item names - */ - public function listItems($path, $options = null) - { - // Options - $returnType = self::RETURN_NAMES; // 1: return list of paths, 2: return raw output from underlying provider - - // Parse options - if (is_array($options)&& isset($options[self::RETURN_TYPE])) { - $returnType = $options[self::RETURN_TYPE]; - } - - try { - // Fetch list - $blobList = $this->_storageClient->listBlobs( - $this->_container, - $path - ); - } catch (Zend_Service_WindowsAzure_Exception $e) { - throw new Zend_Cloud_StorageService_Exception('Error on list: '.$e->getMessage(), $e->getCode(), $e); - } - - // Return - if ($returnType == self::RETURN_LIST) { - return $blobList; - } - - $returnValue = array(); - foreach ($blobList as $blob) { - $returnValue[] = $blob->Name; - } - - return $returnValue; - } - - /** - * Get a key/value array of metadata for the given path. - * - * @param string $path - * @param array $options - * @return array - */ - public function fetchMetadata($path, $options = null) - { - try { - return $this->_storageClient->getBlobMetaData( - $this->_container, - $path - ); - } catch (Zend_Service_WindowsAzure_Exception $e) { - if (strpos($e->getMessage(), "could not be accessed") !== false) { - return false; - } - throw new Zend_Cloud_StorageService_Exception('Error on fetch: '.$e->getMessage(), $e->getCode(), $e); - } - } - - /** - * Store a key/value array of metadata at the given path. - * WARNING: This operation overwrites any metadata that is located at - * $destinationPath. - * - * @param string $destinationPath - * @param array $options - * @return void - */ - public function storeMetadata($destinationPath, $metadata, $options = null) - { - try { - $this->_storageClient->setBlobMetadata($this->_container, $destinationPath, $metadata); - } catch (Zend_Service_WindowsAzure_Exception $e) { - if (strpos($e->getMessage(), "could not be accessed") === false) { - throw new Zend_Cloud_StorageService_Exception('Error on store metadata: '.$e->getMessage(), $e->getCode(), $e); - } - } - } - - /** - * Delete a key/value array of metadata at the given path. - * - * @param string $path - * @param array $options - * @return void - */ - public function deleteMetadata($path, $options = null) - { - try { - $this->_storageClient->setBlobMetadata($this->_container, $destinationPath, array()); - } catch (Zend_Service_WindowsAzure_Exception $e) { - if (strpos($e->getMessage(), "could not be accessed") === false) { - throw new Zend_Cloud_StorageService_Exception('Error on delete metadata: '.$e->getMessage(), $e->getCode(), $e); - } - } - } - - /** - * Delete container - * - * @return void - */ - public function deleteContainer() - { - try { - $this->_storageClient->deleteContainer($this->_container); - } catch (Zend_Service_WindowsAzure_Exception $e) { - throw new Zend_Cloud_StorageService_Exception('Error on delete: '.$e->getMessage(), $e->getCode(), $e); - } - } - - /** - * Get the concrete adapter. - * @return Zend_Service_Azure_Storage_Blob - */ - public function getClient() - { - return $this->_storageClient; - } -} diff --git a/library/Zend/Cloud/StorageService/Exception.php b/library/Zend/Cloud/StorageService/Exception.php deleted file mode 100644 index 1364c1d663..0000000000 --- a/library/Zend/Cloud/StorageService/Exception.php +++ /dev/null @@ -1,38 +0,0 @@ -_init(); - if ($options != null) { - // use Zend_Config objects if provided - if ($options instanceof Zend_Config) { - $options = $options->toArray(); - } - // pass arrays to setOptions - if (is_array($options)) { - $this->setOptions($options); - } - } - $this->_prepare(); - } - - /** - * setConfig() - * - * @param Zend_Config $config - * @return Zend_CodeGenerator_Abstract - */ - public function setConfig(Zend_Config $config) - { - $this->setOptions($config->toArray()); - return $this; - } - - /** - * setOptions() - * - * @param array $options - * @return Zend_CodeGenerator_Abstract - */ - public function setOptions(Array $options) - { - foreach ($options as $optionName => $optionValue) { - $methodName = 'set' . $optionName; - if (method_exists($this, $methodName)) { - $this->{$methodName}($optionValue); - } - } - return $this; - } - - /** - * setSourceContent() - * - * @param string $sourceContent - */ - public function setSourceContent($sourceContent) - { - $this->_sourceContent = $sourceContent; - return; - } - - /** - * getSourceContent() - * - * @return string - */ - public function getSourceContent() - { - return $this->_sourceContent; - } - - /** - * _init() - this is called before the constuctor - * - */ - protected function _init() - { - - } - - /** - * _prepare() - this is called at construction completion - * - */ - protected function _prepare() - { - - } - - /** - * generate() - must be implemented by the child - * - */ - abstract public function generate(); - - /** - * __toString() - casting to a string will in turn call generate() - * - * @return string - */ - final public function __toString() - { - return $this->generate(); - } - -} diff --git a/library/Zend/CodeGenerator/Exception.php b/library/Zend/CodeGenerator/Exception.php deleted file mode 100644 index f4126bf035..0000000000 --- a/library/Zend/CodeGenerator/Exception.php +++ /dev/null @@ -1,35 +0,0 @@ -_isSourceDirty = ($isSourceDirty) ? true : false; - return $this; - } - - /** - * isSourceDirty() - * - * @return bool - */ - public function isSourceDirty() - { - return $this->_isSourceDirty; - } - - /** - * setIndentation() - * - * @param string|int $indentation - * @return Zend_CodeGenerator_Php_Abstract - */ - public function setIndentation($indentation) - { - $this->_indentation = $indentation; - return $this; - } - - /** - * getIndentation() - * - * @return string|int - */ - public function getIndentation() - { - return $this->_indentation; - } - -} diff --git a/library/Zend/CodeGenerator/Php/Body.php b/library/Zend/CodeGenerator/Php/Body.php deleted file mode 100644 index a3ce0683a4..0000000000 --- a/library/Zend/CodeGenerator/Php/Body.php +++ /dev/null @@ -1,73 +0,0 @@ -_content = $content; - return $this; - } - - /** - * getContent() - * - * @return string - */ - public function getContent() - { - return (string) $this->_content; - } - - /** - * generate() - * - * @return string - */ - public function generate() - { - return $this->getContent(); - } -} diff --git a/library/Zend/CodeGenerator/Php/Class.php b/library/Zend/CodeGenerator/Php/Class.php deleted file mode 100644 index d4f24cb3f3..0000000000 --- a/library/Zend/CodeGenerator/Php/Class.php +++ /dev/null @@ -1,618 +0,0 @@ -setSourceContent($class->getSourceContent()); - $class->setSourceDirty(false); - - if ($reflectionClass->getDocComment() != '') { - $class->setDocblock(Zend_CodeGenerator_Php_Docblock::fromReflection($reflectionClass->getDocblock())); - } - - $class->setAbstract($reflectionClass->isAbstract()); - $class->setName($reflectionClass->getName()); - - if ($parentClass = $reflectionClass->getParentClass()) { - $class->setExtendedClass($parentClass->getName()); - $interfaces = array_diff($reflectionClass->getInterfaces(), $parentClass->getInterfaces()); - } else { - $interfaces = $reflectionClass->getInterfaces(); - } - - $interfaceNames = array(); - foreach($interfaces AS $interface) { - $interfaceNames[] = $interface->getName(); - } - - $class->setImplementedInterfaces($interfaceNames); - - $properties = array(); - foreach ($reflectionClass->getProperties() as $reflectionProperty) { - if ($reflectionProperty->getDeclaringClass()->getName() == $class->getName()) { - $properties[] = Zend_CodeGenerator_Php_Property::fromReflection($reflectionProperty); - } - } - $class->setProperties($properties); - - $methods = array(); - foreach ($reflectionClass->getMethods() as $reflectionMethod) { - if ($reflectionMethod->getDeclaringClass()->getName() == $class->getName()) { - $methods[] = Zend_CodeGenerator_Php_Method::fromReflection($reflectionMethod); - } - } - $class->setMethods($methods); - - return $class; - } - - /** - * setDocblock() Set the docblock - * - * @param Zend_CodeGenerator_Php_Docblock|array|string $docblock - * @return Zend_CodeGenerator_Php_File - */ - public function setDocblock($docblock) - { - if (is_string($docblock)) { - $docblock = array('shortDescription' => $docblock); - } - - if (is_array($docblock)) { - $docblock = new Zend_CodeGenerator_Php_Docblock($docblock); - } elseif ((!is_null($docblock)) && (!$docblock instanceof Zend_CodeGenerator_Php_Docblock)) { - #require_once 'Zend/CodeGenerator/Php/Exception.php'; - throw new Zend_CodeGenerator_Php_Exception('setDocblock() is expecting either a string, array or an instance of Zend_CodeGenerator_Php_Docblock'); - } - - $this->_docblock = $docblock; - return $this; - } - - /** - * getDocblock() - * - * @return Zend_CodeGenerator_Php_Docblock - */ - public function getDocblock() - { - return $this->_docblock; - } - - /** - * setName() - * - * @param string $name - * @return Zend_CodeGenerator_Php_Class - */ - public function setName($name) - { - $this->_name = $name; - return $this; - } - - /** - * getName() - * - * @return string - */ - public function getName() - { - return $this->_name; - } - - /** - * setAbstract() - * - * @param bool $isAbstract - * @return Zend_CodeGenerator_Php_Class - */ - public function setAbstract($isAbstract) - { - $this->_isAbstract = ($isAbstract) ? true : false; - return $this; - } - - /** - * isAbstract() - * - * @return bool - */ - public function isAbstract() - { - return $this->_isAbstract; - } - - /** - * setExtendedClass() - * - * @param string $extendedClass - * @return Zend_CodeGenerator_Php_Class - */ - public function setExtendedClass($extendedClass) - { - $this->_extendedClass = $extendedClass; - return $this; - } - - /** - * getExtendedClass() - * - * @return string - */ - public function getExtendedClass() - { - return $this->_extendedClass; - } - - /** - * setImplementedInterfaces() - * - * @param array $implementedInterfaces - * @return Zend_CodeGenerator_Php_Class - */ - public function setImplementedInterfaces(Array $implementedInterfaces) - { - $this->_implementedInterfaces = $implementedInterfaces; - return $this; - } - - /** - * getImplementedInterfaces - * - * @return array - */ - public function getImplementedInterfaces() - { - return $this->_implementedInterfaces; - } - - /** - * setProperties() - * - * @param array $properties - * @return Zend_CodeGenerator_Php_Class - */ - public function setProperties(Array $properties) - { - foreach ($properties as $property) { - $this->setProperty($property); - } - - return $this; - } - - /** - * setConstants() - * - * @param array $constants - * @return Zend_CodeGenerator_Php_Class - */ - public function setConstants(Array $constants) - { - foreach ($constants as $const) { - $this->setConstant($const); - } - - return $this; - } - - /** - * setProperty() - * - * @param array|Zend_CodeGenerator_Php_Property $property - * @return Zend_CodeGenerator_Php_Class - */ - public function setProperty($property) - { - if (is_array($property)) { - $property = new Zend_CodeGenerator_Php_Property($property); - $propertyName = $property->getName(); - } elseif ($property instanceof Zend_CodeGenerator_Php_Property) { - $propertyName = $property->getName(); - } else { - #require_once 'Zend/CodeGenerator/Php/Exception.php'; - throw new Zend_CodeGenerator_Php_Exception('setProperty() expects either an array of property options or an instance of Zend_CodeGenerator_Php_Property'); - } - - if ($property->isConst()) { - return $this->setConstant($property); - } - if (isset($this->_properties[$propertyName])) { - #require_once 'Zend/CodeGenerator/Php/Exception.php'; - throw new Zend_CodeGenerator_Php_Exception('A property by name ' . $propertyName . ' already exists in this class.'); - } - - $this->_properties[$propertyName] = $property; - return $this; - } - - /** - * setConstant() - * - * @param array|Zend_CodeGenerator_Php_Property $const - * @return Zend_CodeGenerator_Php_Class - */ - public function setConstant($const) - { - if (is_array($const)) { - $const = new Zend_CodeGenerator_Php_Property($const); - $constName = $const->getName(); - } elseif ($const instanceof Zend_CodeGenerator_Php_Property) { - $constName = $const->getName(); - } else { - #require_once 'Zend/CodeGenerator/Php/Exception.php'; - throw new Zend_CodeGenerator_Php_Exception('setConstant() expects either an array of property options or an instance of Zend_CodeGenerator_Php_Property'); - } - - if (!$const->isConst()) { - #require_once 'Zend/CodeGenerator/Php/Exception.php'; - throw new Zend_CodeGenerator_Php_Exception('setProperty() expects argument to define a constant'); - } - if (isset($this->_constants[$constName])) { - #require_once 'Zend/CodeGenerator/Php/Exception.php'; - throw new Zend_CodeGenerator_Php_Exception('A constant by name ' . $constName . ' already exists in this class.'); - } - - $this->_constants[$constName] = $const; - return $this; - } - - /** - * getProperties() - * - * @return array - */ - public function getProperties() - { - return $this->_properties; - } - - /** - * getConstants() - * - * @return array - */ - public function getConstants() - { - return $this->_constants; - } - - /** - * getProperty() - * - * @param string $propertyName - * @return Zend_CodeGenerator_Php_Property - */ - public function getProperty($propertyName) - { - foreach ($this->_properties as $property) { - if ($property->getName() == $propertyName) { - return $property; - } - } - return false; - } - - /** - * getConstant() - * - * @param string $constName - * @return Zend_CodeGenerator_Php_Property - */ - public function getConstant($constName) - { - foreach ($this->_constants as $const) { - if ($const->getName() == $constName) { - return $const; - } - } - return false; - } - - /** - * hasProperty() - * - * @param string $propertyName - * @return bool - */ - public function hasProperty($propertyName) - { - return isset($this->_properties[$propertyName]); - } - - /** - * hasConstant() - * - * @param string $constName - * @return bool - */ - public function hasConstant($constName) - { - return isset($this->_constants[$constName]); - } - - /** - * setMethods() - * - * @param array $methods - * @return Zend_CodeGenerator_Php_Class - */ - public function setMethods(Array $methods) - { - foreach ($methods as $method) { - $this->setMethod($method); - } - return $this; - } - - /** - * setMethod() - * - * @param array|Zend_CodeGenerator_Php_Method $method - * @return Zend_CodeGenerator_Php_Class - */ - public function setMethod($method) - { - if (is_array($method)) { - $method = new Zend_CodeGenerator_Php_Method($method); - $methodName = $method->getName(); - } elseif ($method instanceof Zend_CodeGenerator_Php_Method) { - $methodName = $method->getName(); - } else { - #require_once 'Zend/CodeGenerator/Php/Exception.php'; - throw new Zend_CodeGenerator_Php_Exception('setMethod() expects either an array of method options or an instance of Zend_CodeGenerator_Php_Method'); - } - - if (isset($this->_methods[$methodName])) { - #require_once 'Zend/CodeGenerator/Php/Exception.php'; - throw new Zend_CodeGenerator_Php_Exception('A method by name ' . $methodName . ' already exists in this class.'); - } - - $this->_methods[$methodName] = $method; - return $this; - } - - /** - * getMethods() - * - * @return array - */ - public function getMethods() - { - return $this->_methods; - } - - /** - * getMethod() - * - * @param string $methodName - * @return Zend_CodeGenerator_Php_Method - */ - public function getMethod($methodName) - { - foreach ($this->_methods as $method) { - if ($method->getName() == $methodName) { - return $method; - } - } - return false; - } - - /** - * hasMethod() - * - * @param string $methodName - * @return bool - */ - public function hasMethod($methodName) - { - return isset($this->_methods[$methodName]); - } - - /** - * isSourceDirty() - * - * @return bool - */ - public function isSourceDirty() - { - if (($docblock = $this->getDocblock()) && $docblock->isSourceDirty()) { - return true; - } - - foreach ($this->_properties as $property) { - if ($property->isSourceDirty()) { - return true; - } - } - - foreach ($this->_constants as $constant) { - if ($constant->isSourceDirty()) { - return true; - } - } - - foreach ($this->_methods as $method) { - if ($method->isSourceDirty()) { - return true; - } - } - - return parent::isSourceDirty(); - } - - /** - * generate() - * - * @return string - */ - public function generate() - { - if (!$this->isSourceDirty()) { - return $this->getSourceContent(); - } - - $output = ''; - - if (null !== ($docblock = $this->getDocblock())) { - $docblock->setIndentation(''); - $output .= $docblock->generate(); - } - - if ($this->isAbstract()) { - $output .= 'abstract '; - } - - $output .= 'class ' . $this->getName(); - - if ( !empty( $this->_extendedClass) ) { - $output .= ' extends ' . $this->_extendedClass; - } - - $implemented = $this->getImplementedInterfaces(); - if (!empty($implemented)) { - $output .= ' implements ' . implode(', ', $implemented); - } - - $output .= self::LINE_FEED . '{' . self::LINE_FEED . self::LINE_FEED; - - $constants = $this->getConstants(); - if (!empty($constants)) { - foreach ($constants as $const) { - $output .= $const->generate() . self::LINE_FEED . self::LINE_FEED; - } - } - - $properties = $this->getProperties(); - if (!empty($properties)) { - foreach ($properties as $property) { - $output .= $property->generate() . self::LINE_FEED . self::LINE_FEED; - } - } - - $methods = $this->getMethods(); - if (!empty($methods)) { - foreach ($methods as $method) { - $output .= $method->generate() . self::LINE_FEED; - } - } - - $output .= self::LINE_FEED . '}' . self::LINE_FEED; - - return $output; - } - - /** - * _init() - is called at construction time - * - */ - protected function _init() - { - $this->_properties = new Zend_CodeGenerator_Php_Member_Container(Zend_CodeGenerator_Php_Member_Container::TYPE_PROPERTY); - $this->_constants = new Zend_CodeGenerator_Php_Member_Container(Zend_CodeGenerator_Php_Member_Container::TYPE_PROPERTY); - $this->_methods = new Zend_CodeGenerator_Php_Member_Container(Zend_CodeGenerator_Php_Member_Container::TYPE_METHOD); - } - -} diff --git a/library/Zend/CodeGenerator/Php/Docblock.php b/library/Zend/CodeGenerator/Php/Docblock.php deleted file mode 100644 index efefa219f6..0000000000 --- a/library/Zend/CodeGenerator/Php/Docblock.php +++ /dev/null @@ -1,227 +0,0 @@ -setSourceContent($reflectionDocblock->getContents()); - $docblock->setSourceDirty(false); - - $docblock->setShortDescription($reflectionDocblock->getShortDescription()); - $docblock->setLongDescription($reflectionDocblock->getLongDescription()); - - foreach ($reflectionDocblock->getTags() as $tag) { - $docblock->setTag(Zend_CodeGenerator_Php_Docblock_Tag::fromReflection($tag)); - } - - return $docblock; - } - - /** - * setShortDescription() - * - * @param string $shortDescription - * @return Zend_CodeGenerator_Php_Docblock - */ - public function setShortDescription($shortDescription) - { - $this->_shortDescription = $shortDescription; - return $this; - } - - /** - * getShortDescription() - * - * @return string - */ - public function getShortDescription() - { - return $this->_shortDescription; - } - - /** - * setLongDescription() - * - * @param string $longDescription - * @return Zend_CodeGenerator_Php_Docblock - */ - public function setLongDescription($longDescription) - { - $this->_longDescription = $longDescription; - return $this; - } - - /** - * getLongDescription() - * - * @return string - */ - public function getLongDescription() - { - return $this->_longDescription; - } - - /** - * setTags() - * - * @param array $tags - * @return Zend_CodeGenerator_Php_Docblock - */ - public function setTags(Array $tags) - { - foreach ($tags as $tag) { - $this->setTag($tag); - } - - return $this; - } - - /** - * setTag() - * - * @param array|Zend_CodeGenerator_Php_Docblock_Tag $tag - * @return Zend_CodeGenerator_Php_Docblock - */ - public function setTag($tag) - { - if (is_array($tag)) { - $tag = new Zend_CodeGenerator_Php_Docblock_Tag($tag); - } elseif (!$tag instanceof Zend_CodeGenerator_Php_Docblock_Tag) { - #require_once 'Zend/CodeGenerator/Php/Exception.php'; - throw new Zend_CodeGenerator_Php_Exception( - 'setTag() expects either an array of method options or an ' - . 'instance of Zend_CodeGenerator_Php_Docblock_Tag' - ); - } - - $this->_tags[] = $tag; - return $this; - } - - /** - * getTags - * - * @return array Array of Zend_CodeGenerator_Php_Docblock_Tag - */ - public function getTags() - { - return $this->_tags; - } - - /** - * generate() - * - * @return string - */ - public function generate() - { - if (!$this->isSourceDirty()) { - return $this->_docCommentize($this->getSourceContent()); - } - - $output = ''; - if (null !== ($sd = $this->getShortDescription())) { - $output .= $sd . self::LINE_FEED . self::LINE_FEED; - } - if (null !== ($ld = $this->getLongDescription())) { - $output .= $ld . self::LINE_FEED . self::LINE_FEED; - } - - foreach ($this->getTags() as $tag) { - $output .= $tag->generate() . self::LINE_FEED; - } - - return $this->_docCommentize(trim($output)); - } - - /** - * _docCommentize() - * - * @param string $content - * @return string - */ - protected function _docCommentize($content) - { - $indent = $this->getIndentation(); - $output = $indent . '/**' . self::LINE_FEED; - $content = wordwrap($content, 80, self::LINE_FEED); - $lines = explode(self::LINE_FEED, $content); - - foreach ($lines as $line) { - $output .= $indent . ' *'; - if ($line) { - $output .= " $line"; - } - $output .= self::LINE_FEED; - } - - $output = rtrim($output, ' *' . self::LINE_FEED) . self::LINE_FEED; - - $output .= $indent . ' */' . self::LINE_FEED; - return $output; - } -} diff --git a/library/Zend/CodeGenerator/Php/Docblock/Tag.php b/library/Zend/CodeGenerator/Php/Docblock/Tag.php deleted file mode 100644 index 2eede59624..0000000000 --- a/library/Zend/CodeGenerator/Php/Docblock/Tag.php +++ /dev/null @@ -1,178 +0,0 @@ -getName(); - - $codeGenDocblockTag = self::factory($tagName); - - // transport any properties via accessors and mutators from reflection to codegen object - $reflectionClass = new ReflectionClass($reflectionTag); - foreach ($reflectionClass->getMethods(ReflectionMethod::IS_PUBLIC) as $method) { - if (substr($method->getName(), 0, 3) == 'get') { - $propertyName = substr($method->getName(), 3); - if (method_exists($codeGenDocblockTag, 'set' . $propertyName)) { - $codeGenDocblockTag->{'set' . $propertyName}($reflectionTag->{'get' . $propertyName}()); - } - } - } - - return $codeGenDocblockTag; - } - - /** - * setPluginLoader() - * - * @param Zend_Loader_PluginLoader $pluginLoader - */ - public static function setPluginLoader(Zend_Loader_PluginLoader $pluginLoader) - { - self::$_pluginLoader = $pluginLoader; - return; - } - - /** - * getPluginLoader() - * - * @return Zend_Loader_PluginLoader - */ - public static function getPluginLoader() - { - if (self::$_pluginLoader == null) { - #require_once 'Zend/Loader/PluginLoader.php'; - self::setPluginLoader(new Zend_Loader_PluginLoader(array( - 'Zend_CodeGenerator_Php_Docblock_Tag' => dirname(__FILE__) . '/Tag/')) - ); - } - - return self::$_pluginLoader; - } - - public static function factory($tagName) - { - $pluginLoader = self::getPluginLoader(); - - try { - $tagClass = $pluginLoader->load($tagName); - } catch (Zend_Loader_Exception $exception) { - $tagClass = 'Zend_CodeGenerator_Php_Docblock_Tag'; - } - - $tag = new $tagClass(array('name' => $tagName)); - return $tag; - } - - /** - * setName() - * - * @param string $name - * @return Zend_CodeGenerator_Php_Docblock_Tag - */ - public function setName($name) - { - $this->_name = ltrim($name, '@'); - return $this; - } - - /** - * getName() - * - * @return string - */ - public function getName() - { - return $this->_name; - } - - /** - * setDescription() - * - * @param string $description - * @return Zend_CodeGenerator_Php_Docblock_Tag - */ - public function setDescription($description) - { - $this->_description = $description; - return $this; - } - - /** - * getDescription() - * - * @return string - */ - public function getDescription() - { - return $this->_description; - } - - /** - * generate() - * - * @return string - */ - public function generate() - { - $tag = '@' . $this->_name; - if ($this->_description) { - $tag .= ' ' . $this->_description; - } - return $tag; - } - -} diff --git a/library/Zend/CodeGenerator/Php/Docblock/Tag/License.php b/library/Zend/CodeGenerator/Php/Docblock/Tag/License.php deleted file mode 100644 index a588ad1611..0000000000 --- a/library/Zend/CodeGenerator/Php/Docblock/Tag/License.php +++ /dev/null @@ -1,98 +0,0 @@ -setName('license'); - $returnTag->setUrl($reflectionTagLicense->getUrl()); - $returnTag->setDescription($reflectionTagLicense->getDescription()); - - return $returnTag; - } - - /** - * setUrl() - * - * @param string $url - * @return Zend_CodeGenerator_Php_Docblock_Tag_License - */ - public function setUrl($url) - { - $this->_url = $url; - return $this; - } - - /** - * getUrl() - * - * @return string - */ - public function getUrl() - { - return $this->_url; - } - - - /** - * generate() - * - * @return string - */ - public function generate() - { - $output = '@license ' . $this->_url . ' ' . $this->_description . self::LINE_FEED; - return $output; - } - -} diff --git a/library/Zend/CodeGenerator/Php/Docblock/Tag/Param.php b/library/Zend/CodeGenerator/Php/Docblock/Tag/Param.php deleted file mode 100644 index 19d3326e48..0000000000 --- a/library/Zend/CodeGenerator/Php/Docblock/Tag/Param.php +++ /dev/null @@ -1,128 +0,0 @@ -setName('param'); - $paramTag->setDatatype($reflectionTagParam->getType()); // @todo rename - $paramTag->setParamName($reflectionTagParam->getVariableName()); - $paramTag->setDescription($reflectionTagParam->getDescription()); - - return $paramTag; - } - - /** - * setDatatype() - * - * @param string $datatype - * @return Zend_CodeGenerator_Php_Docblock_Tag_Param - */ - public function setDatatype($datatype) - { - $this->_datatype = $datatype; - return $this; - } - - /** - * getDatatype - * - * @return string - */ - public function getDatatype() - { - return $this->_datatype; - } - - /** - * setParamName() - * - * @param string $paramName - * @return Zend_CodeGenerator_Php_Docblock_Tag_Param - */ - public function setParamName($paramName) - { - $this->_paramName = $paramName; - return $this; - } - - /** - * getParamName() - * - * @return string - */ - public function getParamName() - { - return $this->_paramName; - } - - /** - * generate() - * - * @return string - */ - public function generate() - { - $output = '@param ' - . (($this->_datatype != null) ? $this->_datatype : 'unknown') - . (($this->_paramName != null) ? ' $' . $this->_paramName : '') - . (($this->_description != null) ? ' ' . $this->_description : ''); - return $output; - } - -} diff --git a/library/Zend/CodeGenerator/Php/Docblock/Tag/Return.php b/library/Zend/CodeGenerator/Php/Docblock/Tag/Return.php deleted file mode 100644 index f4a0b1a474..0000000000 --- a/library/Zend/CodeGenerator/Php/Docblock/Tag/Return.php +++ /dev/null @@ -1,98 +0,0 @@ -setName('return'); - $returnTag->setDatatype($reflectionTagReturn->getType()); // @todo rename - $returnTag->setDescription($reflectionTagReturn->getDescription()); - - return $returnTag; - } - - /** - * setDatatype() - * - * @param string $datatype - * @return Zend_CodeGenerator_Php_Docblock_Tag_Return - */ - public function setDatatype($datatype) - { - $this->_datatype = $datatype; - return $this; - } - - /** - * getDatatype() - * - * @return string - */ - public function getDatatype() - { - return $this->_datatype; - } - - - /** - * generate() - * - * @return string - */ - public function generate() - { - $output = '@return ' . $this->_datatype . ' ' . $this->_description; - return $output; - } - -} diff --git a/library/Zend/CodeGenerator/Php/Exception.php b/library/Zend/CodeGenerator/Php/Exception.php deleted file mode 100644 index bb4ccd9af4..0000000000 --- a/library/Zend/CodeGenerator/Php/Exception.php +++ /dev/null @@ -1,37 +0,0 @@ -getFilename(); - } - - if ($fileName == '') { - #require_once 'Zend/CodeGenerator/Php/Exception.php'; - throw new Zend_CodeGenerator_Php_Exception('FileName does not exist.'); - } - - // cannot use realpath since the file might not exist, but we do need to have the index - // in the same DIRECTORY_SEPARATOR that realpath would use: - $fileName = str_replace(array('\\', '/'), DIRECTORY_SEPARATOR, $fileName); - - self::$_fileCodeGenerators[$fileName] = $fileCodeGenerator; - - } - - /** - * fromReflectedFileName() - use this if you intend on generating code generation objects based on the same file. - * This will keep previous changes to the file in tact during the same PHP process - * - * @param string $filePath - * @param bool $usePreviousCodeGeneratorIfItExists - * @param bool $includeIfNotAlreadyIncluded - * @return Zend_CodeGenerator_Php_File - */ - public static function fromReflectedFileName($filePath, $usePreviousCodeGeneratorIfItExists = true, $includeIfNotAlreadyIncluded = true) - { - $realpath = realpath($filePath); - - if ($realpath === false) { - if ( ($realpath = Zend_Reflection_File::findRealpathInIncludePath($filePath)) === false) { - #require_once 'Zend/CodeGenerator/Php/Exception.php'; - throw new Zend_CodeGenerator_Php_Exception('No file for ' . $realpath . ' was found.'); - } - } - - if ($usePreviousCodeGeneratorIfItExists && isset(self::$_fileCodeGenerators[$realpath])) { - return self::$_fileCodeGenerators[$realpath]; - } - - if ($includeIfNotAlreadyIncluded && !in_array($realpath, get_included_files())) { - include $realpath; - } - - $codeGenerator = self::fromReflection(($fileReflector = new Zend_Reflection_File($realpath))); - - if (!isset(self::$_fileCodeGenerators[$fileReflector->getFileName()])) { - self::$_fileCodeGenerators[$fileReflector->getFileName()] = $codeGenerator; - } - - return $codeGenerator; - } - - /** - * fromReflection() - * - * @param Zend_Reflection_File $reflectionFile - * @return Zend_CodeGenerator_Php_File - */ - public static function fromReflection(Zend_Reflection_File $reflectionFile) - { - $file = new self(); - - $file->setSourceContent($reflectionFile->getContents()); - $file->setSourceDirty(false); - - $body = $reflectionFile->getContents(); - - // @todo this whole area needs to be reworked with respect to how body lines are processed - foreach ($reflectionFile->getClasses() as $class) { - $file->setClass(Zend_CodeGenerator_Php_Class::fromReflection($class)); - $classStartLine = $class->getStartLine(true); - $classEndLine = $class->getEndLine(); - - $bodyLines = explode("\n", $body); - $bodyReturn = array(); - for ($lineNum = 1; $lineNum <= count($bodyLines); $lineNum++) { - if ($lineNum == $classStartLine) { - $bodyReturn[] = str_replace('?', $class->getName(), self::$_markerClass); //'/* Zend_CodeGenerator_Php_File-ClassMarker: {' . $class->getName() . '} */'; - $lineNum = $classEndLine; - } else { - $bodyReturn[] = $bodyLines[$lineNum - 1]; // adjust for index -> line conversion - } - } - $body = implode("\n", $bodyReturn); - unset($bodyLines, $bodyReturn, $classStartLine, $classEndLine); - } - - if (($reflectionFile->getDocComment() != '')) { - $docblock = $reflectionFile->getDocblock(); - $file->setDocblock(Zend_CodeGenerator_Php_Docblock::fromReflection($docblock)); - - $bodyLines = explode("\n", $body); - $bodyReturn = array(); - for ($lineNum = 1; $lineNum <= count($bodyLines); $lineNum++) { - if ($lineNum == $docblock->getStartLine()) { - $bodyReturn[] = str_replace('?', $class->getName(), self::$_markerDocblock); //'/* Zend_CodeGenerator_Php_File-ClassMarker: {' . $class->getName() . '} */'; - $lineNum = $docblock->getEndLine(); - } else { - $bodyReturn[] = $bodyLines[$lineNum - 1]; // adjust for index -> line conversion - } - } - $body = implode("\n", $bodyReturn); - unset($bodyLines, $bodyReturn, $classStartLine, $classEndLine); - } - - $file->setBody($body); - - return $file; - } - - /** - * setDocblock() Set the docblock - * - * @param Zend_CodeGenerator_Php_Docblock|array|string $docblock - * @return Zend_CodeGenerator_Php_File - */ - public function setDocblock($docblock) - { - if (is_string($docblock)) { - $docblock = array('shortDescription' => $docblock); - } - - if (is_array($docblock)) { - $docblock = new Zend_CodeGenerator_Php_Docblock($docblock); - } elseif (!$docblock instanceof Zend_CodeGenerator_Php_Docblock) { - #require_once 'Zend/CodeGenerator/Php/Exception.php'; - throw new Zend_CodeGenerator_Php_Exception('setDocblock() is expecting either a string, array or an instance of Zend_CodeGenerator_Php_Docblock'); - } - - $this->_docblock = $docblock; - return $this; - } - - /** - * Get docblock - * - * @return Zend_CodeGenerator_Php_Docblock - */ - public function getDocblock() - { - return $this->_docblock; - } - - /** - * setRequiredFiles - * - * @param array $requiredFiles - * @return Zend_CodeGenerator_Php_File - */ - public function setRequiredFiles($requiredFiles) - { - $this->_requiredFiles = $requiredFiles; - return $this; - } - - /** - * getRequiredFiles() - * - * @return array - */ - public function getRequiredFiles() - { - return $this->_requiredFiles; - } - - /** - * setClasses() - * - * @param array $classes - * @return Zend_CodeGenerator_Php_File - */ - public function setClasses(Array $classes) - { - foreach ($classes as $class) { - $this->setClass($class); - } - return $this; - } - - /** - * getClass() - * - * @param string $name - * @return Zend_CodeGenerator_Php_Class - */ - public function getClass($name = null) - { - if ($name == null) { - reset($this->_classes); - return current($this->_classes); - } - - return $this->_classes[$name]; - } - - /** - * setClass() - * - * @param Zend_CodeGenerator_Php_Class|array $class - * @return Zend_CodeGenerator_Php_File - */ - public function setClass($class) - { - if (is_array($class)) { - $class = new Zend_CodeGenerator_Php_Class($class); - $className = $class->getName(); - } elseif ($class instanceof Zend_CodeGenerator_Php_Class) { - $className = $class->getName(); - } else { - #require_once 'Zend/CodeGenerator/Php/Exception.php'; - throw new Zend_CodeGenerator_Php_Exception('Expecting either an array or an instance of Zend_CodeGenerator_Php_Class'); - } - - // @todo check for dup here - - $this->_classes[$className] = $class; - return $this; - } - - /** - * setFilename() - * - * @param string $filename - * @return Zend_CodeGenerator_Php_File - */ - public function setFilename($filename) - { - $this->_filename = $filename; - return $this; - } - - /** - * getFilename() - * - * @return string - */ - public function getFilename() - { - return $this->_filename; - } - - /** - * getClasses() - * - * @return array Array of Zend_CodeGenerator_Php_Class - */ - public function getClasses() - { - return $this->_classes; - } - - /** - * setBody() - * - * @param string $body - * @return Zend_CodeGenerator_Php_File - */ - public function setBody($body) - { - $this->_body = $body; - return $this; - } - - /** - * getBody() - * - * @return string - */ - public function getBody() - { - return $this->_body; - } - - /** - * isSourceDirty() - * - * @return bool - */ - public function isSourceDirty() - { - if (($docblock = $this->getDocblock()) && $docblock->isSourceDirty()) { - return true; - } - - foreach ($this->_classes as $class) { - if ($class->isSourceDirty()) { - return true; - } - } - - return parent::isSourceDirty(); - } - - /** - * generate() - * - * @return string - */ - public function generate() - { - if ($this->isSourceDirty() === false) { - return $this->_sourceContent; - } - - $output = ''; - - // start with the body (if there), or open tag - if (preg_match('#(?:\s*)<\?php#', $this->getBody()) == false) { - $output = 'getBody(); - if (preg_match('#/\* Zend_CodeGenerator_Php_File-(.*?)Marker#', $body)) { - $output .= $body; - $body = ''; - } - - // Add file docblock, if any - if (null !== ($docblock = $this->getDocblock())) { - $docblock->setIndentation(''); - $regex = preg_quote(self::$_markerDocblock, '#'); - if (preg_match('#'.$regex.'#', $output)) { - $output = preg_replace('#'.$regex.'#', $docblock->generate(), $output, 1); - } else { - $output .= $docblock->generate() . self::LINE_FEED; - } - } - - // newline - $output .= self::LINE_FEED; - - // process required files - // @todo marker replacement for required files - $requiredFiles = $this->getRequiredFiles(); - if (!empty($requiredFiles)) { - foreach ($requiredFiles as $requiredFile) { - $output .= 'require_once \'' . $requiredFile . '\';' . self::LINE_FEED; - } - - $output .= self::LINE_FEED; - } - - // process classes - $classes = $this->getClasses(); - if (!empty($classes)) { - foreach ($classes as $class) { - if($this->getDocblock() == $class->getDocblock()) { - $class->setDocblock(null); - } - $regex = str_replace('?', $class->getName(), self::$_markerClass); - $regex = preg_quote($regex, '#'); - if (preg_match('#'.$regex.'#', $output)) { - $output = preg_replace('#'.$regex.'#', $class->generate(), $output, 1); - } else { - $output .= $class->generate() . self::LINE_FEED; - } - } - - } - - if (!empty($body)) { - - // add an extra space betwee clsses and - if (!empty($classes)) { - $output .= self::LINE_FEED; - } - - $output .= $body; - } - - return $output; - } - - public function write() - { - if ($this->_filename == '' || !is_writable(dirname($this->_filename))) { - #require_once 'Zend/CodeGenerator/Php/Exception.php'; - throw new Zend_CodeGenerator_Php_Exception('This code generator object is not writable.'); - } - file_put_contents($this->_filename, $this->generate()); - return $this; - } - -} diff --git a/library/Zend/CodeGenerator/Php/Member/Abstract.php b/library/Zend/CodeGenerator/Php/Member/Abstract.php deleted file mode 100644 index 9896d420fa..0000000000 --- a/library/Zend/CodeGenerator/Php/Member/Abstract.php +++ /dev/null @@ -1,222 +0,0 @@ - $docblock); - } - - if (is_array($docblock)) { - $docblock = new Zend_CodeGenerator_Php_Docblock($docblock); - } elseif (!$docblock instanceof Zend_CodeGenerator_Php_Docblock) { - #require_once 'Zend/CodeGenerator/Php/Exception.php'; - throw new Zend_CodeGenerator_Php_Exception('setDocblock() is expecting either a string, array or an instance of Zend_CodeGenerator_Php_Docblock'); - } - - $this->_docblock = $docblock; - return $this; - } - - /** - * getDocblock() - * - * @return Zend_CodeGenerator_Php_Docblock - */ - public function getDocblock() - { - return $this->_docblock; - } - - /** - * setAbstract() - * - * @param bool $isAbstract - * @return Zend_CodeGenerator_Php_Member_Abstract - */ - public function setAbstract($isAbstract) - { - $this->_isAbstract = ($isAbstract) ? true : false; - return $this; - } - - /** - * isAbstract() - * - * @return bool - */ - public function isAbstract() - { - return $this->_isAbstract; - } - - /** - * setFinal() - * - * @param bool $isFinal - * @return Zend_CodeGenerator_Php_Member_Abstract - */ - public function setFinal($isFinal) - { - $this->_isFinal = ($isFinal) ? true : false; - return $this; - } - - /** - * isFinal() - * - * @return bool - */ - public function isFinal() - { - return $this->_isFinal; - } - - /** - * setStatic() - * - * @param bool $isStatic - * @return Zend_CodeGenerator_Php_Member_Abstract - */ - public function setStatic($isStatic) - { - $this->_isStatic = ($isStatic) ? true : false; - return $this; - } - - /** - * isStatic() - * - * @return bool - */ - public function isStatic() - { - return $this->_isStatic; - } - - /** - * setVisitibility() - * - * @param const $visibility - * @return Zend_CodeGenerator_Php_Member_Abstract - */ - public function setVisibility($visibility) - { - $this->_visibility = $visibility; - return $this; - } - - /** - * getVisibility() - * - * @return const - */ - public function getVisibility() - { - return $this->_visibility; - } - - /** - * setName() - * - * @param string $name - * @return Zend_CodeGenerator_Php_Member_Abstract - */ - public function setName($name) - { - $this->_name = $name; - return $this; - } - - /** - * getName() - * - * @return string - */ - public function getName() - { - return $this->_name; - } -} diff --git a/library/Zend/CodeGenerator/Php/Member/Container.php b/library/Zend/CodeGenerator/Php/Member/Container.php deleted file mode 100644 index d792f13070..0000000000 --- a/library/Zend/CodeGenerator/Php/Member/Container.php +++ /dev/null @@ -1,55 +0,0 @@ -_type = $type; - parent::__construct(array(), self::ARRAY_AS_PROPS); - } - -} diff --git a/library/Zend/CodeGenerator/Php/Method.php b/library/Zend/CodeGenerator/Php/Method.php deleted file mode 100644 index abf2de7677..0000000000 --- a/library/Zend/CodeGenerator/Php/Method.php +++ /dev/null @@ -1,236 +0,0 @@ -setSourceContent($reflectionMethod->getContents(false)); - $method->setSourceDirty(false); - - if ($reflectionMethod->getDocComment() != '') { - $method->setDocblock(Zend_CodeGenerator_Php_Docblock::fromReflection($reflectionMethod->getDocblock())); - } - - $method->setFinal($reflectionMethod->isFinal()); - - if ($reflectionMethod->isPrivate()) { - $method->setVisibility(self::VISIBILITY_PRIVATE); - } elseif ($reflectionMethod->isProtected()) { - $method->setVisibility(self::VISIBILITY_PROTECTED); - } else { - $method->setVisibility(self::VISIBILITY_PUBLIC); - } - - $method->setStatic($reflectionMethod->isStatic()); - - $method->setName($reflectionMethod->getName()); - - foreach ($reflectionMethod->getParameters() as $reflectionParameter) { - $method->setParameter(Zend_CodeGenerator_Php_Parameter::fromReflection($reflectionParameter)); - } - - $method->setBody($reflectionMethod->getBody()); - - return $method; - } - - /** - * setFinal() - * - * @param bool $isFinal - */ - public function setFinal($isFinal) - { - $this->_isFinal = ($isFinal) ? true : false; - } - - /** - * setParameters() - * - * @param array $parameters - * @return Zend_CodeGenerator_Php_Method - */ - public function setParameters(Array $parameters) - { - foreach ($parameters as $parameter) { - $this->setParameter($parameter); - } - return $this; - } - - /** - * setParameter() - * - * @param Zend_CodeGenerator_Php_Parameter|array $parameter - * @return Zend_CodeGenerator_Php_Method - */ - public function setParameter($parameter) - { - if (is_array($parameter)) { - $parameter = new Zend_CodeGenerator_Php_Parameter($parameter); - $parameterName = $parameter->getName(); - } elseif ($parameter instanceof Zend_CodeGenerator_Php_Parameter) { - $parameterName = $parameter->getName(); - } else { - #require_once 'Zend/CodeGenerator/Php/Exception.php'; - throw new Zend_CodeGenerator_Php_Exception('setParameter() expects either an array of method options or an instance of Zend_CodeGenerator_Php_Parameter'); - } - - $this->_parameters[$parameterName] = $parameter; - return $this; - } - - /** - * getParameters() - * - * @return array Array of Zend_CodeGenerator_Php_Parameter - */ - public function getParameters() - { - return $this->_parameters; - } - - /** - * setBody() - * - * @param string $body - * @return Zend_CodeGenerator_Php_Method - */ - public function setBody($body) - { - $this->_body = $body; - return $this; - } - - /** - * getBody() - * - * @return string - */ - public function getBody() - { - return $this->_body; - } - - /** - * generate() - * - * @return string - */ - public function generate() - { - $output = ''; - - $indent = $this->getIndentation(); - - if (($docblock = $this->getDocblock()) !== null) { - $docblock->setIndentation($indent); - $output .= $docblock->generate(); - } - - $output .= $indent; - - if ($this->isAbstract()) { - $output .= 'abstract '; - } else { - $output .= (($this->isFinal()) ? 'final ' : ''); - } - - $output .= $this->getVisibility() - . (($this->isStatic()) ? ' static' : '') - . ' function ' . $this->getName() . '('; - - $parameters = $this->getParameters(); - if (!empty($parameters)) { - foreach ($parameters as $parameter) { - $parameterOuput[] = $parameter->generate(); - } - - $output .= implode(', ', $parameterOuput); - } - - $output .= ')' . self::LINE_FEED . $indent . '{' . self::LINE_FEED; - - if ($this->_body && $this->isSourceDirty()) { - $output .= ' ' - . str_replace(self::LINE_FEED, self::LINE_FEED . $indent . $indent, trim($this->_body)) - . self::LINE_FEED; - } elseif ($this->_body) { - $output .= $this->_body . self::LINE_FEED; - } - - $output .= $indent . '}' . self::LINE_FEED; - - return $output; - } - -} diff --git a/library/Zend/CodeGenerator/Php/Parameter.php b/library/Zend/CodeGenerator/Php/Parameter.php deleted file mode 100644 index 1fa398efb5..0000000000 --- a/library/Zend/CodeGenerator/Php/Parameter.php +++ /dev/null @@ -1,250 +0,0 @@ -setName($reflectionParameter->getName()); - - if($reflectionParameter->isArray()) { - $param->setType('array'); - } else { - $typeClass = $reflectionParameter->getClass(); - if($typeClass !== null) { - $param->setType($typeClass->getName()); - } - } - - $param->setPosition($reflectionParameter->getPosition()); - - if($reflectionParameter->isOptional()) { - $param->setDefaultValue($reflectionParameter->getDefaultValue()); - } - $param->setPassedByReference($reflectionParameter->isPassedByReference()); - - return $param; - } - - /** - * setType() - * - * @param string $type - * @return Zend_CodeGenerator_Php_Parameter - */ - public function setType($type) - { - $this->_type = $type; - return $this; - } - - /** - * getType() - * - * @return string - */ - public function getType() - { - return $this->_type; - } - - /** - * setName() - * - * @param string $name - * @return Zend_CodeGenerator_Php_Parameter - */ - public function setName($name) - { - $this->_name = $name; - return $this; - } - - /** - * getName() - * - * @return string - */ - public function getName() - { - return $this->_name; - } - - /** - * Set the default value of the parameter. - * - * Certain variables are difficult to expres - * - * @param null|bool|string|int|float|Zend_CodeGenerator_Php_Parameter_DefaultValue $defaultValue - * @return Zend_CodeGenerator_Php_Parameter - */ - public function setDefaultValue($defaultValue) - { - if($defaultValue === null) { - $this->_defaultValue = new Zend_CodeGenerator_Php_Parameter_DefaultValue("null"); - } else if(is_array($defaultValue)) { - $defaultValue = str_replace(array("\r", "\n"), "", var_export($defaultValue, true)); - $this->_defaultValue = new Zend_CodeGenerator_Php_Parameter_DefaultValue($defaultValue); - } else if(is_bool($defaultValue)) { - if($defaultValue == true) { - $this->_defaultValue = new Zend_CodeGenerator_Php_Parameter_DefaultValue("true"); - } else { - $this->_defaultValue = new Zend_CodeGenerator_Php_Parameter_DefaultValue("false"); - } - } else { - $this->_defaultValue = $defaultValue; - } - return $this; - } - - /** - * getDefaultValue() - * - * @return string - */ - public function getDefaultValue() - { - return $this->_defaultValue; - } - - /** - * setPosition() - * - * @param int $position - * @return Zend_CodeGenerator_Php_Parameter - */ - public function setPosition($position) - { - $this->_position = $position; - return $this; - } - - /** - * getPosition() - * - * @return int - */ - public function getPosition() - { - return $this->_position; - } - - /** - * @return bool - */ - public function getPassedByReference() - { - return $this->_passedByReference; - } - - /** - * @param bool $passedByReference - * @return Zend_CodeGenerator_Php_Parameter - */ - public function setPassedByReference($passedByReference) - { - $this->_passedByReference = $passedByReference; - return $this; - } - - /** - * generate() - * - * @return string - */ - public function generate() - { - $output = ''; - - if ($this->_type) { - $output .= $this->_type . ' '; - } - - if($this->_passedByReference === true) { - $output .= '&'; - } - - $output .= '$' . $this->_name; - - if ($this->_defaultValue !== null) { - $output .= ' = '; - if (is_string($this->_defaultValue)) { - $output .= '\'' . $this->_defaultValue . '\''; - } else if($this->_defaultValue instanceof Zend_CodeGenerator_Php_Parameter_DefaultValue) { - $output .= (string)$this->_defaultValue; - } else { - $output .= $this->_defaultValue; - } - } - - return $output; - } - -} diff --git a/library/Zend/CodeGenerator/Php/Parameter/DefaultValue.php b/library/Zend/CodeGenerator/Php/Parameter/DefaultValue.php deleted file mode 100644 index 8518ece182..0000000000 --- a/library/Zend/CodeGenerator/Php/Parameter/DefaultValue.php +++ /dev/null @@ -1,60 +0,0 @@ -_defaultValue = $defaultValue; - } - - public function __toString() - { - return $this->_defaultValue; - } -} diff --git a/library/Zend/CodeGenerator/Php/Property.php b/library/Zend/CodeGenerator/Php/Property.php deleted file mode 100644 index 39bcc128cd..0000000000 --- a/library/Zend/CodeGenerator/Php/Property.php +++ /dev/null @@ -1,179 +0,0 @@ -setName($reflectionProperty->getName()); - - $allDefaultProperties = $reflectionProperty->getDeclaringClass()->getDefaultProperties(); - - $property->setDefaultValue($allDefaultProperties[$reflectionProperty->getName()]); - - if ($reflectionProperty->getDocComment() != '') { - $property->setDocblock(Zend_CodeGenerator_Php_Docblock::fromReflection($reflectionProperty->getDocComment())); - } - - if ($reflectionProperty->isStatic()) { - $property->setStatic(true); - } - - if ($reflectionProperty->isPrivate()) { - $property->setVisibility(self::VISIBILITY_PRIVATE); - } elseif ($reflectionProperty->isProtected()) { - $property->setVisibility(self::VISIBILITY_PROTECTED); - } else { - $property->setVisibility(self::VISIBILITY_PUBLIC); - } - - $property->setSourceDirty(false); - - return $property; - } - - /** - * setConst() - * - * @param bool $const - * @return Zend_CodeGenerator_Php_Property - */ - public function setConst($const) - { - $this->_isConst = $const; - return $this; - } - - /** - * isConst() - * - * @return bool - */ - public function isConst() - { - return ($this->_isConst) ? true : false; - } - - /** - * setDefaultValue() - * - * @param Zend_CodeGenerator_Php_Property_DefaultValue|string|array $defaultValue - * @return Zend_CodeGenerator_Php_Property - */ - public function setDefaultValue($defaultValue) - { - // if it looks like - if (is_array($defaultValue) - && array_key_exists('value', $defaultValue) - && array_key_exists('type', $defaultValue)) { - $defaultValue = new Zend_CodeGenerator_Php_Property_DefaultValue($defaultValue); - } - - if (!($defaultValue instanceof Zend_CodeGenerator_Php_Property_DefaultValue)) { - $defaultValue = new Zend_CodeGenerator_Php_Property_DefaultValue(array('value' => $defaultValue)); - } - - $this->_defaultValue = $defaultValue; - return $this; - } - - /** - * getDefaultValue() - * - * @return Zend_CodeGenerator_Php_Property_DefaultValue - */ - public function getDefaultValue() - { - return $this->_defaultValue; - } - - /** - * generate() - * - * @return string - */ - public function generate() - { - $name = $this->getName(); - $defaultValue = $this->getDefaultValue(); - - $output = ''; - - if (($docblock = $this->getDocblock()) !== null) { - $docblock->setIndentation(' '); - $output .= $docblock->generate(); - } - - if ($this->isConst()) { - if ($defaultValue != null && !$defaultValue->isValidConstantType()) { - #require_once 'Zend/CodeGenerator/Php/Exception.php'; - throw new Zend_CodeGenerator_Php_Exception('The property ' . $this->_name . ' is said to be ' - . 'constant but does not have a valid constant value.'); - } - $output .= $this->_indentation . 'const ' . $name . ' = ' - . (($defaultValue !== null) ? $defaultValue->generate() : 'null;'); - } else { - $output .= $this->_indentation - . $this->getVisibility() - . (($this->isStatic()) ? ' static' : '') - . ' $' . $name . ' = ' - . (($defaultValue !== null) ? $defaultValue->generate() : 'null;'); - } - return $output; - } - -} diff --git a/library/Zend/CodeGenerator/Php/Property/DefaultValue.php b/library/Zend/CodeGenerator/Php/Property/DefaultValue.php deleted file mode 100644 index 4679d0a45f..0000000000 --- a/library/Zend/CodeGenerator/Php/Property/DefaultValue.php +++ /dev/null @@ -1,325 +0,0 @@ -getConstants(); - unset($reflect); - } - } - - /** - * isValidConstantType() - * - * @return bool - */ - public function isValidConstantType() - { - if ($this->_type == self::TYPE_AUTO) { - $type = $this->_getAutoDeterminedType($this->_value); - } else { - $type = $this->_type; - } - - // valid types for constants - $scalarTypes = array( - self::TYPE_BOOLEAN, - self::TYPE_BOOL, - self::TYPE_NUMBER, - self::TYPE_INTEGER, - self::TYPE_INT, - self::TYPE_FLOAT, - self::TYPE_DOUBLE, - self::TYPE_STRING, - self::TYPE_CONSTANT, - self::TYPE_NULL - ); - - return in_array($type, $scalarTypes); - } - - /** - * setValue() - * - * @param mixed $value - * @return Zend_CodeGenerator_Php_Property_DefaultValue - */ - public function setValue($value) - { - $this->_value = $value; - return $this; - } - - /** - * getValue() - * - * @return mixed - */ - public function getValue() - { - return $this->_value; - } - - /** - * setType() - * - * @param string $type - * @return Zend_CodeGenerator_Php_Property_DefaultValue - */ - public function setType($type) - { - $this->_type = $type; - return $this; - } - - /** - * getType() - * - * @return string - */ - public function getType() - { - return $this->_type; - } - - /** - * setArrayDepth() - * - * @param int $arrayDepth - * @return Zend_CodeGenerator_Php_Property_DefaultValue - */ - public function setArrayDepth($arrayDepth) - { - $this->_arrayDepth = $arrayDepth; - return $this; - } - - /** - * getArrayDepth() - * - * @return int - */ - public function getArrayDepth() - { - return $this->_arrayDepth; - } - - /** - * _getValidatedType() - * - * @param string $type - * @return string - */ - protected function _getValidatedType($type) - { - if (($constName = array_search($type, self::$_constants)) !== false) { - return $type; - } - - return self::TYPE_AUTO; - } - - /** - * _getAutoDeterminedType() - * - * @param mixed $value - * @return string - */ - public function _getAutoDeterminedType($value) - { - switch (gettype($value)) { - case 'boolean': - return self::TYPE_BOOLEAN; - case 'integer': - return self::TYPE_INT; - case 'string': - return self::TYPE_STRING; - case 'double': - case 'float': - case 'integer': - return self::TYPE_NUMBER; - case 'array': - return self::TYPE_ARRAY; - case 'NULL': - return self::TYPE_NULL; - case 'object': - case 'resource': - case 'unknown type': - default: - return self::TYPE_OTHER; - } - } - - /** - * generate() - * - * @return string - */ - public function generate() - { - $type = $this->_type; - - if ($type != self::TYPE_AUTO) { - $type = $this->_getValidatedType($type); - } - - $value = $this->_value; - - if ($type == self::TYPE_AUTO) { - $type = $this->_getAutoDeterminedType($value); - - if ($type == self::TYPE_ARRAY) { - $rii = new RecursiveIteratorIterator( - $it = new RecursiveArrayIterator($value), - RecursiveIteratorIterator::SELF_FIRST - ); - foreach ($rii as $curKey => $curValue) { - if (!$curValue instanceof Zend_CodeGenerator_Php_Property_DefaultValue) { - $curValue = new self(array('value' => $curValue)); - $rii->getSubIterator()->offsetSet($curKey, $curValue); - } - $curValue->setArrayDepth($rii->getDepth()); - } - $value = $rii->getSubIterator()->getArrayCopy(); - } - - } - - $output = ''; - - switch ($type) { - case self::TYPE_BOOLEAN: - case self::TYPE_BOOL: - $output .= ( $value ? 'true' : 'false' ); - break; - case self::TYPE_STRING: - $output .= "'" . addcslashes($value, "'") . "'"; - break; - case self::TYPE_NULL: - $output .= 'null'; - break; - case self::TYPE_NUMBER: - case self::TYPE_INTEGER: - case self::TYPE_INT: - case self::TYPE_FLOAT: - case self::TYPE_DOUBLE: - case self::TYPE_CONSTANT: - $output .= $value; - break; - case self::TYPE_ARRAY: - $output .= 'array('; - $curArrayMultiblock = false; - if (count($value) > 1) { - $curArrayMultiblock = true; - $output .= PHP_EOL . str_repeat($this->_indentation, $this->_arrayDepth+1); - } - $outputParts = array(); - $noKeyIndex = 0; - foreach ($value as $n => $v) { - $v->setArrayDepth($this->_arrayDepth + 1); - $partV = $v->generate(); - $partV = substr($partV, 0, strlen($partV)-1); - if ($n === $noKeyIndex) { - $outputParts[] = $partV; - $noKeyIndex++; - } else { - $outputParts[] = (is_int($n) ? $n : "'" . addcslashes($n, "'") . "'") . ' => ' . $partV; - } - - } - $output .= implode(',' . PHP_EOL . str_repeat($this->_indentation, $this->_arrayDepth+1), $outputParts); - if ($curArrayMultiblock == true) { - $output .= PHP_EOL . str_repeat($this->_indentation, $this->_arrayDepth+1); - } - $output .= ')'; - break; - case self::TYPE_OTHER: - default: - #require_once "Zend/CodeGenerator/Php/Exception.php"; - throw new Zend_CodeGenerator_Php_Exception( - "Type '".get_class($value)."' is unknown or cannot be used as property default value." - ); - } - - $output .= ';'; - - return $output; - } -} diff --git a/library/Zend/Db/Profiler/Firebug.php b/library/Zend/Db/Profiler/Firebug.php deleted file mode 100644 index 94192c5a0f..0000000000 --- a/library/Zend/Db/Profiler/Firebug.php +++ /dev/null @@ -1,161 +0,0 @@ -_label = $label; - if(!$this->_label) { - $this->_label = 'Zend_Db_Profiler_Firebug'; - } - } - - /** - * Enable or disable the profiler. If $enable is false, the profiler - * is disabled and will not log any queries sent to it. - * - * @param boolean $enable - * @return Zend_Db_Profiler Provides a fluent interface - */ - public function setEnabled($enable) - { - parent::setEnabled($enable); - - if ($this->getEnabled()) { - - if (!$this->_message) { - $this->_message = new Zend_Wildfire_Plugin_FirePhp_TableMessage($this->_label); - $this->_message->setBuffered(true); - $this->_message->setHeader(array('Time','Event','Parameters')); - $this->_message->setDestroy(true); - $this->_message->setOption('includeLineNumbers', false); - Zend_Wildfire_Plugin_FirePhp::getInstance()->send($this->_message); - } - - } else { - - if ($this->_message) { - $this->_message->setDestroy(true); - $this->_message = null; - } - - } - - return $this; - } - - /** - * Intercept the query end and log the profiling data. - * - * @param integer $queryId - * @throws Zend_Db_Profiler_Exception - * @return void - */ - public function queryEnd($queryId) - { - $state = parent::queryEnd($queryId); - - if (!$this->getEnabled() || $state == self::IGNORED) { - return; - } - - $this->_message->setDestroy(false); - - $profile = $this->getQueryProfile($queryId); - - $this->_totalElapsedTime += $profile->getElapsedSecs(); - - $this->_message->addRow(array((string)round($profile->getElapsedSecs(),5), - $profile->getQuery(), - ($params=$profile->getQueryParams())?$params:null)); - - $this->updateMessageLabel(); - } - - /** - * Update the label of the message holding the profile info. - * - * @return void - */ - protected function updateMessageLabel() - { - if (!$this->_message) { - return; - } - $this->_message->setLabel(str_replace(array('%label%', - '%totalCount%', - '%totalDuration%'), - array($this->_label, - $this->getTotalNumQueries(), - (string)round($this->_totalElapsedTime,5)), - $this->_label_template)); - } -} diff --git a/library/Zend/Debug.php b/library/Zend/Debug.php deleted file mode 100644 index 00196269e0..0000000000 --- a/library/Zend/Debug.php +++ /dev/null @@ -1,113 +0,0 @@ - tags, cleans up newlines and indents, and runs - * htmlentities() before output. - * - * @param mixed $var The variable to dump. - * @param string $label OPTIONAL Label to prepend to output. - * @param bool $echo OPTIONAL Echo output if true. - * @return string - */ - public static function dump($var, $label=null, $echo=true) - { - // format the label - $label = ($label===null) ? '' : rtrim($label) . ' '; - - // var_dump the variable into a buffer and keep the output - ob_start(); - var_dump($var); - $output = ob_get_clean(); - - // neaten the newlines and indents - $output = preg_replace("/\]\=\>\n(\s+)/m", "] => ", $output); - if (self::getSapi() == 'cli') { - $output = PHP_EOL . $label - . PHP_EOL . $output - . PHP_EOL; - } else { - if(!extension_loaded('xdebug')) { - $flags = ENT_QUOTES; - // PHP 5.4.0+ - if (defined('ENT_SUBSTITUTE')) { - $flags = ENT_QUOTES | ENT_SUBSTITUTE; - } - $output = htmlspecialchars($output, $flags); - } - - $output = '
'
-                    . $label
-                    . $output
-                    . '
'; - } - - if ($echo) { - echo($output); - } - return $output; - } - -} diff --git a/library/Zend/EventManager/Event.php b/library/Zend/EventManager/Event.php deleted file mode 100644 index 7f9a52c23c..0000000000 --- a/library/Zend/EventManager/Event.php +++ /dev/null @@ -1,225 +0,0 @@ -setName($name); - } - - if (null !== $target) { - $this->setTarget($target); - } - - if (null !== $params) { - $this->setParams($params); - } - } - - /** - * Get event name - * - * @return string - */ - public function getName() - { - return $this->name; - } - - /** - * Get the event target - * - * This may be either an object, or the name of a static method. - * - * @return string|object - */ - public function getTarget() - { - return $this->target; - } - - /** - * Set parameters - * - * Overwrites parameters - * - * @param array|ArrayAccess|object $params - * @return Event - */ - public function setParams($params) - { - if (!is_array($params) && !is_object($params)) { - #require_once 'Zend/EventManager/Exception/InvalidArgumentException.php'; - throw new Zend_EventManager_Exception_InvalidArgumentException(sprintf( - 'Event parameters must be an array or object; received "%s"', - (is_object($params) ? get_class($params) : gettype($params)) - )); - } - - $this->params = $params; - return $this; - } - - /** - * Get all parameters - * - * @return array|object|ArrayAccess - */ - public function getParams() - { - return $this->params; - } - - /** - * Get an individual parameter - * - * If the parameter does not exist, the $default value will be returned. - * - * @param string|int $name - * @param mixed $default - * @return mixed - */ - public function getParam($name, $default = null) - { - // Check in params that are arrays or implement array access - if (is_array($this->params) || $this->params instanceof ArrayAccess) { - if (!isset($this->params[$name])) { - return $default; - } - - return $this->params[$name]; - } - - // Check in normal objects - if (!isset($this->params->{$name})) { - return $default; - } - return $this->params->{$name}; - } - - /** - * Set the event name - * - * @param string $name - * @return Zend_EventManager_Event - */ - public function setName($name) - { - $this->name = (string) $name; - return $this; - } - - /** - * Set the event target/context - * - * @param null|string|object $target - * @return Zend_EventManager_Event - */ - public function setTarget($target) - { - $this->target = $target; - return $this; - } - - /** - * Set an individual parameter to a value - * - * @param string|int $name - * @param mixed $value - * @return Zend_EventManager_Event - */ - public function setParam($name, $value) - { - if (is_array($this->params) || $this->params instanceof ArrayAccess) { - // Arrays or objects implementing array access - $this->params[$name] = $value; - } else { - // Objects - $this->params->{$name} = $value; - } - return $this; - } - - /** - * Stop further event propagation - * - * @param bool $flag - * @return void - */ - public function stopPropagation($flag = true) - { - $this->stopPropagation = (bool) $flag; - } - - /** - * Is propagation stopped? - * - * @return bool - */ - public function propagationIsStopped() - { - return $this->stopPropagation; - } -} diff --git a/library/Zend/EventManager/EventCollection.php b/library/Zend/EventManager/EventCollection.php deleted file mode 100644 index c664a54ab6..0000000000 --- a/library/Zend/EventManager/EventCollection.php +++ /dev/null @@ -1,109 +0,0 @@ -setIdentifiers($identifiers); - } - - /** - * Set the event class to utilize - * - * @param string $class - * @return Zend_EventManager_EventManager - */ - public function setEventClass($class) - { - $this->eventClass = $class; - return $this; - } - - /** - * Set static collections container - * - * @param Zend_EventManager_SharedEventCollection $collections - * @return $this - */ - public function setSharedCollections(Zend_EventManager_SharedEventCollection $collections) - { - $this->sharedCollections = $collections; - return $this; - } - - /** - * Remove any shared collections - * - * Sets {@link $sharedCollections} to boolean false to disable ability - * to lazy-load static event manager instance. - * - * @return void - */ - public function unsetSharedCollections() - { - $this->sharedCollections = false; - } - - /** - * Get static collections container - * - * @return false|Zend_EventManager_SharedEventCollection - */ - public function getSharedCollections() - { - if (null === $this->sharedCollections) { - $this->setSharedCollections(Zend_EventManager_StaticEventManager::getInstance()); - } - return $this->sharedCollections; - } - - /** - * Get the identifier(s) for this Zend_EventManager_EventManager - * - * @return array - */ - public function getIdentifiers() - { - return $this->identifiers; - } - - /** - * Set the identifiers (overrides any currently set identifiers) - * - * @param string|int|array|Traversable $identifiers - * @return Zend_EventManager_EventManager - */ - public function setIdentifiers($identifiers) - { - if (is_array($identifiers) || $identifiers instanceof Traversable) { - $this->identifiers = array_unique((array) $identifiers); - } elseif ($identifiers !== null) { - $this->identifiers = array($identifiers); - } - return $this; - } - - /** - * Add some identifier(s) (appends to any currently set identifiers) - * - * @param string|int|array|Traversable $identifiers - * @return Zend_EventManager_EventManager - */ - public function addIdentifiers($identifiers) - { - if (is_array($identifiers) || $identifiers instanceof Traversable) { - $this->identifiers = array_unique($this->identifiers + (array) $identifiers); - } elseif ($identifiers !== null) { - $this->identifiers = array_unique(array_merge($this->identifiers, array($identifiers))); - } - return $this; - } - - /** - * Trigger all listeners for a given event - * - * Can emulate triggerUntil() if the last argument provided is a callback. - * - * @param string $event - * @param string|object $target Object calling emit, or symbol describing target (such as static method name) - * @param array|ArrayAccess $argv Array of arguments; typically, should be associative - * @param null|callback $callback - * @return Zend_EventManager_ResponseCollection All listener return values - */ - public function trigger($event, $target = null, $argv = array(), $callback = null) - { - if ($event instanceof Zend_EventManager_EventDescription) { - $e = $event; - $event = $e->getName(); - $callback = $target; - } elseif ($target instanceof Zend_EventManager_EventDescription) { - $e = $target; - $e->setName($event); - $callback = $argv; - } elseif ($argv instanceof Zend_EventManager_EventDescription) { - $e = $argv; - $e->setName($event); - $e->setTarget($target); - } else { - $e = new $this->eventClass(); - $e->setName($event); - $e->setTarget($target); - $e->setParams($argv); - } - - if ($callback && !is_callable($callback)) { - #require_once 'Zend/Stdlib/Exception/InvalidCallbackException.php'; - throw new Zend_Stdlib_Exception_InvalidCallbackException('Invalid callback provided'); - } - - return $this->triggerListeners($event, $e, $callback); - } - - /** - * Trigger listeners until return value of one causes a callback to - * evaluate to true - * - * Triggers listeners until the provided callback evaluates the return - * value of one as true, or until all listeners have been executed. - * - * @param string $event - * @param string|object $target Object calling emit, or symbol describing target (such as static method name) - * @param array|ArrayAccess $argv Array of arguments; typically, should be associative - * @param Callable $callback - * @throws Zend_Stdlib_Exception_InvalidCallbackException if invalid callback provided - */ - public function triggerUntil($event, $target, $argv = null, $callback = null) - { - if ($event instanceof Zend_EventManager_EventDescription) { - $e = $event; - $event = $e->getName(); - $callback = $target; - } elseif ($target instanceof Zend_EventManager_EventDescription) { - $e = $target; - $e->setName($event); - $callback = $argv; - } elseif ($argv instanceof Zend_EventManager_EventDescription) { - $e = $argv; - $e->setName($event); - $e->setTarget($target); - } else { - $e = new $this->eventClass(); - $e->setName($event); - $e->setTarget($target); - $e->setParams($argv); - } - - if (!is_callable($callback)) { - #require_once 'Zend/Stdlib/Exception/InvalidCallbackException.php'; - throw new Zend_Stdlib_Exception_InvalidCallbackException('Invalid callback provided'); - } - - return $this->triggerListeners($event, $e, $callback); - } - - /** - * Attach a listener to an event - * - * The first argument is the event, and the next argument describes a - * callback that will respond to that event. A CallbackHandler instance - * describing the event listener combination will be returned. - * - * The last argument indicates a priority at which the event should be - * executed. By default, this value is 1; however, you may set it for any - * integer value. Higher values have higher priority (i.e., execute first). - * - * You can specify "*" for the event name. In such cases, the listener will - * be triggered for every event. - * - * @param string|array|Zend_EventManager_ListenerAggregate $event An event or array of event names. If a ListenerAggregate, proxies to {@link attachAggregate()}. - * @param callback|int $callback If string $event provided, expects PHP callback; for a ListenerAggregate $event, this will be the priority - * @param int $priority If provided, the priority at which to register the callback - * @return Zend_Stdlib_CallbackHandler|mixed CallbackHandler if attaching callback (to allow later unsubscribe); mixed if attaching aggregate - */ - public function attach($event, $callback = null, $priority = 1) - { - // Proxy ListenerAggregate arguments to attachAggregate() - if ($event instanceof Zend_EventManager_ListenerAggregate) { - return $this->attachAggregate($event, $callback); - } - - // Null callback is invalid - if (null === $callback) { - #require_once 'Zend/EventManager/Exception/InvalidArgumentException.php'; - throw new Zend_EventManager_Exception_InvalidArgumentException(sprintf( - '%s: expects a callback; none provided', - __METHOD__ - )); - } - - // Array of events should be registered individually, and return an array of all listeners - if (is_array($event)) { - $listeners = array(); - foreach ($event as $name) { - $listeners[] = $this->attach($name, $callback, $priority); - } - return $listeners; - } - - // If we don't have a priority queue for the event yet, create one - if (empty($this->events[$event])) { - $this->events[$event] = new Zend_Stdlib_PriorityQueue(); - } - - // Create a callback handler, setting the event and priority in its metadata - $listener = new Zend_Stdlib_CallbackHandler($callback, array('event' => $event, 'priority' => $priority)); - - // Inject the callback handler into the queue - $this->events[$event]->insert($listener, $priority); - return $listener; - } - - /** - * Attach a listener aggregate - * - * Listener aggregates accept an EventCollection instance, and call attach() - * one or more times, typically to attach to multiple events using local - * methods. - * - * @param Zend_EventManager_ListenerAggregate $aggregate - * @param int $priority If provided, a suggested priority for the aggregate to use - * @return mixed return value of {@link Zend_EventManager_ListenerAggregate::attach()} - */ - public function attachAggregate(Zend_EventManager_ListenerAggregate $aggregate, $priority = 1) - { - return $aggregate->attach($this, $priority); - } - - /** - * Unsubscribe a listener from an event - * - * @param Zend_Stdlib_CallbackHandler|Zend_EventManager_ListenerAggregate $listener - * @return bool Returns true if event and listener found, and unsubscribed; returns false if either event or listener not found - * @throws Zend_EventManager_Exception_InvalidArgumentException if invalid listener provided - */ - public function detach($listener) - { - if ($listener instanceof Zend_EventManager_ListenerAggregate) { - return $this->detachAggregate($listener); - } - - if (!$listener instanceof Zend_Stdlib_CallbackHandler) { - #require_once 'Zend/EventManager/Exception/InvalidArgumentException.php'; - throw new Zend_EventManager_Exception_InvalidArgumentException(sprintf( - '%s: expected a Zend_EventManager_ListenerAggregate or Zend_Stdlib_CallbackHandler; received "%s"', - __METHOD__, - (is_object($listener) ? get_class($listener) : gettype($listener)) - )); - } - - $event = $listener->getMetadatum('event'); - if (!$event || empty($this->events[$event])) { - return false; - } - $return = $this->events[$event]->remove($listener); - if (!$return) { - return false; - } - if (!count($this->events[$event])) { - unset($this->events[$event]); - } - return true; - } - - /** - * Detach a listener aggregate - * - * Listener aggregates accept an EventCollection instance, and call detach() - * of all previously attached listeners. - * - * @param Zend_EventManager_ListenerAggregate $aggregate - * @return mixed return value of {@link Zend_EventManager_ListenerAggregate::detach()} - */ - public function detachAggregate(Zend_EventManager_ListenerAggregate $aggregate) - { - return $aggregate->detach($this); - } - - /** - * Retrieve all registered events - * - * @return array - */ - public function getEvents() - { - return array_keys($this->events); - } - - /** - * Retrieve all listeners for a given event - * - * @param string $event - * @return Zend_Stdlib_PriorityQueue - */ - public function getListeners($event) - { - if (!array_key_exists($event, $this->events)) { - return new Zend_Stdlib_PriorityQueue(); - } - return $this->events[$event]; - } - - /** - * Clear all listeners for a given event - * - * @param string $event - * @return void - */ - public function clearListeners($event) - { - if (!empty($this->events[$event])) { - unset($this->events[$event]); - } - } - - /** - * Prepare arguments - * - * Use this method if you want to be able to modify arguments from within a - * listener. It returns an ArrayObject of the arguments, which may then be - * passed to trigger() or triggerUntil(). - * - * @param array $args - * @return ArrayObject - */ - public function prepareArgs(array $args) - { - return new ArrayObject($args); - } - - /** - * Trigger listeners - * - * Actual functionality for triggering listeners, to which both trigger() and triggerUntil() - * delegate. - * - * @param string $event Event name - * @param EventDescription $e - * @param null|callback $callback - * @return ResponseCollection - */ - protected function triggerListeners($event, Zend_EventManager_EventDescription $e, $callback = null) - { - $responses = new Zend_EventManager_ResponseCollection; - $listeners = $this->getListeners($event); - - // Add shared/wildcard listeners to the list of listeners, - // but don't modify the listeners object - $sharedListeners = $this->getSharedListeners($event); - $sharedWildcardListeners = $this->getSharedListeners('*'); - $wildcardListeners = $this->getListeners('*'); - if (count($sharedListeners) || count($sharedWildcardListeners) || count($wildcardListeners)) { - $listeners = clone $listeners; - } - - // Shared listeners on this specific event - $this->insertListeners($listeners, $sharedListeners); - - // Shared wildcard listeners - $this->insertListeners($listeners, $sharedWildcardListeners); - - // Add wildcard listeners - $this->insertListeners($listeners, $wildcardListeners); - - if ($listeners->isEmpty()) { - return $responses; - } - - foreach ($listeners as $listener) { - // Trigger the listener's callback, and push its result onto the - // response collection - $responses->push(call_user_func($listener->getCallback(), $e)); - - // If the event was asked to stop propagating, do so - if ($e->propagationIsStopped()) { - $responses->setStopped(true); - break; - } - - // If the result causes our validation callback to return true, - // stop propagation - if ($callback && call_user_func($callback, $responses->last())) { - $responses->setStopped(true); - break; - } - } - - return $responses; - } - - /** - * Get list of all listeners attached to the shared collection for - * identifiers registered by this instance - * - * @param string $event - * @return array - */ - protected function getSharedListeners($event) - { - if (!$sharedCollections = $this->getSharedCollections()) { - return array(); - } - - $identifiers = $this->getIdentifiers(); - $sharedListeners = array(); - - foreach ($identifiers as $id) { - if (!$listeners = $sharedCollections->getListeners($id, $event)) { - continue; - } - - if (!is_array($listeners) && !($listeners instanceof Traversable)) { - continue; - } - - foreach ($listeners as $listener) { - if (!$listener instanceof Zend_Stdlib_CallbackHandler) { - continue; - } - $sharedListeners[] = $listener; - } - } - - return $sharedListeners; - } - - /** - * Add listeners to the master queue of listeners - * - * Used to inject shared listeners and wildcard listeners. - * - * @param Zend_Stdlib_PriorityQueue $masterListeners - * @param Zend_Stdlib_PriorityQueue $listeners - * @return void - */ - protected function insertListeners($masterListeners, $listeners) - { - if (!count($listeners)) { - return; - } - - foreach ($listeners as $listener) { - $priority = $listener->getMetadatum('priority'); - if (null === $priority) { - $priority = 1; - } elseif (is_array($priority)) { - // If we have an array, likely using PriorityQueue. Grab first - // element of the array, as that's the actual priority. - $priority = array_shift($priority); - } - $masterListeners->insert($listener, $priority); - } - } -} diff --git a/library/Zend/EventManager/EventManagerAware.php b/library/Zend/EventManager/EventManagerAware.php deleted file mode 100644 index e1a9b33f81..0000000000 --- a/library/Zend/EventManager/EventManagerAware.php +++ /dev/null @@ -1,40 +0,0 @@ -setExtractFlags(self::EXTR_BOTH); - - // Iterate and remove any matches - $removed = false; - $items = array(); - $this->rewind(); - while (!$this->isEmpty()) { - $item = $this->extract(); - if ($item['data'] === $datum) { - $removed = true; - continue; - } - $items[] = $item; - } - - // Repopulate - foreach ($items as $item) { - $this->insert($item['data'], $item['priority']); - } - - $this->setExtractFlags(self::EXTR_DATA); - return $removed; - } - - /** - * Iterate the next filter in the chain - * - * Iterates and calls the next filter in the chain. - * - * @param mixed $context - * @param array $params - * @param Zend_EventManager_Filter_FilterIterator $chain - * @return mixed - */ - public function next($context = null, array $params = array(), $chain = null) - { - if (empty($context) || $chain->isEmpty()) { - return; - } - - $next = $this->extract(); - if (!$next instanceof Zend_Stdlib_CallbackHandler) { - return; - } - - $return = call_user_func($next->getCallback(), $context, $params, $chain); - return $return; - } -} diff --git a/library/Zend/EventManager/FilterChain.php b/library/Zend/EventManager/FilterChain.php deleted file mode 100644 index daf51899d2..0000000000 --- a/library/Zend/EventManager/FilterChain.php +++ /dev/null @@ -1,139 +0,0 @@ -filters = new Zend_EventManager_Filter_FilterIterator(); - } - - /** - * Apply the filters - * - * Begins iteration of the filters. - * - * @param mixed $context Object under observation - * @param mixed $argv Associative array of arguments - * @return mixed - */ - public function run($context, array $argv = array()) - { - $chain = clone $this->getFilters(); - - if ($chain->isEmpty()) { - return; - } - - $next = $chain->extract(); - if (!$next instanceof Zend_Stdlib_CallbackHandler) { - return; - } - - return call_user_func($next->getCallback(), $context, $argv, $chain); - } - - /** - * Connect a filter to the chain - * - * @param callback $callback PHP Callback - * @param int $priority Priority in the queue at which to execute; defaults to 1 (higher numbers == higher priority) - * @throws Zend_Stdlib_Exception_InvalidCallbackException - * @return Zend_Stdlib_CallbackHandler (to allow later unsubscribe) - */ - public function attach($callback, $priority = 1) - { - if (empty($callback)) { - #require_once 'Zend/Stdlib/Exception/InvalidCallbackException.php'; - throw new Zend_Stdlib_Exception_InvalidCallbackException('No callback provided'); - } - $filter = new Zend_Stdlib_CallbackHandler($callback, array('priority' => $priority)); - $this->filters->insert($filter, $priority); - return $filter; - } - - /** - * Detach a filter from the chain - * - * @param Zend_Stdlib_CallbackHandler $filter - * @return bool Returns true if filter found and unsubscribed; returns false otherwise - */ - public function detach(Zend_Stdlib_CallbackHandler $filter) - { - return $this->filters->remove($filter); - } - - /** - * Retrieve all filters - * - * @return Zend_EventManager_Filter_FilterIterator - */ - public function getFilters() - { - return $this->filters; - } - - /** - * Clear all filters - * - * @return void - */ - public function clearFilters() - { - $this->filters = new Zend_EventManager_Filter_FilterIterator(); - } - - /** - * Return current responses - * - * Only available while the chain is still being iterated. Returns the - * current ResponseCollection. - * - * @return null|Zend_EventManager_ResponseCollection - */ - public function getResponses() - { - return $this->responses; - } -} diff --git a/library/Zend/EventManager/GlobalEventManager.php b/library/Zend/EventManager/GlobalEventManager.php deleted file mode 100644 index 376dafbce2..0000000000 --- a/library/Zend/EventManager/GlobalEventManager.php +++ /dev/null @@ -1,149 +0,0 @@ -trigger($event, $context, $argv); - } - - /** - * Trigger listeenrs until return value of one causes a callback to evaluate - * to true. - * - * @param string $event - * @param string|object $context - * @param array|object $argv - * @param callback $callback - * @return Zend_EventManager_ResponseCollection - */ - public static function triggerUntil($event, $context, $argv, $callback) - { - return self::getEventCollection()->triggerUntil($event, $context, $argv, $callback); - } - - /** - * Attach a listener to an event - * - * @param string $event - * @param callback $callback - * @param int $priority - * @return Zend_Stdlib_CallbackHandler - */ - public static function attach($event, $callback, $priority = 1) - { - return self::getEventCollection()->attach($event, $callback, $priority); - } - - /** - * Detach a callback from a listener - * - * @param Zend_Stdlib_CallbackHandler $listener - * @return bool - */ - public static function detach(Zend_Stdlib_CallbackHandler $listener) - { - return self::getEventCollection()->detach($listener); - } - - /** - * Retrieve list of events this object manages - * - * @return array - */ - public static function getEvents() - { - return self::getEventCollection()->getEvents(); - } - - /** - * Retrieve all listeners for a given event - * - * @param string $event - * @return Zend_Stdlib_PriorityQueue|array - */ - public static function getListeners($event) - { - return self::getEventCollection()->getListeners($event); - } - - /** - * Clear all listeners for a given event - * - * @param string $event - * @return void - */ - public static function clearListeners($event) - { - return self::getEventCollection()->clearListeners($event); - } -} diff --git a/library/Zend/EventManager/ListenerAggregate.php b/library/Zend/EventManager/ListenerAggregate.php deleted file mode 100644 index c360252a58..0000000000 --- a/library/Zend/EventManager/ListenerAggregate.php +++ /dev/null @@ -1,53 +0,0 @@ - true, - self::IT_MODE_KEEP => true, - ); - - if (!isset($expected[$mode])) { - throw new InvalidArgumentException(sprintf('Invalid iterator mode specified ("%s")', $mode)); - } - - $this->mode = $mode; - } - - /** - * Return last element in the stack - * - * @return mixed - */ - public function bottom() - { - $this->rewind(); - $value = array_pop($this->stack); - array_push($this->stack, $value); - return $value; - } - - /** - * Countable: return count of items in the stack - * - * @return int - */ - public function count() - { - return $this->count; - } - - /** - * Iterator: return current item in the stack - * - * @return mixed - */ - public function current() - { - if (!$this->stack) { - $this->rewind(); - } - return current($this->stack); - } - - /** - * Get iteration mode - * - * @return int - */ - public function getIteratorMode() - { - return $this->mode; - } - - /** - * Is the stack empty? - * - * @return bool - */ - public function isEmpty() - { - return ($this->count === 0); - } - - /** - * Iterator: return key of current item in the stack - * - * @return mixed - */ - public function key() - { - if (!$this->stack) { - $this->rewind(); - } - return key($this->stack); - } - - /** - * Iterator: advance pointer to next item in the stack - * - * @return void - */ - public function next() - { - if (!$this->stack) { - $this->rewind(); - } - return next($this->stack); - } - - /** - * ArrayAccess: does an item exist at the specified offset? - * - * @param mixed $index - * @return bool - */ - public function offsetExists($index) - { - return array_key_exists($index, $this->data); - } - - /** - * ArrayAccess: get the item at the specified offset - * - * @param mixed $index - * @return mixed - * @throws OutOfRangeException - */ - public function offsetGet($index) - { - if (!$this->offsetExists($index)) { - throw OutOfRangeException(sprintf('Invalid index ("%s") specified', $index)); - } - return $this->data[$index]; - } - - /** - * ArrayAccess: add an item at the specified offset - * - * @param mixed $index - * @param mixed $newval - * @return void - */ - public function offsetSet($index, $newval) - { - $this->data[$index] = $newval; - $this->stack = false; - $this->count++; - } - - /** - * ArrayAccess: unset the item at the specified offset - * - * @param mixed $index - * @return void - * @throws OutOfRangeException - */ - public function offsetUnset($index) - { - if (!$this->offsetExists($index)) { - throw OutOfRangeException(sprintf('Invalid index ("%s") specified', $index)); - } - unset($this->data[$index]); - $this->stack = false; - $this->count--; - } - - /** - * Pop a node from the end of the stack - * - * @return mixed - * @throws RuntimeException - */ - public function pop() - { - $val = array_pop($this->data); - $this->stack = false; - $this->count--; - return $val; - } - - /** - * Move the iterator to the previous node - * - * @todo Does this need to be implemented? - * @return void - */ - public function prev() - { - } - - /** - * Push an element to the list - * - * @param mixed $value - * @return void - */ - public function push($value) - { - array_push($this->data, $value); - $this->count++; - $this->stack = false; - } - - /** - * Iterator: rewind to beginning of stack - * - * @return void - */ - public function rewind() - { - if (is_array($this->stack)) { - return reset($this->stack); - } - $this->stack = array_reverse($this->data, true); - } - - /** - * Serialize the storage - * - * @return string - */ - public function serialize() - { - return serialize($this->data); - } - - /** - * Shifts a node from the beginning of the list - * - * @return mixed - * @throws RuntimeException - */ - public function shift() - { - $val = array_shift($this->data); - $this->stack = false; - $this->count--; - return $val; - } - - /** - * Peek at the top node of the stack - * - * @return mixed - */ - public function top() - { - $this->rewind(); - $value = array_shift($this->stack); - array_unshift($this->stack, $value); - return $value; - } - - /** - * Unserialize the storage - * - * @param string - * @return void - */ - public function unserialize($serialized) - { - $this->data = unserialize($serialized); - $this->stack = false; - } - - /** - * Unshift a node onto the beginning of the list - * - * @param mixed $value - * @return void - */ - public function unshift($value) - { - array_unshift($this->data, $value); - $this->count++; - $this->stack = false; - } - - /** - * Iterator: is the current pointer valid? - * - * @return bool - */ - public function valid() - { - $key = key($this->stack); - $var = ($key !== null && $key !== false); - return $var; - } - } -} - -/** - * Collection of signal handler return values - * - * @category Zend - * @package Zend_EventManager - * @copyright Copyright (c) 2005-2015 Zend Technologies USA Inc. (http://www.zend.com) - * @license http://framework.zend.com/license/new-bsd New BSD License - */ -class Zend_EventManager_ResponseCollection extends SplStack -{ - protected $stopped = false; - - /** - * Did the last response provided trigger a short circuit of the stack? - * - * @return bool - */ - public function stopped() - { - return $this->stopped; - } - - /** - * Mark the collection as stopped (or its opposite) - * - * @param bool $flag - * @return Zend_EventManager_ResponseCollection - */ - public function setStopped($flag) - { - $this->stopped = (bool) $flag; - return $this; - } - - /** - * Convenient access to the first handler return value. - * - * @return mixed The first handler return value - */ - public function first() - { - return parent::bottom(); - } - - /** - * Convenient access to the last handler return value. - * - * If the collection is empty, returns null. Otherwise, returns value - * returned by last handler. - * - * @return mixed The last handler return value - */ - public function last() - { - if (count($this) === 0) { - return null; - } - return parent::top(); - } - - /** - * Check if any of the responses match the given value. - * - * @param mixed $value The value to look for among responses - */ - public function contains($value) - { - foreach ($this as $response) { - if ($response === $value) { - return true; - } - } - return false; - } -} diff --git a/library/Zend/EventManager/SharedEventCollection.php b/library/Zend/EventManager/SharedEventCollection.php deleted file mode 100644 index 0050c61370..0000000000 --- a/library/Zend/EventManager/SharedEventCollection.php +++ /dev/null @@ -1,32 +0,0 @@ - - * SharedEventManager::getInstance()->connect( - * array('My\Resource\AbstractResource', 'My\Resource\EntityResource'), - * 'getOne', - * function ($e) use ($cache) { - * if (!$id = $e->getParam('id', false)) { - * return; - * } - * if (!$data = $cache->load(get_class($resource) . '::getOne::' . $id )) { - * return; - * } - * return $data; - * } - * ); - * - * - * @param string|array $id Identifier(s) for event emitting component(s) - * @param string $event - * @param callback $callback PHP Callback - * @param int $priority Priority at which listener should execute - * @return void - */ - public function attach($id, $event, $callback, $priority = 1) - { - $ids = (array) $id; - foreach ($ids as $id) { - if (!array_key_exists($id, $this->identifiers)) { - $this->identifiers[$id] = new Zend_EventManager_EventManager(); - } - $this->identifiers[$id]->attach($event, $callback, $priority); - } - } - - /** - * Detach a listener from an event offered by a given resource - * - * @param string|int $id - * @param Zend_Stdlib_CallbackHandler $listener - * @return bool Returns true if event and listener found, and unsubscribed; returns false if either event or listener not found - */ - public function detach($id, Zend_Stdlib_CallbackHandler $listener) - { - if (!array_key_exists($id, $this->identifiers)) { - return false; - } - return $this->identifiers[$id]->detach($listener); - } - - /** - * Retrieve all registered events for a given resource - * - * @param string|int $id - * @return array - */ - public function getEvents($id) - { - if (!array_key_exists($id, $this->identifiers)) { - return false; - } - return $this->identifiers[$id]->getEvents(); - } - - /** - * Retrieve all listeners for a given identifier and event - * - * @param string|int $id - * @param string|int $event - * @return false|Zend_Stdlib_PriorityQueue - */ - public function getListeners($id, $event) - { - if (!array_key_exists($id, $this->identifiers)) { - return false; - } - return $this->identifiers[$id]->getListeners($event); - } - - /** - * Clear all listeners for a given identifier, optionally for a specific event - * - * @param string|int $id - * @param null|string $event - * @return bool - */ - public function clearListeners($id, $event = null) - { - if (!array_key_exists($id, $this->identifiers)) { - return false; - } - - if (null === $event) { - unset($this->identifiers[$id]); - return true; - } - - return $this->identifiers[$id]->clearListeners($event); - } -} diff --git a/library/Zend/EventManager/StaticEventManager.php b/library/Zend/EventManager/StaticEventManager.php deleted file mode 100644 index 850e0c042b..0000000000 --- a/library/Zend/EventManager/StaticEventManager.php +++ /dev/null @@ -1,80 +0,0 @@ -decodeRequest('GET', $uri); - $response = $app->performHttpRequest($requestData['method'], $requestData['url']); - - $feedContent = $response->getBody(); - - $feed = self::importString($feedContent, $className); - if ($client != null) { - $feed->setHttpClient($client); - } - return $feed; - } - - /** - * Retrieve feed as string or object - * - * @param mixed $location The location as string or Zend_Gdata_Query - * @param string $className The class type to use for returning the feed - * @throws Zend_Gdata_App_InvalidArgumentException - * @return string|Zend_Gdata_App_Feed Returns string only if the object - * mapping has been disabled explicitly - * by passing false to the - * useObjectMapping() function. - */ - public function getFeed($location, $className='Zend_Gdata_Feed') - { - if (is_string($location)) { - $uri = $location; - } elseif ($location instanceof Zend_Gdata_Query) { - $uri = $location->getQueryUrl(); - } else { - #require_once 'Zend/Gdata/App/InvalidArgumentException.php'; - throw new Zend_Gdata_App_InvalidArgumentException( - 'You must specify the location as either a string URI ' . - 'or a child of Zend_Gdata_Query'); - } - return parent::getFeed($uri, $className); - } - - /** - * Retrieve entry as string or object - * - * @param mixed $location The location as string or Zend_Gdata_Query - * @throws Zend_Gdata_App_InvalidArgumentException - * @return string|Zend_Gdata_App_Entry Returns string only if the object - * mapping has been disabled explicitly - * by passing false to the - * useObjectMapping() function. - */ - public function getEntry($location, $className='Zend_Gdata_Entry') - { - if (is_string($location)) { - $uri = $location; - } elseif ($location instanceof Zend_Gdata_Query) { - $uri = $location->getQueryUrl(); - } else { - #require_once 'Zend/Gdata/App/InvalidArgumentException.php'; - throw new Zend_Gdata_App_InvalidArgumentException( - 'You must specify the location as either a string URI ' . - 'or a child of Zend_Gdata_Query'); - } - return parent::getEntry($uri, $className); - } - - /** - * Performs a HTTP request using the specified method. - * - * Overrides the definition in the parent (Zend_Gdata_App) - * and uses the Zend_Gdata_HttpClient functionality - * to filter the HTTP requests and responses. - * - * @param string $method The HTTP method for the request - - * 'GET', 'POST', 'PUT', 'DELETE' - * @param string $url The URL to which this request is being performed, - * or null if found in $data - * @param array $headers An associative array of HTTP headers - * for this request - * @param string $body The body of the HTTP request - * @param string $contentType The value for the content type of the - * request body - * @param int $remainingRedirects Number of redirects to follow - * if requests results in one - * @return Zend_Http_Response The response object - */ - public function performHttpRequest($method, $url, $headers = array(), $body = null, $contentType = null, $remainingRedirects = null) - { - if ($this->_httpClient instanceof Zend_Gdata_HttpClient) { - $filterResult = $this->_httpClient->filterHttpRequest($method, $url, $headers, $body, $contentType); - $method = $filterResult['method']; - $url = $filterResult['url']; - $body = $filterResult['body']; - $headers = $filterResult['headers']; - $contentType = $filterResult['contentType']; - return $this->_httpClient->filterHttpResponse(parent::performHttpRequest($method, $url, $headers, $body, $contentType, $remainingRedirects)); - } else { - return parent::performHttpRequest($method, $url, $headers, $body, $contentType, $remainingRedirects); - } - } - - /** - * Determines whether service object is authenticated. - * - * @return boolean True if service object is authenticated, false otherwise. - */ - public function isAuthenticated() - { - $client = parent::getHttpClient(); - if ($client->getClientLoginToken() || - $client->getAuthSubToken()) { - return true; - } - - return false; - } - -} diff --git a/library/Zend/Gdata/Analytics.php b/library/Zend/Gdata/Analytics.php deleted file mode 100644 index f0813a98d1..0000000000 --- a/library/Zend/Gdata/Analytics.php +++ /dev/null @@ -1,137 +0,0 @@ -registerPackage('Zend_Gdata_Analytics'); - $this->registerPackage('Zend_Gdata_Analytics_Extension'); - parent::__construct($client, $applicationId); - $this->_httpClient->setParameterPost('service', self::AUTH_SERVICE_NAME); - } - - /** - * Retrieve account feed object - * - * @param string|Zend_Uri_Uri $uri - * @return Zend_Gdata_Analytics_AccountFeed - */ - public function getAccountFeed($uri = self::ANALYTICS_ACCOUNT_FEED_URI) - { - if ($uri instanceof Query) { - $uri = $uri->getQueryUrl(); - } - return parent::getFeed($uri, 'Zend_Gdata_Analytics_AccountFeed'); - } - - /** - * Retrieve data feed object - * - * @param string|Zend_Uri_Uri $uri - * @return Zend_Gdata_Analytics_DataFeed - */ - public function getDataFeed($uri = self::ANALYTICS_FEED_URI) - { - if ($uri instanceof Query) { - $uri = $uri->getQueryUrl(); - } - return parent::getFeed($uri, 'Zend_Gdata_Analytics_DataFeed'); - } - - /** - * Returns a new DataQuery object. - * - * @return Zend_Gdata_Analytics_DataQuery - */ - public function newDataQuery() - { - return new Zend_Gdata_Analytics_DataQuery(); - } - - /** - * Returns a new AccountQuery object. - * - * @return Zend_Gdata_Analytics_AccountQuery - */ - public function newAccountQuery() - { - return new Zend_Gdata_Analytics_AccountQuery(); - } -} diff --git a/library/Zend/Gdata/Analytics/AccountEntry.php b/library/Zend/Gdata/Analytics/AccountEntry.php deleted file mode 100644 index 26df5ad917..0000000000 --- a/library/Zend/Gdata/Analytics/AccountEntry.php +++ /dev/null @@ -1,102 +0,0 @@ -registerAllNamespaces(Zend_Gdata_Analytics::$namespaces); - parent::__construct($element); - } - - /** - * @param DOMElement $child - * @return void - */ - protected function takeChildFromDOM($child) - { - $absoluteNodeName = $child->namespaceURI . ':' . $child->localName; - switch ($absoluteNodeName){ - case $this->lookupNamespace('analytics') . ':' . 'property'; - $property = new Zend_Gdata_Analytics_Extension_Property(); - $property->transferFromDOM($child); - $this->{$property->getName()} = $property; - break; - case $this->lookupNamespace('analytics') . ':' . 'tableId'; - $tableId = new Zend_Gdata_Analytics_Extension_TableId(); - $tableId->transferFromDOM($child); - $this->_tableId = $tableId; - break; - case $this->lookupNamespace('ga') . ':' . 'goal'; - $goal = new Zend_Gdata_Analytics_Extension_Goal(); - $goal->transferFromDOM($child); - $this->_goal = $goal; - break; - default: - parent::takeChildFromDOM($child); - break; - } - } -} diff --git a/library/Zend/Gdata/Analytics/AccountFeed.php b/library/Zend/Gdata/Analytics/AccountFeed.php deleted file mode 100644 index ffc3675296..0000000000 --- a/library/Zend/Gdata/Analytics/AccountFeed.php +++ /dev/null @@ -1,57 +0,0 @@ -registerAllNamespaces(Zend_Gdata_Analytics::$namespaces); - parent::__construct($element); - } -} diff --git a/library/Zend/Gdata/Analytics/AccountQuery.php b/library/Zend/Gdata/Analytics/AccountQuery.php deleted file mode 100644 index 28e1714017..0000000000 --- a/library/Zend/Gdata/Analytics/AccountQuery.php +++ /dev/null @@ -1,190 +0,0 @@ -_accountId = $accountId; - return $this; - } - - /** - * @return string - */ - public function getAccountId() - { - return $this->_accountId; - } - - /** - * @param string $webpropertyId - * @return Zend_Gdata_Analytics_AccountQuery - */ - public function setWebpropertyId($webpropertyId) - { - $this->_webpropertyId = $webpropertyId; - return $this; - } - - /** - * @return string - */ - public function getWebpropertyId() - { - return $this->_webpropertyId; - } - - /** - * @param string $profileId - * @return Zend_Gdata_Analytics_AccountQuery - */ - public function setProfileId($profileId) - { - $this->_profileId = $profileId; - return $this; - } - - /** - * @return string - */ - public function getProfileId() - { - return $this->_profileId; - } - - /** - * @param string $accountId - * @return Zend_Gdata_Analytics_AccountQuery - */ - public function webproperties($accountId = '~all') - { - $this->_webproperties = true; - $this->setAccountId($accountId); - return $this; - } - - /** - * @param string $webpropertyId - * @param string $accountId - * @return Zend_Gdata_Analytics_AccountQuery - */ - public function profiles($webpropertyId = '~all', $accountId = '~all') - { - $this->_profiles = true; - if (null !== $accountId) { - $this->setAccountId($accountId); - } - $this->setWebpropertyId($webpropertyId); - return $this; - } - - /** - * @param string $webpropertyId - * @param string $accountId - * @param string $accountId - * @return Zend_Gdata_Analytics_AccountQuery - */ - public function goals($profileId = '~all', $webpropertyId = '~all', $accountId = '~all') - { - $this->_goals = true; - if (null !== $accountId) { - $this->setAccountId($accountId); - } - if (null !== $webpropertyId) { - $this->setWebpropertyId($webpropertyId); - } - $this->setProfileId($profileId); - return $this; - } - - /** - * @return string url - */ - public function getQueryUrl() - { - $url = $this->_defaultFeedUri; - - // add account id - if ($this->_webproperties or $this->_profiles or $this->_goals) { - $url .= '/' . $this->_accountId . '/webproperties'; - } - - if ($this->_profiles or $this->_goals) { - $url .= '/' . $this->_webpropertyId . '/profiles'; - } - - if ($this->_goals) { - $url .= '/' . $this->_profileId . '/goals'; - } - - $url .= $this->getQueryString(); - return $url; - } -} diff --git a/library/Zend/Gdata/Analytics/DataEntry.php b/library/Zend/Gdata/Analytics/DataEntry.php deleted file mode 100644 index 5a835cd73a..0000000000 --- a/library/Zend/Gdata/Analytics/DataEntry.php +++ /dev/null @@ -1,116 +0,0 @@ -registerAllNamespaces(Zend_Gdata_Analytics::$namespaces); - parent::__construct($element); - } - - /** - * @param DOMElement $child - * @return void - */ - protected function takeChildFromDOM($child) - { - $absoluteNodeName = $child->namespaceURI . ':' . $child->localName; - switch ($absoluteNodeName) { - case $this->lookupNamespace('analytics') . ':' . 'dimension'; - $dimension = new Zend_Gdata_Analytics_Extension_Dimension(); - $dimension->transferFromDOM($child); - $this->_dimensions[] = $dimension; - break; - case $this->lookupNamespace('analytics') . ':' . 'metric'; - $metric = new Zend_Gdata_Analytics_Extension_Metric(); - $metric->transferFromDOM($child); - $this->_metrics[] = $metric; - break; - default: - parent::takeChildFromDOM($child); - break; - } - } - - /** - * @param string $name - * @return mixed - */ - public function getDimension($name) - { - foreach ($this->_dimensions as $dimension) { - if ($dimension->getName() == $name) { - return $dimension; - } - } - return null; - } - - /** - * @param string $name - * @return mixed - */ - public function getMetric($name) - { - foreach ($this->_metrics as $metric) { - if ($metric->getName() == $name) { - return $metric; - } - } - return null; - } - - /** - * @param string $name - * @return mixed - */ - public function getValue($name) - { - if (null !== ($metric = $this->getMetric($name))) { - return $metric; - } - return $this->getDimension($name); - } -} diff --git a/library/Zend/Gdata/Analytics/DataFeed.php b/library/Zend/Gdata/Analytics/DataFeed.php deleted file mode 100644 index 9d0d4100de..0000000000 --- a/library/Zend/Gdata/Analytics/DataFeed.php +++ /dev/null @@ -1,64 +0,0 @@ -registerAllNamespaces(Zend_Gdata_Analytics::$namespaces); - parent::__construct($element); - } -} diff --git a/library/Zend/Gdata/Analytics/DataQuery.php b/library/Zend/Gdata/Analytics/DataQuery.php deleted file mode 100644 index 6e11e6612d..0000000000 --- a/library/Zend/Gdata/Analytics/DataQuery.php +++ /dev/null @@ -1,403 +0,0 @@ -"; - const LESS = ">"; - const GREATER_EQUAL = ">="; - const LESS_EQUAL = "<="; - const CONTAINS = "=@"; - const CONTAINS_NOT ="!@"; - const REGULAR ="=~"; - const REGULAR_NOT ="!~"; - - /** - * @var string - */ - protected $_profileId; - /** - * @var array - */ - protected $_dimensions = array(); - /** - * @var array - */ - protected $_metrics = array(); - /** - * @var array - */ - protected $_sort = array(); - /** - * @var array - */ - protected $_filters = array(); - - /** - * @param string $id - * @return Zend_Gdata_Analytics_DataQuery - */ - public function setProfileId($id) - { - $this->_profileId = $id; - return $this; - } - - /** - * @return string - */ - public function getProfileId() - { - return $this->_profileId; - } - - /** - * @param string $dimension - * @return Zend_Gdata_Analytics_DataQuery - */ - public function addDimension($dimension) - { - $this->_dimensions[$dimension] = true; - return $this; - } - - /** - * @param string $metric - * @return Zend_Gdata_Analytics_DataQuery - */ - public function addMetric($metric) - { - $this->_metrics[$metric] = true; - return $this; - } - - /** - * @return array - */ - public function getDimensions() - { - return $this->_dimensions; - } - - /** - * @return array - */ - public function getMetrics() - { - return $this->_metrics; - } - - /** - * @param string $dimension - * @return Zend_Gdata_Analytics_DataQuery - */ - public function removeDimension($dimension) - { - unset($this->_dimensions[$dimension]); - return $this; - } - /** - * @param string $metric - * @return Zend_Gdata_Analytics_DataQuery - */ - public function removeMetric($metric) - { - unset($this->_metrics[$metric]); - return $this; - } - /** - * @param string $value - * @return Zend_Gdata_Analytics_DataQuery - */ - public function setStartDate($date) - { - $this->setParam("start-date", $date); - return $this; - } - /** - * @param string $value - * @return Zend_Gdata_Analytics_DataQuery - */ - public function setEndDate($date) - { - $this->setParam("end-date", $date); - return $this; - } - - /** - * @param string $filter - * @return Zend_Gdata_Analytics_DataQuery - */ - public function addFilter($filter) - { - $this->_filters[] = array($filter, true); - return $this; - } - - /** - * @param string $filter - * @return Zend_Gdata_Analytics_DataQuery - */ - public function addOrFilter($filter) - { - $this->_filters[] = array($filter, false); - return $this; - } - - /** - * @param string $sort - * @param boolean[optional] $descending - * @return Zend_Gdata_Analytics_DataQuery - */ - public function addSort($sort, $descending=false) - { - // add to sort storage - $this->_sort[] = ($descending?'-':'').$sort; - return $this; - } - - /** - * @return Zend_Gdata_Analytics_DataQuery - */ - public function clearSort() - { - $this->_sort = array(); - return $this; - } - - /** - * @param string $segment - * @return Zend_Gdata_Analytics_DataQuery - */ - public function setSegment($segment) - { - $this->setParam('segment', $segment); - return $this; - } - - /** - * @return string url - */ - public function getQueryUrl() - { - $uri = $this->_defaultFeedUri; - if (isset($this->_url)) { - $uri = $this->_url; - } - - $dimensions = $this->getDimensions(); - if (!empty($dimensions)) { - $this->setParam('dimensions', implode(",", array_keys($dimensions))); - } - - $metrics = $this->getMetrics(); - if (!empty($metrics)) { - $this->setParam('metrics', implode(",", array_keys($metrics))); - } - - // profile id (ga:tableId) - if ($this->getProfileId() != null) { - $this->setParam('ids', 'ga:'.ltrim($this->getProfileId(), "ga:")); - } - - // sorting - if ($this->_sort) { - $this->setParam('sort', implode(",", $this->_sort)); - } - - // filtering - $filters = ""; - foreach ($this->_filters as $filter) { - $filters.=($filter[1]===true?';':',').$filter[0]; - } - - if ($filters!="") { - $this->setParam('filters', ltrim($filters, ",;")); - } - - $uri .= $this->getQueryString(); - return $uri; - } -} diff --git a/library/Zend/Gdata/Analytics/Extension/Dimension.php b/library/Zend/Gdata/Analytics/Extension/Dimension.php deleted file mode 100644 index 2b53a00f28..0000000000 --- a/library/Zend/Gdata/Analytics/Extension/Dimension.php +++ /dev/null @@ -1,40 +0,0 @@ -registerAllNamespaces(Zend_Gdata_Analytics::$namespaces); - parent::__construct(); - } - - /** - * @return string - */ - public function __toString() - { - $attribs = $this->getExtensionAttributes(); - return $attribs['name']['value']; - } -} diff --git a/library/Zend/Gdata/Analytics/Extension/Metric.php b/library/Zend/Gdata/Analytics/Extension/Metric.php deleted file mode 100644 index 2f8aca5fd1..0000000000 --- a/library/Zend/Gdata/Analytics/Extension/Metric.php +++ /dev/null @@ -1,54 +0,0 @@ -localName) { - case 'name': - $this->_name = $attribute->nodeValue; - break; - case 'value': - $this->_value = $attribute->nodeValue; - break; - default: - parent::takeAttributeFromDOM($attribute); - } - } -} diff --git a/library/Zend/Gdata/Analytics/Extension/Property.php b/library/Zend/Gdata/Analytics/Extension/Property.php deleted file mode 100644 index 86c16653d8..0000000000 --- a/library/Zend/Gdata/Analytics/Extension/Property.php +++ /dev/null @@ -1,122 +0,0 @@ -registerAllNamespaces(Zend_Gdata_Analytics::$namespaces); - parent::__construct(); - $this->_value = $value; - $this->_name = $name; - } - - /** - * Given a DOMNode representing an attribute, tries to map the data into - * instance members. If no mapping is defined, the name and value are - * stored in an array. - * - * @param DOMNode $attribute The DOMNode attribute needed to be handled - */ - protected function takeAttributeFromDOM($attribute) - { - switch ($attribute->localName) { - case 'name': - $name = explode(':', $attribute->nodeValue); - $this->_name = end($name); - break; - case 'value': - $this->_value = $attribute->nodeValue; - break; - default: - parent::takeAttributeFromDOM($attribute); - } - } - - /** - * Get the value for this element's value attribute. - * - * @return string The value associated with this attribute. - */ - public function getValue() - { - return $this->_value; - } - - /** - * Set the value for this element's value attribute. - * - * @param string $value The desired value for this attribute. - * @return Zend_Gdata_Analytics_Extension_Property The element being modified. - */ - public function setValue($value) - { - $this->_value = $value; - return $this; - } - - /** - * @param string $name - * @return Zend_Gdata_Analytics_Extension_Property - */ - public function setName($name) - { - $this->_name = $name; - return $this; - } - - /** - * @return string - */ - public function getName() - { - return $this->_name; - } - - /** - * Magic toString method allows using this directly via echo - * Works best in PHP >= 4.2.0 - */ - public function __toString() - { - return $this->getValue(); - } -} diff --git a/library/Zend/Gdata/Analytics/Extension/TableId.php b/library/Zend/Gdata/Analytics/Extension/TableId.php deleted file mode 100644 index 70956128e4..0000000000 --- a/library/Zend/Gdata/Analytics/Extension/TableId.php +++ /dev/null @@ -1,112 +0,0 @@ -registerAllNamespaces(Zend_Gdata_Analytics::$namespaces); - parent::__construct(); - $this->_value = $value; - } - - /** - * Retrieves a DOMElement which corresponds to this element and all - * child properties. This is used to build an entry back into a DOM - * and eventually XML text for sending to the server upon updates, or - * for application storage/persistence. - * - * @param DOMDocument $doc The DOMDocument used to construct DOMElements - * @return DOMElement The DOMElement representing this element and all - * child properties. - */ - public function getDOM($doc = null, $majorVersion = 1, $minorVersion = null) - { - $element = parent::getDOM($doc, $majorVersion, $minorVersion); - if ($this->_value != null) { - $element->setAttribute('value', $this->_value); - } - return $element; - } - - /** - * Given a DOMNode representing an attribute, tries to map the data into - * instance members. If no mapping is defined, the name and value are - * stored in an array. - * - * @param DOMNode $attribute The DOMNode attribute needed to be handled - */ - protected function takeChildFromDOM($child) - { - $this->_value = $child->nodeValue; - } - - /** - * Get the value for this element's value attribute. - * - * @return string The value associated with this attribute. - */ - public function getValue() - { - return $this->_value; - } - - /** - * Set the value for this element's value attribute. - * - * @param string $value The desired value for this attribute. - * @return Zend_Gdata_Calendar_Extension_Timezone The element being modified. - */ - public function setValue($value) - { - $this->_value = $value; - return $this; - } - - /** - * Magic toString method allows using this directly via echo - * Works best in PHP >= 4.2.0 - */ - public function __toString() - { - return $this->getValue(); - } -} diff --git a/library/Zend/Gdata/App.php b/library/Zend/Gdata/App.php deleted file mode 100644 index 4ddae97afc..0000000000 --- a/library/Zend/Gdata/App.php +++ /dev/null @@ -1,1246 +0,0 @@ -= 1 is considered valid. - * - * Under most circumtances, this will be automatically set by - * Zend_Gdata_App subclasses. - * - * @see setMajorProtocolVersion() - * @see getMajorProtocolVersion() - */ - protected $_majorProtocolVersion; - - /** - * Indicates the minor protocol version that should be used. Can be set - * to either an integer >= 0, or NULL if no minor version should be sent - * to the server. - * - * At present, this field is not used by any Google services, but may be - * used in the future. - * - * Under most circumtances, this will be automatically set by - * Zend_Gdata_App subclasses. - * - * @see setMinorProtocolVersion() - * @see getMinorProtocolVersion() - */ - protected $_minorProtocolVersion; - - /** - * Whether we want to use XML to object mapping when fetching data. - * - * @var boolean - */ - protected $_useObjectMapping = true; - - /** - * Create Gdata object - * - * @param Zend_Http_Client $client - * @param string $applicationId - */ - public function __construct($client = null, $applicationId = 'MyCompany-MyApp-1.0') - { - $this->setHttpClient($client, $applicationId); - // Set default protocol version. Subclasses should override this as - // needed once a given service supports a new version. - $this->setMajorProtocolVersion(self::DEFAULT_MAJOR_PROTOCOL_VERSION); - $this->setMinorProtocolVersion(self::DEFAULT_MINOR_PROTOCOL_VERSION); - } - - /** - * Adds a Zend Framework package to the $_registeredPackages array. - * This array is searched when using the magic __call method below - * to instantiante new objects. - * - * @param string $name The name of the package (eg Zend_Gdata_App) - * @return void - */ - public function registerPackage($name) - { - array_unshift($this->_registeredPackages, $name); - } - - /** - * Retrieve feed as string or object - * - * @param string $uri The uri from which to retrieve the feed - * @param string $className The class which is used as the return type - * @return string|Zend_Gdata_App_Feed Returns string only if the object - * mapping has been disabled explicitly - * by passing false to the - * useObjectMapping() function. - */ - public function getFeed($uri, $className='Zend_Gdata_App_Feed') - { - return $this->importUrl($uri, $className, null); - } - - /** - * Retrieve entry as string or object - * - * @param string $uri - * @param string $className The class which is used as the return type - * @return string|Zend_Gdata_App_Entry Returns string only if the object - * mapping has been disabled explicitly - * by passing false to the - * useObjectMapping() function. - */ - public function getEntry($uri, $className='Zend_Gdata_App_Entry') - { - return $this->importUrl($uri, $className, null); - } - - /** - * Get the Zend_Http_Client object used for communication - * - * @return Zend_Http_Client - */ - public function getHttpClient() - { - return $this->_httpClient; - } - - /** - * Set the Zend_Http_Client object used for communication - * - * @param Zend_Http_Client $client The client to use for communication - * @throws Zend_Gdata_App_HttpException - * @return Zend_Gdata_App Provides a fluent interface - */ - public function setHttpClient($client, - $applicationId = 'MyCompany-MyApp-1.0') - { - if ($client === null) { - $client = new Zend_Http_Client(); - } - if (!$client instanceof Zend_Http_Client) { - #require_once 'Zend/Gdata/App/HttpException.php'; - throw new Zend_Gdata_App_HttpException( - 'Argument is not an instance of Zend_Http_Client.'); - } - $userAgent = $applicationId . ' Zend_Framework_Gdata/' . - Zend_Version::VERSION; - $client->setHeaders('User-Agent', $userAgent); - $client->setConfig(array( - 'strictredirects' => true - ) - ); - $this->_httpClient = $client; - self::setStaticHttpClient($client); - return $this; - } - - /** - * Set the static HTTP client instance - * - * Sets the static HTTP client object to use for retrieving the feed. - * - * @param Zend_Http_Client $httpClient - * @return void - */ - public static function setStaticHttpClient(Zend_Http_Client $httpClient) - { - self::$_staticHttpClient = $httpClient; - } - - - /** - * Gets the HTTP client object. If none is set, a new Zend_Http_Client will be used. - * - * @return Zend_Http_Client - */ - public static function getStaticHttpClient() - { - if (!self::$_staticHttpClient instanceof Zend_Http_Client) { - $client = new Zend_Http_Client(); - $userAgent = 'Zend_Framework_Gdata/' . Zend_Version::VERSION; - $client->setHeaders('User-Agent', $userAgent); - $client->setConfig(array( - 'strictredirects' => true - ) - ); - self::$_staticHttpClient = $client; - } - return self::$_staticHttpClient; - } - - /** - * Toggle using POST instead of PUT and DELETE HTTP methods - * - * Some feed implementations do not accept PUT and DELETE HTTP - * methods, or they can't be used because of proxies or other - * measures. This allows turning on using POST where PUT and - * DELETE would normally be used; in addition, an - * X-Method-Override header will be sent with a value of PUT or - * DELETE as appropriate. - * - * @param boolean $override Whether to override PUT and DELETE with POST. - * @return void - */ - public static function setHttpMethodOverride($override = true) - { - self::$_httpMethodOverride = $override; - } - - /** - * Get the HTTP override state - * - * @return boolean - */ - public static function getHttpMethodOverride() - { - return self::$_httpMethodOverride; - } - - /** - * Toggle requesting gzip encoded responses - * - * @param boolean $enabled Whether or not to enable gzipped responses - * @return void - */ - public static function setGzipEnabled($enabled = false) - { - if ($enabled && !function_exists('gzinflate')) { - #require_once 'Zend/Gdata/App/InvalidArgumentException.php'; - throw new Zend_Gdata_App_InvalidArgumentException( - 'You cannot enable gzipped responses if the zlib module ' . - 'is not enabled in your PHP installation.'); - - } - self::$_gzipEnabled = $enabled; - } - - /** - * Get the HTTP override state - * - * @return boolean - */ - public static function getGzipEnabled() - { - return self::$_gzipEnabled; - } - - /** - * Get whether to use verbose exception messages - * - * In the case of HTTP errors, use the body of the HTTP response - * in the exception message. - * - * @return boolean - */ - public static function getVerboseExceptionMessages() - { - return self::$_verboseExceptionMessages; - } - - /** - * Set whether to use verbose exception messages - * - * In the case of HTTP errors, use the body of the HTTP response - * in the exception message. - * - * @param boolean $verbose Whether to use verbose exception messages - */ - public static function setVerboseExceptionMessages($verbose) - { - self::$_verboseExceptionMessages = $verbose; - } - - /** - * Set the maximum number of redirects to follow during HTTP operations - * - * @param int $maxRedirects Maximum number of redirects to follow - * @return void - */ - public static function setMaxRedirects($maxRedirects) - { - self::$_maxRedirects = $maxRedirects; - } - - /** - * Get the maximum number of redirects to follow during HTTP operations - * - * @return int Maximum number of redirects to follow - */ - public static function getMaxRedirects() - { - return self::$_maxRedirects; - } - - /** - * Set the major protocol version that should be used. Values < 1 will - * cause a Zend_Gdata_App_InvalidArgumentException to be thrown. - * - * @see _majorProtocolVersion - * @param int $value The major protocol version to use. - * @throws Zend_Gdata_App_InvalidArgumentException - */ - public function setMajorProtocolVersion($value) - { - if (!($value >= 1)) { - #require_once('Zend/Gdata/App/InvalidArgumentException.php'); - throw new Zend_Gdata_App_InvalidArgumentException( - 'Major protocol version must be >= 1'); - } - $this->_majorProtocolVersion = $value; - } - - /** - * Get the major protocol version that is in use. - * - * @see _majorProtocolVersion - * @return int The major protocol version in use. - */ - public function getMajorProtocolVersion() - { - return $this->_majorProtocolVersion; - } - - /** - * Set the minor protocol version that should be used. If set to NULL, no - * minor protocol version will be sent to the server. Values < 0 will - * cause a Zend_Gdata_App_InvalidArgumentException to be thrown. - * - * @see _minorProtocolVersion - * @param (int|NULL) $value The minor protocol version to use. - * @throws Zend_Gdata_App_InvalidArgumentException - */ - public function setMinorProtocolVersion($value) - { - if (!($value >= 0)) { - #require_once('Zend/Gdata/App/InvalidArgumentException.php'); - throw new Zend_Gdata_App_InvalidArgumentException( - 'Minor protocol version must be >= 0'); - } - $this->_minorProtocolVersion = $value; - } - - /** - * Get the minor protocol version that is in use. - * - * @see _minorProtocolVersion - * @return (int|NULL) The major protocol version in use, or NULL if no - * minor version is specified. - */ - public function getMinorProtocolVersion() - { - return $this->_minorProtocolVersion; - } - - /** - * Provides pre-processing for HTTP requests to APP services. - * - * 1. Checks the $data element and, if it's an entry, extracts the XML, - * multipart data, edit link (PUT,DELETE), etc. - * 2. If $data is a string, sets the default content-type header as - * 'application/atom+xml' if it's not already been set. - * 3. Adds a x-http-method override header and changes the HTTP method - * to 'POST' if necessary as per getHttpMethodOverride() - * - * @param string $method The HTTP method for the request - 'GET', 'POST', - * 'PUT', 'DELETE' - * @param string $url The URL to which this request is being performed, - * or null if found in $data - * @param array $headers An associative array of HTTP headers for this - * request - * @param mixed $data The Zend_Gdata_App_Entry or XML for the - * body of the request - * @param string $contentTypeOverride The override value for the - * content type of the request body - * @return array An associative array containing the determined - * 'method', 'url', 'data', 'headers', 'contentType' - */ - public function prepareRequest($method, - $url = null, - $headers = array(), - $data = null, - $contentTypeOverride = null) - { - // As a convenience, if $headers is null, we'll convert it back to - // an empty array. - if ($headers === null) { - $headers = array(); - } - - $rawData = null; - $finalContentType = null; - if ($url == null) { - $url = $this->_defaultPostUri; - } - - if (is_string($data)) { - $rawData = $data; - if ($contentTypeOverride === null) { - $finalContentType = 'application/atom+xml'; - } - } elseif ($data instanceof Zend_Gdata_App_MediaEntry) { - $rawData = $data->encode(); - if ($data->getMediaSource() !== null) { - $finalContentType = $rawData->getContentType(); - $headers['MIME-version'] = '1.0'; - $headers['Slug'] = $data->getMediaSource()->getSlug(); - } else { - $finalContentType = 'application/atom+xml'; - } - if ($method == 'PUT' || $method == 'DELETE') { - $editLink = $data->getEditLink(); - if ($editLink != null && $url == null) { - $url = $editLink->getHref(); - } - } - } elseif ($data instanceof Zend_Gdata_App_Entry) { - $rawData = $data->saveXML(); - $finalContentType = 'application/atom+xml'; - if ($method == 'PUT' || $method == 'DELETE') { - $editLink = $data->getEditLink(); - if ($editLink != null) { - $url = $editLink->getHref(); - } - } - } elseif ($data instanceof Zend_Gdata_App_MediaSource) { - $rawData = $data->encode(); - if ($data->getSlug() !== null) { - $headers['Slug'] = $data->getSlug(); - } - $finalContentType = $data->getContentType(); - } - - if ($method == 'DELETE') { - $rawData = null; - } - - // Set an If-Match header if: - // - This isn't a DELETE - // - If this isn't a GET, the Etag isn't weak - // - A similar header (If-Match/If-None-Match) hasn't already been - // set. - if ($method != 'DELETE' && ( - !array_key_exists('If-Match', $headers) && - !array_key_exists('If-None-Match', $headers) - ) ) { - $allowWeak = $method == 'GET'; - if ($ifMatchHeader = $this->generateIfMatchHeaderData( - $data, $allowWeak)) { - $headers['If-Match'] = $ifMatchHeader; - } - } - - if ($method != 'POST' && $method != 'GET' && Zend_Gdata_App::getHttpMethodOverride()) { - $headers['x-http-method-override'] = $method; - $method = 'POST'; - } else { - $headers['x-http-method-override'] = null; - } - - if ($contentTypeOverride != null) { - $finalContentType = $contentTypeOverride; - } - - return array('method' => $method, 'url' => $url, - 'data' => $rawData, 'headers' => $headers, - 'contentType' => $finalContentType); - } - - /** - * Performs a HTTP request using the specified method - * - * @param string $method The HTTP method for the request - 'GET', 'POST', - * 'PUT', 'DELETE' - * @param string $url The URL to which this request is being performed - * @param array $headers An associative array of HTTP headers - * for this request - * @param string $body The body of the HTTP request - * @param string $contentType The value for the content type - * of the request body - * @param int $remainingRedirects Number of redirects to follow if request - * s results in one - * @return Zend_Http_Response The response object - */ - public function performHttpRequest($method, $url, $headers = null, - $body = null, $contentType = null, $remainingRedirects = null) - { - #require_once 'Zend/Http/Client/Exception.php'; - if ($remainingRedirects === null) { - $remainingRedirects = self::getMaxRedirects(); - } - if ($headers === null) { - $headers = array(); - } - // Append a Gdata version header if protocol v2 or higher is in use. - // (Protocol v1 does not use this header.) - $major = $this->getMajorProtocolVersion(); - $minor = $this->getMinorProtocolVersion(); - if ($major >= 2) { - $headers['GData-Version'] = $major + - (($minor === null) ? '.' + $minor : ''); - } - - // check the overridden method - if (($method == 'POST' || $method == 'PUT') && $body === null && - $headers['x-http-method-override'] != 'DELETE') { - #require_once 'Zend/Gdata/App/InvalidArgumentException.php'; - throw new Zend_Gdata_App_InvalidArgumentException( - 'You must specify the data to post as either a ' . - 'string or a child of Zend_Gdata_App_Entry'); - } - if ($url === null) { - #require_once 'Zend/Gdata/App/InvalidArgumentException.php'; - throw new Zend_Gdata_App_InvalidArgumentException( - 'You must specify an URI to which to post.'); - } - $headers['Content-Type'] = $contentType; - if (Zend_Gdata_App::getGzipEnabled()) { - // some services require the word 'gzip' to be in the user-agent - // header in addition to the accept-encoding header - if (strpos($this->_httpClient->getHeader('User-Agent'), - 'gzip') === false) { - $headers['User-Agent'] = - $this->_httpClient->getHeader('User-Agent') . ' (gzip)'; - } - $headers['Accept-encoding'] = 'gzip, deflate'; - } else { - $headers['Accept-encoding'] = 'identity'; - } - - // Make sure the HTTP client object is 'clean' before making a request - // In addition to standard headers to reset via resetParameters(), - // also reset the Slug and If-Match headers - $this->_httpClient->resetParameters(); - $this->_httpClient->setHeaders(array('Slug', 'If-Match')); - - // Set the params for the new request to be performed - $this->_httpClient->setHeaders($headers); - #require_once 'Zend/Uri/Http.php'; - $uri = Zend_Uri_Http::fromString($url); - preg_match("/^(.*?)(\?.*)?$/", $url, $matches); - $this->_httpClient->setUri($matches[1]); - $queryArray = $uri->getQueryAsArray(); - foreach ($queryArray as $name => $value) { - $this->_httpClient->setParameterGet($name, $value); - } - - - $this->_httpClient->setConfig(array('maxredirects' => 0)); - - // Set the proper adapter if we are handling a streaming upload - $usingMimeStream = false; - $oldHttpAdapter = null; - - if ($body instanceof Zend_Gdata_MediaMimeStream) { - $usingMimeStream = true; - $this->_httpClient->setRawDataStream($body, $contentType); - $oldHttpAdapter = $this->_httpClient->getAdapter(); - - if ($oldHttpAdapter instanceof Zend_Http_Client_Adapter_Proxy) { - #require_once 'Zend/Gdata/HttpAdapterStreamingProxy.php'; - $newAdapter = new Zend_Gdata_HttpAdapterStreamingProxy(); - } else { - #require_once 'Zend/Gdata/HttpAdapterStreamingSocket.php'; - $newAdapter = new Zend_Gdata_HttpAdapterStreamingSocket(); - } - $this->_httpClient->setAdapter($newAdapter); - } else { - $this->_httpClient->setRawData($body, $contentType); - } - - try { - $response = $this->_httpClient->request($method); - // reset adapter - if ($usingMimeStream) { - $this->_httpClient->setAdapter($oldHttpAdapter); - } - } catch (Zend_Http_Client_Exception $e) { - // reset adapter - if ($usingMimeStream) { - $this->_httpClient->setAdapter($oldHttpAdapter); - } - #require_once 'Zend/Gdata/App/HttpException.php'; - throw new Zend_Gdata_App_HttpException($e->getMessage(), $e); - } - if ($response->isRedirect() && $response->getStatus() != '304') { - if ($remainingRedirects > 0) { - $newUrl = $response->getHeader('Location'); - $response = $this->performHttpRequest( - $method, $newUrl, $headers, $body, - $contentType, $remainingRedirects); - } else { - #require_once 'Zend/Gdata/App/HttpException.php'; - throw new Zend_Gdata_App_HttpException( - 'Number of redirects exceeds maximum', null, $response); - } - } - if (!$response->isSuccessful()) { - #require_once 'Zend/Gdata/App/HttpException.php'; - $exceptionMessage = 'Expected response code 200, got ' . - $response->getStatus(); - if (self::getVerboseExceptionMessages()) { - $exceptionMessage .= "\n" . $response->getBody(); - } - $exception = new Zend_Gdata_App_HttpException($exceptionMessage); - $exception->setResponse($response); - throw $exception; - } - return $response; - } - - /** - * Imports a feed located at $uri. - * - * @param string $uri - * @param Zend_Http_Client $client The client used for communication - * @param string $className The class which is used as the return type - * @param bool $useObjectMapping Enable/disable the use of XML to object mapping. - * @throws Zend_Gdata_App_Exception - * @return string|Zend_Gdata_App_Feed Returns string only if the fourth - * parameter ($useObjectMapping) is set - * to false. - */ - public static function import($uri, $client = null, - $className='Zend_Gdata_App_Feed', $useObjectMapping = true) - { - $app = new Zend_Gdata_App($client); - $requestData = $app->prepareRequest('GET', $uri); - $response = $app->performHttpRequest( - $requestData['method'], $requestData['url']); - - $feedContent = $response->getBody(); - if (false === $useObjectMapping) { - return $feedContent; - } - $feed = self::importString($feedContent, $className); - if ($client != null) { - $feed->setHttpClient($client); - } - return $feed; - } - - /** - * Imports the specified URL (non-statically). - * - * @param string $url The URL to import - * @param string $className The class which is used as the return type - * @param array $extraHeaders Extra headers to add to the request, as an - * array of string-based key/value pairs. - * @throws Zend_Gdata_App_Exception - * @return string|Zend_Gdata_App_Feed Returns string only if the object - * mapping has been disabled explicitly - * by passing false to the - * useObjectMapping() function. - */ - public function importUrl($url, $className='Zend_Gdata_App_Feed', - $extraHeaders = array()) - { - $response = $this->get($url, $extraHeaders); - - $feedContent = $response->getBody(); - if (!$this->_useObjectMapping) { - return $feedContent; - } - - $protocolVersionStr = $response->getHeader('GData-Version'); - $majorProtocolVersion = null; - $minorProtocolVersion = null; - if ($protocolVersionStr !== null) { - // Extract protocol major and minor version from header - $delimiterPos = strpos($protocolVersionStr, '.'); - $length = strlen($protocolVersionStr); - $major = substr($protocolVersionStr, 0, $delimiterPos); - $minor = substr($protocolVersionStr, $delimiterPos + 1, $length); - $majorProtocolVersion = $major; - $minorProtocolVersion = $minor; - } - - $feed = self::importString($feedContent, $className, - $majorProtocolVersion, $minorProtocolVersion); - if ($this->getHttpClient() != null) { - $feed->setHttpClient($this->getHttpClient()); - } - $etag = $response->getHeader('ETag'); - if ($etag !== null) { - $feed->setEtag($etag); - } - return $feed; - } - - - /** - * Imports a feed represented by $string. - * - * @param string $string - * @param string $className The class which is used as the return type - * @param integer $majorProcolVersion (optional) The major protocol version - * of the data model object that is to be created. - * @param integer $minorProcolVersion (optional) The minor protocol version - * of the data model object that is to be created. - * @throws Zend_Gdata_App_Exception - * @return Zend_Gdata_App_Feed - */ - public static function importString($string, - $className='Zend_Gdata_App_Feed', $majorProtocolVersion = null, - $minorProtocolVersion = null) - { - if (!class_exists($className, false)) { - #require_once 'Zend/Loader.php'; - @Zend_Loader::loadClass($className); - } - - // Load the feed as an XML DOMDocument object - @ini_set('track_errors', 1); - $doc = new DOMDocument(); - $doc = @Zend_Xml_Security::scan($string, $doc); - @ini_restore('track_errors'); - - if (!$doc) { - #require_once 'Zend/Gdata/App/Exception.php'; - throw new Zend_Gdata_App_Exception( - "DOMDocument cannot parse XML: $php_errormsg"); - } - - $feed = new $className(); - $feed->setMajorProtocolVersion($majorProtocolVersion); - $feed->setMinorProtocolVersion($minorProtocolVersion); - $feed->transferFromXML($string); - $feed->setHttpClient(self::getstaticHttpClient()); - return $feed; - } - - - /** - * Imports a feed from a file located at $filename. - * - * @param string $filename - * @param string $className The class which is used as the return type - * @param string $useIncludePath Whether the include_path should be searched - * @throws Zend_Gdata_App_Exception - * @return Zend_Gdata_App_Feed - */ - public static function importFile($filename, - $className='Zend_Gdata_App_Feed', $useIncludePath = false) - { - @ini_set('track_errors', 1); - $feed = @file_get_contents($filename, $useIncludePath); - @ini_restore('track_errors'); - if ($feed === false) { - #require_once 'Zend/Gdata/App/Exception.php'; - throw new Zend_Gdata_App_Exception( - "File could not be loaded: $php_errormsg"); - } - return self::importString($feed, $className); - } - - /** - * GET a URI using client object. - * - * @param string $uri GET URI - * @param array $extraHeaders Extra headers to add to the request, as an - * array of string-based key/value pairs. - * @throws Zend_Gdata_App_HttpException - * @return Zend_Http_Response - */ - public function get($uri, $extraHeaders = array()) - { - $requestData = $this->prepareRequest('GET', $uri, $extraHeaders); - return $this->performHttpRequest( - $requestData['method'], $requestData['url'], - $requestData['headers']); - } - - /** - * POST data with client object - * - * @param mixed $data The Zend_Gdata_App_Entry or XML to post - * @param string $uri POST URI - * @param array $headers Additional HTTP headers to insert. - * @param string $contentType Content-type of the data - * @param array $extraHeaders Extra headers to add to the request, as an - * array of string-based key/value pairs. - * @return Zend_Http_Response - * @throws Zend_Gdata_App_Exception - * @throws Zend_Gdata_App_HttpException - * @throws Zend_Gdata_App_InvalidArgumentException - */ - public function post($data, $uri = null, $remainingRedirects = null, - $contentType = null, $extraHeaders = null) - { - $requestData = $this->prepareRequest( - 'POST', $uri, $extraHeaders, $data, $contentType); - return $this->performHttpRequest( - $requestData['method'], $requestData['url'], - $requestData['headers'], $requestData['data'], - $requestData['contentType']); - } - - /** - * PUT data with client object - * - * @param mixed $data The Zend_Gdata_App_Entry or XML to post - * @param string $uri PUT URI - * @param array $headers Additional HTTP headers to insert. - * @param string $contentType Content-type of the data - * @param array $extraHeaders Extra headers to add to the request, as an - * array of string-based key/value pairs. - * @return Zend_Http_Response - * @throws Zend_Gdata_App_Exception - * @throws Zend_Gdata_App_HttpException - * @throws Zend_Gdata_App_InvalidArgumentException - */ - public function put($data, $uri = null, $remainingRedirects = null, - $contentType = null, $extraHeaders = null) - { - $requestData = $this->prepareRequest( - 'PUT', $uri, $extraHeaders, $data, $contentType); - return $this->performHttpRequest( - $requestData['method'], $requestData['url'], - $requestData['headers'], $requestData['data'], - $requestData['contentType']); - } - - /** - * DELETE entry with client object - * - * @param mixed $data The Zend_Gdata_App_Entry or URL to delete - * @return void - * @throws Zend_Gdata_App_Exception - * @throws Zend_Gdata_App_HttpException - * @throws Zend_Gdata_App_InvalidArgumentException - */ - public function delete($data, $remainingRedirects = null) - { - if (is_string($data)) { - $requestData = $this->prepareRequest('DELETE', $data); - } else { - $headers = array(); - - $requestData = $this->prepareRequest( - 'DELETE', null, $headers, $data); - } - return $this->performHttpRequest($requestData['method'], - $requestData['url'], - $requestData['headers'], - '', - $requestData['contentType'], - $remainingRedirects); - } - - /** - * Inserts an entry to a given URI and returns the response as a - * fully formed Entry. - * - * @param mixed $data The Zend_Gdata_App_Entry or XML to post - * @param string $uri POST URI - * @param string $className The class of entry to be returned. - * @param array $extraHeaders Extra headers to add to the request, as an - * array of string-based key/value pairs. - * @return Zend_Gdata_App_Entry The entry returned by the service after - * insertion. - */ - public function insertEntry($data, $uri, $className='Zend_Gdata_App_Entry', - $extraHeaders = array()) - { - if (!class_exists($className, false)) { - #require_once 'Zend/Loader.php'; - @Zend_Loader::loadClass($className); - } - - $response = $this->post($data, $uri, null, null, $extraHeaders); - - $returnEntry = new $className($response->getBody()); - $returnEntry->setHttpClient(self::getstaticHttpClient()); - - $etag = $response->getHeader('ETag'); - if ($etag !== null) { - $returnEntry->setEtag($etag); - } - - return $returnEntry; - } - - /** - * Update an entry - * - * @param mixed $data Zend_Gdata_App_Entry or XML (w/ID and link rel='edit') - * @param string|null The URI to send requests to, or null if $data - * contains the URI. - * @param string|null The name of the class that should be deserialized - * from the server response. If null, then 'Zend_Gdata_App_Entry' - * will be used. - * @param array $extraHeaders Extra headers to add to the request, as an - * array of string-based key/value pairs. - * @return Zend_Gdata_App_Entry The entry returned from the server - * @throws Zend_Gdata_App_Exception - */ - public function updateEntry($data, $uri = null, $className = null, - $extraHeaders = array()) - { - if ($className === null && $data instanceof Zend_Gdata_App_Entry) { - $className = get_class($data); - } elseif ($className === null) { - $className = 'Zend_Gdata_App_Entry'; - } - - if (!class_exists($className, false)) { - #require_once 'Zend/Loader.php'; - @Zend_Loader::loadClass($className); - } - - $response = $this->put($data, $uri, null, null, $extraHeaders); - $returnEntry = new $className($response->getBody()); - $returnEntry->setHttpClient(self::getstaticHttpClient()); - - $etag = $response->getHeader('ETag'); - if ($etag !== null) { - $returnEntry->setEtag($etag); - } - - return $returnEntry; - } - - /** - * Provides a magic factory method to instantiate new objects with - * shorter syntax than would otherwise be required by the Zend Framework - * naming conventions. For instance, to construct a new - * Zend_Gdata_Calendar_Extension_Color, a developer simply needs to do - * $gCal->newColor(). For this magic constructor, packages are searched - * in the same order as which they appear in the $_registeredPackages - * array - * - * @param string $method The method name being called - * @param array $args The arguments passed to the call - * @throws Zend_Gdata_App_Exception - */ - public function __call($method, $args) - { - if (preg_match('/^new(\w+)/', $method, $matches)) { - $class = $matches[1]; - $foundClassName = null; - foreach ($this->_registeredPackages as $name) { - try { - // Autoloading disabled on next line for compatibility - // with magic factories. See ZF-6660. - if (!class_exists($name . '_' . $class, false)) { - #require_once 'Zend/Loader.php'; - @Zend_Loader::loadClass($name . '_' . $class); - } - $foundClassName = $name . '_' . $class; - break; - } catch (Zend_Exception $e) { - // package wasn't here- continue searching - } catch (ErrorException $e) { - // package wasn't here- continue searching - // @see ZF-7013 and ZF-11959 - } - } - if ($foundClassName != null) { - $reflectionObj = new ReflectionClass($foundClassName); - $instance = $reflectionObj->newInstanceArgs($args); - if ($instance instanceof Zend_Gdata_App_FeedEntryParent) { - $instance->setHttpClient($this->_httpClient); - - // Propogate version data - $instance->setMajorProtocolVersion( - $this->_majorProtocolVersion); - $instance->setMinorProtocolVersion( - $this->_minorProtocolVersion); - } - return $instance; - } else { - #require_once 'Zend/Gdata/App/Exception.php'; - throw new Zend_Gdata_App_Exception( - "Unable to find '${class}' in registered packages"); - } - } else { - #require_once 'Zend/Gdata/App/Exception.php'; - throw new Zend_Gdata_App_Exception("No such method ${method}"); - } - } - - /** - * Retrieve all entries for a feed, iterating through pages as necessary. - * Be aware that calling this function on a large dataset will take a - * significant amount of time to complete. In some cases this may cause - * execution to timeout without proper precautions in place. - * - * @param object $feed The feed to iterate through. - * @return mixed A new feed of the same type as the one originally - * passed in, containing all relevent entries. - */ - public function retrieveAllEntriesForFeed($feed) { - $feedClass = get_class($feed); - $reflectionObj = new ReflectionClass($feedClass); - $result = $reflectionObj->newInstance(); - do { - foreach ($feed as $entry) { - $result->addEntry($entry); - } - - $next = $feed->getLink('next'); - if ($next !== null) { - $feed = $this->getFeed($next->href, $feedClass); - } else { - $feed = null; - } - } - while ($feed != null); - return $result; - } - - /** - * This method enables logging of requests by changing the - * Zend_Http_Client_Adapter used for performing the requests. - * NOTE: This will not work if you have customized the adapter - * already to use a proxy server or other interface. - * - * @param string $logfile The logfile to use when logging the requests - */ - public function enableRequestDebugLogging($logfile) - { - $this->_httpClient->setConfig(array( - 'adapter' => 'Zend_Gdata_App_LoggingHttpClientAdapterSocket', - 'logfile' => $logfile - )); - } - - /** - * Retrieve next set of results based on a given feed. - * - * @param Zend_Gdata_App_Feed $feed The feed from which to - * retreive the next set of results. - * @param string $className (optional) The class of feed to be returned. - * If null, the next feed (if found) will be the same class as - * the feed that was given as the first argument. - * @return Zend_Gdata_App_Feed|null Returns a - * Zend_Gdata_App_Feed or null if no next set of results - * exists. - */ - public function getNextFeed($feed, $className = null) - { - $nextLink = $feed->getNextLink(); - if (!$nextLink) { - return null; - } - $nextLinkHref = $nextLink->getHref(); - - if ($className === null) { - $className = get_class($feed); - } - - return $this->getFeed($nextLinkHref, $className); - } - - /** - * Retrieve previous set of results based on a given feed. - * - * @param Zend_Gdata_App_Feed $feed The feed from which to - * retreive the previous set of results. - * @param string $className (optional) The class of feed to be returned. - * If null, the previous feed (if found) will be the same class as - * the feed that was given as the first argument. - * @return Zend_Gdata_App_Feed|null Returns a - * Zend_Gdata_App_Feed or null if no previous set of results - * exists. - */ - public function getPreviousFeed($feed, $className = null) - { - $previousLink = $feed->getPreviousLink(); - if (!$previousLink) { - return null; - } - $previousLinkHref = $previousLink->getHref(); - - if ($className === null) { - $className = get_class($feed); - } - - return $this->getFeed($previousLinkHref, $className); - } - - /** - * Returns the data for an If-Match header based on the current Etag - * property. If Etags are not supported by the server or cannot be - * extracted from the data, then null will be returned. - * - * @param boolean $allowWeak If false, then if a weak Etag is detected, - * then return null rather than the Etag. - * @return string|null $data - */ - public function generateIfMatchHeaderData($data, $allowWeek) - { - $result = ''; - // Set an If-Match header if an ETag has been set (version >= 2 only) - if ($this->_majorProtocolVersion >= 2 && - $data instanceof Zend_Gdata_App_Entry) { - $etag = $data->getEtag(); - if (($etag !== null) && - ($allowWeek || substr($etag, 0, 2) != 'W/')) { - $result = $data->getEtag(); - } - } - return $result; - } - - /** - * Determine whether service object is using XML to object mapping. - * - * @return boolean True if service object is using XML to object mapping, - * false otherwise. - */ - public function usingObjectMapping() - { - return $this->_useObjectMapping; - } - - /** - * Enable/disable the use of XML to object mapping. - * - * @param boolean $value Pass in true to use the XML to object mapping. - * Pass in false or null to disable it. - * @return void - */ - public function useObjectMapping($value) - { - if ($value === True) { - $this->_useObjectMapping = true; - } else { - $this->_useObjectMapping = false; - } - } - -} diff --git a/library/Zend/Gdata/App/AuthException.php b/library/Zend/Gdata/App/AuthException.php deleted file mode 100644 index 9bd7a8468f..0000000000 --- a/library/Zend/Gdata/App/AuthException.php +++ /dev/null @@ -1,41 +0,0 @@ - array( - 1 => array( - 0 => 'http://www.w3.org/2005/Atom' - ) - ), - 'app' => array( - 1 => array( - 0 => 'http://purl.org/atom/app#' - ), - 2 => array( - 0 => 'http://www.w3.org/2007/app' - ) - ) - ); - - public function __construct() - { - } - - /** - * Returns the child text node of this element - * This represents any raw text contained within the XML element - * - * @return string Child text node - */ - public function getText($trim = true) - { - if ($trim) { - return trim($this->_text); - } else { - return $this->_text; - } - } - - /** - * Sets the child text node of this element - * This represents any raw text contained within the XML element - * - * @param string $value Child text node - * @return Zend_Gdata_App_Base Returns an object of the same type as 'this' to provide a fluent interface. - */ - public function setText($value) - { - $this->_text = $value; - return $this; - } - - /** - * Returns an array of all elements not matched to data model classes - * during the parsing of the XML - * - * @return array All elements not matched to data model classes during parsing - */ - public function getExtensionElements() - { - return $this->_extensionElements; - } - - /** - * Sets an array of all elements not matched to data model classes - * during the parsing of the XML. This method can be used to add arbitrary - * child XML elements to any data model class. - * - * @param array $value All extension elements - * @return Zend_Gdata_App_Base Returns an object of the same type as 'this' to provide a fluent interface. - */ - public function setExtensionElements($value) - { - $this->_extensionElements = $value; - return $this; - } - - /** - * Returns an array of all extension attributes not transformed into data - * model properties during parsing of the XML. Each element of the array - * is a hashed array of the format: - * array('namespaceUri' => string, 'name' => string, 'value' => string); - * - * @return array All extension attributes - */ - public function getExtensionAttributes() - { - return $this->_extensionAttributes; - } - - /** - * Sets an array of all extension attributes not transformed into data - * model properties during parsing of the XML. Each element of the array - * is a hashed array of the format: - * array('namespaceUri' => string, 'name' => string, 'value' => string); - * This can be used to add arbitrary attributes to any data model element - * - * @param array $value All extension attributes - * @return Zend_Gdata_App_Base Returns an object of the same type as 'this' to provide a fluent interface. - */ - public function setExtensionAttributes($value) - { - $this->_extensionAttributes = $value; - return $this; - } - - /** - * Retrieves a DOMElement which corresponds to this element and all - * child properties. This is used to build an entry back into a DOM - * and eventually XML text for sending to the server upon updates, or - * for application storage/persistence. - * - * @param DOMDocument $doc The DOMDocument used to construct DOMElements - * @return DOMElement The DOMElement representing this element and all - * child properties. - */ - public function getDOM($doc = null, $majorVersion = 1, $minorVersion = null) - { - if ($doc === null) { - $doc = new DOMDocument('1.0', 'utf-8'); - } - if ($this->_rootNamespaceURI != null) { - $element = $doc->createElementNS($this->_rootNamespaceURI, $this->_rootElement); - } elseif ($this->_rootNamespace !== null) { - if (strpos($this->_rootElement, ':') === false) { - $elementName = $this->_rootNamespace . ':' . $this->_rootElement; - } else { - $elementName = $this->_rootElement; - } - $element = $doc->createElementNS($this->lookupNamespace($this->_rootNamespace), $elementName); - } else { - $element = $doc->createElement($this->_rootElement); - } - if ($this->_text != null) { - $element->appendChild($element->ownerDocument->createTextNode($this->_text)); - } - foreach ($this->_extensionElements as $extensionElement) { - $element->appendChild($extensionElement->getDOM($element->ownerDocument)); - } - foreach ($this->_extensionAttributes as $attribute) { - $element->setAttribute($attribute['name'], $attribute['value']); - } - return $element; - } - - /** - * Given a child DOMNode, tries to determine how to map the data into - * object instance members. If no mapping is defined, Extension_Element - * objects are created and stored in an array. - * - * @param DOMNode $child The DOMNode needed to be handled - */ - protected function takeChildFromDOM($child) - { - if ($child->nodeType == XML_TEXT_NODE) { - $this->_text = $child->nodeValue; - } else { - $extensionElement = new Zend_Gdata_App_Extension_Element(); - $extensionElement->transferFromDOM($child); - $this->_extensionElements[] = $extensionElement; - } - } - - /** - * Given a DOMNode representing an attribute, tries to map the data into - * instance members. If no mapping is defined, the name and value are - * stored in an array. - * - * @param DOMNode $attribute The DOMNode attribute needed to be handled - */ - protected function takeAttributeFromDOM($attribute) - { - $arrayIndex = ($attribute->namespaceURI != '')?( - $attribute->namespaceURI . ':' . $attribute->name): - $attribute->name; - $this->_extensionAttributes[$arrayIndex] = - array('namespaceUri' => $attribute->namespaceURI, - 'name' => $attribute->localName, - 'value' => $attribute->nodeValue); - } - - /** - * Transfers each child and attribute into member variables. - * This is called when XML is received over the wire and the data - * model needs to be built to represent this XML. - * - * @param DOMNode $node The DOMNode that represents this object's data - */ - public function transferFromDOM($node) - { - foreach ($node->childNodes as $child) { - $this->takeChildFromDOM($child); - } - foreach ($node->attributes as $attribute) { - $this->takeAttributeFromDOM($attribute); - } - } - - /** - * Parses the provided XML text and generates data model classes for - * each know element by turning the XML text into a DOM tree and calling - * transferFromDOM($element). The first data model element with the same - * name as $this->_rootElement is used and the child elements are - * recursively parsed. - * - * @param string $xml The XML text to parse - */ - public function transferFromXML($xml) - { - if ($xml) { - // Load the feed as an XML DOMDocument object - @ini_set('track_errors', 1); - $doc = new DOMDocument(); - $doc = @Zend_Xml_Security::scan($xml, $doc); - @ini_restore('track_errors'); - if (!$doc) { - #require_once 'Zend/Gdata/App/Exception.php'; - throw new Zend_Gdata_App_Exception("DOMDocument cannot parse XML: $php_errormsg"); - } - $element = $doc->getElementsByTagName($this->_rootElement)->item(0); - if (!$element) { - #require_once 'Zend/Gdata/App/Exception.php'; - throw new Zend_Gdata_App_Exception('No root <' . $this->_rootElement . '> element'); - } - $this->transferFromDOM($element); - } else { - #require_once 'Zend/Gdata/App/Exception.php'; - throw new Zend_Gdata_App_Exception('XML passed to transferFromXML cannot be null'); - } - } - - /** - * Converts this element and all children into XML text using getDOM() - * - * @return string XML content - */ - public function saveXML() - { - $element = $this->getDOM(); - return $element->ownerDocument->saveXML($element); - } - - /** - * Alias for saveXML() returns XML content for this element and all - * children - * - * @return string XML content - */ - public function getXML() - { - return $this->saveXML(); - } - - /** - * Alias for saveXML() - * - * Can be overridden by children to provide more complex representations - * of entries. - * - * @return string Encoded string content - */ - public function encode() - { - return $this->saveXML(); - } - - /** - * Get the full version of a namespace prefix - * - * Looks up a prefix (atom:, etc.) in the list of registered - * namespaces and returns the full namespace URI if - * available. Returns the prefix, unmodified, if it's not - * registered. - * - * @param string $prefix The namespace prefix to lookup. - * @param integer $majorVersion The major protocol version in effect. - * Defaults to '1'. - * @param integer $minorVersion The minor protocol version in effect. - * Defaults to null (use latest). - * @return string - */ - public function lookupNamespace($prefix, - $majorVersion = 1, - $minorVersion = null) - { - // Check for a memoized result - $key = $prefix . ' ' . - ($majorVersion === null ? 'NULL' : $majorVersion) . - ' '. ($minorVersion === null ? 'NULL' : $minorVersion); - if (array_key_exists($key, self::$_namespaceLookupCache)) - return self::$_namespaceLookupCache[$key]; - // If no match, return the prefix by default - $result = $prefix; - - // Find tuple of keys that correspond to the namespace we should use - if (isset($this->_namespaces[$prefix])) { - // Major version search - $nsData = $this->_namespaces[$prefix]; - $foundMajorV = Zend_Gdata_App_Util::findGreatestBoundedValue( - $majorVersion, $nsData); - // Minor version search - $nsData = $nsData[$foundMajorV]; - $foundMinorV = Zend_Gdata_App_Util::findGreatestBoundedValue( - $minorVersion, $nsData); - // Extract NS - $result = $nsData[$foundMinorV]; - } - - // Memoize result - self::$_namespaceLookupCache[$key] = $result; - - return $result; - } - - /** - * Add a namespace and prefix to the registered list - * - * Takes a prefix and a full namespace URI and adds them to the - * list of registered namespaces for use by - * $this->lookupNamespace(). - * - * WARNING: Currently, registering a namespace will NOT invalidate any - * memoized data stored in $_namespaceLookupCache. Under normal - * use, this behavior is acceptable. If you are adding - * contradictory data to the namespace lookup table, you must - * call flushNamespaceLookupCache(). - * - * @param string $prefix The namespace prefix - * @param string $namespaceUri The full namespace URI - * @param integer $majorVersion The major protocol version in effect. - * Defaults to '1'. - * @param integer $minorVersion The minor protocol version in effect. - * Defaults to null (use latest). - * @return void - */ - public function registerNamespace($prefix, - $namespaceUri, - $majorVersion = 1, - $minorVersion = 0) - { - $this->_namespaces[$prefix][$majorVersion][$minorVersion] = - $namespaceUri; - } - - /** - * Flush namespace lookup cache. - * - * Empties the namespace lookup cache. Call this function if you have - * added data to the namespace lookup table that contradicts values that - * may have been cached during a previous call to lookupNamespace(). - */ - public static function flushNamespaceLookupCache() - { - self::$_namespaceLookupCache = array(); - } - - /** - * Add an array of namespaces to the registered list. - * - * Takes an array in the format of: - * namespace prefix, namespace URI, major protocol version, - * minor protocol version and adds them with calls to ->registerNamespace() - * - * @param array $namespaceArray An array of namespaces. - * @return void - */ - public function registerAllNamespaces($namespaceArray) - { - foreach($namespaceArray as $namespace) { - $this->registerNamespace( - $namespace[0], $namespace[1], $namespace[2], $namespace[3]); - } - } - - - /** - * Magic getter to allow access like $entry->foo to call $entry->getFoo() - * Alternatively, if no getFoo() is defined, but a $_foo protected variable - * is defined, this is returned. - * - * TODO Remove ability to bypass getFoo() methods?? - * - * @param string $name The variable name sought - */ - public function __get($name) - { - $method = 'get'.ucfirst($name); - if (method_exists($this, $method)) { - return call_user_func(array(&$this, $method)); - } else if (property_exists($this, "_${name}")) { - return $this->{'_' . $name}; - } else { - #require_once 'Zend/Gdata/App/InvalidArgumentException.php'; - throw new Zend_Gdata_App_InvalidArgumentException( - 'Property ' . $name . ' does not exist'); - } - } - - /** - * Magic setter to allow acces like $entry->foo='bar' to call - * $entry->setFoo('bar') automatically. - * - * Alternatively, if no setFoo() is defined, but a $_foo protected variable - * is defined, this is returned. - * - * TODO Remove ability to bypass getFoo() methods?? - * - * @param string $name - * @param string $value - */ - public function __set($name, $val) - { - $method = 'set'.ucfirst($name); - if (method_exists($this, $method)) { - return call_user_func(array(&$this, $method), $val); - } else if (isset($this->{'_' . $name}) || ($this->{'_' . $name} === null)) { - $this->{'_' . $name} = $val; - } else { - #require_once 'Zend/Gdata/App/InvalidArgumentException.php'; - throw new Zend_Gdata_App_InvalidArgumentException( - 'Property ' . $name . ' does not exist'); - } - } - - /** - * Magic __isset method - * - * @param string $name - */ - public function __isset($name) - { - $rc = new ReflectionClass(get_class($this)); - $privName = '_' . $name; - if (!($rc->hasProperty($privName))) { - #require_once 'Zend/Gdata/App/InvalidArgumentException.php'; - throw new Zend_Gdata_App_InvalidArgumentException( - 'Property ' . $name . ' does not exist'); - } else { - if (isset($this->{$privName})) { - if (is_array($this->{$privName})) { - if (count($this->{$privName}) > 0) { - return true; - } else { - return false; - } - } else { - return true; - } - } else { - return false; - } - } - } - - /** - * Magic __unset method - * - * @param string $name - */ - public function __unset($name) - { - if (isset($this->{'_' . $name})) { - if (is_array($this->{'_' . $name})) { - $this->{'_' . $name} = array(); - } else { - $this->{'_' . $name} = null; - } - } - } - - /** - * Magic toString method allows using this directly via echo - * Works best in PHP >= 4.2.0 - * - * @return string The text representation of this object - */ - public function __toString() - { - return $this->getText(); - } - -} diff --git a/library/Zend/Gdata/App/BaseMediaSource.php b/library/Zend/Gdata/App/BaseMediaSource.php deleted file mode 100644 index a93cf868ef..0000000000 --- a/library/Zend/Gdata/App/BaseMediaSource.php +++ /dev/null @@ -1,179 +0,0 @@ -_contentType; - } - - /** - * Set the content type for the file attached (example image/png) - * - * @param string $value The content type - * @return Zend_Gdata_App_MediaFileSource Provides a fluent interface - */ - public function setContentType($value) - { - $this->_contentType = $value; - return $this; - } - - /** - * Returns the Slug header value. Used by some services to determine the - * title for the uploaded file. Returns null if no slug should be used. - * - * @return string - */ - public function getSlug(){ - return $this->_slug; - } - - /** - * Sets the Slug header value. Used by some services to determine the - * title for the uploaded file. A null value indicates no slug header. - * - * @var string The slug value - * @return Zend_Gdata_App_MediaSource Provides a fluent interface - */ - public function setSlug($value){ - $this->_slug = $value; - return $this; - } - - - /** - * Magic getter to allow acces like $source->foo to call $source->getFoo() - * Alternatively, if no getFoo() is defined, but a $_foo protected variable - * is defined, this is returned. - * - * TODO Remove ability to bypass getFoo() methods?? - * - * @param string $name The variable name sought - */ - public function __get($name) - { - $method = 'get'.ucfirst($name); - if (method_exists($this, $method)) { - return call_user_func(array(&$this, $method)); - } else if (property_exists($this, "_${name}")) { - return $this->{'_' . $name}; - } else { - #require_once 'Zend/Gdata/App/InvalidArgumentException.php'; - throw new Zend_Gdata_App_InvalidArgumentException( - 'Property ' . $name . ' does not exist'); - } - } - - /** - * Magic setter to allow acces like $source->foo='bar' to call - * $source->setFoo('bar') automatically. - * - * Alternatively, if no setFoo() is defined, but a $_foo protected variable - * is defined, this is returned. - * - * @param string $name - * @param string $value - */ - public function __set($name, $val) - { - $method = 'set'.ucfirst($name); - if (method_exists($this, $method)) { - return call_user_func(array(&$this, $method), $val); - } else if (isset($this->{'_' . $name}) || ($this->{'_' . $name} === null)) { - $this->{'_' . $name} = $val; - } else { - #require_once 'Zend/Gdata/App/InvalidArgumentException.php'; - throw new Zend_Gdata_App_InvalidArgumentException( - 'Property ' . $name . ' does not exist'); - } - } - - /** - * Magic __isset method - * - * @param string $name - */ - public function __isset($name) - { - $rc = new ReflectionClass(get_class($this)); - $privName = '_' . $name; - if (!($rc->hasProperty($privName))) { - #require_once 'Zend/Gdata/App/InvalidArgumentException.php'; - throw new Zend_Gdata_App_InvalidArgumentException( - 'Property ' . $name . ' does not exist'); - } else { - if (isset($this->{$privName})) { - if (is_array($this->{$privName})) { - if (count($this->{$privName}) > 0) { - return true; - } else { - return false; - } - } else { - return true; - } - } else { - return false; - } - } - } - -} diff --git a/library/Zend/Gdata/App/CaptchaRequiredException.php b/library/Zend/Gdata/App/CaptchaRequiredException.php deleted file mode 100644 index 69f6b1ec13..0000000000 --- a/library/Zend/Gdata/App/CaptchaRequiredException.php +++ /dev/null @@ -1,94 +0,0 @@ -captchaToken = $captchaToken; - $this->captchaUrl = Zend_Gdata_App_CaptchaRequiredException::ACCOUNTS_URL . $captchaUrl; - parent::__construct('CAPTCHA challenge issued by server'); - } - - /** - * Retrieves the token identifier as provided by the server. - * - * @return string - */ - public function getCaptchaToken() { - return $this->captchaToken; - } - - /** - * Retrieves the URL CAPTCHA image as provided by the server. - * - * @return string - */ - public function getCaptchaUrl() { - return $this->captchaUrl; - } - -} diff --git a/library/Zend/Gdata/App/Entry.php b/library/Zend/Gdata/App/Entry.php deleted file mode 100644 index d535a12138..0000000000 --- a/library/Zend/Gdata/App/Entry.php +++ /dev/null @@ -1,389 +0,0 @@ -_content != null) { - $element->appendChild($this->_content->getDOM($element->ownerDocument)); - } - if ($this->_published != null) { - $element->appendChild($this->_published->getDOM($element->ownerDocument)); - } - if ($this->_source != null) { - $element->appendChild($this->_source->getDOM($element->ownerDocument)); - } - if ($this->_summary != null) { - $element->appendChild($this->_summary->getDOM($element->ownerDocument)); - } - if ($this->_control != null) { - $element->appendChild($this->_control->getDOM($element->ownerDocument)); - } - if ($this->_edited != null) { - $element->appendChild($this->_edited->getDOM($element->ownerDocument)); - } - return $element; - } - - protected function takeChildFromDOM($child) - { - $absoluteNodeName = $child->namespaceURI . ':' . $child->localName; - switch ($absoluteNodeName) { - case $this->lookupNamespace('atom') . ':' . 'content': - $content = new Zend_Gdata_App_Extension_Content(); - $content->transferFromDOM($child); - $this->_content = $content; - break; - case $this->lookupNamespace('atom') . ':' . 'published': - $published = new Zend_Gdata_App_Extension_Published(); - $published->transferFromDOM($child); - $this->_published = $published; - break; - case $this->lookupNamespace('atom') . ':' . 'source': - $source = new Zend_Gdata_App_Extension_Source(); - $source->transferFromDOM($child); - $this->_source = $source; - break; - case $this->lookupNamespace('atom') . ':' . 'summary': - $summary = new Zend_Gdata_App_Extension_Summary(); - $summary->transferFromDOM($child); - $this->_summary = $summary; - break; - case $this->lookupNamespace('app') . ':' . 'control': - $control = new Zend_Gdata_App_Extension_Control(); - $control->transferFromDOM($child); - $this->_control = $control; - break; - case $this->lookupNamespace('app') . ':' . 'edited': - $edited = new Zend_Gdata_App_Extension_Edited(); - $edited->transferFromDOM($child); - $this->_edited = $edited; - break; - default: - parent::takeChildFromDOM($child); - break; - } - } - - /** - * Uploads changes in this entry to the server using Zend_Gdata_App - * - * @param string|null $uri The URI to send requests to, or null if $data - * contains the URI. - * @param string|null $className The name of the class that should we - * deserializing the server response. If null, then - * 'Zend_Gdata_App_Entry' will be used. - * @param array $extraHeaders Extra headers to add to the request, as an - * array of string-based key/value pairs. - * @return Zend_Gdata_App_Entry The updated entry. - * @throws Zend_Gdata_App_Exception - */ - public function save($uri = null, $className = null, $extraHeaders = array()) - { - return $this->getService()->updateEntry($this, - $uri, - $className, - $extraHeaders); - } - - /** - * Deletes this entry to the server using the referenced - * Zend_Http_Client to do a HTTP DELETE to the edit link stored in this - * entry's link collection. - * - * @return void - * @throws Zend_Gdata_App_Exception - */ - public function delete() - { - $this->getService()->delete($this); - } - - /** - * Reload the current entry. Returns a new copy of the entry as returned - * by the server, or null if no changes exist. This does not - * modify the current entry instance. - * - * @param string|null The URI to send requests to, or null if $data - * contains the URI. - * @param string|null The name of the class that should we deserializing - * the server response. If null, then 'Zend_Gdata_App_Entry' will - * be used. - * @param array $extraHeaders Extra headers to add to the request, as an - * array of string-based key/value pairs. - * @return mixed A new instance of the current entry with updated data, or - * null if the server reports that no changes have been made. - * @throws Zend_Gdata_App_Exception - */ - public function reload($uri = null, $className = null, $extraHeaders = array()) - { - // Get URI - $editLink = $this->getEditLink(); - if (($uri === null) && $editLink != null) { - $uri = $editLink->getHref(); - } - - // Set classname to current class, if not otherwise set - if ($className === null) { - $className = get_class($this); - } - - // Append ETag, if present (Gdata v2 and above, only) and doesn't - // conflict with existing headers - if ($this->_etag != null - && !array_key_exists('If-Match', $extraHeaders) - && !array_key_exists('If-None-Match', $extraHeaders)) { - $extraHeaders['If-None-Match'] = $this->_etag; - } - - // If an HTTP 304 status (Not Modified)is returned, then we return - // null. - $result = null; - try { - $result = $this->service->importUrl($uri, $className, $extraHeaders); - } catch (Zend_Gdata_App_HttpException $e) { - if ($e->getResponse()->getStatus() != '304') - throw $e; - } - - return $result; - } - - /** - * Gets the value of the atom:content element - * - * @return Zend_Gdata_App_Extension_Content - */ - public function getContent() - { - return $this->_content; - } - - /** - * Sets the value of the atom:content element - * - * @param Zend_Gdata_App_Extension_Content $value - * @return Zend_Gdata_App_Entry Provides a fluent interface - */ - public function setContent($value) - { - $this->_content = $value; - return $this; - } - - /** - * Sets the value of the atom:published element - * This represents the publishing date for an entry - * - * @return Zend_Gdata_App_Extension_Published - */ - public function getPublished() - { - return $this->_published; - } - - /** - * Sets the value of the atom:published element - * This represents the publishing date for an entry - * - * @param Zend_Gdata_App_Extension_Published $value - * @return Zend_Gdata_App_Entry Provides a fluent interface - */ - public function setPublished($value) - { - $this->_published = $value; - return $this; - } - - /** - * Gets the value of the atom:source element - * - * @return Zend_Gdata_App_Extension_Source - */ - public function getSource() - { - return $this->_source; - } - - /** - * Sets the value of the atom:source element - * - * @param Zend_Gdata_App_Extension_Source $value - * @return Zend_Gdata_App_Entry Provides a fluent interface - */ - public function setSource($value) - { - $this->_source = $value; - return $this; - } - - /** - * Gets the value of the atom:summary element - * This represents a textual summary of this entry's content - * - * @return Zend_Gdata_App_Extension_Summary - */ - public function getSummary() - { - return $this->_summary; - } - - /** - * Sets the value of the atom:summary element - * This represents a textual summary of this entry's content - * - * @param Zend_Gdata_App_Extension_Summary $value - * @return Zend_Gdata_App_Entry Provides a fluent interface - */ - public function setSummary($value) - { - $this->_summary = $value; - return $this; - } - - /** - * Gets the value of the app:control element - * - * @return Zend_Gdata_App_Extension_Control - */ - public function getControl() - { - return $this->_control; - } - - /** - * Sets the value of the app:control element - * - * @param Zend_Gdata_App_Extension_Control $value - * @return Zend_Gdata_App_Entry Provides a fluent interface - */ - public function setControl($value) - { - $this->_control = $value; - return $this; - } - -} diff --git a/library/Zend/Gdata/App/Exception.php b/library/Zend/Gdata/App/Exception.php deleted file mode 100644 index 518b01ffd3..0000000000 --- a/library/Zend/Gdata/App/Exception.php +++ /dev/null @@ -1,43 +0,0 @@ -_term = $term; - $this->_scheme = $scheme; - $this->_label = $label; - } - - public function getDOM($doc = null, $majorVersion = 1, $minorVersion = null) - { - $element = parent::getDOM($doc, $majorVersion, $minorVersion); - if ($this->_term !== null) { - $element->setAttribute('term', $this->_term); - } - if ($this->_scheme !== null) { - $element->setAttribute('scheme', $this->_scheme); - } - if ($this->_label !== null) { - $element->setAttribute('label', $this->_label); - } - return $element; - } - - protected function takeAttributeFromDOM($attribute) - { - switch ($attribute->localName) { - case 'term': - $this->_term = $attribute->nodeValue; - break; - case 'scheme': - $this->_scheme = $attribute->nodeValue; - break; - case 'label': - $this->_label = $attribute->nodeValue; - break; - default: - parent::takeAttributeFromDOM($attribute); - } - } - - /** - * @return string|null - */ - public function getTerm() - { - return $this->_term; - } - - /** - * @param string|null $value - * @return Zend_Gdata_App_Extension_Category Provides a fluent interface - */ - public function setTerm($value) - { - $this->_term = $value; - return $this; - } - - /** - * @return string|null - */ - public function getScheme() - { - return $this->_scheme; - } - - /** - * @param string|null $value - * @return Zend_Gdata_App_Extension_Category Provides a fluent interface - */ - public function setScheme($value) - { - $this->_scheme = $value; - return $this; - } - - /** - * @return string|null - */ - public function getLabel() - { - return $this->_label; - } - - /** - * @param string|null $value - * @return Zend_Gdata_App_Extension_Category Provides a fluent interface - */ - public function setLabel($value) - { - $this->_label = $value; - return $this; - } - -} diff --git a/library/Zend/Gdata/App/Extension/Content.php b/library/Zend/Gdata/App/Extension/Content.php deleted file mode 100644 index b59ec9800d..0000000000 --- a/library/Zend/Gdata/App/Extension/Content.php +++ /dev/null @@ -1,88 +0,0 @@ -_src = $src; - } - - public function getDOM($doc = null, $majorVersion = 1, $minorVersion = null) - { - $element = parent::getDOM($doc, $majorVersion, $minorVersion); - if ($this->_src !== null) { - $element->setAttribute('src', $this->_src); - } - return $element; - } - - protected function takeAttributeFromDOM($attribute) - { - switch ($attribute->localName) { - case 'src': - $this->_src = $attribute->nodeValue; - break; - default: - parent::takeAttributeFromDOM($attribute); - } - } - - /** - * @return string - */ - public function getSrc() - { - return $this->_src; - } - - /** - * @param string $value - * @return Zend_Gdata_App_Entry Provides a fluent interface - */ - public function setSrc($value) - { - $this->_src = $value; - return $this; - } - -} diff --git a/library/Zend/Gdata/App/Extension/Contributor.php b/library/Zend/Gdata/App/Extension/Contributor.php deleted file mode 100644 index 562ef25460..0000000000 --- a/library/Zend/Gdata/App/Extension/Contributor.php +++ /dev/null @@ -1,43 +0,0 @@ -_draft = $draft; - } - - public function getDOM($doc = null, $majorVersion = 1, $minorVersion = null) - { - $element = parent::getDOM($doc, $majorVersion, $minorVersion); - if ($this->_draft != null) { - $element->appendChild($this->_draft->getDOM($element->ownerDocument)); - } - return $element; - } - - protected function takeChildFromDOM($child) - { - $absoluteNodeName = $child->namespaceURI . ':' . $child->localName; - switch ($absoluteNodeName) { - case $this->lookupNamespace('app') . ':' . 'draft': - $draft = new Zend_Gdata_App_Extension_Draft(); - $draft->transferFromDOM($child); - $this->_draft = $draft; - break; - default: - parent::takeChildFromDOM($child); - break; - } - } - - /** - * @return Zend_Gdata_App_Extension_Draft - */ - public function getDraft() - { - return $this->_draft; - } - - /** - * @param Zend_Gdata_App_Extension_Draft $value - * @return Zend_Gdata_App_Entry Provides a fluent interface - */ - public function setDraft($value) - { - $this->_draft = $value; - return $this; - } - -} diff --git a/library/Zend/Gdata/App/Extension/Draft.php b/library/Zend/Gdata/App/Extension/Draft.php deleted file mode 100644 index 149e13fa3d..0000000000 --- a/library/Zend/Gdata/App/Extension/Draft.php +++ /dev/null @@ -1,50 +0,0 @@ -_text = $text; - } - -} diff --git a/library/Zend/Gdata/App/Extension/Edited.php b/library/Zend/Gdata/App/Extension/Edited.php deleted file mode 100644 index cb2fe57a2b..0000000000 --- a/library/Zend/Gdata/App/Extension/Edited.php +++ /dev/null @@ -1,49 +0,0 @@ -_text = $text; - } - -} diff --git a/library/Zend/Gdata/App/Extension/Element.php b/library/Zend/Gdata/App/Extension/Element.php deleted file mode 100644 index bb71ac7fa2..0000000000 --- a/library/Zend/Gdata/App/Extension/Element.php +++ /dev/null @@ -1,58 +0,0 @@ -_rootElement = $rootElement; - $this->_rootNamespace = $rootNamespace; - $this->_rootNamespaceURI = $rootNamespaceURI; - $this->_text = $text; - } - - public function transferFromDOM($node) - { - parent::transferFromDOM($node); - $this->_rootNamespace = null; - $this->_rootNamespaceURI = $node->namespaceURI; - $this->_rootElement = $node->localName; - } - -} diff --git a/library/Zend/Gdata/App/Extension/Email.php b/library/Zend/Gdata/App/Extension/Email.php deleted file mode 100644 index b826e7678d..0000000000 --- a/library/Zend/Gdata/App/Extension/Email.php +++ /dev/null @@ -1,49 +0,0 @@ -_text = $text; - } - -} diff --git a/library/Zend/Gdata/App/Extension/Generator.php b/library/Zend/Gdata/App/Extension/Generator.php deleted file mode 100644 index 1a6e3f9f0b..0000000000 --- a/library/Zend/Gdata/App/Extension/Generator.php +++ /dev/null @@ -1,115 +0,0 @@ -_text = $text; - $this->_uri = $uri; - $this->_version = $version; - } - - public function getDOM($doc = null, $majorVersion = 1, $minorVersion = null) - { - $element = parent::getDOM($doc, $majorVersion, $minorVersion); - if ($this->_uri !== null) { - $element->setAttribute('uri', $this->_uri); - } - if ($this->_version !== null) { - $element->setAttribute('version', $this->_version); - } - return $element; - } - - protected function takeAttributeFromDOM($attribute) - { - switch ($attribute->localName) { - case 'uri': - $this->_uri = $attribute->nodeValue; - break; - case 'version': - $this->_version= $attribute->nodeValue; - break; - default: - parent::takeAttributeFromDOM($attribute); - } - } - - /** - * @return Zend_Gdata_App_Extension_Uri - */ - public function getUri() - { - return $this->_uri; - } - - /** - * @param Zend_Gdata_App_Extension_Uri $value - * @return Zend_Gdata_App_Entry Provides a fluent interface - */ - public function setUri($value) - { - $this->_uri = $value; - return $this; - } - - /** - * @return Zend_Gdata_App_Extension_Version - */ - public function getVersion() - { - return $this->_version; - } - - /** - * @param Zend_Gdata_App_Extension_Version $value - * @return Zend_Gdata_App_Entry Provides a fluent interface - */ - public function setVersion($value) - { - $this->_version = $value; - return $this; - } - -} diff --git a/library/Zend/Gdata/App/Extension/Icon.php b/library/Zend/Gdata/App/Extension/Icon.php deleted file mode 100644 index ab520a5550..0000000000 --- a/library/Zend/Gdata/App/Extension/Icon.php +++ /dev/null @@ -1,49 +0,0 @@ -_text = $text; - } - -} diff --git a/library/Zend/Gdata/App/Extension/Id.php b/library/Zend/Gdata/App/Extension/Id.php deleted file mode 100644 index 9ad21b9490..0000000000 --- a/library/Zend/Gdata/App/Extension/Id.php +++ /dev/null @@ -1,49 +0,0 @@ -_text = $text; - } - -} diff --git a/library/Zend/Gdata/App/Extension/Link.php b/library/Zend/Gdata/App/Extension/Link.php deleted file mode 100644 index 1d9a5b4523..0000000000 --- a/library/Zend/Gdata/App/Extension/Link.php +++ /dev/null @@ -1,219 +0,0 @@ -_href = $href; - $this->_rel = $rel; - $this->_type = $type; - $this->_hrefLang = $hrefLang; - $this->_title = $title; - $this->_length = $length; - } - - public function getDOM($doc = null, $majorVersion = 1, $minorVersion = null) - { - $element = parent::getDOM($doc, $majorVersion, $minorVersion); - if ($this->_href !== null) { - $element->setAttribute('href', $this->_href); - } - if ($this->_rel !== null) { - $element->setAttribute('rel', $this->_rel); - } - if ($this->_type !== null) { - $element->setAttribute('type', $this->_type); - } - if ($this->_hrefLang !== null) { - $element->setAttribute('hreflang', $this->_hrefLang); - } - if ($this->_title !== null) { - $element->setAttribute('title', $this->_title); - } - if ($this->_length !== null) { - $element->setAttribute('length', $this->_length); - } - return $element; - } - - protected function takeAttributeFromDOM($attribute) - { - switch ($attribute->localName) { - case 'href': - $this->_href = $attribute->nodeValue; - break; - case 'rel': - $this->_rel = $attribute->nodeValue; - break; - case 'type': - $this->_type = $attribute->nodeValue; - break; - case 'hreflang': - $this->_hrefLang = $attribute->nodeValue; - break; - case 'title': - $this->_title = $attribute->nodeValue; - break; - case 'length': - $this->_length = $attribute->nodeValue; - break; - default: - parent::takeAttributeFromDOM($attribute); - } - } - - /** - * @return string|null - */ - public function getHref() - { - return $this->_href; - } - - /** - * @param string|null $value - * @return Zend_Gdata_App_Entry Provides a fluent interface - */ - public function setHref($value) - { - $this->_href = $value; - return $this; - } - - /** - * @return string|null - */ - public function getRel() - { - return $this->_rel; - } - - /** - * @param string|null $value - * @return Zend_Gdata_App_Entry Provides a fluent interface - */ - public function setRel($value) - { - $this->_rel = $value; - return $this; - } - - /** - * @return string|null - */ - public function getType() - { - return $this->_type; - } - - /** - * @param string|null $value - * @return Zend_Gdata_App_Entry Provides a fluent interface - */ - public function setType($value) - { - $this->_type = $value; - return $this; - } - - /** - * @return string|null - */ - public function getHrefLang() - { - return $this->_hrefLang; - } - - /** - * @param string|null $value - * @return Zend_Gdata_App_Entry Provides a fluent interface - */ - public function setHrefLang($value) - { - $this->_hrefLang = $value; - return $this; - } - - /** - * @return string|null - */ - public function getTitle() - { - return $this->_title; - } - - /** - * @param string|null $value - * @return Zend_Gdata_App_Entry Provides a fluent interface - */ - public function setTitle($value) - { - $this->_title = $value; - return $this; - } - - /** - * @return string|null - */ - public function getLength() - { - return $this->_length; - } - - /** - * @param string|null $value - * @return Zend_Gdata_App_Entry Provides a fluent interface - */ - public function setLength($value) - { - $this->_length = $value; - return $this; - } - -} diff --git a/library/Zend/Gdata/App/Extension/Logo.php b/library/Zend/Gdata/App/Extension/Logo.php deleted file mode 100644 index e3e6969755..0000000000 --- a/library/Zend/Gdata/App/Extension/Logo.php +++ /dev/null @@ -1,49 +0,0 @@ -_text = $text; - } - -} diff --git a/library/Zend/Gdata/App/Extension/Name.php b/library/Zend/Gdata/App/Extension/Name.php deleted file mode 100644 index fff1d84541..0000000000 --- a/library/Zend/Gdata/App/Extension/Name.php +++ /dev/null @@ -1,48 +0,0 @@ -_text = $text; - } -} diff --git a/library/Zend/Gdata/App/Extension/Person.php b/library/Zend/Gdata/App/Extension/Person.php deleted file mode 100644 index 5a69c26813..0000000000 --- a/library/Zend/Gdata/App/Extension/Person.php +++ /dev/null @@ -1,163 +0,0 @@ -_name = $name; - $this->_email = $email; - $this->_uri = $uri; - } - - public function getDOM($doc = null, $majorVersion = 1, $minorVersion = null) - { - $element = parent::getDOM($doc, $majorVersion, $minorVersion); - if ($this->_name != null) { - $element->appendChild($this->_name->getDOM($element->ownerDocument)); - } - if ($this->_email != null) { - $element->appendChild($this->_email->getDOM($element->ownerDocument)); - } - if ($this->_uri != null) { - $element->appendChild($this->_uri->getDOM($element->ownerDocument)); - } - return $element; - } - - protected function takeChildFromDOM($child) - { - $absoluteNodeName = $child->namespaceURI . ':' . $child->localName; - switch ($absoluteNodeName) { - case $this->lookupNamespace('atom') . ':' . 'name': - $name = new Zend_Gdata_App_Extension_Name(); - $name->transferFromDOM($child); - $this->_name = $name; - break; - case $this->lookupNamespace('atom') . ':' . 'email': - $email = new Zend_Gdata_App_Extension_Email(); - $email->transferFromDOM($child); - $this->_email = $email; - break; - case $this->lookupNamespace('atom') . ':' . 'uri': - $uri = new Zend_Gdata_App_Extension_Uri(); - $uri->transferFromDOM($child); - $this->_uri = $uri; - break; - default: - parent::takeChildFromDOM($child); - break; - } - } - - /** - * @return Zend_Gdata_App_Extension_Name - */ - public function getName() - { - return $this->_name; - } - - /** - * @param Zend_Gdata_App_Extension_Name $value - * @return Zend_Gdata_App_Entry Provides a fluent interface - */ - public function setName($value) - { - $this->_name = $value; - return $this; - } - - /** - * @return Zend_Gdata_App_Extension_Email - */ - public function getEmail() - { - return $this->_email; - } - - /** - * @param Zend_Gdata_App_Extension_Email $value - * @return Zend_Gdata_App_Extension_Person Provides a fluent interface - */ - public function setEmail($value) - { - $this->_email = $value; - return $this; - } - - /** - * @return Zend_Gdata_App_Extension_Uri - */ - public function getUri() - { - return $this->_uri; - } - - /** - * @param Zend_Gdata_App_Extension_Uri $value - * @return Zend_Gdata_App_Extension_Person Provides a fluent interface - */ - public function setUri($value) - { - $this->_uri = $value; - return $this; - } - -} diff --git a/library/Zend/Gdata/App/Extension/Published.php b/library/Zend/Gdata/App/Extension/Published.php deleted file mode 100644 index 4c0dc65a37..0000000000 --- a/library/Zend/Gdata/App/Extension/Published.php +++ /dev/null @@ -1,49 +0,0 @@ -_text = $text; - } - -} diff --git a/library/Zend/Gdata/App/Extension/Rights.php b/library/Zend/Gdata/App/Extension/Rights.php deleted file mode 100644 index e546afb9d5..0000000000 --- a/library/Zend/Gdata/App/Extension/Rights.php +++ /dev/null @@ -1,49 +0,0 @@ -_text = $text; - } - -} diff --git a/library/Zend/Gdata/App/Extension/Source.php b/library/Zend/Gdata/App/Extension/Source.php deleted file mode 100644 index d58aa87c30..0000000000 --- a/library/Zend/Gdata/App/Extension/Source.php +++ /dev/null @@ -1,46 +0,0 @@ -_text = $text; - $this->_type = $type; - } - - public function getDOM($doc = null, $majorVersion = 1, $minorVersion = null) - { - $element = parent::getDOM($doc, $majorVersion, $minorVersion); - if ($this->_type !== null) { - $element->setAttribute('type', $this->_type); - } - return $element; - } - - protected function takeAttributeFromDOM($attribute) - { - switch ($attribute->localName) { - case 'type': - $this->_type = $attribute->nodeValue; - break; - default: - parent::takeAttributeFromDOM($attribute); - } - } - - /* - * @return Zend_Gdata_App_Extension_Type - */ - public function getType() - { - return $this->_type; - } - - /* - * @param string $value - * @return Zend_Gdata_App_Extension_Text Provides a fluent interface - */ - public function setType($value) - { - $this->_type = $value; - return $this; - } - -} diff --git a/library/Zend/Gdata/App/Extension/Title.php b/library/Zend/Gdata/App/Extension/Title.php deleted file mode 100644 index a67f4126f0..0000000000 --- a/library/Zend/Gdata/App/Extension/Title.php +++ /dev/null @@ -1,43 +0,0 @@ -_text = $text; - } - -} diff --git a/library/Zend/Gdata/App/Extension/Uri.php b/library/Zend/Gdata/App/Extension/Uri.php deleted file mode 100644 index 9cba145047..0000000000 --- a/library/Zend/Gdata/App/Extension/Uri.php +++ /dev/null @@ -1,49 +0,0 @@ -_text = $text; - } - -} diff --git a/library/Zend/Gdata/App/Feed.php b/library/Zend/Gdata/App/Feed.php deleted file mode 100755 index 342efc191b..0000000000 --- a/library/Zend/Gdata/App/Feed.php +++ /dev/null @@ -1,352 +0,0 @@ -entries as $entry) or foreach - * ($feed->entry as $entry). - * - * @param string $var The property to get. - * @return mixed - */ - public function __get($var) - { - switch ($var) { - case 'entries': - return $this; - default: - return parent::__get($var); - } - } - - /** - * Retrieves the DOM model representing this object and all children - * - * @param DOMDocument $doc - * @return DOMElement - */ - public function getDOM($doc = null, $majorVersion = 1, $minorVersion = null) - { - $element = parent::getDOM($doc, $majorVersion, $minorVersion); - foreach ($this->_entry as $entry) { - $element->appendChild($entry->getDOM($element->ownerDocument)); - } - return $element; - } - - /** - * Creates individual Entry objects of the appropriate type and - * stores them in the $_entry array based upon DOM data. - * - * @param DOMNode $child The DOMNode to process - */ - protected function takeChildFromDOM($child) - { - $absoluteNodeName = $child->namespaceURI . ':' . $child->localName; - switch ($absoluteNodeName) { - case $this->lookupNamespace('atom') . ':' . 'entry': - $newEntry = new $this->_entryClassName($child); - $newEntry->setHttpClient($this->getHttpClient()); - $newEntry->setMajorProtocolVersion($this->getMajorProtocolVersion()); - $newEntry->setMinorProtocolVersion($this->getMinorProtocolVersion()); - $this->_entry[] = $newEntry; - break; - default: - parent::takeChildFromDOM($child); - break; - } - } - - /** - * Get the number of entries in this feed object. - * - * @return integer Entry count. - */ - public function count() - { - return count($this->_entry); - } - - /** - * Required by the Iterator interface. - * - * @return void - */ - public function rewind() - { - $this->_entryIndex = 0; - } - - /** - * Required by the Iterator interface. - * - * @return mixed The current row, or null if no rows. - */ - public function current() - { - return $this->_entry[$this->_entryIndex]; - } - - /** - * Required by the Iterator interface. - * - * @return mixed The current row number (starts at 0), or NULL if no rows - */ - public function key() - { - return $this->_entryIndex; - } - - /** - * Required by the Iterator interface. - * - * @return mixed The next row, or null if no more rows. - */ - public function next() - { - ++$this->_entryIndex; - } - - /** - * Required by the Iterator interface. - * - * @return boolean Whether the iteration is valid - */ - public function valid() - { - return 0 <= $this->_entryIndex && $this->_entryIndex < $this->count(); - } - - /** - * Gets the array of atom:entry elements contained within this - * atom:feed representation - * - * @return array Zend_Gdata_App_Entry array - */ - public function getEntry() - { - return $this->_entry; - } - - /** - * Sets the array of atom:entry elements contained within this - * atom:feed representation - * - * @param array $value The array of Zend_Gdata_App_Entry elements - * @return Zend_Gdata_App_Feed Provides a fluent interface - */ - public function setEntry($value) - { - $this->_entry = $value; - return $this; - } - - /** - * Adds an entry representation to the array of entries - * contained within this feed - * - * @param Zend_Gdata_App_Entry An individual entry to add. - * @return Zend_Gdata_App_Feed Provides a fluent interface - */ - public function addEntry($value) - { - $this->_entry[] = $value; - return $this; - } - - /** - * Required by the ArrayAccess interface - * - * @param int $key The index to set - * @param Zend_Gdata_App_Entry $value The value to set - * @return void - */ - public function offsetSet($key, $value) - { - $this->_entry[$key] = $value; - } - - /** - * Required by the ArrayAccess interface - * - * @param int $key The index to get - * @param Zend_Gdata_App_Entry $value The value to set - */ - public function offsetGet($key) - { - if (array_key_exists($key, $this->_entry)) { - return $this->_entry[$key]; - } - } - - /** - * Required by the ArrayAccess interface - * - * @param int $key The index to set - * @param Zend_Gdata_App_Entry $value The value to set - */ - public function offsetUnset($key) - { - if (array_key_exists($key, $this->_entry)) { - unset($this->_entry[$key]); - } - } - - /** - * Required by the ArrayAccess interface - * - * @param int $key The index to check for existence - * @return boolean - */ - public function offsetExists($key) - { - return (array_key_exists($key, $this->_entry)); - } - - /** - * Retrieve the next set of results from this feed. - * - * @throws Zend_Gdata_App_Exception - * @return mixed|null Returns the next set of results as a feed of the same - * class as this feed, or null if no results exist. - */ - public function getNextFeed() - { - $nextLink = $this->getNextLink(); - if (!$nextLink) { - #require_once 'Zend/Gdata/App/HttpException.php'; - throw new Zend_Gdata_App_Exception('No link to next set ' . - 'of results found.'); - } - $nextLinkHref = $nextLink->getHref(); - $service = new Zend_Gdata_App($this->getHttpClient()); - - return $service->getFeed($nextLinkHref, get_class($this)); - } - - /** - * Retrieve the previous set of results from this feed. - * - * @throws Zend_Gdata_App_Exception - * @return mixed|null Returns the previous set of results as a feed of - * the same class as this feed, or null if no results exist. - */ - public function getPreviousFeed() - { - $previousLink = $this->getPreviousLink(); - if (!$previousLink) { - #require_once 'Zend/Gdata/App/HttpException.php'; - throw new Zend_Gdata_App_Exception('No link to previous set ' . - 'of results found.'); - } - $previousLinkHref = $previousLink->getHref(); - $service = new Zend_Gdata_App($this->getHttpClient()); - - return $service->getFeed($previousLinkHref, get_class($this)); - } - - /** - * Set the major protocol version that should be used. Values < 1 will - * cause a Zend_Gdata_App_InvalidArgumentException to be thrown. - * - * This value will be propogated to all child entries. - * - * @see _majorProtocolVersion - * @param (int|NULL) $value The major protocol version to use. - * @throws Zend_Gdata_App_InvalidArgumentException - */ - public function setMajorProtocolVersion($value) - { - parent::setMajorProtocolVersion($value); - foreach ($this->entries as $entry) { - $entry->setMajorProtocolVersion($value); - } - } - - /** - * Set the minor protocol version that should be used. If set to NULL, no - * minor protocol version will be sent to the server. Values < 0 will - * cause a Zend_Gdata_App_InvalidArgumentException to be thrown. - * - * This value will be propogated to all child entries. - * - * @see _minorProtocolVersion - * @param (int|NULL) $value The minor protocol version to use. - * @throws Zend_Gdata_App_InvalidArgumentException - */ - public function setMinorProtocolVersion($value) - { - parent::setMinorProtocolVersion($value); - foreach ($this->entries as $entry) { - $entry->setMinorProtocolVersion($value); - } - } - -} diff --git a/library/Zend/Gdata/App/FeedEntryParent.php b/library/Zend/Gdata/App/FeedEntryParent.php deleted file mode 100755 index 470522510e..0000000000 --- a/library/Zend/Gdata/App/FeedEntryParent.php +++ /dev/null @@ -1,681 +0,0 @@ -= 1 is considered valid. - * - * @see setMajorProtocolVersion() - * @see getMajorProtocolVersion() - */ - protected $_majorProtocolVersion = 1; - - /** - * Indicates the minor protocol version that should be used. Can be set - * to either an integer >= 0, or NULL if no minor version should be sent - * to the server. - * - * @see setMinorProtocolVersion() - * @see getMinorProtocolVersion() - */ - protected $_minorProtocolVersion = null; - - /** - * Constructs a Feed or Entry - */ - public function __construct($element = null) - { - if (!($element instanceof DOMElement)) { - if ($element) { - $this->transferFromXML($element); - } - } else { - $this->transferFromDOM($element); - } - } - - /** - * Set the HTTP client instance - * - * Sets the HTTP client object to use for retrieving the feed. - * - * @deprecated Deprecated as of Zend Framework 1.7. Use - * setService() instead. - * @param Zend_Http_Client $httpClient - * @return Zend_Gdata_App_FeedEntryParent Provides a fluent interface - */ - public function setHttpClient(Zend_Http_Client $httpClient) - { - if (!$this->_service) { - $this->_service = new Zend_Gdata_App(); - } - $this->_service->setHttpClient($httpClient); - return $this; - } - - /** - * Gets the HTTP client object. If none is set, a new Zend_Http_Client - * will be used. - * - * @deprecated Deprecated as of Zend Framework 1.7. Use - * getService() instead. - * @return Zend_Http_Client_Abstract - */ - public function getHttpClient() - { - if (!$this->_service) { - $this->_service = new Zend_Gdata_App(); - } - $client = $this->_service->getHttpClient(); - return $client; - } - - /** - * Set the active service instance for this object. This will be used to - * perform network requests, such as when calling save() and delete(). - * - * @param Zend_Gdata_App $instance The new service instance. - * @return Zend_Gdata_App_FeedEntryParent Provides a fluent interface. - */ - public function setService($instance) - { - $this->_service = $instance; - return $this; - } - - /** - * Get the active service instance for this object. This will be used to - * perform network requests, such as when calling save() and delete(). - * - * @return Zend_Gdata_App|null The current service instance, or null if - * not set. - */ - public function getService() - { - return $this->_service; - } - - public function getDOM($doc = null, $majorVersion = 1, $minorVersion = null) - { - $element = parent::getDOM($doc, $majorVersion, $minorVersion); - foreach ($this->_author as $author) { - $element->appendChild($author->getDOM($element->ownerDocument)); - } - foreach ($this->_category as $category) { - $element->appendChild($category->getDOM($element->ownerDocument)); - } - foreach ($this->_contributor as $contributor) { - $element->appendChild($contributor->getDOM($element->ownerDocument)); - } - if ($this->_id != null) { - $element->appendChild($this->_id->getDOM($element->ownerDocument)); - } - foreach ($this->_link as $link) { - $element->appendChild($link->getDOM($element->ownerDocument)); - } - if ($this->_rights != null) { - $element->appendChild($this->_rights->getDOM($element->ownerDocument)); - } - if ($this->_title != null) { - $element->appendChild($this->_title->getDOM($element->ownerDocument)); - } - if ($this->_updated != null) { - $element->appendChild($this->_updated->getDOM($element->ownerDocument)); - } - return $element; - } - - protected function takeChildFromDOM($child) - { - $absoluteNodeName = $child->namespaceURI . ':' . $child->localName; - switch ($absoluteNodeName) { - case $this->lookupNamespace('atom') . ':' . 'author': - $author = new Zend_Gdata_App_Extension_Author(); - $author->transferFromDOM($child); - $this->_author[] = $author; - break; - case $this->lookupNamespace('atom') . ':' . 'category': - $category = new Zend_Gdata_App_Extension_Category(); - $category->transferFromDOM($child); - $this->_category[] = $category; - break; - case $this->lookupNamespace('atom') . ':' . 'contributor': - $contributor = new Zend_Gdata_App_Extension_Contributor(); - $contributor->transferFromDOM($child); - $this->_contributor[] = $contributor; - break; - case $this->lookupNamespace('atom') . ':' . 'id': - $id = new Zend_Gdata_App_Extension_Id(); - $id->transferFromDOM($child); - $this->_id = $id; - break; - case $this->lookupNamespace('atom') . ':' . 'link': - $link = new Zend_Gdata_App_Extension_Link(); - $link->transferFromDOM($child); - $this->_link[] = $link; - break; - case $this->lookupNamespace('atom') . ':' . 'rights': - $rights = new Zend_Gdata_App_Extension_Rights(); - $rights->transferFromDOM($child); - $this->_rights = $rights; - break; - case $this->lookupNamespace('atom') . ':' . 'title': - $title = new Zend_Gdata_App_Extension_Title(); - $title->transferFromDOM($child); - $this->_title = $title; - break; - case $this->lookupNamespace('atom') . ':' . 'updated': - $updated = new Zend_Gdata_App_Extension_Updated(); - $updated->transferFromDOM($child); - $this->_updated = $updated; - break; - default: - parent::takeChildFromDOM($child); - break; - } - } - - /** - * @return Zend_Gdata_App_Extension_Author - */ - public function getAuthor() - { - return $this->_author; - } - - /** - * Sets the list of the authors of this feed/entry. In an atom feed, each - * author is represented by an atom:author element - * - * @param array $value - * @return Zend_Gdata_App_FeedEntryParent Provides a fluent interface - */ - public function setAuthor($value) - { - $this->_author = $value; - return $this; - } - - /** - * Returns the array of categories that classify this feed/entry. Each - * category is represented in an atom feed by an atom:category element. - * - * @return array Array of Zend_Gdata_App_Extension_Category - */ - public function getCategory() - { - return $this->_category; - } - - /** - * Sets the array of categories that classify this feed/entry. Each - * category is represented in an atom feed by an atom:category element. - * - * @param array $value Array of Zend_Gdata_App_Extension_Category - * @return Zend_Gdata_App_FeedEntryParent Provides a fluent interface - */ - public function setCategory($value) - { - $this->_category = $value; - return $this; - } - - /** - * Returns the array of contributors to this feed/entry. Each contributor - * is represented in an atom feed by an atom:contributor XML element - * - * @return array An array of Zend_Gdata_App_Extension_Contributor - */ - public function getContributor() - { - return $this->_contributor; - } - - /** - * Sets the array of contributors to this feed/entry. Each contributor - * is represented in an atom feed by an atom:contributor XML element - * - * @param array $value - * @return Zend_Gdata_App_FeedEntryParent Provides a fluent interface - */ - public function setContributor($value) - { - $this->_contributor = $value; - return $this; - } - - /** - * @return Zend_Gdata_App_Extension_Id - */ - public function getId() - { - return $this->_id; - } - - /** - * @param Zend_Gdata_App_Extension_Id $value - * @return Zend_Gdata_App_FeedEntryParent Provides a fluent interface - */ - public function setId($value) - { - $this->_id = $value; - return $this; - } - - /** - * Given a particular 'rel' value, this method returns a matching - * Zend_Gdata_App_Extension_Link element. If the 'rel' value - * is not provided, the full array of Zend_Gdata_App_Extension_Link - * elements is returned. In an atom feed, each link is represented - * by an atom:link element. The 'rel' value passed to this function - * is the atom:link/@rel attribute. Example rel values include 'self', - * 'edit', and 'alternate'. - * - * @param string $rel The rel value of the link to be found. If null, - * the array of Zend_Gdata_App_Extension_link elements is returned - * @return mixed Either a single Zend_Gdata_App_Extension_link element, - * an array of the same or null is returned depending on the rel value - * supplied as the argument to this function - */ - public function getLink($rel = null) - { - if ($rel == null) { - return $this->_link; - } else { - foreach ($this->_link as $link) { - if ($link->rel == $rel) { - return $link; - } - } - return null; - } - } - - /** - * Returns the Zend_Gdata_App_Extension_Link element which represents - * the URL used to edit this resource. This link is in the atom feed/entry - * as an atom:link with a rel attribute value of 'edit'. - * - * @return Zend_Gdata_App_Extension_Link The link, or null if not found - */ - public function getEditLink() - { - return $this->getLink('edit'); - } - - /** - * Returns the Zend_Gdata_App_Extension_Link element which represents - * the URL used to retrieve the next chunk of results when paging through - * a feed. This link is in the atom feed as an atom:link with a - * rel attribute value of 'next'. - * - * @return Zend_Gdata_App_Extension_Link The link, or null if not found - */ - public function getNextLink() - { - return $this->getLink('next'); - } - - /** - * Returns the Zend_Gdata_App_Extension_Link element which represents - * the URL used to retrieve the previous chunk of results when paging - * through a feed. This link is in the atom feed as an atom:link with a - * rel attribute value of 'previous'. - * - * @return Zend_Gdata_App_Extension_Link The link, or null if not found - */ - public function getPreviousLink() - { - return $this->getLink('previous'); - } - - /** - * @return Zend_Gdata_App_Extension_Link - */ - public function getLicenseLink() - { - return $this->getLink('license'); - } - - /** - * Returns the Zend_Gdata_App_Extension_Link element which represents - * the URL used to retrieve the entry or feed represented by this object - * This link is in the atom feed/entry as an atom:link with a - * rel attribute value of 'self'. - * - * @return Zend_Gdata_App_Extension_Link The link, or null if not found - */ - public function getSelfLink() - { - return $this->getLink('self'); - } - - /** - * Returns the Zend_Gdata_App_Extension_Link element which represents - * the URL for an alternate view of the data represented by this feed or - * entry. This alternate view is commonly a user-facing webpage, blog - * post, etc. The MIME type for the data at the URL is available from the - * returned Zend_Gdata_App_Extension_Link element. - * This link is in the atom feed/entry as an atom:link with a - * rel attribute value of 'self'. - * - * @return Zend_Gdata_App_Extension_Link The link, or null if not found - */ - public function getAlternateLink() - { - return $this->getLink('alternate'); - } - - /** - * @param array $value The array of Zend_Gdata_App_Extension_Link elements - * @return Zend_Gdata_App_FeedEntryParent Provides a fluent interface - */ - public function setLink($value) - { - $this->_link = $value; - return $this; - } - - /** - * @return Zend_Gdata_AppExtension_Rights - */ - public function getRights() - { - return $this->_rights; - } - - /** - * @param Zend_Gdata_App_Extension_Rights $value - * @return Zend_Gdata_App_FeedEntryParent Provides a fluent interface - */ - public function setRights($value) - { - $this->_rights = $value; - return $this; - } - - /** - * Returns the title of this feed or entry. The title is an extremely - * short textual representation of this resource and is found as - * an atom:title element in a feed or entry - * - * @return Zend_Gdata_App_Extension_Title - */ - public function getTitle() - { - return $this->_title; - } - - /** - * Returns a string representation of the title of this feed or entry. - * The title is an extremely short textual representation of this - * resource and is found as an atom:title element in a feed or entry - * - * @return string - */ - public function getTitleValue() - { - if (($titleObj = $this->getTitle()) != null) { - return $titleObj->getText(); - } else { - return null; - } - } - - /** - * Returns the title of this feed or entry. The title is an extremely - * short textual representation of this resource and is found as - * an atom:title element in a feed or entry - * - * @param Zend_Gdata_App_Extension_Title $value - * @return Zend_Gdata_App_FeedEntryParent Provides a fluent interface - */ - public function setTitle($value) - { - $this->_title = $value; - return $this; - } - - /** - * @return Zend_Gdata_App_Extension_Updated - */ - public function getUpdated() - { - return $this->_updated; - } - - /** - * @param Zend_Gdata_App_Extension_Updated $value - * @return Zend_Gdata_App_FeedEntryParent Provides a fluent interface - */ - public function setUpdated($value) - { - $this->_updated = $value; - return $this; - } - - /** - * Set the Etag for the current entry to $value. Setting $value to null - * unsets the Etag. - * - * @param string|null $value - * @return Zend_Gdata_App_Entry Provides a fluent interface - */ - public function setEtag($value) { - $this->_etag = $value; - return $this; - } - - /** - * Return the Etag for the current entry, or null if not set. - * - * @return string|null - */ - public function getEtag() { - return $this->_etag; - } - - /** - * Set the major protocol version that should be used. Values < 1 - * (excluding NULL) will cause a Zend_Gdata_App_InvalidArgumentException - * to be thrown. - * - * @see _majorProtocolVersion - * @param (int|NULL) $value The major protocol version to use. - * @throws Zend_Gdata_App_InvalidArgumentException - */ - public function setMajorProtocolVersion($value) - { - if (!($value >= 1) && ($value !== null)) { - #require_once('Zend/Gdata/App/InvalidArgumentException.php'); - throw new Zend_Gdata_App_InvalidArgumentException( - 'Major protocol version must be >= 1'); - } - $this->_majorProtocolVersion = $value; - } - - /** - * Get the major protocol version that is in use. - * - * @see _majorProtocolVersion - * @return (int|NULL) The major protocol version in use. - */ - public function getMajorProtocolVersion() - { - return $this->_majorProtocolVersion; - } - - /** - * Set the minor protocol version that should be used. If set to NULL, no - * minor protocol version will be sent to the server. Values < 0 will - * cause a Zend_Gdata_App_InvalidArgumentException to be thrown. - * - * @see _minorProtocolVersion - * @param (int|NULL) $value The minor protocol version to use. - * @throws Zend_Gdata_App_InvalidArgumentException - */ - public function setMinorProtocolVersion($value) - { - if (!($value >= 0)) { - #require_once('Zend/Gdata/App/InvalidArgumentException.php'); - throw new Zend_Gdata_App_InvalidArgumentException( - 'Minor protocol version must be >= 0 or null'); - } - $this->_minorProtocolVersion = $value; - } - - /** - * Get the minor protocol version that is in use. - * - * @see _minorProtocolVersion - * @return (int|NULL) The major protocol version in use, or NULL if no - * minor version is specified. - */ - public function getMinorProtocolVersion() - { - return $this->_minorProtocolVersion; - } - - /** - * Get the full version of a namespace prefix - * - * Looks up a prefix (atom:, etc.) in the list of registered - * namespaces and returns the full namespace URI if - * available. Returns the prefix, unmodified, if it's not - * registered. - * - * The current entry or feed's version will be used when performing the - * namespace lookup unless overridden using $majorVersion and - * $minorVersion. If the entry/fee has a null version, then the latest - * protocol version will be used by default. - * - * @param string $prefix The namespace prefix to lookup. - * @param integer $majorVersion The major protocol version in effect. - * Defaults to null (auto-select). - * @param integer $minorVersion The minor protocol version in effect. - * Defaults to null (auto-select). - * @return string - */ - public function lookupNamespace($prefix, - $majorVersion = null, - $minorVersion = null) - { - // Auto-select current version - if ($majorVersion === null) { - $majorVersion = $this->getMajorProtocolVersion(); - } - if ($minorVersion === null) { - $minorVersion = $this->getMinorProtocolVersion(); - } - - // Perform lookup - return parent::lookupNamespace($prefix, $majorVersion, $minorVersion); - } - -} diff --git a/library/Zend/Gdata/App/FeedSourceParent.php b/library/Zend/Gdata/App/FeedSourceParent.php deleted file mode 100644 index fae6135d75..0000000000 --- a/library/Zend/Gdata/App/FeedSourceParent.php +++ /dev/null @@ -1,267 +0,0 @@ -_entry as $entry) { - $entry->setHttpClient($httpClient); - } - return $this; - } - - /** - * Set the active service instance for this feed and all enclosed entries. - * This will be used to perform network requests, such as when calling - * save() and delete(). - * - * @param Zend_Gdata_App $instance The new service instance. - * @return Zend_Gdata_App_FeedEntryParent Provides a fluent interface. - */ - public function setService($instance) - { - parent::setService($instance); - foreach ($this->_entry as $entry) { - $entry->setService($instance); - } - return $this; - } - - /** - * Make accessing some individual elements of the feed easier. - * - * Special accessors 'entry' and 'entries' are provided so that if - * you wish to iterate over an Atom feed's entries, you can do so - * using foreach ($feed->entries as $entry) or foreach - * ($feed->entry as $entry). - * - * @param string $var The property to access. - * @return mixed - */ - public function __get($var) - { - switch ($var) { - default: - return parent::__get($var); - } - } - - - public function getDOM($doc = null, $majorVersion = 1, $minorVersion = null) - { - $element = parent::getDOM($doc, $majorVersion, $minorVersion); - if ($this->_generator != null) { - $element->appendChild($this->_generator->getDOM($element->ownerDocument)); - } - if ($this->_icon != null) { - $element->appendChild($this->_icon->getDOM($element->ownerDocument)); - } - if ($this->_logo != null) { - $element->appendChild($this->_logo->getDOM($element->ownerDocument)); - } - if ($this->_subtitle != null) { - $element->appendChild($this->_subtitle->getDOM($element->ownerDocument)); - } - return $element; - } - - /** - * Creates individual Entry objects of the appropriate type and - * stores them in the $_entry array based upon DOM data. - * - * @param DOMNode $child The DOMNode to process - */ - protected function takeChildFromDOM($child) - { - $absoluteNodeName = $child->namespaceURI . ':' . $child->localName; - switch ($absoluteNodeName) { - case $this->lookupNamespace('atom') . ':' . 'generator': - $generator = new Zend_Gdata_App_Extension_Generator(); - $generator->transferFromDOM($child); - $this->_generator = $generator; - break; - case $this->lookupNamespace('atom') . ':' . 'icon': - $icon = new Zend_Gdata_App_Extension_Icon(); - $icon->transferFromDOM($child); - $this->_icon = $icon; - break; - case $this->lookupNamespace('atom') . ':' . 'logo': - $logo = new Zend_Gdata_App_Extension_Logo(); - $logo->transferFromDOM($child); - $this->_logo = $logo; - break; - case $this->lookupNamespace('atom') . ':' . 'subtitle': - $subtitle = new Zend_Gdata_App_Extension_Subtitle(); - $subtitle->transferFromDOM($child); - $this->_subtitle = $subtitle; - break; - default: - parent::takeChildFromDOM($child); - break; - } - } - - /** - * @return Zend_Gdata_AppExtension_Generator - */ - public function getGenerator() - { - return $this->_generator; - } - - /** - * @param Zend_Gdata_App_Extension_Generator $value - * @return Zend_Gdata_App_FeedSourceParent Provides a fluent interface - */ - public function setGenerator($value) - { - $this->_generator = $value; - return $this; - } - - /** - * @return Zend_Gdata_AppExtension_Icon - */ - public function getIcon() - { - return $this->_icon; - } - - /** - * @param Zend_Gdata_App_Extension_Icon $value - * @return Zend_Gdata_App_FeedSourceParent Provides a fluent interface - */ - public function setIcon($value) - { - $this->_icon = $value; - return $this; - } - - /** - * @return Zend_Gdata_AppExtension_logo - */ - public function getlogo() - { - return $this->_logo; - } - - /** - * @param Zend_Gdata_App_Extension_logo $value - * @return Zend_Gdata_App_FeedSourceParent Provides a fluent interface - */ - public function setlogo($value) - { - $this->_logo = $value; - return $this; - } - - /** - * @return Zend_Gdata_AppExtension_Subtitle - */ - public function getSubtitle() - { - return $this->_subtitle; - } - - /** - * @param Zend_Gdata_App_Extension_Subtitle $value - * @return Zend_Gdata_App_FeedSourceParent Provides a fluent interface - */ - public function setSubtitle($value) - { - $this->_subtitle = $value; - return $this; - } - -} diff --git a/library/Zend/Gdata/App/HttpException.php b/library/Zend/Gdata/App/HttpException.php deleted file mode 100644 index c915b6d3e0..0000000000 --- a/library/Zend/Gdata/App/HttpException.php +++ /dev/null @@ -1,121 +0,0 @@ -_httpClientException = $e; - $this->_response = $response; - parent::__construct($message); - } - - /** - * Get the Zend_Http_Client_Exception. - * - * @return Zend_Http_Client_Exception - */ - public function getHttpClientException() - { - return $this->_httpClientException; - } - - /** - * Set the Zend_Http_Client_Exception. - * - * @param Zend_Http_Client_Exception $value - */ - public function setHttpClientException($value) - { - $this->_httpClientException = $value; - return $this; - } - - /** - * Set the Zend_Http_Response. - * - * @param Zend_Http_Response $response - */ - public function setResponse($response) - { - $this->_response = $response; - return $this; - } - - /** - * Get the Zend_Http_Response. - * - * @return Zend_Http_Response - */ - public function getResponse() - { - return $this->_response; - } - - /** - * Get the body of the Zend_Http_Response - * - * @return string - */ - public function getRawResponseBody() - { - if ($this->getResponse()) { - $response = $this->getResponse(); - return $response->getRawBody(); - } - return null; - } - -} diff --git a/library/Zend/Gdata/App/IOException.php b/library/Zend/Gdata/App/IOException.php deleted file mode 100644 index 146557f438..0000000000 --- a/library/Zend/Gdata/App/IOException.php +++ /dev/null @@ -1,43 +0,0 @@ -log_handle == null) { - $this->log_handle = fopen($this->config['logfile'], 'a'); - } - fwrite($this->log_handle, $message); - } - - /** - * Connect to the remote server - * - * @param string $host - * @param int $port - * @param boolean $secure - * @param int $timeout - */ - public function connect($host, $port = 80, $secure = false) - { - $this->log("Connecting to: ${host}:${port}"); - return parent::connect($host, $port, $secure); - } - - /** - * Send request to the remote server - * - * @param string $method - * @param Zend_Uri_Http $uri - * @param string $http_ver - * @param array $headers - * @param string $body - * @return string Request as string - */ - public function write($method, $uri, $http_ver = '1.1', $headers = array(), $body = '') - { - $request = parent::write($method, $uri, $http_ver, $headers, $body); - $this->log("\n\n" . $request); - return $request; - } - - /** - * Read response from server - * - * @return string - */ - public function read() - { - $response = parent::read(); - $this->log("${response}\n\n"); - return $response; - } - - /** - * Close the connection to the server - * - */ - public function close() - { - $this->log("Closing socket\n\n"); - parent::close(); - } - -} diff --git a/library/Zend/Gdata/App/MediaEntry.php b/library/Zend/Gdata/App/MediaEntry.php deleted file mode 100644 index b5b1c0203b..0000000000 --- a/library/Zend/Gdata/App/MediaEntry.php +++ /dev/null @@ -1,119 +0,0 @@ -_mediaSource = $mediaSource; - } - - /** - * Return the MIME multipart representation of this MediaEntry. - * - * @return string|Zend_Gdata_MediaMimeStream The MIME multipart - * representation of this MediaEntry. If the entry consisted only - * of XML, a string is returned. - */ - public function encode() - { - $xmlData = $this->saveXML(); - $mediaSource = $this->getMediaSource(); - if ($mediaSource === null) { - // No attachment, just send XML for entry - return $xmlData; - } else { - return new Zend_Gdata_MediaMimeStream($xmlData, - $mediaSource->getFilename(), $mediaSource->getContentType()); - } - } - - /** - * Return the MediaSource object representing the file attached to this - * MediaEntry. - * - * @return Zend_Gdata_App_MediaSource The attached MediaSource/file - */ - public function getMediaSource() - { - return $this->_mediaSource; - } - - /** - * Set the MediaSource object (file) for this MediaEntry - * - * @param Zend_Gdata_App_MediaSource $value The attached MediaSource/file - * @return Zend_Gdata_App_MediaEntry Provides a fluent interface - */ - public function setMediaSource($value) - { - if ($value instanceof Zend_Gdata_App_MediaSource) { - $this->_mediaSource = $value; - } else { - #require_once 'Zend/Gdata/App/InvalidArgumentException.php'; - throw new Zend_Gdata_App_InvalidArgumentException( - 'You must specify the media data as a class that conforms to Zend_Gdata_App_MediaSource.'); - } - return $this; - } - -} diff --git a/library/Zend/Gdata/App/MediaFileSource.php b/library/Zend/Gdata/App/MediaFileSource.php deleted file mode 100644 index 2ae4655b23..0000000000 --- a/library/Zend/Gdata/App/MediaFileSource.php +++ /dev/null @@ -1,146 +0,0 @@ -setFilename($filename); - } - - /** - * Return the MIME multipart representation of this MediaEntry. - * - * @return string - * @throws Zend_Gdata_App_IOException - */ - public function encode() - { - if ($this->getFilename() !== null && - is_readable($this->getFilename())) { - - // Retrieves the file, using the include path - $fileHandle = fopen($this->getFilename(), 'r', true); - $result = fread($fileHandle, filesize($this->getFilename())); - if ($result === false) { - #require_once 'Zend/Gdata/App/IOException.php'; - throw new Zend_Gdata_App_IOException("Error reading file - " . - $this->getFilename() . '. Read failed.'); - } - fclose($fileHandle); - return $result; - } else { - #require_once 'Zend/Gdata/App/IOException.php'; - throw new Zend_Gdata_App_IOException("Error reading file - " . - $this->getFilename() . '. File is not readable.'); - } - } - - /** - * Get the filename associated with this reader. - * - * @return string - */ - public function getFilename() - { - return $this->_filename; - } - - /** - * Set the filename which is to be read. - * - * @param string $value The desired file handle. - * @return Zend_Gdata_App_MediaFileSource Provides a fluent interface. - */ - public function setFilename($value) - { - $this->_filename = $value; - return $this; - } - - /** - * The content type for the file attached (example image/png) - * - * @return string The content type - */ - public function getContentType() - { - return $this->_contentType; - } - - /** - * Set the content type for the file attached (example image/png) - * - * @param string $value The content type - * @return Zend_Gdata_App_MediaFileSource Provides a fluent interface - */ - public function setContentType($value) - { - $this->_contentType = $value; - return $this; - } - - /** - * Alias for getFilename(). - * - * @return string - */ - public function __toString() - { - return $this->getFilename(); - } - -} diff --git a/library/Zend/Gdata/App/MediaSource.php b/library/Zend/Gdata/App/MediaSource.php deleted file mode 100644 index 31f509c53b..0000000000 --- a/library/Zend/Gdata/App/MediaSource.php +++ /dev/null @@ -1,73 +0,0 @@ - 0) { - // timestamp is already properly formatted - return $timestamp; - } else { - $ts = strtotime($timestamp); - if ($ts === false) { - #require_once 'Zend/Gdata/App/InvalidArgumentException.php'; - throw new Zend_Gdata_App_InvalidArgumentException("Invalid timestamp: $timestamp."); - } - return date('Y-m-d\TH:i:s', $ts); - } - } - - /** Find the greatest key that is less than or equal to a given upper - * bound, and return the value associated with that key. - * - * @param integer|null $maximumKey The upper bound for keys. If null, the - * maxiumum valued key will be found. - * @param array $collection An two-dimensional array of key/value pairs - * to search through. - * @returns mixed The value corresponding to the located key. - * @throws Zend_Gdata_App_Exception Thrown if $collection is empty. - */ - public static function findGreatestBoundedValue($maximumKey, $collection) - { - $found = false; - $foundKey = $maximumKey; - - // Sanity check: Make sure that the collection isn't empty - if (sizeof($collection) == 0) { - #require_once 'Zend/Gdata/App/Exception.php'; - throw new Zend_Gdata_App_Exception("Empty namespace collection encountered."); - } - - if ($maximumKey === null) { - // If the key is null, then we return the maximum available - $keys = array_keys($collection); - sort($keys); - $found = true; - $foundKey = end($keys); - } else { - // Otherwise, we optimistically guess that the current version - // will have a matching namespce. If that fails, we decrement the - // version until we find a match. - while (!$found && $foundKey >= 0) { - if (array_key_exists($foundKey, $collection)) - $found = true; - else - $foundKey--; - } - } - - // Guard: A namespace wasn't found. Either none were registered, or - // the current protcol version is lower than the maximum namespace. - if (!$found) { - #require_once 'Zend/Gdata/App/Exception.php'; - throw new Zend_Gdata_App_Exception("Namespace compatible with current protocol not found."); - } - - return $foundKey; - } - -} diff --git a/library/Zend/Gdata/App/VersionException.php b/library/Zend/Gdata/App/VersionException.php deleted file mode 100644 index dfa33c63db..0000000000 --- a/library/Zend/Gdata/App/VersionException.php +++ /dev/null @@ -1,42 +0,0 @@ -filterHttpRequest('GET', $request_uri); - $url = $filterResult['url']; - $headers = $filterResult['headers']; - $client->setHeaders($headers); - $client->setUri($url); - } else { - $client->setUri($request_uri); - } - - try { - $response = $client->request('GET'); - } catch (Zend_Http_Client_Exception $e) { - #require_once 'Zend/Gdata/App/HttpException.php'; - throw new Zend_Gdata_App_HttpException($e->getMessage(), $e); - } - - // Parse Google's response - if ($response->isSuccessful()) { - $goog_resp = array(); - foreach (explode("\n", $response->getBody()) as $l) { - $l = chop($l); - if ($l) { - list($key, $val) = explode('=', chop($l), 2); - $goog_resp[$key] = $val; - } - } - return $goog_resp['Token']; - } else { - #require_once 'Zend/Gdata/App/AuthException.php'; - throw new Zend_Gdata_App_AuthException( - 'Token upgrade failed. Reason: ' . $response->getBody()); - } - } - - /** - * Revoke a token - * - * @param string $token The token to revoke - * @param Zend_Http_Client $client (optional) HTTP client to use to make the request - * @param string $request_uri (optional) URI to which to direct the revokation request - * @return boolean Whether the revokation was successful - * @throws Zend_Gdata_App_HttpException - */ - public static function AuthSubRevokeToken($token, $client = null, - $request_uri = self::AUTHSUB_REVOKE_TOKEN_URI) - { - $client = self::getHttpClient($token, $client); - - if ($client instanceof Zend_Gdata_HttpClient) { - $filterResult = $client->filterHttpRequest('GET', $request_uri); - $url = $filterResult['url']; - $headers = $filterResult['headers']; - $client->setHeaders($headers); - $client->setUri($url); - $client->resetParameters(); - } else { - $client->setUri($request_uri); - } - - ob_start(); - try { - $response = $client->request('GET'); - } catch (Zend_Http_Client_Exception $e) { - ob_end_clean(); - #require_once 'Zend/Gdata/App/HttpException.php'; - throw new Zend_Gdata_App_HttpException($e->getMessage(), $e); - } - ob_end_clean(); - // Parse Google's response - if ($response->isSuccessful()) { - return true; - } else { - return false; - } - } - - - /** - * get token information - * - * @param string $token The token to retrieve information about - * @param Zend_Http_Client $client (optional) HTTP client to use to - * make the request - * @param string $request_uri (optional) URI to which to direct - * the information request - */ - public static function getAuthSubTokenInfo( - $token, $client = null, $request_uri = self::AUTHSUB_TOKEN_INFO_URI) - { - $client = self::getHttpClient($token, $client); - - if ($client instanceof Zend_Gdata_HttpClient) { - $filterResult = $client->filterHttpRequest('GET', $request_uri); - $url = $filterResult['url']; - $headers = $filterResult['headers']; - $client->setHeaders($headers); - $client->setUri($url); - } else { - $client->setUri($request_uri); - } - - ob_start(); - try { - $response = $client->request('GET'); - } catch (Zend_Http_Client_Exception $e) { - ob_end_clean(); - #require_once 'Zend/Gdata/App/HttpException.php'; - throw new Zend_Gdata_App_HttpException($e->getMessage(), $e); - } - ob_end_clean(); - return $response->getBody(); - } - - /** - * Retrieve a HTTP client object with AuthSub credentials attached - * as the Authorization header - * - * @param string $token The token to retrieve information about - * @param Zend_Gdata_HttpClient $client (optional) HTTP client to use to make the request - */ - public static function getHttpClient($token, $client = null) - { - if ($client == null) { - $client = new Zend_Gdata_HttpClient(); - } - if (!$client instanceof Zend_Gdata_HttpClient) { - #require_once 'Zend/Gdata/App/HttpException.php'; - throw new Zend_Gdata_App_HttpException('Client is not an instance of Zend_Gdata_HttpClient.'); - } - $useragent = 'Zend_Framework_Gdata/' . Zend_Version::VERSION; - $client->setConfig(array( - 'strictredirects' => true, - 'useragent' => $useragent - ) - ); - $client->setAuthSubToken($token); - return $client; - } - -} diff --git a/library/Zend/Gdata/Books.php b/library/Zend/Gdata/Books.php deleted file mode 100755 index 2a599bed66..0000000000 --- a/library/Zend/Gdata/Books.php +++ /dev/null @@ -1,204 +0,0 @@ -registerPackage('Zend_Gdata_Books'); - $this->registerPackage('Zend_Gdata_Books_Extension'); - parent::__construct($client, $applicationId); - $this->_httpClient->setParameterPost('service', self::AUTH_SERVICE_NAME); - } - - /** - * Retrieves a feed of volumes. - * - * @param Zend_Gdata_Query|string|null $location (optional) The URL to - * query or a Zend_Gdata_Query object from which a URL can be - * determined. - * @return Zend_Gdata_Books_VolumeFeed The feed of volumes found at the - * specified URL. - */ - public function getVolumeFeed($location = null) - { - if ($location == null) { - $uri = self::VOLUME_FEED_URI; - } else if ($location instanceof Zend_Gdata_Query) { - $uri = $location->getQueryUrl(); - } else { - $uri = $location; - } - return parent::getFeed($uri, 'Zend_Gdata_Books_VolumeFeed'); - } - - /** - * Retrieves a specific volume entry. - * - * @param string|null $volumeId The volumeId of interest. - * @param Zend_Gdata_Query|string|null $location (optional) The URL to - * query or a Zend_Gdata_Query object from which a URL can be - * determined. - * @return Zend_Gdata_Books_VolumeEntry The feed of volumes found at the - * specified URL. - */ - public function getVolumeEntry($volumeId = null, $location = null) - { - if ($volumeId !== null) { - $uri = self::VOLUME_FEED_URI . "/" . $volumeId; - } else if ($location instanceof Zend_Gdata_Query) { - $uri = $location->getQueryUrl(); - } else { - $uri = $location; - } - return parent::getEntry($uri, 'Zend_Gdata_Books_VolumeEntry'); - } - - /** - * Retrieves a feed of volumes, by default the User library feed. - * - * @param Zend_Gdata_Query|string|null $location (optional) The URL to - * query. - * @return Zend_Gdata_Books_VolumeFeed The feed of volumes found at the - * specified URL. - */ - public function getUserLibraryFeed($location = null) - { - if ($location == null) { - $uri = self::MY_LIBRARY_FEED_URI; - } else { - $uri = $location; - } - return parent::getFeed($uri, 'Zend_Gdata_Books_VolumeFeed'); - } - - /** - * Retrieves a feed of volumes, by default the User annotation feed - * - * @param Zend_Gdata_Query|string|null $location (optional) The URL to - * query. - * @return Zend_Gdata_Books_VolumeFeed The feed of volumes found at the - * specified URL. - */ - public function getUserAnnotationFeed($location = null) - { - if ($location == null) { - $uri = self::MY_ANNOTATION_FEED_URI; - } else { - $uri = $location; - } - return parent::getFeed($uri, 'Zend_Gdata_Books_VolumeFeed'); - } - - /** - * Insert a Volume / Annotation - * - * @param Zend_Gdata_Books_VolumeEntry $entry - * @param Zend_Gdata_Query|string|null $location (optional) The URL to - * query - * @return Zend_Gdata_Books_VolumeEntry The inserted volume entry. - */ - public function insertVolume($entry, $location = null) - { - if ($location == null) { - $uri = self::MY_LIBRARY_FEED_URI; - } else { - $uri = $location; - } - return parent::insertEntry( - $entry, $uri, 'Zend_Gdata_Books_VolumeEntry'); - } - - /** - * Delete a Volume - * - * @param Zend_Gdata_Books_VolumeEntry $entry - * @return void - */ - public function deleteVolume($entry) - { - $entry->delete(); - } - -} diff --git a/library/Zend/Gdata/Books/CollectionEntry.php b/library/Zend/Gdata/Books/CollectionEntry.php deleted file mode 100644 index 12e53c2e7b..0000000000 --- a/library/Zend/Gdata/Books/CollectionEntry.php +++ /dev/null @@ -1,56 +0,0 @@ -registerAllNamespaces(Zend_Gdata_Books::$namespaces); - parent::__construct($element); - } - - -} - diff --git a/library/Zend/Gdata/Books/CollectionFeed.php b/library/Zend/Gdata/Books/CollectionFeed.php deleted file mode 100644 index 6ce759abcf..0000000000 --- a/library/Zend/Gdata/Books/CollectionFeed.php +++ /dev/null @@ -1,62 +0,0 @@ -registerAllNamespaces(Zend_Gdata_Books::$namespaces); - parent::__construct($element); - } - - /** - * The classname for individual feed elements. - * - * @var string - */ - protected $_entryClassName = 'Zend_Gdata_Books_CollectionEntry'; - -} - diff --git a/library/Zend/Gdata/Books/Extension/AnnotationLink.php b/library/Zend/Gdata/Books/Extension/AnnotationLink.php deleted file mode 100644 index 979da188cc..0000000000 --- a/library/Zend/Gdata/Books/Extension/AnnotationLink.php +++ /dev/null @@ -1,63 +0,0 @@ -registerAllNamespaces(Zend_Gdata_Books::$namespaces); - parent::__construct($href, $rel, $type, $hrefLang, $title, $length); - } - -} - diff --git a/library/Zend/Gdata/Books/Extension/BooksCategory.php b/library/Zend/Gdata/Books/Extension/BooksCategory.php deleted file mode 100644 index 08834f8dcd..0000000000 --- a/library/Zend/Gdata/Books/Extension/BooksCategory.php +++ /dev/null @@ -1,59 +0,0 @@ -registerAllNamespaces(Zend_Gdata_Books::$namespaces); - parent::__construct($term, $scheme, $label); - } - -} diff --git a/library/Zend/Gdata/Books/Extension/BooksLink.php b/library/Zend/Gdata/Books/Extension/BooksLink.php deleted file mode 100644 index b877e0e312..0000000000 --- a/library/Zend/Gdata/Books/Extension/BooksLink.php +++ /dev/null @@ -1,61 +0,0 @@ -registerAllNamespaces(Zend_Gdata_Books::$namespaces); - parent::__construct($href, $rel, $type, $hrefLang, $title, $length); - } - - -} - diff --git a/library/Zend/Gdata/Books/Extension/Embeddability.php b/library/Zend/Gdata/Books/Extension/Embeddability.php deleted file mode 100644 index 05d5e4509c..0000000000 --- a/library/Zend/Gdata/Books/Extension/Embeddability.php +++ /dev/null @@ -1,122 +0,0 @@ -registerAllNamespaces(Zend_Gdata_Books::$namespaces); - parent::__construct(); - $this->_value = $value; - } - - /** - * Retrieves DOMElement which corresponds to this element and all - * child properties. This is used to build this object back into a DOM - * and eventually XML text for sending to the server upon updates, or - * for application storage/persistance. - * - * @param DOMDocument $doc The DOMDocument used to construct DOMElements - * @return DOMElement The DOMElement representing this element and all - * child properties. - */ - public function getDOM($doc = null, $majorVersion = 1, $minorVersion = null) - { - $element = parent::getDOM($doc); - if ($this->_value !== null) { - $element->setAttribute('value', $this->_value); - } - return $element; - } - - /** - * Extracts XML attributes from the DOM and converts them to the - * appropriate object members. - * - * @param DOMNode $attribute The DOMNode attribute to be handled. - */ - protected function takeAttributeFromDOM($attribute) - { - switch ($attribute->localName) { - case 'value': - $this->_value = $attribute->nodeValue; - break; - default: - parent::takeAttributeFromDOM($attribute); - } - } - - /** - * Returns the programmatic value that describes the embeddability of a - * volume in Google Book Search - * - * @return string|null The value - */ - public function getValue() - { - return $this->_value; - } - - /** - * Sets the programmatic value that describes the embeddability of a - * volume in Google Book Search - * - * @param string|null $value Programmatic value that describes the - * embeddability of a volume in Google Book Search - * @return Zend_Gdata_Books_Extension_Embeddability Provides a fluent - * interface - */ - public function setValue($value) - { - $this->_value = $value; - return $this; - } - -} - diff --git a/library/Zend/Gdata/Books/Extension/InfoLink.php b/library/Zend/Gdata/Books/Extension/InfoLink.php deleted file mode 100644 index f30b87c9ee..0000000000 --- a/library/Zend/Gdata/Books/Extension/InfoLink.php +++ /dev/null @@ -1,59 +0,0 @@ -registerAllNamespaces(Zend_Gdata_Books::$namespaces); - parent::__construct($href, $rel, $type, $hrefLang, $title, $length); - } - -} diff --git a/library/Zend/Gdata/Books/Extension/PreviewLink.php b/library/Zend/Gdata/Books/Extension/PreviewLink.php deleted file mode 100644 index fc2c4862c4..0000000000 --- a/library/Zend/Gdata/Books/Extension/PreviewLink.php +++ /dev/null @@ -1,60 +0,0 @@ -registerAllNamespaces(Zend_Gdata_Books::$namespaces); - parent::__construct($href, $rel, $type, $hrefLang, $title, $length); - } - -} diff --git a/library/Zend/Gdata/Books/Extension/Review.php b/library/Zend/Gdata/Books/Extension/Review.php deleted file mode 100644 index 85ddeb6dd9..0000000000 --- a/library/Zend/Gdata/Books/Extension/Review.php +++ /dev/null @@ -1,152 +0,0 @@ -registerAllNamespaces(Zend_Gdata_Books::$namespaces); - parent::__construct(); - $this->_lang = $lang; - $this->_type = $type; - $this->_text = $value; - } - - /** - * Retrieves DOMElement which corresponds to this element and all - * child properties. This is used to build this object back into a DOM - * and eventually XML text for sending to the server upon updates, or - * for application storage/persistance. - * - * @param DOMDocument $doc The DOMDocument used to construct DOMElements - * @return DOMElement The DOMElement representing this element and all - * child properties. - */ - public function getDOM($doc = null, $majorVersion = 1, $minorVersion = null) - { - $element = parent::getDOM($doc); - if ($this->_lang !== null) { - $element->setAttribute('lang', $this->_lang); - } - if ($this->_type !== null) { - $element->setAttribute('type', $this->_type); - } - return $element; - } - - /** - * Extracts XML attributes from the DOM and converts them to the - * appropriate object members. - * - * @param DOMNode $attribute The DOMNode attribute to be handled. - */ - protected function takeAttributeFromDOM($attribute) - { - switch ($attribute->localName) { - case 'lang': - $this->_lang = $attribute->nodeValue; - break; - case 'type': - $this->_type = $attribute->nodeValue; - break; - default: - parent::takeAttributeFromDOM($attribute); - } - } - - /** - * Returns the language of link title - * - * @return string The lang - */ - public function getLang() - { - return $this->_lang; - } - - /** - * Returns the type of text construct (typically 'text', 'html' or 'xhtml') - * - * @return string The type - */ - public function getType() - { - return $this->_type; - } - - /** - * Sets the language of link title - * - * @param string $lang language of link title - * @return Zend_Gdata_Books_Extension_Review Provides a fluent interface - */ - public function setLang($lang) - { - $this->_lang = $lang; - return $this; - } - - /** - * Sets the type of text construct (typically 'text', 'html' or 'xhtml') - * - * @param string $type type of text construct (typically 'text', 'html' or 'xhtml') - * @return Zend_Gdata_Books_Extension_Review Provides a fluent interface - */ - public function setType($type) - { - $this->_type = $type; - return $this; - } - - -} - diff --git a/library/Zend/Gdata/Books/Extension/ThumbnailLink.php b/library/Zend/Gdata/Books/Extension/ThumbnailLink.php deleted file mode 100644 index 1aeb18c159..0000000000 --- a/library/Zend/Gdata/Books/Extension/ThumbnailLink.php +++ /dev/null @@ -1,60 +0,0 @@ -registerAllNamespaces(Zend_Gdata_Books::$namespaces); - parent::__construct($href, $rel, $type, $hrefLang, $title, $length); - } - -} diff --git a/library/Zend/Gdata/Books/Extension/Viewability.php b/library/Zend/Gdata/Books/Extension/Viewability.php deleted file mode 100644 index 84c6819850..0000000000 --- a/library/Zend/Gdata/Books/Extension/Viewability.php +++ /dev/null @@ -1,123 +0,0 @@ -registerAllNamespaces(Zend_Gdata_Books::$namespaces); - parent::__construct(); - $this->_value = $value; - } - - /** - * Retrieves DOMElement which corresponds to this element and all - * child properties. This is used to build this object back into a DOM - * and eventually XML text for sending to the server upon updates, or - * for application storage/persistance. - * - * @param DOMDocument $doc The DOMDocument used to construct DOMElements - * @return DOMElement The DOMElement representing this element and all - * child properties. - */ - public function getDOM($doc = null, $majorVersion = 1, $minorVersion = null) - { - $element = parent::getDOM($doc); - if ($this->_value !== null) { - $element->setAttribute('value', $this->_value); - } - return $element; - } - - /** - * Extracts XML attributes from the DOM and converts them to the - * appropriate object members. - * - * @param DOMNode $attribute The DOMNode attribute to be handled. - */ - protected function takeAttributeFromDOM($attribute) - { - switch ($attribute->localName) { - case 'value': - $this->_value = $attribute->nodeValue; - break; - default: - parent::takeAttributeFromDOM($attribute); - } - } - - /** - * Returns the programmatic value that describes the viewability of a volume - * in Google Book Search - * - * @return string The value - */ - public function getValue() - { - return $this->_value; - } - - /** - * Sets the programmatic value that describes the viewability of a volume in - * Google Book Search - * - * @param string $value programmatic value that describes the viewability - * of a volume in Googl eBook Search - * @return Zend_Gdata_Books_Extension_Viewability Provides a fluent - * interface - */ - public function setValue($value) - { - $this->_value = $value; - return $this; - } - - -} - diff --git a/library/Zend/Gdata/Books/VolumeEntry.php b/library/Zend/Gdata/Books/VolumeEntry.php deleted file mode 100644 index e450aba091..0000000000 --- a/library/Zend/Gdata/Books/VolumeEntry.php +++ /dev/null @@ -1,687 +0,0 @@ -registerAllNamespaces(Zend_Gdata_Books::$namespaces); - parent::__construct($element); - } - - /** - * Retrieves DOMElement which corresponds to this element and all - * child properties. This is used to build this object back into a DOM - * and eventually XML text for sending to the server upon updates, or - * for application storage/persistance. - * - * @param DOMDocument $doc The DOMDocument used to construct DOMElements - * @return DOMElement The DOMElement representing this element and all - * child properties. - */ - public function getDOM($doc = null, $majorVersion = 1, $minorVersion = null) - { - $element = parent::getDOM($doc); - if ($this->_creators !== null) { - foreach ($this->_creators as $creators) { - $element->appendChild($creators->getDOM( - $element->ownerDocument)); - } - } - if ($this->_dates !== null) { - foreach ($this->_dates as $dates) { - $element->appendChild($dates->getDOM($element->ownerDocument)); - } - } - if ($this->_descriptions !== null) { - foreach ($this->_descriptions as $descriptions) { - $element->appendChild($descriptions->getDOM( - $element->ownerDocument)); - } - } - if ($this->_formats !== null) { - foreach ($this->_formats as $formats) { - $element->appendChild($formats->getDOM( - $element->ownerDocument)); - } - } - if ($this->_identifiers !== null) { - foreach ($this->_identifiers as $identifiers) { - $element->appendChild($identifiers->getDOM( - $element->ownerDocument)); - } - } - if ($this->_languages !== null) { - foreach ($this->_languages as $languages) { - $element->appendChild($languages->getDOM( - $element->ownerDocument)); - } - } - if ($this->_publishers !== null) { - foreach ($this->_publishers as $publishers) { - $element->appendChild($publishers->getDOM( - $element->ownerDocument)); - } - } - if ($this->_subjects !== null) { - foreach ($this->_subjects as $subjects) { - $element->appendChild($subjects->getDOM( - $element->ownerDocument)); - } - } - if ($this->_titles !== null) { - foreach ($this->_titles as $titles) { - $element->appendChild($titles->getDOM($element->ownerDocument)); - } - } - if ($this->_comments !== null) { - $element->appendChild($this->_comments->getDOM( - $element->ownerDocument)); - } - if ($this->_embeddability !== null) { - $element->appendChild($this->_embeddability->getDOM( - $element->ownerDocument)); - } - if ($this->_rating !== null) { - $element->appendChild($this->_rating->getDOM( - $element->ownerDocument)); - } - if ($this->_review !== null) { - $element->appendChild($this->_review->getDOM( - $element->ownerDocument)); - } - if ($this->_viewability !== null) { - $element->appendChild($this->_viewability->getDOM( - $element->ownerDocument)); - } - return $element; - } - - /** - * Creates individual objects of the appropriate type and stores - * them in this object based upon DOM data. - * - * @param DOMNode $child The DOMNode to process. - */ - protected function takeChildFromDOM($child) - { - $absoluteNodeName = $child->namespaceURI . ':' . $child->localName; - switch ($absoluteNodeName) { - case $this->lookupNamespace('dc') . ':' . 'creator': - $creators = new Zend_Gdata_DublinCore_Extension_Creator(); - $creators->transferFromDOM($child); - $this->_creators[] = $creators; - break; - case $this->lookupNamespace('dc') . ':' . 'date': - $dates = new Zend_Gdata_DublinCore_Extension_Date(); - $dates->transferFromDOM($child); - $this->_dates[] = $dates; - break; - case $this->lookupNamespace('dc') . ':' . 'description': - $descriptions = new Zend_Gdata_DublinCore_Extension_Description(); - $descriptions->transferFromDOM($child); - $this->_descriptions[] = $descriptions; - break; - case $this->lookupNamespace('dc') . ':' . 'format': - $formats = new Zend_Gdata_DublinCore_Extension_Format(); - $formats->transferFromDOM($child); - $this->_formats[] = $formats; - break; - case $this->lookupNamespace('dc') . ':' . 'identifier': - $identifiers = new Zend_Gdata_DublinCore_Extension_Identifier(); - $identifiers->transferFromDOM($child); - $this->_identifiers[] = $identifiers; - break; - case $this->lookupNamespace('dc') . ':' . 'language': - $languages = new Zend_Gdata_DublinCore_Extension_Language(); - $languages->transferFromDOM($child); - $this->_languages[] = $languages; - break; - case $this->lookupNamespace('dc') . ':' . 'publisher': - $publishers = new Zend_Gdata_DublinCore_Extension_Publisher(); - $publishers->transferFromDOM($child); - $this->_publishers[] = $publishers; - break; - case $this->lookupNamespace('dc') . ':' . 'subject': - $subjects = new Zend_Gdata_DublinCore_Extension_Subject(); - $subjects->transferFromDOM($child); - $this->_subjects[] = $subjects; - break; - case $this->lookupNamespace('dc') . ':' . 'title': - $titles = new Zend_Gdata_DublinCore_Extension_Title(); - $titles->transferFromDOM($child); - $this->_titles[] = $titles; - break; - case $this->lookupNamespace('gd') . ':' . 'comments': - $comments = new Zend_Gdata_Extension_Comments(); - $comments->transferFromDOM($child); - $this->_comments = $comments; - break; - case $this->lookupNamespace('gbs') . ':' . 'embeddability': - $embeddability = new Zend_Gdata_Books_Extension_Embeddability(); - $embeddability->transferFromDOM($child); - $this->_embeddability = $embeddability; - break; - case $this->lookupNamespace('gd') . ':' . 'rating': - $rating = new Zend_Gdata_Extension_Rating(); - $rating->transferFromDOM($child); - $this->_rating = $rating; - break; - case $this->lookupNamespace('gbs') . ':' . 'review': - $review = new Zend_Gdata_Books_Extension_Review(); - $review->transferFromDOM($child); - $this->_review = $review; - break; - case $this->lookupNamespace('gbs') . ':' . 'viewability': - $viewability = new Zend_Gdata_Books_Extension_Viewability(); - $viewability->transferFromDOM($child); - $this->_viewability = $viewability; - break; - default: - parent::takeChildFromDOM($child); - break; - } - } - - /** - * Returns the Comments class - * - * @return Zend_Gdata_Extension_Comments|null The comments - */ - public function getComments() - { - return $this->_comments; - } - - /** - * Returns the creators - * - * @return array The creators - */ - public function getCreators() - { - return $this->_creators; - } - - /** - * Returns the dates - * - * @return array The dates - */ - public function getDates() - { - return $this->_dates; - } - - /** - * Returns the descriptions - * - * @return array The descriptions - */ - public function getDescriptions() - { - return $this->_descriptions; - } - - /** - * Returns the embeddability - * - * @return Zend_Gdata_Books_Extension_Embeddability|null The embeddability - */ - public function getEmbeddability() - { - return $this->_embeddability; - } - - /** - * Returns the formats - * - * @return array The formats - */ - public function getFormats() - { - return $this->_formats; - } - - /** - * Returns the identifiers - * - * @return array The identifiers - */ - public function getIdentifiers() - { - return $this->_identifiers; - } - - /** - * Returns the languages - * - * @return array The languages - */ - public function getLanguages() - { - return $this->_languages; - } - - /** - * Returns the publishers - * - * @return array The publishers - */ - public function getPublishers() - { - return $this->_publishers; - } - - /** - * Returns the rating - * - * @return Zend_Gdata_Extension_Rating|null The rating - */ - public function getRating() - { - return $this->_rating; - } - - /** - * Returns the review - * - * @return Zend_Gdata_Books_Extension_Review|null The review - */ - public function getReview() - { - return $this->_review; - } - - /** - * Returns the subjects - * - * @return array The subjects - */ - public function getSubjects() - { - return $this->_subjects; - } - - /** - * Returns the titles - * - * @return array The titles - */ - public function getTitles() - { - return $this->_titles; - } - - /** - * Returns the viewability - * - * @return Zend_Gdata_Books_Extension_Viewability|null The viewability - */ - public function getViewability() - { - return $this->_viewability; - } - - /** - * Sets the Comments class - * - * @param Zend_Gdata_Extension_Comments|null $comments Comments class - * @return Zend_Gdata_Books_VolumeEntry Provides a fluent interface - */ - public function setComments($comments) - { - $this->_comments = $comments; - return $this; - } - - /** - * Sets the creators - * - * @param array $creators Creators|null - * @return Zend_Gdata_Books_VolumeEntry Provides a fluent interface - */ - public function setCreators($creators) - { - $this->_creators = $creators; - return $this; - } - - /** - * Sets the dates - * - * @param array $dates dates - * @return Zend_Gdata_Books_VolumeEntry Provides a fluent interface - */ - public function setDates($dates) - { - $this->_dates = $dates; - return $this; - } - - /** - * Sets the descriptions - * - * @param array $descriptions descriptions - * @return Zend_Gdata_Books_VolumeEntry Provides a fluent interface - */ - public function setDescriptions($descriptions) - { - $this->_descriptions = $descriptions; - return $this; - } - - /** - * Sets the embeddability - * - * @param Zend_Gdata_Books_Extension_Embeddability|null $embeddability - * embeddability - * @return Zend_Gdata_Books_VolumeEntry Provides a fluent interface - */ - public function setEmbeddability($embeddability) - { - $this->_embeddability = $embeddability; - return $this; - } - - /** - * Sets the formats - * - * @param array $formats formats - * @return Zend_Gdata_Books_VolumeEntry Provides a fluent interface - */ - public function setFormats($formats) - { - $this->_formats = $formats; - return $this; - } - - /** - * Sets the identifiers - * - * @param array $identifiers identifiers - * @return Zend_Gdata_Books_VolumeEntry Provides a fluent interface - */ - public function setIdentifiers($identifiers) - { - $this->_identifiers = $identifiers; - return $this; - } - - /** - * Sets the languages - * - * @param array $languages languages - * @return Zend_Gdata_Books_VolumeEntry Provides a fluent interface - */ - public function setLanguages($languages) - { - $this->_languages = $languages; - return $this; - } - - /** - * Sets the publishers - * - * @param array $publishers publishers - * @return Zend_Gdata_Books_VolumeEntry Provides a fluent interface - */ - public function setPublishers($publishers) - { - $this->_publishers = $publishers; - return $this; - } - - /** - * Sets the rating - * - * @param Zend_Gdata_Extension_Rating|null $rating rating - * @return Zend_Gdata_Books_VolumeEntry Provides a fluent interface - */ - public function setRating($rating) - { - $this->_rating = $rating; - return $this; - } - - /** - * Sets the review - * - * @param Zend_Gdata_Books_Extension_Review|null $review review - * @return Zend_Gdata_Books_VolumeEntry Provides a fluent interface - */ - public function setReview($review) - { - $this->_review = $review; - return $this; - } - - /** - * Sets the subjects - * - * @param array $subjects subjects - * @return Zend_Gdata_Books_VolumeEntry Provides a fluent interface - */ - public function setSubjects($subjects) - { - $this->_subjects = $subjects; - return $this; - } - - /** - * Sets the titles - * - * @param array $titles titles - * @return Zend_Gdata_Books_VolumeEntry Provides a fluent interface - */ - public function setTitles($titles) - { - $this->_titles = $titles; - return $this; - } - - /** - * Sets the viewability - * - * @param Zend_Gdata_Books_Extension_Viewability|null $viewability - * viewability - * @return Zend_Gdata_Books_VolumeEntry Provides a fluent interface - */ - public function setViewability($viewability) - { - $this->_viewability = $viewability; - return $this; - } - - - /** - * Gets the volume ID based upon the atom:id value - * - * @return string The volume ID - * @throws Zend_Gdata_App_Exception - */ - public function getVolumeId() - { - $fullId = $this->getId()->getText(); - $position = strrpos($fullId, '/'); - if ($position === false) { - #require_once 'Zend/Gdata/App/Exception.php'; - throw new Zend_Gdata_App_Exception('Slash not found in atom:id'); - } else { - return substr($fullId, strrpos($fullId,'/') + 1); - } - } - - /** - * Gets the thumbnail link - * - * @return Zend_Gdata_App_Extension_link|null The thumbnail link - */ - public function getThumbnailLink() - { - return $this->getLink(self::THUMBNAIL_LINK_REL); - } - - /** - * Gets the preview link - * - * @return Zend_Gdata_App_Extension_Link|null The preview link - */ - public function getPreviewLink() - { - return $this->getLink(self::PREVIEW_LINK_REL); - } - - /** - * Gets the info link - * - * @return Zend_Gdata_App_Extension_Link|null The info link - */ - public function getInfoLink() - { - return $this->getLink(self::INFO_LINK_REL); - } - - /** - * Gets the annotations link - * - * @return Zend_Gdata_App_Extension_Link|null The annotations link - */ - public function getAnnotationLink() - { - return $this->getLink(self::ANNOTATION_LINK_REL); - } - -} diff --git a/library/Zend/Gdata/Books/VolumeFeed.php b/library/Zend/Gdata/Books/VolumeFeed.php deleted file mode 100644 index 36d3f43b66..0000000000 --- a/library/Zend/Gdata/Books/VolumeFeed.php +++ /dev/null @@ -1,62 +0,0 @@ -registerAllNamespaces(Zend_Gdata_Books::$namespaces); - parent::__construct($element); - } - - /** - * The classname for individual feed elements. - * - * @var string - */ - protected $_entryClassName = 'Zend_Gdata_Books_VolumeEntry'; - -} - diff --git a/library/Zend/Gdata/Books/VolumeQuery.php b/library/Zend/Gdata/Books/VolumeQuery.php deleted file mode 100755 index 9336cd9aed..0000000000 --- a/library/Zend/Gdata/Books/VolumeQuery.php +++ /dev/null @@ -1,112 +0,0 @@ -_params['min-viewability'] = 'full'; - break; - case 'partial_view': - $this->_params['min-viewability'] = 'partial'; - break; - case null: - unset($this->_params['min-viewability']); - break; - } - return $this; - } - - /** - * Minimum viewability of volumes to include in search results - * - * @return string|null min-viewability - */ - public function getMinViewability() - { - if (array_key_exists('min-viewability', $this->_params)) { - return $this->_params['min-viewability']; - } else { - return null; - } - } - - /** - * Returns the generated full query URL - * - * @return string The URL - */ - public function getQueryUrl() - { - if (isset($this->_url)) { - $url = $this->_url; - } else { - $url = Zend_Gdata_Books::VOLUME_FEED_URI; - } - if ($this->getCategory() !== null) { - $url .= '/-/' . $this->getCategory(); - } - $url = $url . $this->getQueryString(); - return $url; - } - -} diff --git a/library/Zend/Gdata/Calendar.php b/library/Zend/Gdata/Calendar.php deleted file mode 100644 index 951bacaf7a..0000000000 --- a/library/Zend/Gdata/Calendar.php +++ /dev/null @@ -1,169 +0,0 @@ -registerPackage('Zend_Gdata_Calendar'); - $this->registerPackage('Zend_Gdata_Calendar_Extension'); - parent::__construct($client, $applicationId); - $this->_httpClient->setParameterPost('service', self::AUTH_SERVICE_NAME); - } - - /** - * Retreive feed object - * - * @param mixed $location The location for the feed, as a URL or Query - * @return Zend_Gdata_Calendar_EventFeed - */ - public function getCalendarEventFeed($location = null) - { - if ($location == null) { - $uri = self::CALENDAR_EVENT_FEED_URI; - } else if ($location instanceof Zend_Gdata_Query) { - $uri = $location->getQueryUrl(); - } else { - $uri = $location; - } - return parent::getFeed($uri, 'Zend_Gdata_Calendar_EventFeed'); - } - - /** - * Retreive entry object - * - * @return Zend_Gdata_Calendar_EventEntry - */ - public function getCalendarEventEntry($location = null) - { - if ($location == null) { - #require_once 'Zend/Gdata/App/InvalidArgumentException.php'; - throw new Zend_Gdata_App_InvalidArgumentException( - 'Location must not be null'); - } else if ($location instanceof Zend_Gdata_Query) { - $uri = $location->getQueryUrl(); - } else { - $uri = $location; - } - return parent::getEntry($uri, 'Zend_Gdata_Calendar_EventEntry'); - } - - - /** - * Retrieve feed object - * - * @return Zend_Gdata_Calendar_ListFeed - */ - public function getCalendarListFeed() - { - $uri = self::CALENDAR_FEED_URI . '/default'; - return parent::getFeed($uri,'Zend_Gdata_Calendar_ListFeed'); - } - - /** - * Retreive entryobject - * - * @return Zend_Gdata_Calendar_ListEntry - */ - public function getCalendarListEntry($location = null) - { - if ($location == null) { - #require_once 'Zend/Gdata/App/InvalidArgumentException.php'; - throw new Zend_Gdata_App_InvalidArgumentException( - 'Location must not be null'); - } else if ($location instanceof Zend_Gdata_Query) { - $uri = $location->getQueryUrl(); - } else { - $uri = $location; - } - return parent::getEntry($uri,'Zend_Gdata_Calendar_ListEntry'); - } - - public function insertEvent($event, $uri=null) - { - if ($uri == null) { - $uri = $this->_defaultPostUri; - } - $newEvent = $this->insertEntry($event, $uri, 'Zend_Gdata_Calendar_EventEntry'); - return $newEvent; - } - -} diff --git a/library/Zend/Gdata/Calendar/EventEntry.php b/library/Zend/Gdata/Calendar/EventEntry.php deleted file mode 100644 index 9365a1949e..0000000000 --- a/library/Zend/Gdata/Calendar/EventEntry.php +++ /dev/null @@ -1,164 +0,0 @@ -registerAllNamespaces(Zend_Gdata_Calendar::$namespaces); - parent::__construct($element); - } - - public function getDOM($doc = null, $majorVersion = 1, $minorVersion = null) - { - $element = parent::getDOM($doc, $majorVersion, $minorVersion); - if ($this->_sendEventNotifications != null) { - $element->appendChild($this->_sendEventNotifications->getDOM($element->ownerDocument)); - } - if ($this->_timezone != null) { - $element->appendChild($this->_timezone->getDOM($element->ownerDocument)); - } - if ($this->_quickadd != null) { - $element->appendChild($this->_quickadd->getDOM($element->ownerDocument)); - } - return $element; - } - - protected function takeChildFromDOM($child) - { - $absoluteNodeName = $child->namespaceURI . ':' . $child->localName; - - switch ($absoluteNodeName) { - case $this->lookupNamespace('gCal') . ':' . 'sendEventNotifications'; - $sendEventNotifications = new Zend_Gdata_Calendar_Extension_SendEventNotifications(); - $sendEventNotifications->transferFromDOM($child); - $this->_sendEventNotifications = $sendEventNotifications; - break; - case $this->lookupNamespace('gCal') . ':' . 'timezone'; - $timezone = new Zend_Gdata_Calendar_Extension_Timezone(); - $timezone->transferFromDOM($child); - $this->_timezone = $timezone; - break; - case $this->lookupNamespace('atom') . ':' . 'link'; - $link = new Zend_Gdata_Calendar_Extension_Link(); - $link->transferFromDOM($child); - $this->_link[] = $link; - break; - case $this->lookupNamespace('gCal') . ':' . 'quickadd'; - $quickadd = new Zend_Gdata_Calendar_Extension_QuickAdd(); - $quickadd->transferFromDOM($child); - $this->_quickadd = $quickadd; - break; - default: - parent::takeChildFromDOM($child); - break; - } - } - - public function getSendEventNotifications() - { - return $this->_sendEventNotifications; - } - - public function setSendEventNotifications($value) - { - $this->_sendEventNotifications = $value; - return $this; - } - - public function getTimezone() - { - return $this->_timezone; - } - - /** - * @param Zend_Gdata_Calendar_Extension_Timezone $value - * @return Zend_Gdata_Extension_EventEntry Provides a fluent interface - */ - public function setTimezone($value) - { - $this->_timezone = $value; - return $this; - } - - public function getQuickAdd() - { - return $this->_quickadd; - } - - /** - * @param Zend_Gdata_Calendar_Extension_QuickAdd $value - * @return Zend_Gdata_Extension_ListEntry Provides a fluent interface - */ - public function setQuickAdd($value) - { - $this->_quickadd = $value; - return $this; - } - -} diff --git a/library/Zend/Gdata/Calendar/EventFeed.php b/library/Zend/Gdata/Calendar/EventFeed.php deleted file mode 100644 index 38346e76e0..0000000000 --- a/library/Zend/Gdata/Calendar/EventFeed.php +++ /dev/null @@ -1,106 +0,0 @@ -registerAllNamespaces(Zend_Gdata_Calendar::$namespaces); - parent::__construct($element); - } - - public function getDOM($doc = null, $majorVersion = 1, $minorVersion = null) - { - $element = parent::getDOM($doc, $majorVersion, $minorVersion); - if ($this->_timezone != null) { - $element->appendChild($this->_timezone->getDOM($element->ownerDocument)); - } - - return $element; - } - - protected function takeChildFromDOM($child) - { - $absoluteNodeName = $child->namespaceURI . ':' . $child->localName; - - switch ($absoluteNodeName) { - case $this->lookupNamespace('gCal') . ':' . 'timezone'; - $timezone = new Zend_Gdata_Calendar_Extension_Timezone(); - $timezone->transferFromDOM($child); - $this->_timezone = $timezone; - break; - - default: - parent::takeChildFromDOM($child); - break; - } - } - - public function getTimezone() - { - return $this->_timezone; - } - - public function setTimezone($value) - { - $this->_timezone = $value; - return $this; - } - -} diff --git a/library/Zend/Gdata/Calendar/EventQuery.php b/library/Zend/Gdata/Calendar/EventQuery.php deleted file mode 100644 index ad5c8cc4c6..0000000000 --- a/library/Zend/Gdata/Calendar/EventQuery.php +++ /dev/null @@ -1,491 +0,0 @@ -_comments = $value; - return $this; - } - - /** - * @see $_event - * @param string $value - * @return Zend_Gdata_Calendar_EventQuery Provides a fluent interface - */ - public function setEvent($value) - { - $this->_event = $value; - return $this; - } - - /** - * @see $_projection - * @param string $value - * @return Zend_Gdata_Calendar_EventQuery Provides a fluent interface - */ - public function setProjection($value) - { - $this->_projection = $value; - return $this; - } - - /** - * @see $_user - * @param string $value - * @return Zend_Gdata_Calendar_EventQuery Provides a fluent interface - */ - public function setUser($value) - { - $this->_user = $value; - return $this; - } - - /** - * @see $_visibility - * @param bool $value - * @return Zend_Gdata_Calendar_EventQuery Provides a fluent interface - */ - public function setVisibility($value) - { - $this->_visibility = $value; - return $this; - } - - /** - * @see $_comments; - * @return string comments - */ - public function getComments() - { - return $this->_comments; - } - - /** - * @see $_event; - * @return string event - */ - public function getEvent() - { - return $this->_event; - } - - /** - * @see $_projection - * @return string projection - */ - public function getProjection() - { - return $this->_projection; - } - - /** - * @see $_user - * @return string user - */ - public function getUser() - { - return $this->_user; - } - - /** - * @see $_visibility - * @return string visibility - */ - public function getVisibility() - { - return $this->_visibility; - } - - /** - * @param int $value - * @return Zend_Gdata_Calendar_EventQuery Provides a fluent interface - */ - public function setStartMax($value) - { - if ($value != null) { - $this->_params['start-max'] = Zend_Gdata_App_Util::formatTimestamp($value); - } else { - unset($this->_params['start-max']); - } - return $this; - } - - /** - * @param int $value - * @return Zend_Gdata_Calendar_EventQuery Provides a fluent interface - */ - public function setStartMin($value) - { - if ($value != null) { - $this->_params['start-min'] = Zend_Gdata_App_Util::formatTimestamp($value); - } else { - unset($this->_params['start-min']); - } - return $this; - } - - /** - * @param string $value - * @return Zend_Gdata_Calendar_EventQuery Provides a fluent interface - */ - public function setOrderBy($value) - { - if ($value != null) { - $this->_params['orderby'] = $value; - } else { - unset($this->_params['orderby']); - } - return $this; - } - - /** - * @return int start-max - */ - public function getStartMax() - { - if (array_key_exists('start-max', $this->_params)) { - return $this->_params['start-max']; - } else { - return null; - } - } - - /** - * @return int start-min - */ - public function getStartMin() - { - if (array_key_exists('start-min', $this->_params)) { - return $this->_params['start-min']; - } else { - return null; - } - } - - /** - * @return string orderby - */ - public function getOrderBy() - { - if (array_key_exists('orderby', $this->_params)) { - return $this->_params['orderby']; - } else { - return null; - } - } - - /** - * @return string sortorder - */ - public function getSortOrder() - { - if (array_key_exists('sortorder', $this->_params)) { - return $this->_params['sortorder']; - } else { - return null; - } - } - - /** - * @return string sortorder - */ - public function setSortOrder($value) - { - if ($value != null) { - $this->_params['sortorder'] = $value; - } else { - unset($this->_params['sortorder']); - } - return $this; - } - - /** - * @return string recurrence-expansion-start - */ - public function getRecurrenceExpansionStart() - { - if (array_key_exists('recurrence-expansion-start', $this->_params)) { - return $this->_params['recurrence-expansion-start']; - } else { - return null; - } - } - - /** - * @return string recurrence-expansion-start - */ - public function setRecurrenceExpansionStart($value) - { - if ($value != null) { - $this->_params['recurrence-expansion-start'] = Zend_Gdata_App_Util::formatTimestamp($value); - } else { - unset($this->_params['recurrence-expansion-start']); - } - return $this; - } - - - /** - * @return string recurrence-expansion-end - */ - public function getRecurrenceExpansionEnd() - { - if (array_key_exists('recurrence-expansion-end', $this->_params)) { - return $this->_params['recurrence-expansion-end']; - } else { - return null; - } - } - - /** - * @return string recurrence-expansion-end - */ - public function setRecurrenceExpansionEnd($value) - { - if ($value != null) { - $this->_params['recurrence-expansion-end'] = Zend_Gdata_App_Util::formatTimestamp($value); - } else { - unset($this->_params['recurrence-expansion-end']); - } - return $this; - } - - /** - * @param string $value Also accepts bools. - * @return Zend_Gdata_Calendar_EventQuery Provides a fluent interface - */ - public function getSingleEvents() - { - if (array_key_exists('singleevents', $this->_params)) { - $value = $this->_params['singleevents']; - switch ($value) { - case 'true': - return true; - break; - case 'false': - return false; - break; - default: - #require_once 'Zend/Gdata/App/Exception.php'; - throw new Zend_Gdata_App_Exception( - 'Invalid query param value for futureevents: ' . - $value . ' It must be a boolean.'); - } - } else { - return null; - } - } - - /** - * @param string $value Also accepts bools. If using a string, must be either "true" or "false". - * @return Zend_Gdata_Calendar_EventQuery Provides a fluent interface - */ - public function setSingleEvents($value) - { - if ($value !== null) { - if (is_bool($value)) { - $this->_params['singleevents'] = ($value?'true':'false'); - } elseif ($value == 'true' | $value == 'false') { - $this->_params['singleevents'] = $value; - } else { - #require_once 'Zend/Gdata/App/Exception.php'; - throw new Zend_Gdata_App_Exception( - 'Invalid query param value for futureevents: ' . - $value . ' It must be a boolean.'); - } - } else { - unset($this->_params['singleevents']); - } - return $this; - } - - /** - * @return string futureevents - */ - public function getFutureEvents() - { - if (array_key_exists('futureevents', $this->_params)) { - $value = $this->_params['futureevents']; - switch ($value) { - case 'true': - return true; - break; - case 'false': - return false; - break; - default: - #require_once 'Zend/Gdata/App/Exception.php'; - throw new Zend_Gdata_App_Exception( - 'Invalid query param value for futureevents: ' . - $value . ' It must be a boolean.'); - } - } else { - return null; - } - } - - /** - * @param string $value Also accepts bools. If using a string, must be either "true" or "false" or - * an exception will be thrown on retrieval. - * @return Zend_Gdata_Calendar_EventQuery Provides a fluent interface - */ - public function setFutureEvents($value) - { - if ($value !== null) { - if (is_bool($value)) { - $this->_params['futureevents'] = ($value?'true':'false'); - } elseif ($value == 'true' | $value == 'false') { - $this->_params['futureevents'] = $value; - } else { - #require_once 'Zend/Gdata/App/Exception.php'; - throw new Zend_Gdata_App_Exception( - 'Invalid query param value for futureevents: ' . - $value . ' It must be a boolean.'); - } - } else { - unset($this->_params['futureevents']); - } - return $this; - } - - /** - * @return string url - */ - public function getQueryUrl() - { - if (isset($this->_url)) { - $uri = $this->_url; - } else { - $uri = $this->_defaultFeedUri; - } - if ($this->getUser() != null) { - $uri .= '/' . $this->getUser(); - } - if ($this->getVisibility() != null) { - $uri .= '/' . $this->getVisibility(); - } - if ($this->getProjection() != null) { - $uri .= '/' . $this->getProjection(); - } - if ($this->getEvent() != null) { - $uri .= '/' . $this->getEvent(); - if ($this->getComments() != null) { - $uri .= '/comments/' . $this->getComments(); - } - } - $uri .= $this->getQueryString(); - return $uri; - } - -} diff --git a/library/Zend/Gdata/Calendar/Extension/AccessLevel.php b/library/Zend/Gdata/Calendar/Extension/AccessLevel.php deleted file mode 100644 index 2b59043267..0000000000 --- a/library/Zend/Gdata/Calendar/Extension/AccessLevel.php +++ /dev/null @@ -1,125 +0,0 @@ -registerAllNamespaces(Zend_Gdata_Calendar::$namespaces); - parent::__construct(); - $this->_value = $value; - } - - /** - * Retrieves a DOMElement which corresponds to this element and all - * child properties. This is used to build an entry back into a DOM - * and eventually XML text for sending to the server upon updates, or - * for application storage/persistence. - * - * @param DOMDocument $doc The DOMDocument used to construct DOMElements - * @return DOMElement The DOMElement representing this element and all - * child properties. - */ - public function getDOM($doc = null, $majorVersion = 1, $minorVersion = null) - { - $element = parent::getDOM($doc, $majorVersion, $minorVersion); - if ($this->_value != null) { - $element->setAttribute('value', $this->_value); - } - return $element; - } - - /** - * Given a DOMNode representing an attribute, tries to map the data into - * instance members. If no mapping is defined, the name and value are - * stored in an array. - * - * @param DOMNode $attribute The DOMNode attribute needed to be handled - */ - protected function takeAttributeFromDOM($attribute) - { - switch ($attribute->localName) { - case 'value': - $this->_value = $attribute->nodeValue; - break; - default: - parent::takeAttributeFromDOM($attribute); - } - } - - /** - * Get the value for this element's value attribute. - * - * @return string The attribute being modified. - */ - public function getValue() - { - return $this->_value; - } - - - /** - * Set the value for this element's value attribute. - * - * @param string $value The desired value for this attribute. - * @return Zend_Gdata_Calendar_Extension_Selected The element being modified. - */ - public function setValue($value) - { - $this->_value = $value; - return $this; - } - - /** - * Magic toString method allows using this directly via echo - * Works best in PHP >= 4.2.0 - */ - public function __toString() - { - return $this->getValue(); - } - -} diff --git a/library/Zend/Gdata/Calendar/Extension/Color.php b/library/Zend/Gdata/Calendar/Extension/Color.php deleted file mode 100644 index 86c4352ac2..0000000000 --- a/library/Zend/Gdata/Calendar/Extension/Color.php +++ /dev/null @@ -1,125 +0,0 @@ -registerAllNamespaces(Zend_Gdata_Calendar::$namespaces); - parent::__construct(); - $this->_value = $value; - } - - /** - * Retrieves a DOMElement which corresponds to this element and all - * child properties. This is used to build an entry back into a DOM - * and eventually XML text for sending to the server upon updates, or - * for application storage/persistence. - * - * @param DOMDocument $doc The DOMDocument used to construct DOMElements - * @return DOMElement The DOMElement representing this element and all - * child properties. - */ - public function getDOM($doc = null, $majorVersion = 1, $minorVersion = null) - { - $element = parent::getDOM($doc, $majorVersion, $minorVersion); - if ($this->_value != null) { - $element->setAttribute('value', $this->_value); - } - return $element; - } - - /** - * Given a DOMNode representing an attribute, tries to map the data into - * instance members. If no mapping is defined, the name and value are - * stored in an array. - * - * @param DOMNode $attribute The DOMNode attribute needed to be handled - */ - protected function takeAttributeFromDOM($attribute) - { - switch ($attribute->localName) { - case 'value': - $this->_value = $attribute->nodeValue; - break; - default: - parent::takeAttributeFromDOM($attribute); - } - } - - /** - * Get the value for this element's value attribute. - * - * @return string The value associated with this attribute. - */ - public function getValue() - { - return $this->_value; - } - - /** - * Set the value for this element's value attribute. - * - * @param string $value The desired value for this attribute. - * @return Zend_Gdata_Calendar_Extension_Color The element being modified. - */ - public function setValue($value) - { - $this->_value = $value; - return $this; - } - - /** - * Magic toString method allows using this directly via echo - * Works best in PHP >= 4.2.0 - */ - public function __toString() - { - return $this->_value; - } - -} diff --git a/library/Zend/Gdata/Calendar/Extension/Hidden.php b/library/Zend/Gdata/Calendar/Extension/Hidden.php deleted file mode 100644 index 8befc17b48..0000000000 --- a/library/Zend/Gdata/Calendar/Extension/Hidden.php +++ /dev/null @@ -1,134 +0,0 @@ -registerAllNamespaces(Zend_Gdata_Calendar::$namespaces); - parent::__construct(); - $this->_value = $value; - } - - /** - * Retrieves a DOMElement which corresponds to this element and all - * child properties. This is used to build an entry back into a DOM - * and eventually XML text for sending to the server upon updates, or - * for application storage/persistence. - * - * @param DOMDocument $doc The DOMDocument used to construct DOMElements - * @return DOMElement The DOMElement representing this element and all - * child properties. - */ - public function getDOM($doc = null, $majorVersion = 1, $minorVersion = null) - { - $element = parent::getDOM($doc, $majorVersion, $minorVersion); - if ($this->_value !== null) { - $element->setAttribute('value', ($this->_value ? "true" : "false")); - } - return $element; - } - - /** - * Given a DOMNode representing an attribute, tries to map the data into - * instance members. If no mapping is defined, the name and value are - * stored in an array. - * - * @param DOMNode $attribute The DOMNode attribute needed to be handled - */ - protected function takeAttributeFromDOM($attribute) - { - switch ($attribute->localName) { - case 'value': - if ($attribute->nodeValue == "true") { - $this->_value = true; - } - else if ($attribute->nodeValue == "false") { - $this->_value = false; - } - else { - #require_once 'Zend/Gdata/App/InvalidArgumentException.php'; - throw new Zend_Gdata_App_InvalidArgumentException("Expected 'true' or 'false' for gCal:selected#value."); - } - break; - default: - parent::takeAttributeFromDOM($attribute); - } - } - - /** - * Get the value for this element's value attribute. - * - * @return string The requested attribute. - */ - public function getValue() - { - return $this->_value; - } - - /** - * Set the value for this element's value attribute. - * - * @param bool $value The desired value for this attribute. - * @return Zend_Gdata_Calendar_Extension_Hidden The element being modified. - */ - public function setValue($value) - { - $this->_value = $value; - return $this; - } - - /** - * Magic toString method allows using this directly via echo - * Works best in PHP >= 4.2.0 - */ - public function __toString() - { - return $this->_value; - } - -} - diff --git a/library/Zend/Gdata/Calendar/Extension/Link.php b/library/Zend/Gdata/Calendar/Extension/Link.php deleted file mode 100644 index 55935b200d..0000000000 --- a/library/Zend/Gdata/Calendar/Extension/Link.php +++ /dev/null @@ -1,125 +0,0 @@ -registerAllNamespaces(Zend_Gdata_Calendar::$namespaces); - parent::__construct($href, $rel, $type, $hrefLang, $title, $length); - $this->_webContent = $webContent; - } - - /** - * Retrieves a DOMElement which corresponds to this element and all - * child properties. This is used to build an entry back into a DOM - * and eventually XML text for sending to the server upon updates, or - * for application storage/persistence. - * - * @param DOMDocument $doc The DOMDocument used to construct DOMElements - * @return DOMElement The DOMElement representing this element and all - * child properties. - */ - public function getDOM($doc = null, $majorVersion = 1, $minorVersion = null) - { - $element = parent::getDOM($doc, $majorVersion, $minorVersion); - if ($this->_webContent != null) { - $element->appendChild($this->_webContent->getDOM($element->ownerDocument)); - } - return $element; - } - - /** - * Creates individual Entry objects of the appropriate type and - * stores them as members of this entry based upon DOM data. - * - * @param DOMNode $child The DOMNode to process - */ - protected function takeChildFromDOM($child) - { - $absoluteNodeName = $child->namespaceURI . ':' . $child->localName; - switch ($absoluteNodeName) { - case $this->lookupNamespace('gCal') . ':' . 'webContent': - $webContent = new Zend_Gdata_Calendar_Extension_WebContent(); - $webContent->transferFromDOM($child); - $this->_webContent = $webContent; - break; - default: - parent::takeChildFromDOM($child); - break; - } - } - - /** - * Get the value for this element's WebContent attribute. - * - * @return Zend_Gdata_Calendar_Extension_Webcontent The WebContent value - */ - public function getWebContent() - { - return $this->_webContent; - } - - /** - * Set the value for this element's WebContent attribute. - * - * @param Zend_Gdata_Calendar_Extension_WebContent $value The desired value for this attribute. - * @return Zend_Calendar_Extension_Link The element being modified. Provides a fluent interface. - */ - public function setWebContent($value) - { - $this->_webContent = $value; - return $this; - } - - -} - diff --git a/library/Zend/Gdata/Calendar/Extension/QuickAdd.php b/library/Zend/Gdata/Calendar/Extension/QuickAdd.php deleted file mode 100644 index 41bb0d109a..0000000000 --- a/library/Zend/Gdata/Calendar/Extension/QuickAdd.php +++ /dev/null @@ -1,132 +0,0 @@ -registerAllNamespaces(Zend_Gdata_Calendar::$namespaces); - parent::__construct(); - $this->_value = $value; - } - - /** - * Retrieves a DOMElement which corresponds to this element and all - * child properties. This is used to build an entry back into a DOM - * and eventually XML text for sending to the server upon updates, or - * for application storage/persistence. - * - * @param DOMDocument $doc The DOMDocument used to construct DOMElements - * @return DOMElement The DOMElement representing this element and all - * child properties. - */ - public function getDOM($doc = null, $majorVersion = 1, $minorVersion = null) - { - $element = parent::getDOM($doc, $majorVersion, $minorVersion); - if ($this->_value !== null) { - $element->setAttribute('value', ($this->_value ? "true" : "false")); - } - return $element; - } - - /** - * Given a DOMNode representing an attribute, tries to map the data into - * instance members. If no mapping is defined, the name and value are - * stored in an array. - * - * @param DOMNode $attribute The DOMNode attribute needed to be handled - */ - protected function takeAttributeFromDOM($attribute) - { - switch ($attribute->localName) { - case 'value': - if ($attribute->nodeValue == "true") { - $this->_value = true; - } - else if ($attribute->nodeValue == "false") { - $this->_value = false; - } - else { - throw new Zend_Gdata_App_InvalidArgumentException("Expected 'true' or 'false' for gCal:selected#value."); - } - break; - default: - parent::takeAttributeFromDOM($attribute); - } - } - - /** - * Get the value for this element's value attribute. - * - * @return string The value associated with this attribute. - */ - public function getValue() - { - return $this->_value; - } - - /** - * Set the value for this element's value attribute. - * - * @param string $value The desired value for this attribute. - * @return Zend_Gdata_Calendar_Extension_QuickAdd The element being modified. - */ - public function setValue($value) - { - $this->_value = $value; - return $this; - } - - /** - * Magic toString method allows using this directly via echo - * Works best in PHP >= 4.2.0 - */ - public function __toString() - { - return $this->getValue(); - } - -} diff --git a/library/Zend/Gdata/Calendar/Extension/Selected.php b/library/Zend/Gdata/Calendar/Extension/Selected.php deleted file mode 100644 index 70cd0dc7b9..0000000000 --- a/library/Zend/Gdata/Calendar/Extension/Selected.php +++ /dev/null @@ -1,133 +0,0 @@ -registerAllNamespaces(Zend_Gdata_Calendar::$namespaces); - parent::__construct(); - $this->_value = $value; - } - - /** - * Retrieves a DOMElement which corresponds to this element and all - * child properties. This is used to build an entry back into a DOM - * and eventually XML text for sending to the server upon updates, or - * for application storage/persistence. - * - * @param DOMDocument $doc The DOMDocument used to construct DOMElements - * @return DOMElement The DOMElement representing this element and all - * child properties. - */ - public function getDOM($doc = null, $majorVersion = 1, $minorVersion = null) - { - $element = parent::getDOM($doc, $majorVersion, $minorVersion); - if ($this->_value !== null) { - $element->setAttribute('value', ($this->_value ? "true" : "false")); - } - return $element; - } - - /** - * Given a DOMNode representing an attribute, tries to map the data into - * instance members. If no mapping is defined, the name and value are - * stored in an array. - * - * @param DOMNode $attribute The DOMNode attribute needed to be handled - */ - protected function takeAttributeFromDOM($attribute) - { - switch ($attribute->localName) { - case 'value': - if ($attribute->nodeValue == "true") { - $this->_value = true; - } - else if ($attribute->nodeValue == "false") { - $this->_value = false; - } - else { - #require_once 'Zend/Gdata/App/InvalidArgumentException.php'; - throw new Zend_Gdata_App_InvalidArgumentException("Expected 'true' or 'false' for gCal:selected#value."); - } - break; - default: - parent::takeAttributeFromDOM($attribute); - } - } - - /** - * Get the value for this element's value attribute. - * - * @return bool The value associated with this attribute. - */ - public function getValue() - { - return $this->_value; - } - - /** - * Set the value for this element's value attribute. - * - * @param bool $value The desired value for this attribute. - * @return Zend_Gdata_Calendar_Extension_Selected The element being modified. - */ - public function setValue($value) - { - $this->_value = $value; - return $this; - } - - /** - * Magic toString method allows using this directly via echo - * Works best in PHP >= 4.2.0 - */ - public function __toString() - { - return $this->_value; - } - -} diff --git a/library/Zend/Gdata/Calendar/Extension/SendEventNotifications.php b/library/Zend/Gdata/Calendar/Extension/SendEventNotifications.php deleted file mode 100644 index 3bc3fbb2e5..0000000000 --- a/library/Zend/Gdata/Calendar/Extension/SendEventNotifications.php +++ /dev/null @@ -1,132 +0,0 @@ -registerAllNamespaces(Zend_Gdata_Calendar::$namespaces); - parent::__construct(); - $this->_value = $value; - } - - /** - * Retrieves a DOMElement which corresponds to this element and all - * child properties. This is used to build an entry back into a DOM - * and eventually XML text for sending to the server upon updates, or - * for application storage/persistence. - * - * @param DOMDocument $doc The DOMDocument used to construct DOMElements - * @return DOMElement The DOMElement representing this element and all - * child properties. - */ - public function getDOM($doc = null, $majorVersion = 1, $minorVersion = null) - { - $element = parent::getDOM($doc, $majorVersion, $minorVersion); - if ($this->_value !== null) { - $element->setAttribute('value', ($this->_value ? "true" : "false")); - } - return $element; - } - - /** - * Given a DOMNode representing an attribute, tries to map the data into - * instance members. If no mapping is defined, the name and value are - * stored in an array. - * - * @param DOMNode $attribute The DOMNode attribute needed to be handled - */ - protected function takeAttributeFromDOM($attribute) - { - switch ($attribute->localName) { - case 'value': - if ($attribute->nodeValue == "true") { - $this->_value = true; - } - else if ($attribute->nodeValue == "false") { - $this->_value = false; - } - else { - throw new Zend_Gdata_App_InvalidArgumentException("Expected 'true' or 'false' for gCal:selected#value."); - } - break; - default: - parent::takeAttributeFromDOM($attribute); - } - } - - /** - * Get the value for this element's Value attribute. - * - * @return string The requested attribute. - */ - public function getValue() - { - return $this->_value; - } - - /** - * Set the value for this element's Value attribute. - * - * @param string $value The desired value for this attribute. - * @return Zend_Gdata_Extension_SendEventNotifications The element being modified. - */ - public function setValue($value) - { - $this->_value = $value; - return $this; - } - - /** - * Magic toString method allows using this directly via echo - * Works best in PHP >= 4.2.0 - */ - public function __toString() - { - return $this->getValue(); - } - -} - diff --git a/library/Zend/Gdata/Calendar/Extension/Timezone.php b/library/Zend/Gdata/Calendar/Extension/Timezone.php deleted file mode 100644 index 6cbad0d613..0000000000 --- a/library/Zend/Gdata/Calendar/Extension/Timezone.php +++ /dev/null @@ -1,124 +0,0 @@ -registerAllNamespaces(Zend_Gdata_Calendar::$namespaces); - parent::__construct(); - $this->_value = $value; - } - - /** - * Retrieves a DOMElement which corresponds to this element and all - * child properties. This is used to build an entry back into a DOM - * and eventually XML text for sending to the server upon updates, or - * for application storage/persistence. - * - * @param DOMDocument $doc The DOMDocument used to construct DOMElements - * @return DOMElement The DOMElement representing this element and all - * child properties. - */ - public function getDOM($doc = null, $majorVersion = 1, $minorVersion = null) - { - $element = parent::getDOM($doc, $majorVersion, $minorVersion); - if ($this->_value != null) { - $element->setAttribute('value', $this->_value); - } - return $element; - } - - /** - * Given a DOMNode representing an attribute, tries to map the data into - * instance members. If no mapping is defined, the name and value are - * stored in an array. - * - * @param DOMNode $attribute The DOMNode attribute needed to be handled - */ - protected function takeAttributeFromDOM($attribute) - { - switch ($attribute->localName) { - case 'value': - $this->_value = $attribute->nodeValue; - break; - default: - parent::takeAttributeFromDOM($attribute); - } - } - - /** - * Get the value for this element's value attribute. - * - * @return string The value associated with this attribute. - */ - public function getValue() - { - return $this->_value; - } - - /** - * Set the value for this element's value attribute. - * - * @param string $value The desired value for this attribute. - * @return Zend_Gdata_Calendar_Extension_Timezone The element being modified. - */ - public function setValue($value) - { - $this->_value = $value; - return $this; - } - - /** - * Magic toString method allows using this directly via echo - * Works best in PHP >= 4.2.0 - */ - public function __toString() - { - return $this->getValue(); - } - -} diff --git a/library/Zend/Gdata/Calendar/Extension/WebContent.php b/library/Zend/Gdata/Calendar/Extension/WebContent.php deleted file mode 100644 index 7710508297..0000000000 --- a/library/Zend/Gdata/Calendar/Extension/WebContent.php +++ /dev/null @@ -1,177 +0,0 @@ -registerAllNamespaces(Zend_Gdata_Calendar::$namespaces); - parent::__construct(); - $this->_url = $url; - $this->_height = $height; - $this->_width = $width; - } - - /** - * Retrieves a DOMElement which corresponds to this element and all - * child properties. This is used to build an entry back into a DOM - * and eventually XML text for sending to the server upon updates, or - * for application storage/persistence. - * - * @param DOMDocument $doc The DOMDocument used to construct DOMElements - * @return DOMElement The DOMElement representing this element and all - * child properties. - */ - public function getDOM($doc = null, $majorVersion = 1, $minorVersion = null) - { - $element = parent::getDOM($doc, $majorVersion, $minorVersion); - if ($this->url != null) { - $element->setAttribute('url', $this->_url); - } - if ($this->height != null) { - $element->setAttribute('height', $this->_height); - } - if ($this->width != null) { - $element->setAttribute('width', $this->_width); - } - return $element; - } - - /** - * Given a DOMNode representing an attribute, tries to map the data into - * instance members. If no mapping is defined, the name and value are - * stored in an array. - * - * @param DOMNode $attribute The DOMNode attribute needed to be handled - */ - protected function takeAttributeFromDOM($attribute) - { - switch ($attribute->localName) { - case 'url': - $this->_url = $attribute->nodeValue; - break; - case 'height': - $this->_height = $attribute->nodeValue; - break; - case 'width': - $this->_width = $attribute->nodeValue; - break; - default: - parent::takeAttributeFromDOM($attribute); - } - } - - /** - * Get the value for this element's URL attribute. - * - * @return string The desired value for this attribute. - */ - public function getURL() - { - return $this->_url; - } - - /** - * Set the value for this element's URL attribute. - * - * @param bool $value The desired value for this attribute. - * @return Zend_Gdata_Calendar_Extension_WebContent The element being modified. - */ - public function setURL($value) - { - $this->_url = $value; - return $this; - } - - /** - * Get the value for this element's height attribute. - * - * @return int The desired value for this attribute. - */ - public function getHeight() - { - return $this->_height; - } - - /** - * Set the value for this element's height attribute. - * - * @param int $value The desired value for this attribute. - * @return Zend_Gdata_Calendar_Extension_WebContent The element being modified. - */ - public function setHeight($value) - { - $this->_height = $value; - return $this; - } - - /** - * Get the value for this element's height attribute. - * - * @return int The desired value for this attribute. - */ - public function getWidth() - { - return $this->_width; - } - - /** - * Set the value for this element's height attribute. - * - * @param int $value The desired value for this attribute. - * @return Zend_Gdata_Calendar_Extension_WebContent The element being modified. - */ - public function setWidth($value) - { - $this->_width = $value; - return $this; - } - -} diff --git a/library/Zend/Gdata/Calendar/ListEntry.php b/library/Zend/Gdata/Calendar/ListEntry.php deleted file mode 100644 index 74897c5791..0000000000 --- a/library/Zend/Gdata/Calendar/ListEntry.php +++ /dev/null @@ -1,246 +0,0 @@ -registerAllNamespaces(Zend_Gdata_Calendar::$namespaces); - parent::__construct($element); - } - - public function getDOM($doc = null, $majorVersion = 1, $minorVersion = null) - { - $element = parent::getDOM($doc, $majorVersion, $minorVersion); - if ($this->_accessLevel != null) { - $element->appendChild($this->_accessLevel->getDOM($element->ownerDocument)); - } - if ($this->_color != null) { - $element->appendChild($this->_color->getDOM($element->ownerDocument)); - } - if ($this->_hidden != null) { - $element->appendChild($this->_hidden->getDOM($element->ownerDocument)); - } - if ($this->_selected != null) { - $element->appendChild($this->_selected->getDOM($element->ownerDocument)); - } - if ($this->_timezone != null) { - $element->appendChild($this->_timezone->getDOM($element->ownerDocument)); - } - if ($this->_where != null) { - foreach ($this->_where as $where) { - $element->appendChild($where->getDOM($element->ownerDocument)); - } - } - return $element; - } - - protected function takeChildFromDOM($child) - { - $absoluteNodeName = $child->namespaceURI . ':' . $child->localName; - switch ($absoluteNodeName) { - case $this->lookupNamespace('gCal') . ':' . 'accesslevel'; - $accessLevel = new Zend_Gdata_Calendar_Extension_AccessLevel(); - $accessLevel->transferFromDOM($child); - $this->_accessLevel = $accessLevel; - break; - case $this->lookupNamespace('gCal') . ':' . 'color'; - $color = new Zend_Gdata_Calendar_Extension_Color(); - $color->transferFromDOM($child); - $this->_color = $color; - break; - case $this->lookupNamespace('gCal') . ':' . 'hidden'; - $hidden = new Zend_Gdata_Calendar_Extension_Hidden(); - $hidden->transferFromDOM($child); - $this->_hidden = $hidden; - break; - case $this->lookupNamespace('gCal') . ':' . 'selected'; - $selected = new Zend_Gdata_Calendar_Extension_Selected(); - $selected->transferFromDOM($child); - $this->_selected = $selected; - break; - case $this->lookupNamespace('gCal') . ':' . 'timezone'; - $timezone = new Zend_Gdata_Calendar_Extension_Timezone(); - $timezone->transferFromDOM($child); - $this->_timezone = $timezone; - break; - case $this->lookupNamespace('gd') . ':' . 'where'; - $where = new Zend_Gdata_Extension_Where(); - $where->transferFromDOM($child); - $this->_where[] = $where; - break; - default: - parent::takeChildFromDOM($child); - break; - } - } - - public function getAccessLevel() - { - return $this->_accessLevel; - } - - /** - * @param Zend_Gdata_Calendar_Extension_AccessLevel $value - * @return Zend_Gdata_Extension_ListEntry Provides a fluent interface - */ - public function setAccessLevel($value) - { - $this->_accessLevel = $value; - return $this; - } - public function getColor() - { - return $this->_color; - } - - /** - * @param Zend_Gdata_Calendar_Extension_Color $value - * @return Zend_Gdata_Extension_ListEntry Provides a fluent interface - */ - public function setColor($value) - { - $this->_color = $value; - return $this; - } - - public function getHidden() - { - return $this->_hidden; - } - - /** - * @param Zend_Gdata_Calendar_Extension_Hidden $value - * @return Zend_Gdata_Extension_ListEntry Provides a fluent interface - */ - public function setHidden($value) - { - $this->_hidden = $value; - return $this; - } - - public function getSelected() - { - return $this->_selected; - } - - /** - * @param Zend_Gdata_Calendar_Extension_Selected $value - * @return Zend_Gdata_Extension_ListEntry Provides a fluent interface - */ - public function setSelected($value) - { - $this->_selected = $value; - return $this; - } - - public function getTimezone() - { - return $this->_timezone; - } - - /** - * @param Zend_Gdata_Calendar_Extension_Timezone $value - * @return Zend_Gdata_Extension_ListEntry Provides a fluent interface - */ - public function setTimezone($value) - { - $this->_timezone = $value; - return $this; - } - - public function getWhere() - { - return $this->_where; - } - - /** - * @param Zend_Gdata_Extension_Where $value - * @return Zend_Gdata_Extension_ListEntry Provides a fluent interface - */ - public function setWhere($value) - { - $this->_where = $value; - return $this; - } - -} diff --git a/library/Zend/Gdata/Calendar/ListFeed.php b/library/Zend/Gdata/Calendar/ListFeed.php deleted file mode 100644 index 97ec5a3c01..0000000000 --- a/library/Zend/Gdata/Calendar/ListFeed.php +++ /dev/null @@ -1,106 +0,0 @@ -registerAllNamespaces(Zend_Gdata_Calendar::$namespaces); - parent::__construct($element); - } - - public function getDOM($doc = null, $majorVersion = 1, $minorVersion = null) - { - $element = parent::getDOM($doc, $majorVersion, $minorVersion); - if ($this->_timezone != null) { - $element->appendChild($this->_timezone->getDOM($element->ownerDocument)); - } - return $element; - } - - protected function takeChildFromDOM($child) - { - $absoluteNodeName = $child->namespaceURI . ':' . $child->localName; - switch ($absoluteNodeName) { - case $this->lookupNamespace('gCal') . ':' . 'timezone'; - $timezone = new Zend_Gdata_Calendar_Extension_Timezone(); - $timezone->transferFromDOM($child); - $this->_timezone = $timezone; - break; - default: - parent::takeChildFromDOM($child); - break; - } - } - - public function getTimezone() - { - return $this->_timezone; - } - - /** - * @param Zend_Gdata_Calendar_Extension_Timezone $value - * @return Zend_Gdata_Extension_ListEntry Provides a fluent interface - */ - public function setTimezone($value) - { - $this->_timezone = $value; - return $this; - } - -} diff --git a/library/Zend/Gdata/ClientLogin.php b/library/Zend/Gdata/ClientLogin.php deleted file mode 100644 index e868d1f381..0000000000 --- a/library/Zend/Gdata/ClientLogin.php +++ /dev/null @@ -1,182 +0,0 @@ -setUri($loginUri); - $useragent = $source . ' Zend_Framework_Gdata/' . Zend_Version::VERSION; - $client->setConfig(array( - 'maxredirects' => 0, - 'strictredirects' => true, - 'useragent' => $useragent - ) - ); - $client->setParameterPost('accountType', $accountType); - $client->setParameterPost('Email', (string) $email); - $client->setParameterPost('Passwd', (string) $password); - $client->setParameterPost('service', (string) $service); - $client->setParameterPost('source', (string) $source); - if ($loginToken || $loginCaptcha) { - if($loginToken && $loginCaptcha) { - $client->setParameterPost('logintoken', (string) $loginToken); - $client->setParameterPost('logincaptcha', - (string) $loginCaptcha); - } - else { - #require_once 'Zend/Gdata/App/AuthException.php'; - throw new Zend_Gdata_App_AuthException( - 'Please provide both a token ID and a user\'s response ' . - 'to the CAPTCHA challenge.'); - } - } - - // Send the authentication request - // For some reason Google's server causes an SSL error. We use the - // output buffer to supress an error from being shown. Ugly - but works! - ob_start(); - try { - $response = $client->request('POST'); - } catch (Zend_Http_Client_Exception $e) { - #require_once 'Zend/Gdata/App/HttpException.php'; - throw new Zend_Gdata_App_HttpException($e->getMessage(), $e); - } - ob_end_clean(); - - // Parse Google's response - $goog_resp = array(); - foreach (explode("\n", $response->getBody()) as $l) { - $l = chop($l); - if ($l) { - list($key, $val) = explode('=', chop($l), 2); - $goog_resp[$key] = $val; - } - } - - if ($response->getStatus() == 200) { - $client->setClientLoginToken($goog_resp['Auth']); - $useragent = $source . ' Zend_Framework_Gdata/' . Zend_Version::VERSION; - $client->setConfig(array( - 'strictredirects' => true, - 'useragent' => $useragent - ) - ); - return $client; - - } elseif ($response->getStatus() == 403) { - // Check if the server asked for a CAPTCHA - if (array_key_exists('Error', $goog_resp) && - $goog_resp['Error'] == 'CaptchaRequired') { - #require_once 'Zend/Gdata/App/CaptchaRequiredException.php'; - throw new Zend_Gdata_App_CaptchaRequiredException( - $goog_resp['CaptchaToken'], $goog_resp['CaptchaUrl']); - } - else { - #require_once 'Zend/Gdata/App/AuthException.php'; - throw new Zend_Gdata_App_AuthException('Authentication with Google failed. Reason: ' . - (isset($goog_resp['Error']) ? $goog_resp['Error'] : 'Unspecified.')); - } - } - } - -} - diff --git a/library/Zend/Gdata/Docs.php b/library/Zend/Gdata/Docs.php deleted file mode 100755 index 2627ba47b4..0000000000 --- a/library/Zend/Gdata/Docs.php +++ /dev/null @@ -1,321 +0,0 @@ - 'text/plain', - 'CSV' => 'text/csv', - 'TSV' => 'text/tab-separated-values', - 'TAB' => 'text/tab-separated-values', - 'HTML' => 'text/html', - 'HTM' => 'text/html', - 'DOC' => 'application/msword', - 'DOCX' => 'application/vnd.openxmlformats-officedocument.wordprocessingml.document', - 'ODS' => 'application/vnd.oasis.opendocument.spreadsheet', - 'ODT' => 'application/vnd.oasis.opendocument.text', - 'RTF' => 'application/rtf', - 'SXW' => 'application/vnd.sun.xml.writer', - 'XLS' => 'application/vnd.ms-excel', - 'XLSX' => 'application/vnd.ms-excel', - 'PPT' => 'application/vnd.ms-powerpoint', - 'PPS' => 'application/vnd.ms-powerpoint' - ); - - /** - * Create Gdata_Docs object - * - * @param Zend_Http_Client $client (optional) The HTTP client to use when - * when communicating with the Google servers. - * @param string $applicationId The identity of the app in the form of Company-AppName-Version - */ - public function __construct($client = null, $applicationId = 'MyCompany-MyApp-1.0') - { - $this->registerPackage('Zend_Gdata_Docs'); - parent::__construct($client, $applicationId); - $this->_httpClient->setParameterPost('service', self::AUTH_SERVICE_NAME); - } - - /** - * Looks up the mime type based on the file name extension. For example, - * calling this method with 'csv' would return - * 'text/comma-separated-values'. The Mime type is sent as a header in - * the upload HTTP POST request. - * - * @param string $fileExtension - * @return string The mime type to be sent to the server to tell it how the - * multipart mime data should be interpreted. - */ - public static function lookupMimeType($fileExtension) - { - return self::$SUPPORTED_FILETYPES[strtoupper($fileExtension)]; - } - - /** - * Retreive feed object containing entries for the user's documents. - * - * @param mixed $location The location for the feed, as a URL or Query - * @return Zend_Gdata_Docs_DocumentListFeed - */ - public function getDocumentListFeed($location = null) - { - if ($location === null) { - $uri = self::DOCUMENTS_LIST_FEED_URI; - } else if ($location instanceof Zend_Gdata_Query) { - $uri = $location->getQueryUrl(); - } else { - $uri = $location; - } - return parent::getFeed($uri, 'Zend_Gdata_Docs_DocumentListFeed'); - } - - /** - * Retreive entry object representing a single document. - * - * @param mixed $location The location for the entry, as a URL or Query - * @return Zend_Gdata_Docs_DocumentListEntry - * @throws Zend_Gdata_App_InvalidArgumentException - */ - public function getDocumentListEntry($location = null) - { - if ($location === null) { - #require_once 'Zend/Gdata/App/InvalidArgumentException.php'; - throw new Zend_Gdata_App_InvalidArgumentException( - 'Location must not be null' - ); - } else if ($location instanceof Zend_Gdata_Query) { - $uri = $location->getQueryUrl(); - } else { - $uri = $location; - } - return parent::getEntry($uri, 'Zend_Gdata_Docs_DocumentListEntry'); - } - - /** - * Retreive entry object representing a single document. - * - * This method builds the URL where this item is stored using the type - * and the id of the document. - * @param string $docId The URL key for the document. Examples: - * dcmg89gw_62hfjj8m, pKq0CzjiF3YmGd0AIlHKqeg - * @param string $docType The type of the document as used in the Google - * Document List URLs. Examples: document, spreadsheet, presentation - * @return Zend_Gdata_Docs_DocumentListEntry - */ - public function getDoc($docId, $docType) - { - $location = 'https://docs.google.com/feeds/documents/private/full/' . - $docType . '%3A' . $docId; - - return $this->getDocumentListEntry($location); - } - - /** - * Retreive entry object for the desired word processing document. - * - * @param string $id The URL id for the document. Example: dcmg89gw_62hfjj8m - * @return Zend_Gdata_Docs_DocumentListEntry - */ - public function getDocument($id) - { - return $this->getDoc($id, 'document'); - } - - /** - * Retreive entry object for the desired spreadsheet. - * - * @param string $id The URL id for the document. Example: pKq0CzjiF3YmGd0AIlHKqeg - * @return Zend_Gdata_Docs_DocumentListEntry - */ - public function getSpreadsheet($id) - { - return $this->getDoc($id, 'spreadsheet'); - } - - /** - * Retreive entry object for the desired presentation. - * - * @param string $id The URL id for the document. Example: dcmg89gw_21gtrjcn - * @return Zend_Gdata_Docs_DocumentListEntry - */ - public function getPresentation($id) - { - return $this->getDoc($id, 'presentation'); - } - - /** - * Upload a local file to create a new Google Document entry. - * - * @param string $fileLocation The full or relative path of the file to - * be uploaded. - * @param string $title The name that this document should have on the - * server. If set, the title is used as the slug header in the - * POST request. If no title is provided, the location of the - * file will be used as the slug header in the request. If no - * mimeType is provided, this method attempts to determine the - * mime type based on the slugHeader by looking for .doc, - * .csv, .txt, etc. at the end of the file name. - * Example value: 'test.doc'. - * @param string $mimeType Describes the type of data which is being sent - * to the server. This must be one of the accepted mime types - * which are enumerated in SUPPORTED_FILETYPES. - * @param string $uri (optional) The URL to which the upload should be - * made. - * Example: 'https://docs.google.com/feeds/documents/private/full'. - * @return Zend_Gdata_Docs_DocumentListEntry The entry for the newly - * created Google Document. - */ - public function uploadFile($fileLocation, $title = null, $mimeType = null, - $uri = null - ) - { - // Set the URI to which the file will be uploaded. - if ($uri === null) { - $uri = $this->_defaultPostUri; - } - - // Create the media source which describes the file. - $fs = $this->newMediaFileSource($fileLocation); - if ($title !== null) { - $slugHeader = $title; - } else { - $slugHeader = $fileLocation; - } - - // Set the slug header to tell the Google Documents server what the - // title of the document should be and what the file extension was - // for the original file. - $fs->setSlug($slugHeader); - - // Set the mime type of the data. - if ($mimeType === null) { - $filenameParts = explode('.', $fileLocation); - $fileExtension = end($filenameParts); - $mimeType = self::lookupMimeType($fileExtension); - } - - // Set the mime type for the upload request. - $fs->setContentType($mimeType); - - // Send the data to the server. - return $this->insertDocument($fs, $uri); - } - - /** - * Creates a new folder in Google Docs - * - * @param string $folderName The folder name to create - * @param string|null $folderResourceId The parent folder to create it in - * ("folder%3Amy_parent_folder") - * @return Zend_Gdata_Entry The folder entry created. - * @todo ZF-8732: This should return a *subclass* of Zend_Gdata_Entry, but - * the appropriate type doesn't exist yet. - */ - public function createFolder($folderName, $folderResourceId = null) - { - $category = new Zend_Gdata_App_Extension_Category( - self::DOCUMENTS_CATEGORY_TERM, - self::DOCUMENTS_CATEGORY_SCHEMA - ); - $title = new Zend_Gdata_App_Extension_Title($folderName); - $entry = new Zend_Gdata_Entry(); - - $entry->setCategory(array($category)); - $entry->setTitle($title); - - $uri = self::DOCUMENTS_LIST_FEED_URI; - if ($folderResourceId != null) { - $uri = self::DOCUMENTS_FOLDER_FEED_URI . '/' . $folderResourceId; - } - - return $this->insertEntry($entry, $uri); - } - - /** - * Inserts an entry to a given URI and returns the response as an Entry. - * - * @param mixed $data The Zend_Gdata_Docs_DocumentListEntry or media - * source to post. If it is a DocumentListEntry, the mediaSource - * should already have been set. If $data is a mediaSource, it - * should have the correct slug header and mime type. - * @param string $uri POST URI - * @param string $className (optional) The class of entry to be returned. - * The default is a 'Zend_Gdata_Docs_DocumentListEntry'. - * @return Zend_Gdata_Docs_DocumentListEntry The entry returned by the - * service after insertion. - */ - public function insertDocument($data, $uri, - $className = 'Zend_Gdata_Docs_DocumentListEntry') - { - return $this->insertEntry($data, $uri, $className); - } -} diff --git a/library/Zend/Gdata/Docs/DocumentListEntry.php b/library/Zend/Gdata/Docs/DocumentListEntry.php deleted file mode 100755 index 1bd3d71cfe..0000000000 --- a/library/Zend/Gdata/Docs/DocumentListEntry.php +++ /dev/null @@ -1,54 +0,0 @@ -registerAllNamespaces(Zend_Gdata_Docs::$namespaces); - parent::__construct($element); - } - -} diff --git a/library/Zend/Gdata/Docs/DocumentListFeed.php b/library/Zend/Gdata/Docs/DocumentListFeed.php deleted file mode 100755 index b0ad66ee79..0000000000 --- a/library/Zend/Gdata/Docs/DocumentListFeed.php +++ /dev/null @@ -1,68 +0,0 @@ -registerAllNamespaces(Zend_Gdata_Docs::$namespaces); - parent::__construct($element); - } - -} diff --git a/library/Zend/Gdata/Docs/Query.php b/library/Zend/Gdata/Docs/Query.php deleted file mode 100755 index b4589111cd..0000000000 --- a/library/Zend/Gdata/Docs/Query.php +++ /dev/null @@ -1,222 +0,0 @@ -_projection = $value; - return $this; - } - - /** - * Sets the visibility for this query. Common values for visibility - * include 'private'. - * - * @return Zend_Gdata_Docs_Query Provides a fluent interface - */ - public function setVisibility($value) - { - $this->_visibility = $value; - return $this; - } - - /** - * Gets the projection for this query. - * - * @return string projection - */ - public function getProjection() - { - return $this->_projection; - } - - /** - * Gets the visibility for this query. - * - * @return string visibility - */ - public function getVisibility() - { - return $this->_visibility; - } - - /** - * Sets the title attribute for this query. The title parameter is used - * to restrict the results to documents whose titles either contain or - * completely match the title. - * - * @param string $value - * @return Zend_Gdata_Docs_Query Provides a fluent interface - */ - public function setTitle($value) - { - if ($value !== null) { - $this->_params['title'] = $value; - } else { - unset($this->_params['title']); - } - return $this; - } - - /** - * Gets the title attribute for this query. - * - * @return string title - */ - public function getTitle() - { - if (array_key_exists('title', $this->_params)) { - return $this->_params['title']; - } else { - return null; - } - } - - /** - * Sets the title-exact attribute for this query. - * If title-exact is set to true, the title query parameter will be used - * in an exact match. Only documents with a title identical to the - * title parameter will be returned. - * - * @param boolean $value Use either true or false - * @return Zend_Gdata_Docs_Query Provides a fluent interface - */ - public function setTitleExact($value) - { - if ($value) { - $this->_params['title-exact'] = $value; - } else { - unset($this->_params['title-exact']); - } - return $this; - } - - /** - * Gets the title-exact attribute for this query. - * - * @return string title-exact - */ - public function getTitleExact() - { - if (array_key_exists('title-exact', $this->_params)) { - return $this->_params['title-exact']; - } else { - return false; - } - } - - /** - * Gets the full query URL for this query. - * - * @return string url - */ - public function getQueryUrl() - { - $uri = $this->_defaultFeedUri; - - if ($this->_visibility !== null) { - $uri .= '/' . $this->_visibility; - } else { - #require_once 'Zend/Gdata/App/Exception.php'; - throw new Zend_Gdata_App_Exception( - 'A visibility must be provided for cell queries.'); - } - - if ($this->_projection !== null) { - $uri .= '/' . $this->_projection; - } else { - #require_once 'Zend/Gdata/App/Exception.php'; - throw new Zend_Gdata_App_Exception( - 'A projection must be provided for cell queries.'); - } - - $uri .= $this->getQueryString(); - return $uri; - } - -} diff --git a/library/Zend/Gdata/DublinCore.php b/library/Zend/Gdata/DublinCore.php deleted file mode 100755 index b52ed54ae0..0000000000 --- a/library/Zend/Gdata/DublinCore.php +++ /dev/null @@ -1,65 +0,0 @@ -registerPackage('Zend_Gdata_DublinCore'); - $this->registerPackage('Zend_Gdata_DublinCore_Extension'); - parent::__construct($client, $applicationId); - } - -} diff --git a/library/Zend/Gdata/DublinCore/Extension/Creator.php b/library/Zend/Gdata/DublinCore/Extension/Creator.php deleted file mode 100644 index cc76cc10ee..0000000000 --- a/library/Zend/Gdata/DublinCore/Extension/Creator.php +++ /dev/null @@ -1,58 +0,0 @@ -registerAllNamespaces(Zend_Gdata_DublinCore::$namespaces); - parent::__construct(); - $this->_text = $value; - } - -} diff --git a/library/Zend/Gdata/DublinCore/Extension/Date.php b/library/Zend/Gdata/DublinCore/Extension/Date.php deleted file mode 100644 index 441f69c822..0000000000 --- a/library/Zend/Gdata/DublinCore/Extension/Date.php +++ /dev/null @@ -1,60 +0,0 @@ -registerAllNamespaces(Zend_Gdata_DublinCore::$namespaces); - parent::__construct(); - $this->_text = $value; - } - -} diff --git a/library/Zend/Gdata/DublinCore/Extension/Description.php b/library/Zend/Gdata/DublinCore/Extension/Description.php deleted file mode 100644 index ea242ca53f..0000000000 --- a/library/Zend/Gdata/DublinCore/Extension/Description.php +++ /dev/null @@ -1,58 +0,0 @@ -registerAllNamespaces(Zend_Gdata_DublinCore::$namespaces); - parent::__construct(); - $this->_text = $value; - } - -} diff --git a/library/Zend/Gdata/DublinCore/Extension/Format.php b/library/Zend/Gdata/DublinCore/Extension/Format.php deleted file mode 100644 index aed0fceae8..0000000000 --- a/library/Zend/Gdata/DublinCore/Extension/Format.php +++ /dev/null @@ -1,58 +0,0 @@ -registerAllNamespaces(Zend_Gdata_DublinCore::$namespaces); - parent::__construct(); - $this->_text = $value; - } - -} diff --git a/library/Zend/Gdata/DublinCore/Extension/Identifier.php b/library/Zend/Gdata/DublinCore/Extension/Identifier.php deleted file mode 100644 index 8a92526694..0000000000 --- a/library/Zend/Gdata/DublinCore/Extension/Identifier.php +++ /dev/null @@ -1,58 +0,0 @@ -registerAllNamespaces(Zend_Gdata_DublinCore::$namespaces); - parent::__construct(); - $this->_text = $value; - } - -} diff --git a/library/Zend/Gdata/DublinCore/Extension/Language.php b/library/Zend/Gdata/DublinCore/Extension/Language.php deleted file mode 100644 index 0680da8b2b..0000000000 --- a/library/Zend/Gdata/DublinCore/Extension/Language.php +++ /dev/null @@ -1,58 +0,0 @@ -registerAllNamespaces(Zend_Gdata_DublinCore::$namespaces); - parent::__construct(); - $this->_text = $value; - } - -} diff --git a/library/Zend/Gdata/DublinCore/Extension/Publisher.php b/library/Zend/Gdata/DublinCore/Extension/Publisher.php deleted file mode 100644 index 7a8dfdad58..0000000000 --- a/library/Zend/Gdata/DublinCore/Extension/Publisher.php +++ /dev/null @@ -1,58 +0,0 @@ -registerAllNamespaces(Zend_Gdata_DublinCore::$namespaces); - parent::__construct(); - $this->_text = $value; - } - -} diff --git a/library/Zend/Gdata/DublinCore/Extension/Rights.php b/library/Zend/Gdata/DublinCore/Extension/Rights.php deleted file mode 100644 index a77aad3415..0000000000 --- a/library/Zend/Gdata/DublinCore/Extension/Rights.php +++ /dev/null @@ -1,58 +0,0 @@ -registerAllNamespaces(Zend_Gdata_DublinCore::$namespaces); - parent::__construct(); - $this->_text = $value; - } - -} diff --git a/library/Zend/Gdata/DublinCore/Extension/Subject.php b/library/Zend/Gdata/DublinCore/Extension/Subject.php deleted file mode 100644 index d2b2c1e9c6..0000000000 --- a/library/Zend/Gdata/DublinCore/Extension/Subject.php +++ /dev/null @@ -1,58 +0,0 @@ -registerAllNamespaces(Zend_Gdata_DublinCore::$namespaces); - parent::__construct(); - $this->_text = $value; - } - -} diff --git a/library/Zend/Gdata/DublinCore/Extension/Title.php b/library/Zend/Gdata/DublinCore/Extension/Title.php deleted file mode 100644 index 5785e98fb8..0000000000 --- a/library/Zend/Gdata/DublinCore/Extension/Title.php +++ /dev/null @@ -1,58 +0,0 @@ -registerAllNamespaces(Zend_Gdata_DublinCore::$namespaces); - parent::__construct(); - $this->_text = $value; - } - -} diff --git a/library/Zend/Gdata/Entry.php b/library/Zend/Gdata/Entry.php deleted file mode 100644 index 3b3ef81fc5..0000000000 --- a/library/Zend/Gdata/Entry.php +++ /dev/null @@ -1,132 +0,0 @@ -registerAllNamespaces(Zend_Gdata::$namespaces); - parent::__construct($element); - } - - public function getDOM($doc = null, $majorVersion = 1, $minorVersion = null) - { - $element = parent::getDOM($doc, $majorVersion, $minorVersion); - // ETags are special. We only support them in protocol >= 2.X. - // This will be duplicated by the HTTP ETag header. - if ($majorVersion >= 2) { - if ($this->_etag != null) { - $element->setAttributeNS($this->lookupNamespace('gd'), - 'gd:etag', - $this->_etag); - } - } - return $element; - } - - protected function takeChildFromDOM($child) - { - $absoluteNodeName = $child->namespaceURI . ':' . $child->localName; - switch ($absoluteNodeName) { - case $this->lookupNamespace('atom') . ':' . 'content': - $content = new Zend_Gdata_App_Extension_Content(); - $content->transferFromDOM($child); - $this->_content = $content; - break; - case $this->lookupNamespace('atom') . ':' . 'published': - $published = new Zend_Gdata_App_Extension_Published(); - $published->transferFromDOM($child); - $this->_published = $published; - break; - case $this->lookupNamespace('atom') . ':' . 'source': - $source = new Zend_Gdata_App_Extension_Source(); - $source->transferFromDOM($child); - $this->_source = $source; - break; - case $this->lookupNamespace('atom') . ':' . 'summary': - $summary = new Zend_Gdata_App_Extension_Summary(); - $summary->transferFromDOM($child); - $this->_summary = $summary; - break; - case $this->lookupNamespace('app') . ':' . 'control': - $control = new Zend_Gdata_App_Extension_Control(); - $control->transferFromDOM($child); - $this->_control = $control; - break; - default: - parent::takeChildFromDOM($child); - break; - } - } - - /** - * Given a DOMNode representing an attribute, tries to map the data into - * instance members. If no mapping is defined, the name and value are - * stored in an array. - * - * @param DOMNode $attribute The DOMNode attribute needed to be handled - */ - protected function takeAttributeFromDOM($attribute) - { - switch ($attribute->localName) { - case 'etag': - // ETags are special, since they can be conveyed by either the - // HTTP ETag header or as an XML attribute. - $etag = $attribute->nodeValue; - if ($this->_etag === null) { - $this->_etag = $etag; - } - elseif ($this->_etag != $etag) { - #require_once('Zend/Gdata/App/IOException.php'); - throw new Zend_Gdata_App_IOException("ETag mismatch"); - } - break; - default: - parent::takeAttributeFromDOM($attribute); - break; - } - } - -} diff --git a/library/Zend/Gdata/Exif.php b/library/Zend/Gdata/Exif.php deleted file mode 100755 index bba5bfd618..0000000000 --- a/library/Zend/Gdata/Exif.php +++ /dev/null @@ -1,65 +0,0 @@ -registerPackage('Zend_Gdata_Exif'); - $this->registerPackage('Zend_Gdata_Exif_Extension'); - parent::__construct($client, $applicationId); - } - -} diff --git a/library/Zend/Gdata/Exif/Entry.php b/library/Zend/Gdata/Exif/Entry.php deleted file mode 100755 index d1b9000ce1..0000000000 --- a/library/Zend/Gdata/Exif/Entry.php +++ /dev/null @@ -1,145 +0,0 @@ -registerAllNamespaces(Zend_Gdata_Exif::$namespaces); - parent::__construct($element); - } - - /** - * Retrieves a DOMElement which corresponds to this element and all - * child properties. This is used to build an entry back into a DOM - * and eventually XML text for sending to the server upon updates, or - * for application storage/persistence. - * - * @param DOMDocument $doc The DOMDocument used to construct DOMElements - * @return DOMElement The DOMElement representing this element and all - * child properties. - */ - public function getDOM($doc = null, $majorVersion = 1, $minorVersion = null) - { - $element = parent::getDOM($doc, $majorVersion, $minorVersion); - if ($this->_tags != null) { - $element->appendChild($this->_tags->getDOM($element->ownerDocument)); - } - return $element; - } - - /** - * Creates individual Entry objects of the appropriate type and - * stores them as members of this entry based upon DOM data. - * - * @param DOMNode $child The DOMNode to process - */ - protected function takeChildFromDOM($child) - { - $absoluteNodeName = $child->namespaceURI . ':' . $child->localName; - switch ($absoluteNodeName) { - case $this->lookupNamespace('exif') . ':' . 'tags': - $tags = new Zend_Gdata_Exif_Extension_Tags(); - $tags->transferFromDOM($child); - $this->_tags = $tags; - break; - default: - parent::takeChildFromDOM($child); - break; - } - } - - /** - * Retrieve the tags for this entry. - * - * @see setTags - * @return Zend_Gdata_Exif_Extension_Tags The requested object - * or null if not set. - */ - public function getTags() - { - return $this->_tags; - } - - /** - * Set the tags property for this entry. This property contains - * various Exif data. - * - * This corresponds to the property in the Google Data - * protocol. - * - * @param Zend_Gdata_Exif_Extension_Tags $value The desired value - * this element, or null to unset. - * @return Zend_Gdata_Exif_Entry Provides a fluent interface - */ - public function setTags($value) - { - $this->_tags = $value; - return $this; - } - -} diff --git a/library/Zend/Gdata/Exif/Extension/Distance.php b/library/Zend/Gdata/Exif/Extension/Distance.php deleted file mode 100755 index 7653142c29..0000000000 --- a/library/Zend/Gdata/Exif/Extension/Distance.php +++ /dev/null @@ -1,61 +0,0 @@ -registerAllNamespaces(Zend_Gdata_Exif::$namespaces); - parent::__construct(); - $this->setText($text); - } - -} diff --git a/library/Zend/Gdata/Exif/Extension/Exposure.php b/library/Zend/Gdata/Exif/Extension/Exposure.php deleted file mode 100755 index c9f40a39cb..0000000000 --- a/library/Zend/Gdata/Exif/Extension/Exposure.php +++ /dev/null @@ -1,61 +0,0 @@ -registerAllNamespaces(Zend_Gdata_Exif::$namespaces); - parent::__construct(); - $this->setText($text); - } - -} diff --git a/library/Zend/Gdata/Exif/Extension/FStop.php b/library/Zend/Gdata/Exif/Extension/FStop.php deleted file mode 100755 index 32076fc1d5..0000000000 --- a/library/Zend/Gdata/Exif/Extension/FStop.php +++ /dev/null @@ -1,61 +0,0 @@ -registerAllNamespaces(Zend_Gdata_Exif::$namespaces); - parent::__construct(); - $this->setText($text); - } - -} diff --git a/library/Zend/Gdata/Exif/Extension/Flash.php b/library/Zend/Gdata/Exif/Extension/Flash.php deleted file mode 100755 index dc2e35b33f..0000000000 --- a/library/Zend/Gdata/Exif/Extension/Flash.php +++ /dev/null @@ -1,61 +0,0 @@ -registerAllNamespaces(Zend_Gdata_Exif::$namespaces); - parent::__construct(); - $this->setText($text); - } - -} diff --git a/library/Zend/Gdata/Exif/Extension/FocalLength.php b/library/Zend/Gdata/Exif/Extension/FocalLength.php deleted file mode 100755 index 285a769f85..0000000000 --- a/library/Zend/Gdata/Exif/Extension/FocalLength.php +++ /dev/null @@ -1,61 +0,0 @@ -registerAllNamespaces(Zend_Gdata_Exif::$namespaces); - parent::__construct(); - $this->setText($text); - } - -} diff --git a/library/Zend/Gdata/Exif/Extension/ImageUniqueId.php b/library/Zend/Gdata/Exif/Extension/ImageUniqueId.php deleted file mode 100755 index af5a1b4880..0000000000 --- a/library/Zend/Gdata/Exif/Extension/ImageUniqueId.php +++ /dev/null @@ -1,61 +0,0 @@ -registerAllNamespaces(Zend_Gdata_Exif::$namespaces); - parent::__construct(); - $this->setText($text); - } - -} diff --git a/library/Zend/Gdata/Exif/Extension/Iso.php b/library/Zend/Gdata/Exif/Extension/Iso.php deleted file mode 100755 index ace044cbbe..0000000000 --- a/library/Zend/Gdata/Exif/Extension/Iso.php +++ /dev/null @@ -1,61 +0,0 @@ -registerAllNamespaces(Zend_Gdata_Exif::$namespaces); - parent::__construct(); - $this->setText($text); - } - -} diff --git a/library/Zend/Gdata/Exif/Extension/Make.php b/library/Zend/Gdata/Exif/Extension/Make.php deleted file mode 100755 index d9725d0c4b..0000000000 --- a/library/Zend/Gdata/Exif/Extension/Make.php +++ /dev/null @@ -1,61 +0,0 @@ -registerAllNamespaces(Zend_Gdata_Exif::$namespaces); - parent::__construct(); - $this->setText($text); - } - -} diff --git a/library/Zend/Gdata/Exif/Extension/Model.php b/library/Zend/Gdata/Exif/Extension/Model.php deleted file mode 100755 index c2587d9cd8..0000000000 --- a/library/Zend/Gdata/Exif/Extension/Model.php +++ /dev/null @@ -1,61 +0,0 @@ -registerAllNamespaces(Zend_Gdata_Exif::$namespaces); - parent::__construct(); - $this->setText($text); - } - -} diff --git a/library/Zend/Gdata/Exif/Extension/Tags.php b/library/Zend/Gdata/Exif/Extension/Tags.php deleted file mode 100755 index a9f1c35c4d..0000000000 --- a/library/Zend/Gdata/Exif/Extension/Tags.php +++ /dev/null @@ -1,549 +0,0 @@ -registerAllNamespaces(Zend_Gdata_Exif::$namespaces); - parent::__construct(); - $this->setDistance($distance); - $this->setExposure($exposure); - $this->setFlash($flash); - $this->setFocalLength($focalLength); - $this->setFStop($fStop); - $this->setImageUniqueId($imageUniqueId); - $this->setIso($iso); - $this->setMake($make); - $this->setModel($model); - $this->setTime($time); - } - - /** - * Retrieves a DOMElement which corresponds to this element and all - * child properties. This is used to build an entry back into a DOM - * and eventually XML text for application storage/persistence. - * - * @param DOMDocument $doc The DOMDocument used to construct DOMElements - * @return DOMElement The DOMElement representing this element and all - * child properties. - */ - public function getDOM($doc = null, $majorVersion = 1, $minorVersion = null) - { - $element = parent::getDOM($doc, $majorVersion, $minorVersion); - if ($this->_distance !== null) { - $element->appendChild($this->_distance->getDOM($element->ownerDocument)); - } - if ($this->_exposure !== null) { - $element->appendChild($this->_exposure->getDOM($element->ownerDocument)); - } - if ($this->_flash !== null) { - $element->appendChild($this->_flash->getDOM($element->ownerDocument)); - } - if ($this->_focalLength !== null) { - $element->appendChild($this->_focalLength->getDOM($element->ownerDocument)); - } - if ($this->_fStop !== null) { - $element->appendChild($this->_fStop->getDOM($element->ownerDocument)); - } - if ($this->_imageUniqueId !== null) { - $element->appendChild($this->_imageUniqueId->getDOM($element->ownerDocument)); - } - if ($this->_iso !== null) { - $element->appendChild($this->_iso->getDOM($element->ownerDocument)); - } - if ($this->_make !== null) { - $element->appendChild($this->_make->getDOM($element->ownerDocument)); - } - if ($this->_model !== null) { - $element->appendChild($this->_model->getDOM($element->ownerDocument)); - } - if ($this->_time !== null) { - $element->appendChild($this->_time->getDOM($element->ownerDocument)); - } - return $element; - } - - /** - * Creates individual Entry objects of the appropriate type and - * stores them as members of this entry based upon DOM data. - * - * @param DOMNode $child The DOMNode to process - */ - protected function takeChildFromDOM($child) - { - $absoluteNodeName = $child->namespaceURI . ':' . $child->localName; - switch ($absoluteNodeName) { - case $this->lookupNamespace('exif') . ':' . 'distance'; - $distance = new Zend_Gdata_Exif_Extension_Distance(); - $distance->transferFromDOM($child); - $this->_distance = $distance; - break; - case $this->lookupNamespace('exif') . ':' . 'exposure'; - $exposure = new Zend_Gdata_Exif_Extension_Exposure(); - $exposure->transferFromDOM($child); - $this->_exposure = $exposure; - break; - case $this->lookupNamespace('exif') . ':' . 'flash'; - $flash = new Zend_Gdata_Exif_Extension_Flash(); - $flash->transferFromDOM($child); - $this->_flash = $flash; - break; - case $this->lookupNamespace('exif') . ':' . 'focallength'; - $focalLength = new Zend_Gdata_Exif_Extension_FocalLength(); - $focalLength->transferFromDOM($child); - $this->_focalLength = $focalLength; - break; - case $this->lookupNamespace('exif') . ':' . 'fstop'; - $fStop = new Zend_Gdata_Exif_Extension_FStop(); - $fStop->transferFromDOM($child); - $this->_fStop = $fStop; - break; - case $this->lookupNamespace('exif') . ':' . 'imageUniqueID'; - $imageUniqueId = new Zend_Gdata_Exif_Extension_ImageUniqueId(); - $imageUniqueId->transferFromDOM($child); - $this->_imageUniqueId = $imageUniqueId; - break; - case $this->lookupNamespace('exif') . ':' . 'iso'; - $iso = new Zend_Gdata_Exif_Extension_Iso(); - $iso->transferFromDOM($child); - $this->_iso = $iso; - break; - case $this->lookupNamespace('exif') . ':' . 'make'; - $make = new Zend_Gdata_Exif_Extension_Make(); - $make->transferFromDOM($child); - $this->_make = $make; - break; - case $this->lookupNamespace('exif') . ':' . 'model'; - $model = new Zend_Gdata_Exif_Extension_Model(); - $model->transferFromDOM($child); - $this->_model = $model; - break; - case $this->lookupNamespace('exif') . ':' . 'time'; - $time = new Zend_Gdata_Exif_Extension_Time(); - $time->transferFromDOM($child); - $this->_time = $time; - break; - } - } - - /** - * Get the value for this element's distance attribute. - * - * @see setDistance - * @return Zend_Gdata_Exif_Extension_Distance The requested attribute. - */ - public function getDistance() - { - return $this->_distance; - } - - /** - * Set the value for this element's distance attribute. - * - * @param Zend_Gdata_Exif_Extension_Distance $value The desired value for this attribute. - * @return Zend_Gdata_Exif_Extension_Tags Provides a fluent interface - */ - public function setDistance($value) - { - $this->_distance = $value; - return $this; - } - - /** - * Get the value for this element's exposure attribute. - * - * @see setExposure - * @return Zend_Gdata_Exif_Extension_Exposure The requested attribute. - */ - public function getExposure() - { - return $this->_exposure; - } - - /** - * Set the value for this element's exposure attribute. - * - * @param Zend_Gdata_Exif_Extension_Exposure $value The desired value for this attribute. - * @return Zend_Gdata_Exif_Extension_Tags Provides a fluent interface - */ - public function setExposure($value) - { - $this->_exposure = $value; - return $this; - } - - /** - * Get the value for this element's flash attribute. - * - * @see setFlash - * @return Zend_Gdata_Exif_Extension_Flash The requested attribute. - */ - public function getFlash() - { - return $this->_flash; - } - - /** - * Set the value for this element's flash attribute. - * - * @param Zend_Gdata_Exif_Extension_Flash $value The desired value for this attribute. - * @return Zend_Gdata_Exif_Extension_Tags Provides a fluent interface - */ - public function setFlash($value) - { - $this->_flash = $value; - return $this; - } - - /** - * Get the value for this element's name attribute. - * - * @see setFocalLength - * @return Zend_Gdata_Exif_Extension_FocalLength The requested attribute. - */ - public function getFocalLength() - { - return $this->_focalLength; - } - - /** - * Set the value for this element's focalLength attribute. - * - * @param Zend_Gdata_Exif_Extension_FocalLength $value The desired value for this attribute. - * @return Zend_Gdata_Exif_Extension_Tags Provides a fluent interface - */ - public function setFocalLength($value) - { - $this->_focalLength = $value; - return $this; - } - - /** - * Get the value for this element's fStop attribute. - * - * @see setFStop - * @return Zend_Gdata_Exif_Extension_FStop The requested attribute. - */ - public function getFStop() - { - return $this->_fStop; - } - - /** - * Set the value for this element's fStop attribute. - * - * @param Zend_Gdata_Exif_Extension_FStop $value The desired value for this attribute. - * @return Zend_Gdata_Exif_Extension_Tags Provides a fluent interface - */ - public function setFStop($value) - { - $this->_fStop = $value; - return $this; - } - - /** - * Get the value for this element's imageUniqueId attribute. - * - * @see setImageUniqueId - * @return Zend_Gdata_Exif_Extension_ImageUniqueId The requested attribute. - */ - public function getImageUniqueId() - { - return $this->_imageUniqueId; - } - - /** - * Set the value for this element's imageUniqueId attribute. - * - * @param Zend_Gdata_Exif_Extension_ImageUniqueId $value The desired value for this attribute. - * @return Zend_Gdata_Exif_Extension_Tags Provides a fluent interface - */ - public function setImageUniqueId($value) - { - $this->_imageUniqueId = $value; - return $this; - } - - /** - * Get the value for this element's iso attribute. - * - * @see setIso - * @return Zend_Gdata_Exif_Extension_Iso The requested attribute. - */ - public function getIso() - { - return $this->_iso; - } - - /** - * Set the value for this element's iso attribute. - * - * @param Zend_Gdata_Exif_Extension_Iso $value The desired value for this attribute. - * @return Zend_Gdata_Exif_Extension_Tags Provides a fluent interface - */ - public function setIso($value) - { - $this->_iso = $value; - return $this; - } - /** - * Get the value for this element's make attribute. - * - * @see setMake - * @return Zend_Gdata_Exif_Extension_Make The requested attribute. - */ - public function getMake() - { - return $this->_make; - } - - /** - * Set the value for this element's make attribute. - * - * @param Zend_Gdata_Exif_Extension_Make $value The desired value for this attribute. - * @return Zend_Gdata_Exif_Extension_Tags Provides a fluent interface - */ - public function setMake($value) - { - $this->_make = $value; - return $this; - } - - /** - * Get the value for this element's model attribute. - * - * @see setModel - * @return Zend_Gdata_Exif_Extension_Model The requested attribute. - */ - public function getModel() - { - return $this->_model; - } - - /** - * Set the value for this element's model attribute. - * - * @param Zend_Gdata_Exif_Extension_Model $value The desired value for this attribute. - * @return Zend_Gdata_Exif_Extension_Tags Provides a fluent interface - */ - public function setModel($value) - { - $this->_model = $value; - return $this; - } - - /** - * Get the value for this element's time attribute. - * - * @see setTime - * @return Zend_Gdata_Exif_Extension_Time The requested attribute. - */ - public function getTime() - { - return $this->_time; - } - - /** - * Set the value for this element's time attribute. - * - * @param Zend_Gdata_Exif_Extension_Time $value The desired value for this attribute. - * @return Zend_Gdata_Exif_Extension_Tags Provides a fluent interface - */ - public function setTime($value) - { - $this->_time = $value; - return $this; - } - -} diff --git a/library/Zend/Gdata/Exif/Extension/Time.php b/library/Zend/Gdata/Exif/Extension/Time.php deleted file mode 100755 index 6b02196e64..0000000000 --- a/library/Zend/Gdata/Exif/Extension/Time.php +++ /dev/null @@ -1,61 +0,0 @@ -registerAllNamespaces(Zend_Gdata_Exif::$namespaces); - parent::__construct(); - $this->setText($text); - } - -} diff --git a/library/Zend/Gdata/Exif/Feed.php b/library/Zend/Gdata/Exif/Feed.php deleted file mode 100755 index e1a5822eea..0000000000 --- a/library/Zend/Gdata/Exif/Feed.php +++ /dev/null @@ -1,70 +0,0 @@ -registerAllNamespaces(Zend_Gdata_Exif::$namespaces); - parent::__construct($element); - } - -} diff --git a/library/Zend/Gdata/Extension.php b/library/Zend/Gdata/Extension.php deleted file mode 100644 index dddf55eddf..0000000000 --- a/library/Zend/Gdata/Extension.php +++ /dev/null @@ -1,58 +0,0 @@ -registerNamespace('gd', - 'http://schemas.google.com/g/2005'); - $this->registerNamespace('openSearch', - 'http://a9.com/-/spec/opensearchrss/1.0/', 1, 0); - $this->registerNamespace('openSearch', - 'http://a9.com/-/spec/opensearch/1.1/', 2, 0); - $this->registerNamespace('rss', - 'http://blogs.law.harvard.edu/tech/rss'); - - parent::__construct(); - } - -} diff --git a/library/Zend/Gdata/Extension/AttendeeStatus.php b/library/Zend/Gdata/Extension/AttendeeStatus.php deleted file mode 100644 index 7c2ef3502c..0000000000 --- a/library/Zend/Gdata/Extension/AttendeeStatus.php +++ /dev/null @@ -1,123 +0,0 @@ -_value = $value; - } - - /** - * Retrieves a DOMElement which corresponds to this element and all - * child properties. This is used to build an entry back into a DOM - * and eventually XML text for sending to the server upon updates, or - * for application storage/persistence. - * - * @param DOMDocument $doc The DOMDocument used to construct DOMElements - * @return DOMElement The DOMElement representing this element and all - * child properties. - */ - public function getDOM($doc = null, $majorVersion = 1, $minorVersion = null) - { - $element = parent::getDOM($doc, $majorVersion, $minorVersion); - if ($this->_value !== null) { - $element->setAttribute('value', $this->_value); - } - return $element; - } - - /** - * Given a DOMNode representing an attribute, tries to map the data into - * instance members. If no mapping is defined, the name and value are - * stored in an array. - * - * @param DOMNode $attribute The DOMNode attribute needed to be handled - */ - protected function takeAttributeFromDOM($attribute) - { - switch ($attribute->localName) { - case 'value': - $this->_value = $attribute->nodeValue; - break; - default: - parent::takeAttributeFromDOM($attribute); - } - } - - /** - * Get the value for this element's Value attribute. - * - * @return string The requested attribute. - */ - public function getValue() - { - return $this->_value; - } - - /** - * Set the value for this element's Value attribute. - * - * @param string $value The desired value for this attribute. - * @return Zend_Gdata_Extension_Visibility The element being modified. - */ - public function setValue($value) - { - $this->_value = $value; - return $this; - } - - /** - * Magic toString method allows using this directly via echo - * Works best in PHP >= 4.2.0 - */ - public function __toString() - { - return $this->getValue(); - } - -} - diff --git a/library/Zend/Gdata/Extension/AttendeeType.php b/library/Zend/Gdata/Extension/AttendeeType.php deleted file mode 100644 index 0b668220b4..0000000000 --- a/library/Zend/Gdata/Extension/AttendeeType.php +++ /dev/null @@ -1,123 +0,0 @@ -_value = $value; - } - - /** - * Retrieves a DOMElement which corresponds to this element and all - * child properties. This is used to build an entry back into a DOM - * and eventually XML text for sending to the server upon updates, or - * for application storage/persistence. - * - * @param DOMDocument $doc The DOMDocument used to construct DOMElements - * @return DOMElement The DOMElement representing this element and all - * child properties. - */ - public function getDOM($doc = null, $majorVersion = 1, $minorVersion = null) - { - $element = parent::getDOM($doc, $majorVersion, $minorVersion); - if ($this->_value !== null) { - $element->setAttribute('value', $this->_value); - } - return $element; - } - - /** - * Given a DOMNode representing an attribute, tries to map the data into - * instance members. If no mapping is defined, the name and value are - * stored in an array. - * - * @param DOMNode $attribute The DOMNode attribute needed to be handled - */ - protected function takeAttributeFromDOM($attribute) - { - switch ($attribute->localName) { - case 'value': - $this->_value = $attribute->nodeValue; - break; - default: - parent::takeAttributeFromDOM($attribute); - } - } - - /** - * Get the value for this element's Value attribute. - * - * @return string The requested attribute. - */ - public function getValue() - { - return $this->_value; - } - - /** - * Set the value for this element's Value attribute. - * - * @param string $value The desired value for this attribute. - * @return Zend_Gdata_Extension_Visibility The element being modified. - */ - public function setValue($value) - { - $this->_value = $value; - return $this; - } - - /** - * Magic toString method allows using this directly via echo - * Works best in PHP >= 4.2.0 - */ - public function __toString() - { - return $this->getValue(); - } - -} - diff --git a/library/Zend/Gdata/Extension/Comments.php b/library/Zend/Gdata/Extension/Comments.php deleted file mode 100644 index d455b8af3c..0000000000 --- a/library/Zend/Gdata/Extension/Comments.php +++ /dev/null @@ -1,117 +0,0 @@ -_rel = $rel; - $this->_feedLink = $feedLink; - } - - public function getDOM($doc = null, $majorVersion = 1, $minorVersion = null) - { - $element = parent::getDOM($doc, $majorVersion, $minorVersion); - if ($this->_rel !== null) { - $element->setAttribute('rel', $this->_rel); - } - if ($this->_feedLink !== null) { - $element->appendChild($this->_feedLink->getDOM($element->ownerDocument)); - } - return $element; - } - - protected function takeChildFromDOM($child) - { - $absoluteNodeName = $child->namespaceURI . ':' . $child->localName; - switch ($absoluteNodeName) { - case $this->lookupNamespace('gd') . ':' . 'feedLink'; - $feedLink = new Zend_Gdata_Extension_FeedLink(); - $feedLink->transferFromDOM($child); - $this->_feedLink = $feedLink; - break; - default: - parent::takeChildFromDOM($child); - break; - } - } - - protected function takeAttributeFromDOM($attribute) - { - switch ($attribute->localName) { - case 'rel': - $this->_rel = $attribute->nodeValue; - break; - default: - parent::takeAttributeFromDOM($attribute); - } - } - - public function getRel() - { - return $this->_rel; - } - - public function setRel($value) - { - $this->_rel = $value; - return $this; - } - - public function getFeedLink() - { - return $this->_feedLink; - } - - public function setFeedLink($value) - { - $this->_feedLink = $value; - return $this; - } - -} diff --git a/library/Zend/Gdata/Extension/EntryLink.php b/library/Zend/Gdata/Extension/EntryLink.php deleted file mode 100644 index c8b8f2970f..0000000000 --- a/library/Zend/Gdata/Extension/EntryLink.php +++ /dev/null @@ -1,167 +0,0 @@ -_href = $href; - $this->_readOnly = $readOnly; - $this->_rel = $rel; - $this->_entry = $entry; - } - - public function getDOM($doc = null, $majorVersion = 1, $minorVersion = null) - { - $element = parent::getDOM($doc, $majorVersion, $minorVersion); - if ($this->_href !== null) { - $element->setAttribute('href', $this->_href); - } - if ($this->_readOnly !== null) { - $element->setAttribute('readOnly', ($this->_readOnly ? "true" : "false")); - } - if ($this->_rel !== null) { - $element->setAttribute('rel', $this->_rel); - } - if ($this->_entry !== null) { - $element->appendChild($this->_entry->getDOM($element->ownerDocument)); - } - return $element; - } - - protected function takeChildFromDOM($child) - { - $absoluteNodeName = $child->namespaceURI . ':' . $child->localName; - switch ($absoluteNodeName) { - case $this->lookupNamespace('atom') . ':' . 'entry'; - $entry = new Zend_Gdata_Entry(); - $entry->transferFromDOM($child); - $this->_entry = $entry; - break; - default: - parent::takeChildFromDOM($child); - break; - } - } - - protected function takeAttributeFromDOM($attribute) - { - switch ($attribute->localName) { - case 'href': - $this->_href = $attribute->nodeValue; - break; - case 'readOnly': - if ($attribute->nodeValue == "true") { - $this->_readOnly = true; - } - else if ($attribute->nodeValue == "false") { - $this->_readOnly = false; - } - else { - throw new Zend_Gdata_App_InvalidArgumentException("Expected 'true' or 'false' for gCal:selected#value."); - } - break; - case 'rel': - $this->_rel = $attribute->nodeValue; - break; - default: - parent::takeAttributeFromDOM($attribute); - } - } - - /** - * @return string - */ - public function getHref() - { - return $this->_href; - } - - public function setHref($value) - { - $this->_href = $value; - return $this; - } - - public function getReadOnly() - { - return $this->_readOnly; - } - - public function setReadOnly($value) - { - $this->_readOnly = $value; - return $this; - } - - public function getRel() - { - return $this->_rel; - } - - public function setRel($value) - { - $this->_rel = $value; - return $this; - } - - public function getEntry() - { - return $this->_entry; - } - - public function setEntry($value) - { - $this->_entry = $value; - return $this; - } - -} diff --git a/library/Zend/Gdata/Extension/EventStatus.php b/library/Zend/Gdata/Extension/EventStatus.php deleted file mode 100644 index 979d049ed5..0000000000 --- a/library/Zend/Gdata/Extension/EventStatus.php +++ /dev/null @@ -1,101 +0,0 @@ -_value = $value; - } - - public function getDOM($doc = null, $majorVersion = 1, $minorVersion = null) - { - $element = parent::getDOM($doc, $majorVersion, $minorVersion); - if ($this->_value !== null) { - $element->setAttribute('value', $this->_value); - } - return $element; - } - - protected function takeAttributeFromDOM($attribute) - { - switch ($attribute->localName) { - case 'value': - $this->_value = $attribute->nodeValue; - break; - default: - parent::takeAttributeFromDOM($attribute); - } - } - - /** - * Get the value for this element's Value attribute. - * - * @return string The requested attribute. - */ - public function getValue() - { - return $this->_value; - } - - /** - * Set the value for this element's Value attribute. - * - * @param string $value The desired value for this attribute. - * @return Zend_Gdata_Extension_Visibility The element being modified. - */ - public function setValue($value) - { - $this->_value = $value; - return $this; - } - - /** - * Magic toString method allows using this directly via echo - * Works best in PHP >= 4.2.0 - */ - public function __toString() - { - return $this->getValue(); - } - -} diff --git a/library/Zend/Gdata/Extension/ExtendedProperty.php b/library/Zend/Gdata/Extension/ExtendedProperty.php deleted file mode 100644 index d011cfc455..0000000000 --- a/library/Zend/Gdata/Extension/ExtendedProperty.php +++ /dev/null @@ -1,106 +0,0 @@ -_name = $name; - $this->_value = $value; - } - - public function getDOM($doc = null, $majorVersion = 1, $minorVersion = null) - { - $element = parent::getDOM($doc, $majorVersion, $minorVersion); - if ($this->_name !== null) { - $element->setAttribute('name', $this->_name); - } - if ($this->_value !== null) { - $element->setAttribute('value', $this->_value); - } - return $element; - } - - protected function takeAttributeFromDOM($attribute) - { - switch ($attribute->localName) { - case 'name': - $this->_name = $attribute->nodeValue; - break; - case 'value': - $this->_value = $attribute->nodeValue; - break; - default: - parent::takeAttributeFromDOM($attribute); - } - } - - public function __toString() - { - return $this->getName() . '=' . $this->getValue(); - } - - public function getName() - { - return $this->_name; - } - - public function setName($value) - { - $this->_name = $value; - return $this; - } - - public function getValue() - { - return $this->_value; - } - - public function setValue($value) - { - $this->_value = $value; - return $this; - } - -} diff --git a/library/Zend/Gdata/Extension/FeedLink.php b/library/Zend/Gdata/Extension/FeedLink.php deleted file mode 100644 index 8af166878b..0000000000 --- a/library/Zend/Gdata/Extension/FeedLink.php +++ /dev/null @@ -1,175 +0,0 @@ -_countHint = $countHint; - $this->_href = $href; - $this->_readOnly = $readOnly; - $this->_rel = $rel; - $this->_feed = $feed; - } - - public function getDOM($doc = null, $majorVersion = 1, $minorVersion = null) - { - $element = parent::getDOM($doc, $majorVersion, $minorVersion); - if ($this->_countHint !== null) { - $element->setAttribute('countHint', $this->_countHint); - } - if ($this->_href !== null) { - $element->setAttribute('href', $this->_href); - } - if ($this->_readOnly !== null) { - $element->setAttribute('readOnly', ($this->_readOnly ? "true" : "false")); - } - if ($this->_rel !== null) { - $element->setAttribute('rel', $this->_rel); - } - if ($this->_feed !== null) { - $element->appendChild($this->_feed->getDOM($element->ownerDocument)); - } - return $element; - } - - protected function takeChildFromDOM($child) - { - $absoluteNodeName = $child->namespaceURI . ':' . $child->localName; - switch ($absoluteNodeName) { - case $this->lookupNamespace('atom') . ':' . 'feed'; - $feed = new Zend_Gdata_Feed(); - $feed->transferFromDOM($child); - $this->_feed = $feed; - break; - default: - parent::takeChildFromDOM($child); - break; - } - } - - protected function takeAttributeFromDOM($attribute) - { - switch ($attribute->localName) { - case 'countHint': - $this->_countHint = $attribute->nodeValue; - break; - case 'href': - $this->_href = $attribute->nodeValue; - break; - case 'readOnly': - if ($attribute->nodeValue == "true") { - $this->_readOnly = true; - } - else if ($attribute->nodeValue == "false") { - $this->_readOnly = false; - } - else { - throw new Zend_Gdata_App_InvalidArgumentException("Expected 'true' or 'false' for gCal:selected#value."); - } - break; - case 'rel': - $this->_rel = $attribute->nodeValue; - break; - default: - parent::takeAttributeFromDOM($attribute); - } - } - - /** - * @return string - */ - public function getHref() - { - return $this->_href; - } - - public function setHref($value) - { - $this->_href = $value; - return $this; - } - - public function getReadOnly() - { - return $this->_readOnly; - } - - public function setReadOnly($value) - { - $this->_readOnly = $value; - return $this; - } - - public function getRel() - { - return $this->_rel; - } - - public function setRel($value) - { - $this->_rel = $value; - return $this; - } - - public function getFeed() - { - return $this->_feed; - } - - public function setFeed($value) - { - $this->_feed = $value; - return $this; - } - -} diff --git a/library/Zend/Gdata/Extension/OpenSearchItemsPerPage.php b/library/Zend/Gdata/Extension/OpenSearchItemsPerPage.php deleted file mode 100644 index ef2399104b..0000000000 --- a/library/Zend/Gdata/Extension/OpenSearchItemsPerPage.php +++ /dev/null @@ -1,50 +0,0 @@ -_text = $text; - } - -} diff --git a/library/Zend/Gdata/Extension/OpenSearchStartIndex.php b/library/Zend/Gdata/Extension/OpenSearchStartIndex.php deleted file mode 100644 index e4dfe59667..0000000000 --- a/library/Zend/Gdata/Extension/OpenSearchStartIndex.php +++ /dev/null @@ -1,50 +0,0 @@ -_text = $text; - } - -} diff --git a/library/Zend/Gdata/Extension/OpenSearchTotalResults.php b/library/Zend/Gdata/Extension/OpenSearchTotalResults.php deleted file mode 100644 index db4be96072..0000000000 --- a/library/Zend/Gdata/Extension/OpenSearchTotalResults.php +++ /dev/null @@ -1,50 +0,0 @@ -_text = $text; - } - -} diff --git a/library/Zend/Gdata/Extension/OriginalEvent.php b/library/Zend/Gdata/Extension/OriginalEvent.php deleted file mode 100644 index 63ab2a2406..0000000000 --- a/library/Zend/Gdata/Extension/OriginalEvent.php +++ /dev/null @@ -1,142 +0,0 @@ -_id = $id; - $this->_href = $href; - $this->_when = $when; - } - - public function getDOM($doc = null, $majorVersion = 1, $minorVersion = null) - { - $element = parent::getDOM($doc, $majorVersion, $minorVersion); - if ($this->_id !== null) { - $element->setAttribute('id', $this->_id); - } - if ($this->_href !== null) { - $element->setAttribute('href', $this->_href); - } - if ($this->_when !== null) { - $element->appendChild($this->_when->getDOM($element->ownerDocument)); - } - return $element; - } - - protected function takeAttributeFromDOM($attribute) - { - switch ($attribute->localName) { - case 'id': - $this->_id = $attribute->nodeValue; - break; - case 'href': - $this->_href = $attribute->nodeValue; - break; - default: - parent::takeAttributeFromDOM($attribute); - } - } - - protected function takeChildFromDOM($child) - { - $absoluteNodeName = $child->namespaceURI . ':' . $child->localName; - switch ($absoluteNodeName) { - case $this->lookupNamespace('gd') . ':' . 'when'; - $when = new Zend_Gdata_Extension_When(); - $when->transferFromDOM($child); - $this->_when = $when; - break; - default: - parent::takeChildFromDOM($child); - break; - } - } - - public function getId() - { - return $this->_id; - } - - public function setId($value) - { - $this->_id = $value; - return $this; - } - - public function getHref() - { - return $this->_href; - } - - public function setHref($value) - { - $this->_href = $value; - return $this; - } - - public function getWhen() - { - return $this->_when; - } - - public function setWhen($value) - { - $this->_when = $value; - return $this; - } - - -} diff --git a/library/Zend/Gdata/Extension/Rating.php b/library/Zend/Gdata/Extension/Rating.php deleted file mode 100644 index 8fdfb53b65..0000000000 --- a/library/Zend/Gdata/Extension/Rating.php +++ /dev/null @@ -1,240 +0,0 @@ -_average = $average; - $this->_min = $min; - $this->_max = $max; - $this->_numRaters = $numRaters; - $this->_value = $value; - } - - /** - * Retrieves a DOMElement which corresponds to this element and all - * child properties. This is used to build an entry back into a DOM - * and eventually XML text for sending to the server upon updates, or - * for application storage/persistence. - * - * @param DOMDocument $doc The DOMDocument used to construct DOMElements - * @return DOMElement The DOMElement representing this element and all - * child properties. - */ - public function getDOM($doc = null, $majorVersion = 1, $minorVersion = null) - { - $element = parent::getDOM($doc, $majorVersion, $minorVersion); - if ($this->_min !== null) { - $element->setAttribute('min', $this->_min); - } - if ($this->_max !== null) { - $element->setAttribute('max', $this->_max); - } - if ($this->_numRaters !== null) { - $element->setAttribute('numRaters', $this->_numRaters); - } - if ($this->_average !== null) { - $element->setAttribute('average', $this->_average); - } - if ($this->_value !== null) { - $element->setAttribute('value', $this->_value); - } - - return $element; - } - - /** - * Given a DOMNode representing an attribute, tries to map the data into - * instance members. If no mapping is defined, the name and value are - * stored in an array. - * - * @param DOMNode $attribute The DOMNode attribute needed to be handled - */ - protected function takeAttributeFromDOM($attribute) - { - switch ($attribute->localName) { - case 'min': - $this->_min = $attribute->nodeValue; - break; - case 'max': - $this->_max = $attribute->nodeValue; - break; - case 'numRaters': - $this->_numRaters = $attribute->nodeValue; - break; - case 'average': - $this->_average = $attribute->nodeValue; - break; - case 'value': - $this->_value = $attribute->nodeValue; - default: - parent::takeAttributeFromDOM($attribute); - } - } - - /** - * Get the value for this element's min attribute. - * - * @return integer The requested attribute. - */ - public function getMin() - { - return $this->_min; - } - - /** - * Set the value for this element's min attribute. - * - * @param bool $value The desired value for this attribute. - * @return Zend_Gdata_Extension_Rating The element being modified. - */ - public function setMin($value) - { - $this->_min = $value; - return $this; - } - - /** - * Get the value for this element's numRaters attribute. - * - * @return integer The requested attribute. - */ - public function getNumRaters() - { - return $this->_numRaters; - } - - /** - * Set the value for this element's numRaters attribute. - * - * @param bool $value The desired value for this attribute. - * @return Zend_Gdata_Extension_Rating The element being modified. - */ - public function setNumRaters($value) - { - $this->_numRaters = $value; - return $this; - } - - /** - * Get the value for this element's average attribute. - * - * @return integer The requested attribute. - */ - public function getAverage() - { - return $this->_average; - } - - /** - * Set the value for this element's average attribute. - * - * @param bool $value The desired value for this attribute. - * @return Zend_Gdata_Extension_Rating The element being modified. - */ - public function setAverage($value) - { - $this->_average = $value; - return $this; - } - - /** - * Get the value for this element's max attribute. - * - * @return integer The requested attribute. - */ - public function getMax() - { - return $this->_max; - } - - /** - * Set the value for this element's max attribute. - * - * @param bool $value The desired value for this attribute. - * @return Zend_Gdata_Extension_Rating The element being modified. - */ - public function setMax($value) - { - $this->_max = $value; - return $this; - } - - /** - * Get the value for this element's value attribute. - * - * @return integer The requested attribute. - */ - public function getValue() - { - return $this->_value; - } - - /** - * Set the value for this element's value attribute. - * - * @param bool $value The desired value for this attribute. - * @return Zend_Gdata_Extension_Rating The element being modified. - */ - public function setValue($value) - { - $this->_value = $value; - return $this; - } - -} diff --git a/library/Zend/Gdata/Extension/Recurrence.php b/library/Zend/Gdata/Extension/Recurrence.php deleted file mode 100644 index 748a362abc..0000000000 --- a/library/Zend/Gdata/Extension/Recurrence.php +++ /dev/null @@ -1,49 +0,0 @@ -_text = $text; - } - -} diff --git a/library/Zend/Gdata/Extension/RecurrenceException.php b/library/Zend/Gdata/Extension/RecurrenceException.php deleted file mode 100644 index 4fe82fb7e8..0000000000 --- a/library/Zend/Gdata/Extension/RecurrenceException.php +++ /dev/null @@ -1,215 +0,0 @@ -_specialized = $specialized; - $this->_entryLink = $entryLink; - $this->_originalEvent = $originalEvent; - } - - /** - * Retrieves a DOMElement which corresponds to this element and all - * child properties. This is used to build an entry back into a DOM - * and eventually XML text for sending to the server upon updates, or - * for application storage/persistence. - * - * @param DOMDocument $doc The DOMDocument used to construct DOMElements - * @return DOMElement The DOMElement representing this element and all - * child properties. - */ - public function getDOM($doc = null, $majorVersion = 1, $minorVersion = null) - { - $element = parent::getDOM($doc, $majorVersion, $minorVersion); - if ($this->_specialized !== null) { - $element->setAttribute('specialized', ($this->_specialized ? "true" : "false")); - } - if ($this->_entryLink !== null) { - $element->appendChild($this->_entryLink->getDOM($element->ownerDocument)); - } - if ($this->_originalEvent !== null) { - $element->appendChild($this->_originalEvent->getDOM($element->ownerDocument)); - } - return $element; - } - - /** - * Given a DOMNode representing an attribute, tries to map the data into - * instance members. If no mapping is defined, the name and value are - * stored in an array. - * - * @param DOMNode $attribute The DOMNode attribute needed to be handled - */ - protected function takeAttributeFromDOM($attribute) - { - switch ($attribute->localName) { - case 'specialized': - if ($attribute->nodeValue == "true") { - $this->_specialized = true; - } - else if ($attribute->nodeValue == "false") { - $this->_specialized = false; - } - else { - throw new Zend_Gdata_App_InvalidArgumentException("Expected 'true' or 'false' for gCal:selected#value."); - } - break; - default: - parent::takeAttributeFromDOM($attribute); - } - } - - /** - * Creates individual Entry objects of the appropriate type and - * stores them as members of this entry based upon DOM data. - * - * @param DOMNode $child The DOMNode to process - */ - protected function takeChildFromDOM($child) - { - $absoluteNodeName = $child->namespaceURI . ':' . $child->localName; - switch ($absoluteNodeName) { - case $this->lookupNamespace('gd') . ':' . 'entryLink': - $entryLink = new Zend_Gdata_Extension_EntryLink(); - $entryLink->transferFromDOM($child); - $this->_entryLink = $entryLink; - break; - case $this->lookupNamespace('gd') . ':' . 'originalEvent': - $originalEvent = new Zend_Gdata_Extension_OriginalEvent(); - $originalEvent->transferFromDOM($child); - $this->_originalEvent = $originalEvent; - break; - default: - parent::takeChildFromDOM($child); - break; - } - } - - /** - * Get the value for this element's Specialized attribute. - * - * @return bool The requested attribute. - */ - public function getSpecialized() - { - return $this->_specialized; - } - - /** - * Set the value for this element's Specialized attribute. - * - * @param bool $value The desired value for this attribute. - * @return Zend_Gdata_Extension_RecurrenceException The element being modified. - */ - public function setSpecialized($value) - { - $this->_specialized = $value; - return $this; - } - - /** - * Get the value for this element's EntryLink attribute. - * - * @return Zend_Gdata_Extension_EntryLink The requested attribute. - */ - public function getEntryLink() - { - return $this->_entryLink; - } - - /** - * Set the value for this element's EntryLink attribute. - * - * @param Zend_Gdata_Extension_EntryLink $value The desired value for this attribute. - * @return Zend_Gdata_Extension_RecurrenceException The element being modified. - */ - public function setEntryLink($value) - { - $this->_entryLink = $value; - return $this; - } - - /** - * Get the value for this element's Specialized attribute. - * - * @return Zend_Gdata_Extension_OriginalEvent The requested attribute. - */ - public function getOriginalEvent() - { - return $this->_originalEvent; - } - - /** - * Set the value for this element's Specialized attribute. - * - * @param Zend_Gdata_Extension_OriginalEvent $value The desired value for this attribute. - * @return Zend_Gdata_Extension_RecurrenceException The element being modified. - */ - public function setOriginalEvent($value) - { - $this->_originalEvent = $value; - return $this; - } - -} - diff --git a/library/Zend/Gdata/Extension/Reminder.php b/library/Zend/Gdata/Extension/Reminder.php deleted file mode 100644 index fdd0ccb639..0000000000 --- a/library/Zend/Gdata/Extension/Reminder.php +++ /dev/null @@ -1,171 +0,0 @@ -_absoluteTime = $absoluteTime; - $this->_method = $method; - $this->_days = $days; - $this->_hours = $hours; - $this->_minutes = $minutes; - } - - public function getDOM($doc = null, $majorVersion = 1, $minorVersion = null) - { - $element = parent::getDOM($doc, $majorVersion, $minorVersion); - if ($this->_absoluteTime !== null) { - $element->setAttribute('absoluteTime', $this->_absoluteTime); - } - if ($this->_method !== null) { - $element->setAttribute('method', $this->_method); - } - if ($this->_days !== null) { - $element->setAttribute('days', $this->_days); - } - if ($this->_hours !== null) { - $element->setAttribute('hours', $this->_hours); - } - if ($this->_minutes !== null) { - $element->setAttribute('minutes', $this->_minutes); - } - return $element; - } - - protected function takeAttributeFromDOM($attribute) - { - switch ($attribute->localName) { - case 'absoluteTime': - $this->_absoluteTime = $attribute->nodeValue; - break; - case 'method': - $this->_method = $attribute->nodeValue; - break; - case 'days': - $this->_days = $attribute->nodeValue; - break; - case 'hours': - $this->_hours = $attribute->nodeValue; - break; - case 'minutes': - $this->_minutes = $attribute->nodeValue; - break; - default: - parent::takeAttributeFromDOM($attribute); - } - } - - public function __toString() - { - $s = ''; - if ($this->_absoluteTime) - $s = " at " . $this->_absoluteTime; - else if ($this->_days) - $s = " in " . $this->_days . " days"; - else if ($this->_hours) - $s = " in " . $this->_hours . " hours"; - else if ($this->_minutes) - $s = " in " . $this->_minutes . " minutes"; - return $this->_method . $s; - } - - public function getAbsoluteTime() - { - return $this->_absoluteTime; - } - - public function setAbsoluteTime($value) - { - $this->_absoluteTime = $value; - return $this; - } - - public function getDays() - { - return $this->_days; - } - - public function setDays($value) - { - $this->_days = $value; - return $this; - } - public function getHours() - { - return $this->_hours; - } - - public function setHours($value) - { - $this->_hours = $value; - return $this; - } - - public function getMinutes() - { - return $this->_minutes; - } - - public function setMinutes($value) - { - $this->_minutes = $value; - return $this; - } - - public function getMethod() - { - return $this->_method; - } - - public function setMethod($value) - { - $this->_method = $value; - return $this; - } - -} diff --git a/library/Zend/Gdata/Extension/Transparency.php b/library/Zend/Gdata/Extension/Transparency.php deleted file mode 100644 index c34c82cb27..0000000000 --- a/library/Zend/Gdata/Extension/Transparency.php +++ /dev/null @@ -1,123 +0,0 @@ -_value = $value; - } - - /** - * Retrieves a DOMElement which corresponds to this element and all - * child properties. This is used to build an entry back into a DOM - * and eventually XML text for sending to the server upon updates, or - * for application storage/persistence. - * - * @param DOMDocument $doc The DOMDocument used to construct DOMElements - * @return DOMElement The DOMElement representing this element and all - * child properties. - */ - public function getDOM($doc = null, $majorVersion = 1, $minorVersion = null) - { - $element = parent::getDOM($doc, $majorVersion, $minorVersion); - if ($this->_value !== null) { - $element->setAttribute('value', $this->_value); - } - return $element; - } - - /** - * Given a DOMNode representing an attribute, tries to map the data into - * instance members. If no mapping is defined, the name and value are - * stored in an array. - * - * @param DOMNode $attribute The DOMNode attribute needed to be handled - */ - protected function takeAttributeFromDOM($attribute) - { - switch ($attribute->localName) { - case 'value': - $this->_value = $attribute->nodeValue; - break; - default: - parent::takeAttributeFromDOM($attribute); - } - } - - /** - * Get the value for this element's Value attribute. - * - * @return bool The requested attribute. - */ - public function getValue() - { - return $this->_value; - } - - /** - * Set the value for this element's Value attribute. - * - * @param bool $value The desired value for this attribute. - * @return Zend_Gdata_Extension_Transparency The element being modified. - */ - public function setValue($value) - { - $this->_value = $value; - return $this; - } - - /** - * Magic toString method allows using this directly via echo - * Works best in PHP >= 4.2.0 - */ - public function __toString() - { - return $this->getValue(); - } - -} - diff --git a/library/Zend/Gdata/Extension/Visibility.php b/library/Zend/Gdata/Extension/Visibility.php deleted file mode 100644 index 31412c96ef..0000000000 --- a/library/Zend/Gdata/Extension/Visibility.php +++ /dev/null @@ -1,123 +0,0 @@ -_value = $value; - } - - /** - * Retrieves a DOMElement which corresponds to this element and all - * child properties. This is used to build an entry back into a DOM - * and eventually XML text for sending to the server upon updates, or - * for application storage/persistence. - * - * @param DOMDocument $doc The DOMDocument used to construct DOMElements - * @return DOMElement The DOMElement representing this element and all - * child properties. - */ - public function getDOM($doc = null, $majorVersion = 1, $minorVersion = null) - { - $element = parent::getDOM($doc, $majorVersion, $minorVersion); - if ($this->_value !== null) { - $element->setAttribute('value', $this->_value); - } - return $element; - } - - /** - * Given a DOMNode representing an attribute, tries to map the data into - * instance members. If no mapping is defined, the name and value are - * stored in an array. - * - * @param DOMNode $attribute The DOMNode attribute needed to be handled - */ - protected function takeAttributeFromDOM($attribute) - { - switch ($attribute->localName) { - case 'value': - $this->_value = $attribute->nodeValue; - break; - default: - parent::takeAttributeFromDOM($attribute); - } - } - - /** - * Get the value for this element's Value attribute. - * - * @return bool The requested attribute. - */ - public function getValue() - { - return $this->_value; - } - - /** - * Set the value for this element's Value attribute. - * - * @param bool $value The desired value for this attribute. - * @return Zend_Gdata_Extension_Visibility The element being modified. - */ - public function setValue($value) - { - $this->_value = $value; - return $this; - } - - /** - * Magic toString method allows using this directly via echo - * Works best in PHP >= 4.2.0 - */ - public function __toString() - { - return $this->getValue(); - } - -} - diff --git a/library/Zend/Gdata/Extension/When.php b/library/Zend/Gdata/Extension/When.php deleted file mode 100644 index b138544e42..0000000000 --- a/library/Zend/Gdata/Extension/When.php +++ /dev/null @@ -1,169 +0,0 @@ -_startTime = $startTime; - $this->_endTime = $endTime; - $this->_valueString = $valueString; - $this->_reminders = $reminders; - } - - public function getDOM($doc = null, $majorVersion = 1, $minorVersion = null) - { - $element = parent::getDOM($doc, $majorVersion, $minorVersion); - if ($this->_startTime !== null) { - $element->setAttribute('startTime', $this->_startTime); - } - if ($this->_endTime !== null) { - $element->setAttribute('endTime', $this->_endTime); - } - if ($this->_valueString !== null) { - $element->setAttribute('valueString', $this->_valueString); - } - if ($this->_reminders !== null) { - foreach ($this->_reminders as $reminder) { - $element->appendChild( - $reminder->getDOM($element->ownerDocument)); - } - } - return $element; - } - - protected function takeChildFromDOM($child) - { - $absoluteNodeName = $child->namespaceURI . ':' . $child->localName; - switch ($absoluteNodeName) { - case $this->lookupNamespace('gd') . ':' . 'reminder'; - $reminder = new Zend_Gdata_Extension_Reminder(); - $reminder->transferFromDOM($child); - $this->_reminders[] = $reminder; - break; - default: - parent::takeChildFromDOM($child); - break; - } - } - - protected function takeAttributeFromDOM($attribute) - { - switch ($attribute->localName) { - case 'startTime': - $this->_startTime = $attribute->nodeValue; - break; - case 'endTime': - $this->_endTime = $attribute->nodeValue; - break; - case 'valueString': - $this->_valueString = $attribute->nodeValue; - break; - default: - parent::takeAttributeFromDOM($attribute); - } - } - - public function __toString() - { - if ($this->_valueString) - return $this->_valueString; - else { - return 'Starts: ' . $this->getStartTime() . ' ' . - 'Ends: ' . $this->getEndTime(); - } - } - - public function getStartTime() - { - return $this->_startTime; - } - - public function setStartTime($value) - { - $this->_startTime = $value; - return $this; - } - - public function getEndTime() - { - return $this->_endTime; - } - - public function setEndTime($value) - { - $this->_endTime = $value; - return $this; - } - - public function getValueString() - { - return $this->_valueString; - } - - public function setValueString($value) - { - $this->_valueString = $value; - return $this; - } - - public function getReminders() - { - return $this->_reminders; - } - - public function setReminders($value) - { - $this->_reminders = $value; - return $this; - } - -} diff --git a/library/Zend/Gdata/Extension/Where.php b/library/Zend/Gdata/Extension/Where.php deleted file mode 100644 index f241728fe8..0000000000 --- a/library/Zend/Gdata/Extension/Where.php +++ /dev/null @@ -1,171 +0,0 @@ -_valueString = $valueString; - $this->_label = $label; - $this->_rel = $rel; - $this->_entryLink = $entryLink; - } - - public function getDOM($doc = null, $majorVersion = 1, $minorVersion = null) - { - $element = parent::getDOM($doc, $majorVersion, $minorVersion); - if ($this->_label !== null) { - $element->setAttribute('label', $this->_label); - } - if ($this->_rel !== null) { - $element->setAttribute('rel', $this->_rel); - } - if ($this->_valueString !== null) { - $element->setAttribute('valueString', $this->_valueString); - } - if ($this->entryLink !== null) { - $element->appendChild($this->_entryLink->getDOM($element->ownerDocument)); - } - return $element; - } - - protected function takeAttributeFromDOM($attribute) - { - switch ($attribute->localName) { - case 'label': - $this->_label = $attribute->nodeValue; - break; - case 'rel': - $this->_rel = $attribute->nodeValue; - break; - case 'valueString': - $this->_valueString = $attribute->nodeValue; - break; - default: - parent::takeAttributeFromDOM($attribute); - } - } - - /** - * Creates individual Entry objects of the appropriate type and - * stores them in the $_entry array based upon DOM data. - * - * @param DOMNode $child The DOMNode to process - */ - protected function takeChildFromDOM($child) - { - $absoluteNodeName = $child->namespaceURI . ':' . $child->localName; - switch ($absoluteNodeName) { - case $this->lookupNamespace('gd') . ':' . 'entryLink': - $entryLink = new Zend_Gdata_Extension_EntryLink(); - $entryLink->transferFromDOM($child); - $this->_entryLink = $entryLink; - break; - default: - parent::takeChildFromDOM($child); - break; - } - } - - public function __toString() - { - if ($this->_valueString != null) { - return $this->_valueString; - } - else { - return parent::__toString(); - } - } - - public function getLabel() - { - return $this->_label; - } - - public function setLabel($value) - { - $this->_label = $value; - return $this; - } - - public function getRel() - { - return $this->_rel; - } - - public function setRel($value) - { - $this->_rel = $value; - return $this; - } - - public function getValueString() - { - return $this->_valueString; - } - - public function setValueString($value) - { - $this->_valueString = $value; - return $this; - } - - public function getEntryLink() - { - return $this->_entryLink; - } - - public function setEntryLink($value) - { - $this->_entryLink = $value; - return $this; - } - -} diff --git a/library/Zend/Gdata/Extension/Who.php b/library/Zend/Gdata/Extension/Who.php deleted file mode 100644 index bd25c3c74c..0000000000 --- a/library/Zend/Gdata/Extension/Who.php +++ /dev/null @@ -1,299 +0,0 @@ -_email = $email; - $this->_rel = $rel; - $this->_valueString = $valueString; - $this->_attendeeStatus = $attendeeStatus; - $this->_attendeeType = $attendeeType; - $this->_entryLink = $entryLink; - } - - /** - * Retrieves a DOMElement which corresponds to this element and all - * child properties. This is used to build an entry back into a DOM - * and eventually XML text for sending to the server upon updates, or - * for application storage/persistence. - * - * @param DOMDocument $doc The DOMDocument used to construct DOMElements - * @return DOMElement The DOMElement representing this element and all - * child properties. - */ - public function getDOM($doc = null, $majorVersion = 1, $minorVersion = null) - { - $element = parent::getDOM($doc, $majorVersion, $minorVersion); - if ($this->_email !== null) { - $element->setAttribute('email', $this->_email); - } - if ($this->_rel !== null) { - $element->setAttribute('rel', $this->_rel); - } - if ($this->_valueString !== null) { - $element->setAttribute('valueString', $this->_valueString); - } - if ($this->_attendeeStatus !== null) { - $element->appendChild($this->_attendeeStatus->getDOM($element->ownerDocument)); - } - if ($this->_attendeeType !== null) { - $element->appendChild($this->_attendeeType->getDOM($element->ownerDocument)); - } - if ($this->_entryLink !== null) { - $element->appendChild($this->_entryLink->getDOM($element->ownerDocument)); - } - return $element; - } - - /** - * Given a DOMNode representing an attribute, tries to map the data into - * instance members. If no mapping is defined, the name and value are - * stored in an array. - * - * @param DOMNode $attribute The DOMNode attribute needed to be handled - */ - protected function takeAttributeFromDOM($attribute) - { - switch ($attribute->localName) { - case 'email': - $this->_email = $attribute->nodeValue; - break; - case 'rel': - $this->_rel = $attribute->nodeValue; - break; - case 'valueString': - $this->_valueString = $attribute->nodeValue; - break; - default: - parent::takeAttributeFromDOM($attribute); - } - } - - /** - * Creates individual Entry objects of the appropriate type and - * stores them as members of this entry based upon DOM data. - * - * @param DOMNode $child The DOMNode to process - */ - protected function takeChildFromDOM($child) - { - $absoluteNodeName = $child->namespaceURI . ':' . $child->localName; - switch ($absoluteNodeName) { - case $this->lookupNamespace('gd') . ':' . 'attendeeStatus': - $attendeeStatus = new Zend_Gdata_Extension_AttendeeStatus(); - $attendeeStatus->transferFromDOM($child); - $this->_attendeeStatus = $attendeeStatus; - break; - case $this->lookupNamespace('gd') . ':' . 'attendeeType': - $attendeeType = new Zend_Gdata_Extension_AttendeeType(); - $attendeeType->transferFromDOM($child); - $this->_attendeeType = $attendeeType; - break; - case $this->lookupNamespace('gd') . ':' . 'entryLink': - $entryLink = new Zend_Gdata_Extension_EntryLink(); - $entryLink->transferFromDOM($child); - $this->_entryLink = $entryLink; - break; - default: - parent::takeChildFromDOM($child); - break; - } - } - - /** - * Retrieves a human readable string describing this attribute's value. - * - * @return string The attribute value. - */ - public function __toString() - { - if ($this->_valueString != null) { - return $this->_valueString; - } - else { - return parent::__toString(); - } - } - - /** - * Get the value for this element's ValueString attribute. - * - * @return string The requested attribute. - */ - public function getValueString() - { - return $this->_valueString; - } - - /** - * Set the value for this element's ValueString attribute. - * - * @param string $value The desired value for this attribute. - * @return Zend_Gdata_Extension_Who The element being modified. - */ - public function setValueString($value) - { - $this->_valueString = $value; - return $this; - } - - /** - * Get the value for this element's Email attribute. - * - * @return string The requested attribute. - */ - public function getEmail() - { - return $this->_email; - } - - /** - * Set the value for this element's Email attribute. - * - * @param string $value The desired value for this attribute. - * @return Zend_Gdata_Extension_Who The element being modified. - */ - public function setEmail($value) - { - $this->_email = $value; - return $this; - } - - /** - * Get the value for this element's Rel attribute. - * - * @return string The requested attribute. - */ - public function getRel() - { - return $this->_rel; - } - - /** - * Set the value for this element's Rel attribute. - * - * @param string $value The desired value for this attribute. - * @return Zend_Gdata_Extension_Who The element being modified. - */ - public function setRel($value) - { - $this->_rel = $value; - return $this; - } - - /** - * Get this entry's AttendeeStatus element. - * - * @return Zend_Gdata_Extension_AttendeeStatus The requested entry. - */ - public function getAttendeeStatus() - { - return $this->_attendeeStatus; - } - - /** - * Set the child's AttendeeStatus element. - * - * @param Zend_Gdata_Extension_AttendeeStatus $value The desired value for this attribute. - * @return Zend_Gdata_Extension_Who The element being modified. - */ - public function setAttendeeStatus($value) - { - $this->_attendeeStatus = $value; - return $this; - } - - /** - * Get this entry's AttendeeType element. - * - * @return Zend_Gdata_Extension_AttendeeType The requested entry. - */ - public function getAttendeeType() - { - return $this->_attendeeType; - } - - /** - * Set the child's AttendeeType element. - * - * @param Zend_Gdata_Extension_AttendeeType $value The desired value for this attribute. - * @return Zend_Gdata_Extension_Who The element being modified. - */ - public function setAttendeeType($value) - { - $this->_attendeeType = $value; - return $this; - } - -} diff --git a/library/Zend/Gdata/Feed.php b/library/Zend/Gdata/Feed.php deleted file mode 100644 index f4c714e4d8..0000000000 --- a/library/Zend/Gdata/Feed.php +++ /dev/null @@ -1,251 +0,0 @@ -registerAllNamespaces(Zend_Gdata::$namespaces); - parent::__construct($element); - } - - public function getDOM($doc = null, $majorVersion = 1, $minorVersion = null) - { - $element = parent::getDOM($doc, $majorVersion, $minorVersion); - if ($this->_totalResults != null) { - $element->appendChild($this->_totalResults->getDOM($element->ownerDocument)); - } - if ($this->_startIndex != null) { - $element->appendChild($this->_startIndex->getDOM($element->ownerDocument)); - } - if ($this->_itemsPerPage != null) { - $element->appendChild($this->_itemsPerPage->getDOM($element->ownerDocument)); - } - - // ETags are special. We only support them in protocol >= 2.X. - // This will be duplicated by the HTTP ETag header. - if ($majorVersion >= 2) { - if ($this->_etag != null) { - $element->setAttributeNS($this->lookupNamespace('gd'), - 'gd:etag', - $this->_etag); - } - } - - return $element; - } - - /** - * Creates individual Entry objects of the appropriate type and - * stores them in the $_entry array based upon DOM data. - * - * @param DOMNode $child The DOMNode to process - */ - protected function takeChildFromDOM($child) - { - $absoluteNodeName = $child->namespaceURI . ':' . $child->localName; - switch ($absoluteNodeName) { - case $this->lookupNamespace('openSearch') . ':' . 'totalResults': - $totalResults = new Zend_Gdata_Extension_OpenSearchTotalResults(); - $totalResults->transferFromDOM($child); - $this->_totalResults = $totalResults; - break; - case $this->lookupNamespace('openSearch') . ':' . 'startIndex': - $startIndex = new Zend_Gdata_Extension_OpenSearchStartIndex(); - $startIndex->transferFromDOM($child); - $this->_startIndex = $startIndex; - break; - case $this->lookupNamespace('openSearch') . ':' . 'itemsPerPage': - $itemsPerPage = new Zend_Gdata_Extension_OpenSearchItemsPerPage(); - $itemsPerPage->transferFromDOM($child); - $this->_itemsPerPage = $itemsPerPage; - break; - default: - parent::takeChildFromDOM($child); - break; - } - } - - /** - * Given a DOMNode representing an attribute, tries to map the data into - * instance members. If no mapping is defined, the name and value are - * stored in an array. - * - * @param DOMNode $attribute The DOMNode attribute needed to be handled - */ - protected function takeAttributeFromDOM($attribute) - { - switch ($attribute->localName) { - case 'etag': - // ETags are special, since they can be conveyed by either the - // HTTP ETag header or as an XML attribute. - $etag = $attribute->nodeValue; - if ($this->_etag === null) { - $this->_etag = $etag; - } - elseif ($this->_etag != $etag) { - #require_once('Zend/Gdata/App/IOException.php'); - throw new Zend_Gdata_App_IOException("ETag mismatch"); - } - break; - default: - parent::takeAttributeFromDOM($attribute); - break; - } - } - - /** - * Set the value of the totalResults property. - * - * @param Zend_Gdata_Extension_OpenSearchTotalResults|null $value The - * value of the totalResults property. Use null to unset. - * @return Zend_Gdata_Feed Provides a fluent interface. - */ - function setTotalResults($value) { - $this->_totalResults = $value; - return $this; - } - - /** - * Get the value of the totalResults property. - * - * @return Zend_Gdata_Extension_OpenSearchTotalResults|null The value of - * the totalResults property, or null if unset. - */ - function getTotalResults() { - return $this->_totalResults; - } - - /** - * Set the start index property for feed paging. - * - * @param Zend_Gdata_Extension_OpenSearchStartIndex|null $value The value - * for the startIndex property. Use null to unset. - * @return Zend_Gdata_Feed Provides a fluent interface. - */ - function setStartIndex($value) { - $this->_startIndex = $value; - return $this; - } - - /** - * Get the value of the startIndex property. - * - * @return Zend_Gdata_Extension_OpenSearchStartIndex|null The value of the - * startIndex property, or null if unset. - */ - function getStartIndex() { - return $this->_startIndex; - } - - /** - * Set the itemsPerPage property. - * - * @param Zend_Gdata_Extension_OpenSearchItemsPerPage|null $value The - * value for the itemsPerPage property. Use nul to unset. - * @return Zend_Gdata_Feed Provides a fluent interface. - */ - function setItemsPerPage($value) { - $this->_itemsPerPage = $value; - return $this; - } - - /** - * Get the value of the itemsPerPage property. - * - * @return Zend_Gdata_Extension_OpenSearchItemsPerPage|null The value of - * the itemsPerPage property, or null if unset. - */ - function getItemsPerPage() { - return $this->_itemsPerPage; - } - -} diff --git a/library/Zend/Gdata/Gapps.php b/library/Zend/Gdata/Gapps.php deleted file mode 100644 index 59d998fbf1..0000000000 --- a/library/Zend/Gdata/Gapps.php +++ /dev/null @@ -1,1683 +0,0 @@ -registerPackage('Zend_Gdata_Gapps'); - $this->registerPackage('Zend_Gdata_Gapps_Extension'); - parent::__construct($client, $applicationId); - $this->_httpClient->setParameterPost('service', self::AUTH_SERVICE_NAME); - $this->_domain = $domain; - } - - /** - * Convert an exception to an ServiceException if an AppsForYourDomain - * XML document is contained within the original exception's HTTP - * response. If conversion fails, throw the original error. - * - * @param Zend_Gdata_Exception $e The exception to convert. - * @throws Zend_Gdata_Gapps_ServiceException - * @throws mixed - */ - public static function throwServiceExceptionIfDetected($e) { - // Check to make sure that there actually response! - // This can happen if the connection dies before the request - // completes. (See ZF-5949) - $response = $e->getResponse(); - if (!$response) { - #require_once('Zend/Gdata/App/IOException.php'); - throw new Zend_Gdata_App_IOException('No HTTP response received (possible connection failure)'); - } - - try { - // Check to see if there is an AppsForYourDomainErrors - // datastructure in the response. If so, convert it to - // an exception and throw it. - #require_once 'Zend/Gdata/Gapps/ServiceException.php'; - $error = new Zend_Gdata_Gapps_ServiceException(); - $error->importFromString($response->getBody()); - throw $error; - } catch (Zend_Gdata_App_Exception $e2) { - // Unable to convert the response to a ServiceException, - // most likely because the server didn't return an - // AppsForYourDomainErrors document. Throw the original - // exception. - throw $e; - } - } - - /** - * Imports a feed located at $uri. - * This method overrides the default behavior of Zend_Gdata_App, - * providing support for Zend_Gdata_Gapps_ServiceException. - * - * @param string $uri - * @param Zend_Http_Client $client (optional) The client used for - * communication - * @param string $className (optional) The class which is used as the - * return type - * @throws Zend_Gdata_App_Exception - * @throws Zend_Gdata_App_HttpException - * @throws Zend_Gdata_Gapps_ServiceException - * @return Zend_Gdata_App_Feed - */ - public static function import($uri, $client = null, $className='Zend_Gdata_App_Feed', $useObjectMapping = true) - { - try { - return parent::import($uri, $client, $className, $useObjectMapping); - } catch (Zend_Gdata_App_HttpException $e) { - self::throwServiceExceptionIfDetected($e); - } - } - - /** - * GET a URI using client object. - * This method overrides the default behavior of Zend_Gdata_App, - * providing support for Zend_Gdata_Gapps_ServiceException. - * - * @param string $uri GET URI - * @param array $extraHeaders Extra headers to add to the request, as an - * array of string-based key/value pairs. - * @throws Zend_Gdata_App_HttpException - * @throws Zend_Gdata_Gapps_ServiceException - * @return Zend_Http_Response - */ - public function get($uri, $extraHeaders = array()) - { - try { - return parent::get($uri, $extraHeaders); - } catch (Zend_Gdata_App_HttpException $e) { - self::throwServiceExceptionIfDetected($e); - } - } - - /** - * POST data with client object. - * This method overrides the default behavior of Zend_Gdata_App, - * providing support for Zend_Gdata_Gapps_ServiceException. - * - * @param mixed $data The Zend_Gdata_App_Entry or XML to post - * @param string $uri (optional) POST URI - * @param integer $remainingRedirects (optional) - * @param string $contentType Content-type of the data - * @param array $extraHaders Extra headers to add tot he request - * @return Zend_Http_Response - * @throws Zend_Gdata_App_HttpException - * @throws Zend_Gdata_App_InvalidArgumentException - * @throws Zend_Gdata_Gapps_ServiceException - */ - public function post($data, $uri = null, $remainingRedirects = null, - $contentType = null, $extraHeaders = null) - { - try { - return parent::post($data, $uri, $remainingRedirects, $contentType, $extraHeaders); - } catch (Zend_Gdata_App_HttpException $e) { - self::throwServiceExceptionIfDetected($e); - } - } - - /** - * PUT data with client object - * This method overrides the default behavior of Zend_Gdata_App, - * providing support for Zend_Gdata_Gapps_ServiceException. - * - * @param mixed $data The Zend_Gdata_App_Entry or XML to post - * @param string $uri (optional) PUT URI - * @param integer $remainingRedirects (optional) - * @param string $contentType Content-type of the data - * @param array $extraHaders Extra headers to add tot he request - * @return Zend_Http_Response - * @throws Zend_Gdata_App_HttpException - * @throws Zend_Gdata_App_InvalidArgumentException - * @throws Zend_Gdata_Gapps_ServiceException - */ - public function put($data, $uri = null, $remainingRedirects = null, - $contentType = null, $extraHeaders = null) - { - try { - return parent::put($data, $uri, $remainingRedirects, $contentType, $extraHeaders); - } catch (Zend_Gdata_App_HttpException $e) { - self::throwServiceExceptionIfDetected($e); - } - } - - /** - * DELETE entry with client object - * This method overrides the default behavior of Zend_Gdata_App, - * providing support for Zend_Gdata_Gapps_ServiceException. - * - * @param mixed $data The Zend_Gdata_App_Entry or URL to delete - * @param integer $remainingRedirects (optional) - * @return void - * @throws Zend_Gdata_App_HttpException - * @throws Zend_Gdata_App_InvalidArgumentException - * @throws Zend_Gdata_Gapps_ServiceException - */ - public function delete($data, $remainingRedirects = null) - { - try { - return parent::delete($data, $remainingRedirects); - } catch (Zend_Gdata_App_HttpException $e) { - self::throwServiceExceptionIfDetected($e); - } - } - - /** - * Set domain for this service instance. This should be a fully qualified - * domain, such as 'foo.example.com'. - * - * This value is used when calculating URLs for retrieving and posting - * entries. If no value is specified, a URL will have to be manually - * constructed prior to using any methods which interact with the Google - * Apps provisioning service. - * - * @param string $value The domain to be used for this session. - */ - public function setDomain($value) - { - $this->_domain = $value; - } - - /** - * Get domain for this service instance. This should be a fully qualified - * domain, such as 'foo.example.com'. If no domain is set, null will be - * returned. - * - * @return string The domain to be used for this session, or null if not - * set. - */ - public function getDomain() - { - return $this->_domain; - } - - /** - * Returns the base URL used to access the Google Apps service, based - * on the current domain. The current domain can be temporarily - * overridden by providing a fully qualified domain as $domain. - * - * @param string $domain (optional) A fully-qualified domain to use - * instead of the default domain for this service instance. - * @throws Zend_Gdata_App_InvalidArgumentException - */ - public function getBaseUrl($domain = null) - { - if ($domain !== null) { - return self::APPS_BASE_FEED_URI . '/' . $domain; - } else if ($this->_domain !== null) { - return self::APPS_BASE_FEED_URI . '/' . $this->_domain; - } else { - #require_once 'Zend/Gdata/App/InvalidArgumentException.php'; - throw new Zend_Gdata_App_InvalidArgumentException( - 'Domain must be specified.'); - } - } - - /** - * Retrieve a UserFeed containing multiple UserEntry objects. - * - * @param mixed $location (optional) The location for the feed, as a URL - * or Query. - * @return Zend_Gdata_Gapps_UserFeed - * @throws Zend_Gdata_App_Exception - * @throws Zend_Gdata_App_HttpException - * @throws Zend_Gdata_Gapps_ServiceException - */ - public function getUserFeed($location = null) - { - if ($location === null) { - $uri = $this->getBaseUrl() . self::APPS_USER_PATH; - } else if ($location instanceof Zend_Gdata_Query) { - $uri = $location->getQueryUrl(); - } else { - $uri = $location; - } - return parent::getFeed($uri, 'Zend_Gdata_Gapps_UserFeed'); - } - - /** - * Retreive NicknameFeed object containing multiple NicknameEntry objects. - * - * @param mixed $location (optional) The location for the feed, as a URL - * or Query. - * @return Zend_Gdata_Gapps_NicknameFeed - * @throws Zend_Gdata_App_Exception - * @throws Zend_Gdata_App_HttpException - * @throws Zend_Gdata_Gapps_ServiceException - */ - public function getNicknameFeed($location = null) - { - if ($location === null) { - $uri = $this->getBaseUrl() . self::APPS_NICKNAME_PATH; - } else if ($location instanceof Zend_Gdata_Query) { - $uri = $location->getQueryUrl(); - } else { - $uri = $location; - } - return parent::getFeed($uri, 'Zend_Gdata_Gapps_NicknameFeed'); - } - - /** - * Retreive GroupFeed object containing multiple GroupEntry - * objects. - * - * @param mixed $location (optional) The location for the feed, as a URL - * or Query. - * @return Zend_Gdata_Gapps_GroupFeed - * @throws Zend_Gdata_App_Exception - * @throws Zend_Gdata_App_HttpException - * @throws Zend_Gdata_Gapps_ServiceException - */ - public function getGroupFeed($location = null) - { - if ($location === null) { - $uri = self::APPS_BASE_FEED_URI . self::APPS_GROUP_PATH . '/'; - $uri .= $this->getDomain(); - } else if ($location instanceof Zend_Gdata_Query) { - $uri = $location->getQueryUrl(); - } else { - $uri = $location; - } - return parent::getFeed($uri, 'Zend_Gdata_Gapps_GroupFeed'); - } - - /** - * Retreive MemberFeed object containing multiple MemberEntry - * objects. - * - * @param mixed $location (optional) The location for the feed, as a URL - * or Query. - * @return Zend_Gdata_Gapps_MemberFeed - * @throws Zend_Gdata_App_Exception - * @throws Zend_Gdata_App_HttpException - * @throws Zend_Gdata_Gapps_ServiceException - */ - public function getMemberFeed($location = null) - { - if ($location === null) { - #require_once 'Zend/Gdata/App/InvalidArgumentException.php'; - throw new Zend_Gdata_App_InvalidArgumentException( - 'Location must not be null'); - } else if ($location instanceof Zend_Gdata_Query) { - $uri = $location->getQueryUrl(); - } else { - $uri = $location; - } - return parent::getFeed($uri, 'Zend_Gdata_Gapps_MemberFeed'); - } - - /** - * Retreive OwnerFeed object containing multiple OwnerEntry - * objects. - * - * @param mixed $location (optional) The location for the feed, as a URL - * or Query. - * @return Zend_Gdata_Gapps_OwnerFeed - * @throws Zend_Gdata_App_Exception - * @throws Zend_Gdata_App_HttpException - * @throws Zend_Gdata_Gapps_ServiceException - */ - public function getOwnerFeed($location = null) - { - if ($location === null) { - #require_once 'Zend/Gdata/App/InvalidArgumentException.php'; - throw new Zend_Gdata_App_InvalidArgumentException( - 'Location must not be null'); - } else if ($location instanceof Zend_Gdata_Query) { - $uri = $location->getQueryUrl(); - } else { - $uri = $location; - } - return parent::getFeed($uri, 'Zend_Gdata_Gapps_OwnerFeed'); - } - - /** - * Retreive EmailListFeed object containing multiple EmailListEntry - * objects. - * - * @param mixed $location (optional) The location for the feed, as a URL - * or Query. - * @return Zend_Gdata_Gapps_EmailListFeed - * @throws Zend_Gdata_App_Exception - * @throws Zend_Gdata_App_HttpException - * @throws Zend_Gdata_Gapps_ServiceException - */ - public function getEmailListFeed($location = null) - { - if ($location === null) { - $uri = $this->getBaseUrl() . self::APPS_NICKNAME_PATH; - } else if ($location instanceof Zend_Gdata_Query) { - $uri = $location->getQueryUrl(); - } else { - $uri = $location; - } - return parent::getFeed($uri, 'Zend_Gdata_Gapps_EmailListFeed'); - } - - /** - * Retreive EmailListRecipientFeed object containing multiple - * EmailListRecipientEntry objects. - * - * @param mixed $location The location for the feed, as a URL or Query. - * @return Zend_Gdata_Gapps_EmailListRecipientFeed - * @throws Zend_Gdata_App_Exception - * @throws Zend_Gdata_App_HttpException - * @throws Zend_Gdata_Gapps_ServiceException - */ - public function getEmailListRecipientFeed($location) - { - if ($location === null) { - #require_once 'Zend/Gdata/App/InvalidArgumentException.php'; - throw new Zend_Gdata_App_InvalidArgumentException( - 'Location must not be null'); - } else if ($location instanceof Zend_Gdata_Query) { - $uri = $location->getQueryUrl(); - } else { - $uri = $location; - } - return parent::getFeed($uri, 'Zend_Gdata_Gapps_EmailListRecipientFeed'); - } - - /** - * Retreive a single UserEntry object. - * - * @param mixed $location The location for the feed, as a URL or Query. - * @return Zend_Gdata_Gapps_UserEntry - * @throws Zend_Gdata_App_Exception - * @throws Zend_Gdata_App_HttpException - * @throws Zend_Gdata_Gapps_ServiceException - */ - public function getUserEntry($location) - { - if ($location === null) { - #require_once 'Zend/Gdata/App/InvalidArgumentException.php'; - throw new Zend_Gdata_App_InvalidArgumentException( - 'Location must not be null'); - } else if ($location instanceof Zend_Gdata_Query) { - $uri = $location->getQueryUrl(); - } else { - $uri = $location; - } - return parent::getEntry($uri, 'Zend_Gdata_Gapps_UserEntry'); - } - - /** - * Retreive a single NicknameEntry object. - * - * @param mixed $location The location for the feed, as a URL or Query. - * @return Zend_Gdata_Gapps_NicknameEntry - * @throws Zend_Gdata_App_Exception - * @throws Zend_Gdata_App_HttpException - * @throws Zend_Gdata_Gapps_ServiceException - */ - public function getNicknameEntry($location) - { - if ($location === null) { - #require_once 'Zend/Gdata/App/InvalidArgumentException.php'; - throw new Zend_Gdata_App_InvalidArgumentException( - 'Location must not be null'); - } else if ($location instanceof Zend_Gdata_Query) { - $uri = $location->getQueryUrl(); - } else { - $uri = $location; - } - return parent::getEntry($uri, 'Zend_Gdata_Gapps_NicknameEntry'); - } - - /** - * Retreive a single GroupEntry object. - * - * @param mixed $location The location for the feed, as a URL or Query. - * @return Zend_Gdata_Gapps_GroupEntry - * @throws Zend_Gdata_App_Exception - * @throws Zend_Gdata_App_HttpException - * @throws Zend_Gdata_Gapps_ServiceException - */ - public function getGroupEntry($location = null) - { - if ($location === null) { - #require_once 'Zend/Gdata/App/InvalidArgumentException.php'; - throw new Zend_Gdata_App_InvalidArgumentException( - 'Location must not be null'); - } else if ($location instanceof Zend_Gdata_Query) { - $uri = $location->getQueryUrl(); - } else { - $uri = $location; - } - return parent::getEntry($uri, 'Zend_Gdata_Gapps_GroupEntry'); - } - - /** - * Retreive a single MemberEntry object. - * - * @param mixed $location The location for the feed, as a URL or Query. - * @return Zend_Gdata_Gapps_MemberEntry - * @throws Zend_Gdata_App_Exception - * @throws Zend_Gdata_App_HttpException - * @throws Zend_Gdata_Gapps_ServiceException - */ - public function getMemberEntry($location = null) - { - if ($location === null) { - #require_once 'Zend/Gdata/App/InvalidArgumentException.php'; - throw new Zend_Gdata_App_InvalidArgumentException( - 'Location must not be null'); - } else if ($location instanceof Zend_Gdata_Query) { - $uri = $location->getQueryUrl(); - } else { - $uri = $location; - } - return parent::getEntry($uri, 'Zend_Gdata_Gapps_MemberEntry'); - } - - /** - * Retreive a single OwnerEntry object. - * - * @param mixed $location The location for the feed, as a URL or Query. - * @return Zend_Gdata_Gapps_OwnerEntry - * @throws Zend_Gdata_App_Exception - * @throws Zend_Gdata_App_HttpException - * @throws Zend_Gdata_Gapps_ServiceException - */ - public function getOwnerEntry($location = null) - { - if ($location === null) { - #require_once 'Zend/Gdata/App/InvalidArgumentException.php'; - throw new Zend_Gdata_App_InvalidArgumentException( - 'Location must not be null'); - } else if ($location instanceof Zend_Gdata_Query) { - $uri = $location->getQueryUrl(); - } else { - $uri = $location; - } - return parent::getEntry($uri, 'Zend_Gdata_Gapps_OwnerEntry'); - } - - /** - * Retreive a single EmailListEntry object. - * - * @param mixed $location The location for the feed, as a URL or Query. - * @return Zend_Gdata_Gapps_EmailListEntry - * @throws Zend_Gdata_App_Exception - * @throws Zend_Gdata_App_HttpException - * @throws Zend_Gdata_Gapps_ServiceException - */ - public function getEmailListEntry($location) - { - if ($location === null) { - #require_once 'Zend/Gdata/App/InvalidArgumentException.php'; - throw new Zend_Gdata_App_InvalidArgumentException( - 'Location must not be null'); - } else if ($location instanceof Zend_Gdata_Query) { - $uri = $location->getQueryUrl(); - } else { - $uri = $location; - } - return parent::getEntry($uri, 'Zend_Gdata_Gapps_EmailListEntry'); - } - - /** - * Retreive a single EmailListRecipientEntry object. - * - * @param mixed $location The location for the feed, as a URL or Query. - * @return Zend_Gdata_Gapps_EmailListRecipientEntry - * @throws Zend_Gdata_App_Exception - * @throws Zend_Gdata_App_HttpException - * @throws Zend_Gdata_Gapps_ServiceException - */ - public function getEmailListRecipientEntry($location) - { - if ($location === null) { - #require_once 'Zend/Gdata/App/InvalidArgumentException.php'; - throw new Zend_Gdata_App_InvalidArgumentException( - 'Location must not be null'); - } else if ($location instanceof Zend_Gdata_Query) { - $uri = $location->getQueryUrl(); - } else { - $uri = $location; - } - return parent::getEntry($uri, 'Zend_Gdata_Gapps_EmailListRecipientEntry'); - } - - /** - * Create a new user from a UserEntry. - * - * @param Zend_Gdata_Gapps_UserEntry $user The user entry to insert. - * @param string $uri (optional) The URI where the user should be - * uploaded to. If null, the default user creation URI for - * this domain will be used. - * @return Zend_Gdata_Gapps_UserEntry The inserted user entry as - * returned by the server. - * @throws Zend_Gdata_App_Exception - * @throws Zend_Gdata_App_HttpException - * @throws Zend_Gdata_Gapps_ServiceException - */ - public function insertUser($user, $uri = null) - { - if ($uri === null) { - $uri = $this->getBaseUrl() . self::APPS_USER_PATH; - } - $newEntry = $this->insertEntry($user, $uri, 'Zend_Gdata_Gapps_UserEntry'); - return $newEntry; - } - - /** - * Create a new nickname from a NicknameEntry. - * - * @param Zend_Gdata_Gapps_NicknameEntry $nickname The nickname entry to - * insert. - * @param string $uri (optional) The URI where the nickname should be - * uploaded to. If null, the default nickname creation URI for - * this domain will be used. - * @return Zend_Gdata_Gapps_NicknameEntry The inserted nickname entry as - * returned by the server. - * @throws Zend_Gdata_App_Exception - * @throws Zend_Gdata_App_HttpException - * @throws Zend_Gdata_Gapps_ServiceException - */ - public function insertNickname($nickname, $uri = null) - { - if ($uri === null) { - $uri = $this->getBaseUrl() . self::APPS_NICKNAME_PATH; - } - $newEntry = $this->insertEntry($nickname, $uri, 'Zend_Gdata_Gapps_NicknameEntry'); - return $newEntry; - } - - /** - * Create a new group from a GroupEntry. - * - * @param Zend_Gdata_Gapps_GroupEntry $group The group entry to insert. - * @param string $uri (optional) The URI where the group should be - * uploaded to. If null, the default user creation URI for - * this domain will be used. - * @return Zend_Gdata_Gapps_GroupEntry The inserted group entry as - * returned by the server. - * @throws Zend_Gdata_App_Exception - * @throws Zend_Gdata_App_HttpException - * @throws Zend_Gdata_Gapps_ServiceException - */ - public function insertGroup($group, $uri = null) - { - if ($uri === null) { - $uri = self::APPS_BASE_FEED_URI . self::APPS_GROUP_PATH . '/'; - $uri .= $this->getDomain(); - } - $newEntry = $this->insertEntry($group, $uri, 'Zend_Gdata_Gapps_GroupEntry'); - return $newEntry; - } - - /** - * Create a new member from a MemberEntry. - * - * @param Zend_Gdata_Gapps_MemberEntry $member The member entry to insert. - * @param string $uri (optional) The URI where the group should be - * uploaded to. If null, the default user creation URI for - * this domain will be used. - * @return Zend_Gdata_Gapps_MemberEntry The inserted member entry as - * returned by the server. - * @throws Zend_Gdata_App_Exception - * @throws Zend_Gdata_App_HttpException - * @throws Zend_Gdata_Gapps_ServiceException - */ - public function insertMember($member, $uri = null) - { - if ($uri === null) { - #require_once 'Zend/Gdata/App/InvalidArgumentException.php'; - throw new Zend_Gdata_App_InvalidArgumentException( - 'URI must not be null'); - } - $newEntry = $this->insertEntry($member, $uri, 'Zend_Gdata_Gapps_MemberEntry'); - return $newEntry; - } - - /** - * Create a new group from a OwnerEntry. - * - * @param Zend_Gdata_Gapps_OwnerEntry $owner The owner entry to insert. - * @param string $uri (optional) The URI where the owner should be - * uploaded to. If null, the default user creation URI for - * this domain will be used. - * @return Zend_Gdata_Gapps_OwnerEntry The inserted owner entry as - * returned by the server. - * @throws Zend_Gdata_App_Exception - * @throws Zend_Gdata_App_HttpException - * @throws Zend_Gdata_Gapps_ServiceException - */ - public function insertOwner($owner, $uri = null) - { - if ($uri === null) { - #require_once 'Zend/Gdata/App/InvalidArgumentException.php'; - throw new Zend_Gdata_App_InvalidArgumentException( - 'URI must not be null'); - } - $newEntry = $this->insertEntry($owner, $uri, 'Zend_Gdata_Gapps_OwnerEntry'); - return $newEntry; - } - - /** - * Create a new email list from an EmailListEntry. - * - * @param Zend_Gdata_Gapps_EmailListEntry $emailList The email list entry - * to insert. - * @param string $uri (optional) The URI where the email list should be - * uploaded to. If null, the default email list creation URI for - * this domain will be used. - * @return Zend_Gdata_Gapps_EmailListEntry The inserted email list entry - * as returned by the server. - * @throws Zend_Gdata_App_Exception - * @throws Zend_Gdata_App_HttpException - * @throws Zend_Gdata_Gapps_ServiceException - */ - public function insertEmailList($emailList, $uri = null) - { - if ($uri === null) { - $uri = $this->getBaseUrl() . self::APPS_EMAIL_LIST_PATH; - } - $newEntry = $this->insertEntry($emailList, $uri, 'Zend_Gdata_Gapps_EmailListEntry'); - return $newEntry; - } - - /** - * Create a new email list recipient from an EmailListRecipientEntry. - * - * @param Zend_Gdata_Gapps_EmailListRecipientEntry $recipient The recipient - * entry to insert. - * @param string $uri (optional) The URI where the recipient should be - * uploaded to. If null, the default recipient creation URI for - * this domain will be used. - * @return Zend_Gdata_Gapps_EmailListRecipientEntry The inserted - * recipient entry as returned by the server. - * @throws Zend_Gdata_App_Exception - * @throws Zend_Gdata_App_HttpException - * @throws Zend_Gdata_Gapps_ServiceException - */ - public function insertEmailListRecipient($recipient, $uri = null) - { - if ($uri === null) { - #require_once 'Zend/Gdata/App/InvalidArgumentException.php'; - throw new Zend_Gdata_App_InvalidArgumentException( - 'URI must not be null'); - } elseif ($uri instanceof Zend_Gdata_Gapps_EmailListEntry) { - $uri = $uri->getLink('edit')->href; - } - $newEntry = $this->insertEntry($recipient, $uri, 'Zend_Gdata_Gapps_EmailListRecipientEntry'); - return $newEntry; - } - - /** - * Provides a magic factory method to instantiate new objects with - * shorter syntax than would otherwise be required by the Zend Framework - * naming conventions. For more information, see Zend_Gdata_App::__call(). - * - * This overrides the default behavior of __call() so that query classes - * do not need to have their domain manually set when created with - * a magic factory method. - * - * @see Zend_Gdata_App::__call() - * @param string $method The method name being called - * @param array $args The arguments passed to the call - * @throws Zend_Gdata_App_Exception - */ - public function __call($method, $args) { - if (preg_match('/^new(\w+Query)/', $method, $matches)) { - $class = $matches[1]; - $foundClassName = null; - foreach ($this->_registeredPackages as $name) { - try { - // Autoloading disabled on next line for compatibility - // with magic factories. See ZF-6660. - if (!class_exists($name . '_' . $class, false)) { - #require_once 'Zend/Loader.php'; - @Zend_Loader::loadClass($name . '_' . $class); - } - $foundClassName = $name . '_' . $class; - break; - } catch (Zend_Exception $e) { - // package wasn't here- continue searching - } - } - if ($foundClassName != null) { - $reflectionObj = new ReflectionClass($foundClassName); - // Prepend the domain to the query - $args = array_merge(array($this->getDomain()), $args); - return $reflectionObj->newInstanceArgs($args); - } else { - #require_once 'Zend/Gdata/App/Exception.php'; - throw new Zend_Gdata_App_Exception( - "Unable to find '${class}' in registered packages"); - } - } else { - return parent::__call($method, $args); - } - - } - - // Convenience methods - // Specified at http://code.google.com/apis/apps/gdata_provisioning_api_v2.0_reference.html#appendix_e - - /** - * Create a new user entry and send it to the Google Apps servers. - * - * @param string $username The username for the new user. - * @param string $givenName The given name for the new user. - * @param string $familyName The family name for the new user. - * @param string $password The password for the new user as a plaintext string - * (if $passwordHashFunction is null) or a SHA-1 hashed - * value (if $passwordHashFunction = 'SHA-1'). - * @param string $quotaLimitInMB (optional) The quota limit for the new user in MB. - * @return Zend_Gdata_Gapps_UserEntry (optional) The new user entry as returned by - * server. - * @throws Zend_Gdata_App_Exception - * @throws Zend_Gdata_App_HttpException - * @throws Zend_Gdata_Gapps_ServiceException - */ - public function createUser ($username, $givenName, $familyName, $password, - $passwordHashFunction = null, $quotaLimitInMB = null) { - $user = $this->newUserEntry(); - $user->login = $this->newLogin(); - $user->login->username = $username; - $user->login->password = $password; - $user->login->hashFunctionName = $passwordHashFunction; - $user->name = $this->newName(); - $user->name->givenName = $givenName; - $user->name->familyName = $familyName; - if ($quotaLimitInMB !== null) { - $user->quota = $this->newQuota(); - $user->quota->limit = $quotaLimitInMB; - } - return $this->insertUser($user); - } - - /** - * Retrieve a user based on their username. - * - * @param string $username The username to search for. - * @return Zend_Gdata_Gapps_UserEntry The username to search for, or null - * if no match found. - * @throws Zend_Gdata_App_InvalidArgumentException - * @throws Zend_Gdata_App_HttpException - */ - public function retrieveUser ($username) { - $query = $this->newUserQuery($username); - try { - $user = $this->getUserEntry($query); - } catch (Zend_Gdata_Gapps_ServiceException $e) { - // Set the user to null if not found - if ($e->hasError(Zend_Gdata_Gapps_Error::ENTITY_DOES_NOT_EXIST)) { - $user = null; - } else { - throw $e; - } - } - return $user; - } - - /** - * Retrieve a page of users in alphabetical order, starting with the - * provided username. - * - * @param string $startUsername (optional) The first username to retrieve. - * If null or not declared, the page will begin with the first - * user in the domain. - * @return Zend_Gdata_Gapps_UserFeed Collection of Zend_Gdata_UserEntry - * objects representing all users in the domain. - * @throws Zend_Gdata_App_Exception - * @throws Zend_Gdata_App_HttpException - * @throws Zend_Gdata_Gapps_ServiceException - */ - public function retrievePageOfUsers ($startUsername = null) { - $query = $this->newUserQuery(); - $query->setStartUsername($startUsername); - return $this->getUserFeed($query); - } - - /** - * Retrieve all users in the current domain. Be aware that - * calling this function on a domain with many users will take a - * signifigant amount of time to complete. On larger domains this may - * may cause execution to timeout without proper precautions in place. - * - * @return Zend_Gdata_Gapps_UserFeed Collection of Zend_Gdata_UserEntry - * objects representing all users in the domain. - * @throws Zend_Gdata_App_Exception - * @throws Zend_Gdata_App_HttpException - * @throws Zend_Gdata_Gapps_ServiceException - */ - public function retrieveAllUsers () { - return $this->retrieveAllEntriesForFeed($this->retrievePageOfUsers()); - } - - /** - * Overwrite a specified username with the provided UserEntry. The - * UserEntry does not need to contain an edit link. - * - * This method is provided for compliance with the Google Apps - * Provisioning API specification. Normally users will instead want to - * call UserEntry::save() instead. - * - * @see Zend_Gdata_App_Entry::save - * @param string $username The username whose data will be overwritten. - * @param Zend_Gdata_Gapps_UserEntry $userEntry The user entry which - * will be overwritten. - * @return Zend_Gdata_Gapps_UserEntry The UserEntry returned by the - * server. - * @throws Zend_Gdata_App_Exception - * @throws Zend_Gdata_App_HttpException - * @throws Zend_Gdata_Gapps_ServiceException - */ - public function updateUser($username, $userEntry) { - return $this->updateEntry($userEntry, $this->getBaseUrl() . - self::APPS_USER_PATH . '/' . $username); - } - - /** - * Mark a given user as suspended. - * - * @param string $username The username associated with the user who - * should be suspended. - * @return Zend_Gdata_Gapps_UserEntry The UserEntry for the modified - * user. - * @throws Zend_Gdata_App_Exception - * @throws Zend_Gdata_App_HttpException - * @throws Zend_Gdata_Gapps_ServiceException - */ - public function suspendUser($username) { - $user = $this->retrieveUser($username); - $user->login->suspended = true; - return $user->save(); - } - - /** - * Mark a given user as not suspended. - * - * @param string $username The username associated with the user who - * should be restored. - * @return Zend_Gdata_Gapps_UserEntry The UserEntry for the modified - * user. - * @throws Zend_Gdata_App_Exception - * @throws Zend_Gdata_App_HttpException - * @throws Zend_Gdata_Gapps_ServiceException - */ - public function restoreUser($username) { - $user = $this->retrieveUser($username); - $user->login->suspended = false; - return $user->save(); - } - - /** - * Delete a user by username. - * - * @param string $username The username associated with the user who - * should be deleted. - * @throws Zend_Gdata_App_Exception - * @throws Zend_Gdata_App_HttpException - * @throws Zend_Gdata_Gapps_ServiceException - */ - public function deleteUser($username) { - $this->delete($this->getBaseUrl() . self::APPS_USER_PATH . '/' . - $username); - } - - /** - * Create a nickname for a given user. - * - * @param string $username The username to which the new nickname should - * be associated. - * @param string $nickname The new nickname to be created. - * @return Zend_Gdata_Gapps_NicknameEntry The nickname entry which was - * created by the server. - * @throws Zend_Gdata_App_Exception - * @throws Zend_Gdata_App_HttpException - * @throws Zend_Gdata_Gapps_ServiceException - */ - public function createNickname($username, $nickname) { - $entry = $this->newNicknameEntry(); - $nickname = $this->newNickname($nickname); - $login = $this->newLogin($username); - $entry->nickname = $nickname; - $entry->login = $login; - return $this->insertNickname($entry); - } - - /** - * Retrieve the entry for a specified nickname. - * - * @param string $nickname The nickname to be retrieved. - * @return Zend_Gdata_Gapps_NicknameEntry The requested nickname entry. - * @throws Zend_Gdata_App_Exception - * @throws Zend_Gdata_App_HttpException - * @throws Zend_Gdata_Gapps_ServiceException - */ - public function retrieveNickname($nickname) { - $query = $this->newNicknameQuery(); - $query->setNickname($nickname); - try { - $nickname = $this->getNicknameEntry($query); - } catch (Zend_Gdata_Gapps_ServiceException $e) { - // Set the nickname to null if not found - if ($e->hasError(Zend_Gdata_Gapps_Error::ENTITY_DOES_NOT_EXIST)) { - $nickname = null; - } else { - throw $e; - } - } - return $nickname; - } - - /** - * Retrieve all nicknames associated with a specific username. - * - * @param string $username The username whose nicknames should be - * returned. - * @return Zend_Gdata_Gapps_NicknameFeed A feed containing all nicknames - * for the given user, or null if - * @throws Zend_Gdata_App_Exception - * @throws Zend_Gdata_App_HttpException - * @throws Zend_Gdata_Gapps_ServiceException - */ - public function retrieveNicknames($username) { - $query = $this->newNicknameQuery(); - $query->setUsername($username); - $nicknameFeed = $this->retrieveAllEntriesForFeed( - $this->getNicknameFeed($query)); - return $nicknameFeed; - } - - /** - * Retrieve a page of nicknames in alphabetical order, starting with the - * provided nickname. - * - * @param string $startNickname (optional) The first nickname to - * retrieve. If null or not declared, the page will begin with - * the first nickname in the domain. - * @return Zend_Gdata_Gapps_NicknameFeed Collection of Zend_Gdata_NicknameEntry - * objects representing all nicknames in the domain. - * @throws Zend_Gdata_App_Exception - * @throws Zend_Gdata_App_HttpException - * @throws Zend_Gdata_Gapps_ServiceException - */ - public function retrievePageOfNicknames ($startNickname = null) { - $query = $this->newNicknameQuery(); - $query->setStartNickname($startNickname); - return $this->getNicknameFeed($query); - } - - /** - * Retrieve all nicknames in the current domain. Be aware that - * calling this function on a domain with many nicknames will take a - * signifigant amount of time to complete. On larger domains this may - * may cause execution to timeout without proper precautions in place. - * - * @return Zend_Gdata_Gapps_NicknameFeed Collection of Zend_Gdata_NicknameEntry - * objects representing all nicknames in the domain. - * @throws Zend_Gdata_App_Exception - * @throws Zend_Gdata_App_HttpException - * @throws Zend_Gdata_Gapps_ServiceException - */ - public function retrieveAllNicknames () { - return $this->retrieveAllEntriesForFeed($this->retrievePageOfNicknames()); - } - - /** - * Delete a specified nickname. - * - * @param string $nickname The name of the nickname to be deleted. - * @throws Zend_Gdata_App_Exception - * @throws Zend_Gdata_App_HttpException - * @throws Zend_Gdata_Gapps_ServiceException - */ - public function deleteNickname($nickname) { - $this->delete($this->getBaseUrl() . self::APPS_NICKNAME_PATH . '/' . $nickname); - } - - /** - * Create a new group. - * - * @param string $groupId A unique identifier for the group - * @param string $groupName The name of the group - * @param string $description A description of the group - * @param string $emailPermission The subscription permission of the group - * @return Zend_Gdata_Gapps_GroupEntry The group entry as created on the server. - */ - public function createGroup($groupId, $groupName, $description = null, $emailPermission = null) - { - $i = 0; - $group = $this->newGroupEntry(); - - $properties[$i] = $this->newProperty(); - $properties[$i]->name = 'groupId'; - $properties[$i]->value = $groupId; - $i++; - $properties[$i] = $this->newProperty(); - $properties[$i]->name = 'groupName'; - $properties[$i]->value = $groupName; - $i++; - - if($description != null) { - $properties[$i] = $this->newProperty(); - $properties[$i]->name = 'description'; - $properties[$i]->value = $description; - $i++; - } - - if($emailPermission != null) { - $properties[$i] = $this->newProperty(); - $properties[$i]->name = 'emailPermission'; - $properties[$i]->value = $emailPermission; - $i++; - } - - $group->property = $properties; - - return $this->insertGroup($group); - } - - /** - * Retrieves a group based on group id - * - * @param string $groupId The unique identifier for the group - * @return Zend_Gdata_Gapps_GroupEntry The group entry as returned by the server. - */ - public function retrieveGroup($groupId) - { - $query = $this->newGroupQuery($groupId); - //$query->setGroupId($groupId); - - try { - $group = $this->getGroupEntry($query); - } catch (Zend_Gdata_Gapps_ServiceException $e) { - // Set the group to null if not found - if ($e->hasError(Zend_Gdata_Gapps_Error::ENTITY_DOES_NOT_EXIST)) { - $group = null; - } else { - throw $e; - } - } - return $group; - } - - /** - * Retrieve all groups in the current domain. Be aware that - * calling this function on a domain with many groups will take a - * signifigant amount of time to complete. On larger domains this may - * may cause execution to timeout without proper precautions in place. - * - * @return Zend_Gdata_Gapps_GroupFeed Collection of Zend_Gdata_GroupEntry objects - * representing all groups apart of the domain. - */ - public function retrieveAllGroups() - { - return $this->retrieveAllEntriesForFeed($this->retrievePageOfGroups()); - } - - /** - * Delete a group - * - * @param string $groupId The unique identifier for the group - */ - public function deleteGroup($groupId) - { - $uri = self::APPS_BASE_FEED_URI . self::APPS_GROUP_PATH . '/'; - $uri .= $this->getDomain() . '/' . $groupId; - - $this->delete($uri); - } - - /** - * Check to see if a member id or group id is a member of group - * - * @param string $memberId Member id or group group id - * @param string $groupId Group to be checked for - * @return bool True, if given entity is a member - */ - public function isMember($memberId, $groupId) - { - $uri = self::APPS_BASE_FEED_URI . self::APPS_GROUP_PATH . '/'; - $uri .= $this->getDomain() . '/' . $groupId . '/member/' . $memberId; - - //if the enitiy is not a member, an exception is thrown - try { - $results = $this->get($uri); - } catch (Exception $e) { - $results = false; - } - - if($results) { - return TRUE; - } else { - return FALSE; - } - } - - /** - * Add an email address to a group as a member - * - * @param string $recipientAddress Email address, member id, or group id - * @param string $groupId The unique id of the group - * @return Zend_Gdata_Gapps_MemberEntry The member entry returned by the server - */ - public function addMemberToGroup($recipientAddress, $groupId) - { - $member = $this->newMemberEntry(); - - $properties[] = $this->newProperty(); - $properties[0]->name = 'memberId'; - $properties[0]->value = $recipientAddress; - - $member->property = $properties; - - $uri = self::APPS_BASE_FEED_URI . self::APPS_GROUP_PATH . '/'; - $uri .= $this->getDomain() . '/' . $groupId . '/member'; - - return $this->insertMember($member, $uri); - } - - /** - * Remove a member id from a group - * - * @param string $memberId Member id or group id - * @param string $groupId The unique id of the group - */ - public function removeMemberFromGroup($memberId, $groupId) - { - $uri = self::APPS_BASE_FEED_URI . self::APPS_GROUP_PATH . '/'; - $uri .= $this->getDomain() . '/' . $groupId . '/member/' . $memberId; - - return $this->delete($uri); - } - - /** - * Retrieves all the members of a group - * - * @param string $groupId The unique id of the group - * @return Zend_Gdata_Gapps_MemberFeed Collection of MemberEntry objects - * representing all members apart of the group. - */ - public function retrieveAllMembers($groupId) - { - return $this->retrieveAllEntriesForFeed( - $this->retrievePageOfMembers($groupId)); - } - - /** - * Add an email as an owner of a group - * - * @param string $email Owner's email - * @param string $groupId Group ownership to be checked for - * @return Zend_Gdata_Gapps_OwnerEntry The OwnerEntry returned by the server - */ - public function addOwnerToGroup($email, $groupId) - { - $owner = $this->newOwnerEntry(); - - $properties[] = $this->newProperty(); - $properties[0]->name = 'email'; - $properties[0]->value = $email; - - $owner->property = $properties; - - $uri = self::APPS_BASE_FEED_URI . self::APPS_GROUP_PATH . '/'; - $uri .= $this->getDomain() . '/' . $groupId . '/owner'; - - return $this->insertOwner($owner, $uri); - } - - /** - * Retrieves all the owners of a group - * - * @param string $groupId The unique identifier for the group - * @return Zend_Gdata_Gapps_OwnerFeed Collection of Zend_Gdata_OwnerEntry - * objects representing all owners apart of the group. - */ - public function retrieveGroupOwners($groupId) - { - $uri = self::APPS_BASE_FEED_URI . self::APPS_GROUP_PATH . '/'; - $uri .= $this->getDomain() . '/' . $groupId . '/owner'; - - return $this->getOwnerFeed($uri); - } - - /** - * Checks to see if an email is an owner of a group - * - * @param string $email Owner's email - * @param string $groupId Group ownership to be checked for - * @return bool True, if given entity is an owner - */ - public function isOwner($email, $groupId) - { - $uri = self::APPS_BASE_FEED_URI . self::APPS_GROUP_PATH . '/'; - $uri .= $this->getDomain() . '/' . $groupId . '/owner/' . $email; - - //if the enitiy is not an owner of the group, an exception is thrown - try { - $results = $this->get($uri); - } catch (Exception $e) { - $results = false; - } - - if($results) { - return TRUE; - } else { - return FALSE; - } - } - - /** - * Remove email as an owner of a group - * - * @param string $email Owner's email - * @param string $groupId The unique identifier for the group - */ - public function removeOwnerFromGroup($email, $groupId) - { - $uri = self::APPS_BASE_FEED_URI . self::APPS_GROUP_PATH . '/'; - $uri .= $this->getDomain() . '/' . $groupId . '/owner/' . $email; - - return $this->delete($uri); - } - - /** - * Update group properties with new values. any property not defined will not - * be updated - * - * @param string $groupId A unique identifier for the group - * @param string $groupName The name of the group - * @param string $description A description of the group - * @param string $emailPermission The subscription permission of the group - * @return Zend_Gdata_Gapps_GroupEntry The group entry as updated on the server. - */ - public function updateGroup($groupId, $groupName = null, $description = null, - $emailPermission = null) - { - $i = 0; - $group = $this->newGroupEntry(); - - $properties[$i] = $this->newProperty(); - $properties[$i]->name = 'groupId'; - $properties[$i]->value = $groupId; - $i++; - - if($groupName != null) { - $properties[$i] = $this->newProperty(); - $properties[$i]->name = 'groupName'; - $properties[$i]->value = $groupName; - $i++; - } - - if($description != null) { - $properties[$i] = $this->newProperty(); - $properties[$i]->name = 'description'; - $properties[$i]->value = $description; - $i++; - } - - if($emailPermission != null) { - $properties[$i] = $this->newProperty(); - $properties[$i]->name = 'emailPermission'; - $properties[$i]->value = $emailPermission; - $i++; - } - - $group->property = $properties; - - $uri = self::APPS_BASE_FEED_URI . self::APPS_GROUP_PATH . '/'; - $uri .= $this->getDomain() . '/' . $groupId; - - return $this->updateEntry($group, $uri, 'Zend_Gdata_Gapps_GroupEntry'); - } - - /** - * Retrieve all of the groups that a user is a member of - * - * @param string $memberId Member username - * @param bool $directOnly (Optional) If true, members with direct association - * only will be considered - * @return Zend_Gdata_Gapps_GroupFeed Collection of Zend_Gdata_GroupEntry - * objects representing all groups member is apart of in the domain. - */ - public function retrieveGroups($memberId, $directOnly = null) - { - $query = $this->newGroupQuery(); - $query->setMember($memberId); - if($directOnly != null) { - $query->setDirectOnly($directOnly); - } - return $this->getGroupFeed($query); - } - - /** - * Retrieve a page of groups in alphabetical order, starting with the - * provided group. - * - * @param string $startGroup (optional) The first group to - * retrieve. If null or not defined, the page will begin - * with the first group in the domain. - * @return Zend_Gdata_Gapps_GroupFeed Collection of Zend_Gdata_GroupEntry - * objects representing the groups in the domain. - * @throws Zend_Gdata_App_Exception - * @throws Zend_Gdata_App_HttpException - * @throws Zend_Gdata_Gapps_ServiceException - */ - public function retrievePageOfGroups ($startGroup = null) - { - $query = $this->newGroupQuery(); - $query->setStartGroupId($startGroup); - return $this->getGroupFeed($query); - } - - /** - * Gets page of Members - * - * @param string $groupId The group id which should be searched. - * @param string $startMember (optinal) The address of the first member, - * or null to start with the first member in the list. - * @return Zend_Gdata_Gapps_MemberFeed Collection of Zend_Gdata_MemberEntry - * objects - */ - public function retrievePageOfMembers($groupId, $startMember = null) - { - $query = $this->newMemberQuery($groupId); - $query->setStartMemberId($startMember); - return $this->getMemberFeed($query); - } - - /** - * Create a new email list. - * - * @param string $emailList The name of the email list to be created. - * @return Zend_Gdata_Gapps_EmailListEntry The email list entry - * as created on the server. - * @throws Zend_Gdata_App_Exception - * @throws Zend_Gdata_App_HttpException - * @throws Zend_Gdata_Gapps_ServiceException - */ - public function createEmailList($emailList) { - $entry = $this->newEmailListEntry(); - $list = $this->newEmailList(); - $list->name = $emailList; - $entry->emailList = $list; - return $this->insertEmailList($entry); - } - - /** - * Retrieve all email lists associated with a recipient. - * - * @param string $username The recipient whose associated email lists - * should be returned. - * @return Zend_Gdata_Gapps_EmailListFeed The list of email lists found as - * Zend_Gdata_EmailListEntry objects. - * @throws Zend_Gdata_App_Exception - * @throws Zend_Gdata_App_HttpException - * @throws Zend_Gdata_Gapps_ServiceException - */ - public function retrieveEmailLists($recipient) { - $query = $this->newEmailListQuery(); - $query->recipient = $recipient; - return $this->getEmailListFeed($query); - } - - /** - * Retrieve a page of email lists in alphabetical order, starting with the - * provided email list. - * - * @param string $startEmailListName (optional) The first list to - * retrieve. If null or not defined, the page will begin - * with the first email list in the domain. - * @return Zend_Gdata_Gapps_EmailListFeed Collection of Zend_Gdata_EmailListEntry - * objects representing all nicknames in the domain. - * @throws Zend_Gdata_App_Exception - * @throws Zend_Gdata_App_HttpException - * @throws Zend_Gdata_Gapps_ServiceException - */ - public function retrievePageOfEmailLists ($startNickname = null) { - $query = $this->newEmailListQuery(); - $query->setStartEmailListName($startNickname); - return $this->getEmailListFeed($query); - } - - /** - * Retrieve all email lists associated with the curent domain. Be aware that - * calling this function on a domain with many email lists will take a - * signifigant amount of time to complete. On larger domains this may - * may cause execution to timeout without proper precautions in place. - * - * @return Zend_Gdata_Gapps_EmailListFeed The list of email lists found - * as Zend_Gdata_Gapps_EmailListEntry objects. - * @throws Zend_Gdata_App_Exception - * @throws Zend_Gdata_App_HttpException - * @throws Zend_Gdata_Gapps_ServiceException - */ - public function retrieveAllEmailLists() { - return $this->retrieveAllEntriesForFeed($this->retrievePageOfEmailLists()); - } - - /** - * Delete a specified email list. - * - * @param string $emailList The name of the emailList to be deleted. - * @throws Zend_Gdata_App_Exception - * @throws Zend_Gdata_App_HttpException - * @throws Zend_Gdata_Gapps_ServiceException - */ - public function deleteEmailList($emailList) { - $this->delete($this->getBaseUrl() . self::APPS_EMAIL_LIST_PATH . '/' - . $emailList); - } - - /** - * Add a specified recipient to an existing emailList. - * - * @param string $recipientAddress The address of the recipient to be - * added to the email list. - * @param string $emailList The name of the email address to which the - * recipient should be added. - * @return Zend_Gdata_Gapps_EmailListRecipientEntry The recipient entry - * created by the server. - * @throws Zend_Gdata_App_Exception - * @throws Zend_Gdata_App_HttpException - * @throws Zend_Gdata_Gapps_ServiceException - */ - public function addRecipientToEmailList($recipientAddress, $emailList) { - $entry = $this->newEmailListRecipientEntry(); - $who = $this->newWho(); - $who->email = $recipientAddress; - $entry->who = $who; - $address = $this->getBaseUrl() . self::APPS_EMAIL_LIST_PATH . '/' . - $emailList . self::APPS_EMAIL_LIST_RECIPIENT_POSTFIX . '/'; - return $this->insertEmailListRecipient($entry, $address); - } - - /** - * Retrieve a page of email list recipients in alphabetical order, - * starting with the provided email list recipient. - * - * @param string $emaiList The email list which should be searched. - * @param string $startRecipient (optinal) The address of the first - * recipient, or null to start with the first recipient in - * the list. - * @return Zend_Gdata_Gapps_EmailListRecipientFeed Collection of - * Zend_Gdata_EmailListRecipientEntry objects representing all - * recpients in the specified list. - * @throws Zend_Gdata_App_Exception - * @throws Zend_Gdata_App_HttpException - * @throws Zend_Gdata_Gapps_ServiceException - */ - public function retrievePageOfRecipients ($emailList, - $startRecipient = null) { - $query = $this->newEmailListRecipientQuery(); - $query->setEmailListName($emailList); - $query->setStartRecipient($startRecipient); - return $this->getEmailListRecipientFeed($query); - } - - /** - * Retrieve all recipients associated with an email list. Be aware that - * calling this function on a domain with many email lists will take a - * signifigant amount of time to complete. On larger domains this may - * may cause execution to timeout without proper precautions in place. - * - * @param string $emaiList The email list which should be searched. - * @return Zend_Gdata_Gapps_EmailListRecipientFeed The list of email lists - * found as Zend_Gdata_Gapps_EmailListRecipientEntry objects. - * @throws Zend_Gdata_App_Exception - * @throws Zend_Gdata_App_HttpException - * @throws Zend_Gdata_Gapps_ServiceException - */ - public function retrieveAllRecipients($emailList) { - return $this->retrieveAllEntriesForFeed( - $this->retrievePageOfRecipients($emailList)); - } - - /** - * Remove a specified recipient from an email list. - * - * @param string $recipientAddress The recipient to be removed. - * @param string $emailList The list from which the recipient should - * be removed. - * @throws Zend_Gdata_App_Exception - * @throws Zend_Gdata_App_HttpException - * @throws Zend_Gdata_Gapps_ServiceException - */ - public function removeRecipientFromEmailList($recipientAddress, $emailList) { - $this->delete($this->getBaseUrl() . self::APPS_EMAIL_LIST_PATH . '/' - . $emailList . self::APPS_EMAIL_LIST_RECIPIENT_POSTFIX . '/' - . $recipientAddress); - } - -} diff --git a/library/Zend/Gdata/Gapps/EmailListEntry.php b/library/Zend/Gdata/Gapps/EmailListEntry.php deleted file mode 100644 index 9a20595511..0000000000 --- a/library/Zend/Gdata/Gapps/EmailListEntry.php +++ /dev/null @@ -1,214 +0,0 @@ - in the Google Data protocol. - * - * @category Zend - * @package Zend_Gdata - * @subpackage Gapps - * @copyright Copyright (c) 2005-2015 Zend Technologies USA Inc. (http://www.zend.com) - * @license http://framework.zend.com/license/new-bsd New BSD License - */ -class Zend_Gdata_Gapps_EmailListEntry extends Zend_Gdata_Entry -{ - - protected $_entryClassName = 'Zend_Gdata_Gapps_EmailListEntry'; - - /** - * child element containing general information about - * this email list. - * - * @var Zend_Gdata_Gapps_Extension_EmailList - */ - protected $_emailList = null; - - /** - * element containing information about other feeds - * relevant to this entry. - * - * @var Zend_Gdata_Extension_FeedLink - */ - protected $_feedLink = array(); - - /** - * Create a new instance. - * - * @param DOMElement $element (optional) DOMElement from which this - * object should be constructed. - */ - public function __construct($element = null) - { - $this->registerAllNamespaces(Zend_Gdata_Gapps::$namespaces); - parent::__construct($element); - } - - /** - * Retrieves a DOMElement which corresponds to this element and all - * child properties. This is used to build an entry back into a DOM - * and eventually XML text for application storage/persistence. - * - * @param DOMDocument $doc The DOMDocument used to construct DOMElements - * @return DOMElement The DOMElement representing this element and all - * child properties. - */ - public function getDOM($doc = null, $majorVersion = 1, $minorVersion = null) - { - $element = parent::getDOM($doc, $majorVersion, $minorVersion); - if ($this->_emailList !== null) { - $element->appendChild($this->_emailList->getDOM($element->ownerDocument)); - } - foreach ($this->_feedLink as $feedLink) { - $element->appendChild($feedLink->getDOM($element->ownerDocument)); - } - return $element; - } - - /** - * Creates individual Entry objects of the appropriate type and - * stores them as members of this entry based upon DOM data. - * - * @param DOMNode $child The DOMNode to process - */ - protected function takeChildFromDOM($child) - { - $absoluteNodeName = $child->namespaceURI . ':' . $child->localName; - - switch ($absoluteNodeName) { - case $this->lookupNamespace('apps') . ':' . 'emailList'; - $emailList = new Zend_Gdata_Gapps_Extension_EmailList(); - $emailList->transferFromDOM($child); - $this->_emailList = $emailList; - break; - case $this->lookupNamespace('gd') . ':' . 'feedLink'; - $feedLink = new Zend_Gdata_Extension_FeedLink(); - $feedLink->transferFromDOM($child); - $this->_feedLink[] = $feedLink; - break; - default: - parent::takeChildFromDOM($child); - break; - } - } - - /** - * Retrieve the email list property for this entry. - * - * @see setEmailList - * @return Zend_Gdata_Gapps_Extension_EmailList The requested object - * or null if not set. - */ - public function getEmailList() - { - return $this->_emailList; - } - - /** - * Set the email list property for this entry. This property contains - * information such as the name of this email list. - * - * This corresponds to the property in the Google Data - * protocol. - * - * @param Zend_Gdata_Gapps_Extension_EmailList $value The desired value - * this element, or null to unset. - * @return Zend_Gdata_Gapps_EventEntry Provides a fluent interface - */ - public function setEmailList($value) - { - $this->_emailList = $value; - return $this; - } - - /** - * Get the feed link property for this entry. - * - * @see setFeedLink - * @param string $rel (optional) The rel value of the link to be found. - * If null, the array of links is returned. - * @return mixed If $rel is specified, a Zend_Gdata_Extension_FeedLink - * object corresponding to the requested rel value is returned - * if found, or null if the requested value is not found. If - * $rel is null or not specified, an array of all available - * feed links for this entry is returned, or null if no feed - * links are set. - */ - public function getFeedLink($rel = null) - { - if ($rel == null) { - return $this->_feedLink; - } else { - foreach ($this->_feedLink as $feedLink) { - if ($feedLink->rel == $rel) { - return $feedLink; - } - } - return null; - } - } - - /** - * Set the feed link property for this entry. Feed links provide - * information about other feeds associated with this entry. - * - * This corresponds to the property in the Google Data - * protocol. - * - * @param array $value A collection of Zend_Gdata_Gapps_Extension_FeedLink - * instances representing all feed links for this entry, or - * null to unset. - * @return Zend_Gdata_Gapps_EventEntry Provides a fluent interface - */ - public function setFeedLink($value) - { - $this->_feedLink = $value; - return $this; - } - -} diff --git a/library/Zend/Gdata/Gapps/EmailListFeed.php b/library/Zend/Gdata/Gapps/EmailListFeed.php deleted file mode 100644 index af7b10c899..0000000000 --- a/library/Zend/Gdata/Gapps/EmailListFeed.php +++ /dev/null @@ -1,53 +0,0 @@ -setEmailListName($emailListName); - $this->setRecipient($recipient); - $this->setStartEmailListName($startEmailListName); - } - - /** - * Set the email list name to query for. When set, only lists with a name - * matching this value will be returned in search results. Set to - * null to disable filtering by list name. - * - * @param string $value The email list name to filter search results by, - * or null to disable. - */ - public function setEmailListName($value) - { - $this->_emailListName = $value; - } - - /** - * Get the email list name to query for. If no name is set, null will be - * returned. - * - * @see setEmailListName - * @return string The email list name to filter search results by, or null - * if disabled. - */ - public function getEmailListName() - { - return $this->_emailListName; - } - - /** - * Set the recipient to query for. When set, only subscribers with an - * email address matching this value will be returned in search results. - * Set to null to disable filtering by username. - * - * @param string $value The recipient email address to filter search - * results by, or null to disable. - */ - public function setRecipient($value) - { - if ($value !== null) { - $this->_params['recipient'] = $value; - } - else { - unset($this->_params['recipient']); - } - } - - /** - * Get the recipient email address to query for. If no recipient is set, - * null will be returned. - * - * @see setRecipient - * @return string The recipient email address to filter search results by, - * or null if disabled. - */ - public function getRecipient() - { - if (array_key_exists('recipient', $this->_params)) { - return $this->_params['recipient']; - } else { - return null; - } - } - - /** - * Set the first email list which should be displayed when retrieving - * a list of email lists. - * - * @param string $value The first email list to be returned, or null to - * disable. - */ - public function setStartEmailListName($value) - { - if ($value !== null) { - $this->_params['startEmailListName'] = $value; - } else { - unset($this->_params['startEmailListName']); - } - } - - /** - * Get the first email list which should be displayed when retrieving - * a list of email lists. - * - * @return string The first email list to be returned, or null to - * disable. - */ - public function getStartEmailListName() - { - if (array_key_exists('startEmailListName', $this->_params)) { - return $this->_params['startEmailListName']; - } else { - return null; - } - } - - /** - * Returns the URL generated for this query, based on it's current - * parameters. - * - * @return string A URL generated based on the state of this query. - * @throws Zend_Gdata_App_InvalidArgumentException - */ - public function getQueryUrl() - { - - $uri = $this->getBaseUrl(); - $uri .= Zend_Gdata_Gapps::APPS_EMAIL_LIST_PATH; - if ($this->_emailListName !== null) { - $uri .= '/' . $this->_emailListName; - } - $uri .= $this->getQueryString(); - return $uri; - } - -} diff --git a/library/Zend/Gdata/Gapps/EmailListRecipientEntry.php b/library/Zend/Gdata/Gapps/EmailListRecipientEntry.php deleted file mode 100644 index e1dd0af31e..0000000000 --- a/library/Zend/Gdata/Gapps/EmailListRecipientEntry.php +++ /dev/null @@ -1,146 +0,0 @@ - in the Google Data protocol. - * - * @category Zend - * @package Zend_Gdata - * @subpackage Gapps - * @copyright Copyright (c) 2005-2015 Zend Technologies USA Inc. (http://www.zend.com) - * @license http://framework.zend.com/license/new-bsd New BSD License - */ -class Zend_Gdata_Gapps_EmailListRecipientEntry extends Zend_Gdata_Entry -{ - - protected $_entryClassName = 'Zend_Gdata_Gapps_EmailListRecipientEntry'; - - /** - * element used to store the email address of the current - * recipient. Only the email property of this element should be - * populated. - * - * @var Zend_Gdata_Extension_Who - */ - protected $_who = null; - - /** - * Create a new instance. - * - * @param DOMElement $element (optional) DOMElement from which this - * object should be constructed. - */ - public function __construct($element = null) - { - $this->registerAllNamespaces(Zend_Gdata_Gapps::$namespaces); - parent::__construct($element); - } - - /** - * Retrieves a DOMElement which corresponds to this element and all - * child properties. This is used to build an entry back into a DOM - * and eventually XML text for application storage/persistence. - * - * @param DOMDocument $doc The DOMDocument used to construct DOMElements - * @return DOMElement The DOMElement representing this element and all - * child properties. - */ - public function getDOM($doc = null, $majorVersion = 1, $minorVersion = null) - { - $element = parent::getDOM($doc, $majorVersion, $minorVersion); - if ($this->_who !== null) { - $element->appendChild($this->_who->getDOM($element->ownerDocument)); - } - return $element; - } - - /** - * Creates individual Entry objects of the appropriate type and - * stores them as members of this entry based upon DOM data. - * - * @param DOMNode $child The DOMNode to process - */ - protected function takeChildFromDOM($child) - { - $absoluteNodeName = $child->namespaceURI . ':' . $child->localName; - - switch ($absoluteNodeName) { - case $this->lookupNamespace('gd') . ':' . 'who'; - $who = new Zend_Gdata_Extension_Who(); - $who->transferFromDOM($child); - $this->_who = $who; - break; - default: - parent::takeChildFromDOM($child); - break; - } - } - - /** - * Get the value of the who property for this object. - * - * @see setWho - * @return Zend_Gdata_Extension_Who The requested object. - */ - public function getWho() - { - return $this->_who; - } - - /** - * Set the value of the who property for this object. This property - * is used to store the email address of the current recipient. - * - * @param Zend_Gdata_Extension_Who $value The desired value for this - * instance's who property. - * @return Zend_Gdata_Gapps_EventEntry Provides a fluent interface. - */ - public function setWho($value) - { - $this->_who = $value; - return $this; - } - -} diff --git a/library/Zend/Gdata/Gapps/EmailListRecipientFeed.php b/library/Zend/Gdata/Gapps/EmailListRecipientFeed.php deleted file mode 100644 index e5327bcfa4..0000000000 --- a/library/Zend/Gdata/Gapps/EmailListRecipientFeed.php +++ /dev/null @@ -1,53 +0,0 @@ -setEmailListName($emailListName); - $this->setStartRecipient($startRecipient); - } - - /** - * Set the email list name to query for. When set, only lists with a name - * matching this value will be returned in search results. Set to - * null to disable filtering by list name. - * - * @param string $value The email list name to filter search results by, - * or null to disable. - */ - public function setEmailListName($value) - { - $this->_emailListName = $value; - } - - /** - * Get the email list name to query for. If no name is set, null will be - * returned. - * - * @param string $value The email list name to filter search results by, - * or null if disabled. - */ - public function getEmailListName() - { - return $this->_emailListName; - } - - /** - * Set the first recipient which should be displayed when retrieving - * a list of email list recipients. - * - * @param string $value The first recipient to be returned, or null to - * disable. - */ - public function setStartRecipient($value) - { - if ($value !== null) { - $this->_params['startRecipient'] = $value; - } else { - unset($this->_params['startRecipient']); - } - } - - /** - * Get the first recipient which should be displayed when retrieving - * a list of email list recipients. - * - * @return string The first recipient to be returned, or null if - * disabled. - */ - public function getStartRecipient() - { - if (array_key_exists('startRecipient', $this->_params)) { - return $this->_params['startRecipient']; - } else { - return null; - } - } - - /** - * Returns the URL generated for this query, based on it's current - * parameters. - * - * @return string A URL generated based on the state of this query. - * @throws Zend_Gdata_App_InvalidArgumentException - */ - public function getQueryUrl() - { - - $uri = $this->getBaseUrl(); - $uri .= Zend_Gdata_Gapps::APPS_EMAIL_LIST_PATH; - if ($this->_emailListName !== null) { - $uri .= '/' . $this->_emailListName; - } else { - #require_once 'Zend/Gdata/App/InvalidArgumentException.php'; - throw new Zend_Gdata_App_InvalidArgumentException( - 'EmailListName must not be null'); - } - $uri .= Zend_Gdata_Gapps::APPS_EMAIL_LIST_RECIPIENT_POSTFIX . '/'; - $uri .= $this->getQueryString(); - return $uri; - } - -} diff --git a/library/Zend/Gdata/Gapps/Error.php b/library/Zend/Gdata/Gapps/Error.php deleted file mode 100644 index 7d49bfe6fc..0000000000 --- a/library/Zend/Gdata/Gapps/Error.php +++ /dev/null @@ -1,233 +0,0 @@ -_errorCode = $errorCode; - $this->_reason = $reason; - $this->_invalidInput = $invalidInput; - } - - /** - * Set the error code for this exception. For more information about - * error codes, see getErrorCode. - * - * @see getErrorCode - * @param integer $value The new value for the error code. - */ - public function setErrorCode($value) { - $this->_errorCode = $value; - } - - /** - * Get the error code for this exception. Currently valid values are - * available as constants within this class. These values are: - * - * UNKNOWN_ERROR (1000) - * USER_DELETED_RECENTLY (1100) - * USER_SUSPENDED (1101) - * DOMAIN_USER_LIMIT_EXCEEDED (1200) - * DOMAIN_ALIAS_LIMIT_EXCEEDED (1201) - * DOMAIN_SUSPENDED (1202) - * DOMAIN_FEATURE_UNAVAILABLE (1203) - * ENTITY_EXISTS (1300) - * ENTITY_DOES_NOT_EXIST (1301) - * ENTITY_NAME_IS_RESERVED (1302) - * ENTITY_NAME_NOT_VALID (1303) - * INVALID_GIVEN_NAME (1400) - * INVALID_FAMILY_NAME (1401) - * INVALID_PASSWORD (1402) - * INVALID_USERNAME (1403) - * INVALID_HASH_FUNCTION_NAME (1404) - * INVALID_HASH_DIGEST_LENGTH (1405) - * INVALID_EMAIL_ADDRESS (1406) - * INVALID_QUERY_PARAMETER_VALUE (1407) - * TOO_MANY_RECIPIENTS_ON_EMAIL_LIST (1500) - * - * Numbers in parenthesis indicate the actual integer value of the - * constant. This list should not be treated as exhaustive, as additional - * error codes may be added at any time. - * - * For more information about these codes and their meaning, please - * see Appendix D of the Google Apps Provisioning API Reference. - * - * @link http://code.google.com/apis/apps/gdata_provisioning_api_v2.0_reference.html#appendix_d Google Apps Provisioning API Reference: Appendix D - Gdata Error Codes - * @see setErrorCode - * @return integer The error code returned by the Google Apps server. - */ - public function getErrorCode() { - return $this->_errorCode; - } - - /** - * Set human-readable text describing the reason this exception occurred. - * - * @see getReason - * @param string $value The reason this exception occurred. - */ - public function setReason($value) { - $this->_reason = $value; - } - - /** - * Get human-readable text describing the reason this exception occurred. - * - * @see setReason - * @return string The reason this exception occurred. - */ - public function getReason() { - return $this->_reason; - } - - /** - * Set the invalid input which caused this exception. - * - * @see getInvalidInput - * @param string $value The invalid input that triggered this exception. - */ - public function setInvalidInput($value) { - $this->_invalidInput = $value; - } - - /** - * Set the invalid input which caused this exception. - * - * @see setInvalidInput - * @return string The reason this exception occurred. - */ - public function getInvalidInput() { - return $this->_invalidInput; - } - - /** - * Retrieves a DOMElement which corresponds to this element and all - * child properties. This is used to build an entry back into a DOM - * and eventually XML text for application storage/persistence. - * - * @param DOMDocument $doc The DOMDocument used to construct DOMElements - * @return DOMElement The DOMElement representing this element and all - * child properties. - */ - public function getDOM($doc = null, $majorVersion = 1, $minorVersion = null) - { - $element = parent::getDOM($doc, $majorVersion, $minorVersion); - if ($this->_errorCode !== null) { - $element->setAttribute('errorCode', $this->_errorCode); - } - if ($this->_reason !== null) { - $element->setAttribute('reason', $this->_reason); - } - if ($this->_invalidInput !== null) { - $element->setAttribute('invalidInput', $this->_invalidInput); - } - return $element; - } - - /** - * Given a DOMNode representing an attribute, tries to map the data into - * instance members. If no mapping is defined, the name and value are - * stored in an array. - * - * @param DOMNode $attribute The DOMNode attribute needed to be handled - */ - protected function takeAttributeFromDOM($attribute) - { - switch ($attribute->localName) { - case 'errorCode': - $this->_errorCode = $attribute->nodeValue; - break; - case 'reason': - $this->_reason = $attribute->nodeValue; - break; - case 'invalidInput': - $this->_invalidInput = $attribute->nodeValue; - break; - default: - parent::takeAttributeFromDOM($attribute); - } - } - - /** - * Get a human readable version of this exception. - * - * @return string - */ - public function __toString() { - return "Error " . $this->getErrorCode() . ": " . $this->getReason() . - "\n\tInvalid Input: \"" . $this->getInvalidInput() . "\""; - } - -} diff --git a/library/Zend/Gdata/Gapps/Extension/EmailList.php b/library/Zend/Gdata/Gapps/Extension/EmailList.php deleted file mode 100644 index 47173901d8..0000000000 --- a/library/Zend/Gdata/Gapps/Extension/EmailList.php +++ /dev/null @@ -1,144 +0,0 @@ -registerAllNamespaces(Zend_Gdata_Gapps::$namespaces); - parent::__construct(); - $this->_name = $name; - } - - /** - * Retrieves a DOMElement which corresponds to this element and all - * child properties. This is used to build an entry back into a DOM - * and eventually XML text for sending to the server upon updates, or - * for application storage/persistence. - * - * @param DOMDocument $doc The DOMDocument used to construct DOMElements - * @return DOMElement The DOMElement representing this element and all - * child properties. - */ - public function getDOM($doc = null, $majorVersion = 1, $minorVersion = null) - { - $element = parent::getDOM($doc, $majorVersion, $minorVersion); - if ($this->_name !== null) { - $element->setAttribute('name', $this->_name); - } - return $element; - } - - /** - * Given a DOMNode representing an attribute, tries to map the data into - * instance members. If no mapping is defined, the name and value are - * stored in an array. - * - * @param DOMNode $attribute The DOMNode attribute needed to be handled - */ - protected function takeAttributeFromDOM($attribute) - { - switch ($attribute->localName) { - case 'name': - $this->_name = $attribute->nodeValue; - break; - default: - parent::takeAttributeFromDOM($attribute); - } - } - - /** - * Get the value for this element's name attribute. - * - * @see setName - * @return string The requested attribute. - */ - public function getName() - { - return $this->_name; - } - - /** - * Set the value for this element's name attribute. This is the unique - * name which will be used to identify this email list within this - * domain, and will be used to form this email list's email address. - * - * @param string $value The desired value for this attribute. - * @return Zend_Gdata_Gapps_Extension_EmailList The element being modified. - */ - public function setName($value) - { - $this->_name = $value; - return $this; - } - - /** - * Magic toString method allows using this directly via echo - * Works best in PHP >= 4.2.0 - * - * @return string - */ - public function __toString() - { - return $this->getName(); - } - -} diff --git a/library/Zend/Gdata/Gapps/Extension/Login.php b/library/Zend/Gdata/Gapps/Extension/Login.php deleted file mode 100644 index b9e4c33472..0000000000 --- a/library/Zend/Gdata/Gapps/Extension/Login.php +++ /dev/null @@ -1,485 +0,0 @@ -registerAllNamespaces(Zend_Gdata_Gapps::$namespaces); - parent::__construct(); - $this->_username = $username; - $this->_password = $password; - $this->_hashFunctionName = $hashFunctionName; - $this->_admin = $admin; - $this->_agreedToTerms = $agreedToTerms; - $this->_suspended = $suspended; - $this->_changePasswordAtNextLogin = $changePasswordAtNextLogin; - } - - /** - * Retrieves a DOMElement which corresponds to this element and all - * child properties. This is used to build an entry back into a DOM - * and eventually XML text for sending to the server upon updates, or - * for application storage/persistence. - * - * @param DOMDocument $doc The DOMDocument used to construct DOMElements - * @return DOMElement The DOMElement representing this element and all - * child properties. - */ - public function getDOM($doc = null, $majorVersion = 1, $minorVersion = null) - { - $element = parent::getDOM($doc, $majorVersion, $minorVersion); - if ($this->_username !== null) { - $element->setAttribute('userName', $this->_username); - } - if ($this->_password !== null) { - $element->setAttribute('password', $this->_password); - } - if ($this->_hashFunctionName !== null) { - $element->setAttribute('hashFunctionName', $this->_hashFunctionName); - } - if ($this->_admin !== null) { - $element->setAttribute('admin', ($this->_admin ? "true" : "false")); - } - if ($this->_agreedToTerms !== null) { - $element->setAttribute('agreedToTerms', ($this->_agreedToTerms ? "true" : "false")); - } - if ($this->_suspended !== null) { - $element->setAttribute('suspended', ($this->_suspended ? "true" : "false")); - } - if ($this->_changePasswordAtNextLogin !== null) { - $element->setAttribute('changePasswordAtNextLogin', ($this->_changePasswordAtNextLogin ? "true" : "false")); - } - - return $element; - } - - /** - * Given a DOMNode representing an attribute, tries to map the data into - * instance members. If no mapping is defined, the name and value are - * stored in an array. - * - * @param DOMNode $attribute The DOMNode attribute needed to be handled - * @throws Zend_Gdata_App_InvalidArgumentException - */ - protected function takeAttributeFromDOM($attribute) - { - switch ($attribute->localName) { - case 'userName': - $this->_username = $attribute->nodeValue; - break; - case 'password': - $this->_password = $attribute->nodeValue; - break; - case 'hashFunctionName': - $this->_hashFunctionName = $attribute->nodeValue; - break; - case 'admin': - if ($attribute->nodeValue == "true") { - $this->_admin = true; - } - else if ($attribute->nodeValue == "false") { - $this->_admin = false; - } - else { - #require_once('Zend/Gdata/App/InvalidArgumentException.php'); - throw new Zend_Gdata_App_InvalidArgumentException("Expected 'true' or 'false' for apps:login#admin."); - } - break; - case 'agreedToTerms': - if ($attribute->nodeValue == "true") { - $this->_agreedToTerms = true; - } - else if ($attribute->nodeValue == "false") { - $this->_agreedToTerms = false; - } - else { - #require_once('Zend/Gdata/App/InvalidArgumentException.php'); - throw new Zend_Gdata_App_InvalidArgumentException("Expected 'true' or 'false' for apps:login#agreedToTerms."); - } - break; - case 'suspended': - if ($attribute->nodeValue == "true") { - $this->_suspended = true; - } - else if ($attribute->nodeValue == "false") { - $this->_suspended = false; - } - else { - #require_once('Zend/Gdata/App/InvalidArgumentException.php'); - throw new Zend_Gdata_App_InvalidArgumentException("Expected 'true' or 'false' for apps:login#suspended."); - } - break; - case 'changePasswordAtNextLogin': - if ($attribute->nodeValue == "true") { - $this->_changePasswordAtNextLogin = true; - } - else if ($attribute->nodeValue == "false") { - $this->_changePasswordAtNextLogin = false; - } - else { - #require_once('Zend/Gdata/App/InvalidArgumentException.php'); - throw new Zend_Gdata_App_InvalidArgumentException("Expected 'true' or 'false' for apps:login#changePasswordAtNextLogin."); - } - break; - default: - parent::takeAttributeFromDOM($attribute); - } - } - - /** - * Get the value for this element's username attribute. - * - * @see setUsername - * @return string The attribute being modified. - */ - public function getUsername() - { - return $this->_username; - } - - /** - * Set the value for this element's username attribute. This string - * is used to uniquely identify the user in this domian and is used - * to form this user's email address. - * - * @param string $value The desired value for this attribute. - * @return Zend_Gdata_Gapps_Extension_Login Provides a fluent interface. - */ - public function setUsername($value) - { - $this->_username = $value; - return $this; - } - - /** - * Get the value for this element's password attribute. - * - * @see setPassword - * @return string The requested attribute. - */ - public function getPassword() - { - return $this->_password; - } - - /** - * Set the value for this element's password attribute. As of this - * writing, this can be either be provided as plaintext or hashed using - * the SHA-1 algorithm for protection. If using a hash function, - * this must be indicated by calling setHashFunctionName(). - * - * @param string $value The desired value for this attribute. - * @return Zend_Gdata_Gapps_Extension_Login Provides a fluent interface. - */ - public function setPassword($value) - { - $this->_password = $value; - return $this; - } - - /** - * Get the value for this element's hashFunctionName attribute. - * - * @see setHashFunctionName - * @return string The requested attribute. - */ - public function getHashFunctionName() - { - return $this->_hashFunctionName; - } - - /** - * Set the value for this element's hashFunctionName attribute. This - * indicates whether the password supplied with setPassword() is in - * plaintext or has had a hash function applied to it. If null, - * plaintext is assumed. As of this writing, the only valid hash - * function is 'SHA-1'. - * - * @param string $value The desired value for this attribute. - * @return Zend_Gdata_Gapps_Extension_Login Provides a fluent interface. - */ - public function setHashFunctionName($value) - { - $this->_hashFunctionName = $value; - return $this; - } - - /** - * Get the value for this element's admin attribute. - * - * @see setAdmin - * @return boolean The requested attribute. - * @throws Zend_Gdata_App_InvalidArgumentException - */ - public function getAdmin() - { - if (!(is_bool($this->_admin))) { - #require_once('Zend/Gdata/App/InvalidArgumentException.php'); - throw new Zend_Gdata_App_InvalidArgumentException('Expected boolean for admin.'); - } - return $this->_admin; - } - - /** - * Set the value for this element's admin attribute. This indicates - * whether this user is an administrator for this domain. - * - * @param boolean $value The desired value for this attribute. - * @return Zend_Gdata_Gapps_Extension_Login Provides a fluent interface. - * @throws Zend_Gdata_App_InvalidArgumentException - */ - public function setAdmin($value) - { - if (!(is_bool($value))) { - #require_once('Zend/Gdata/App/InvalidArgumentException.php'); - throw new Zend_Gdata_App_InvalidArgumentException('Expected boolean for $value.'); - } - $this->_admin = $value; - return $this; - } - - /** - * Get the value for this element's agreedToTerms attribute. - * - * @see setAgreedToTerms - * @return boolean The requested attribute. - * @throws Zend_Gdata_App_InvalidArgumentException - */ - public function getAgreedToTerms() - { - if (!(is_bool($this->_agreedToTerms))) { - #require_once('Zend/Gdata/App/InvalidArgumentException.php'); - throw new Zend_Gdata_App_InvalidArgumentException('Expected boolean for agreedToTerms.'); - } - return $this->_agreedToTerms; - } - - /** - * Set the value for this element's agreedToTerms attribute. This - * indicates whether this user has agreed to the terms of service. - * - * @param boolean $value The desired value for this attribute. - * @return Zend_Gdata_Gapps_Extension_Login Provides a fluent interface. - * @throws Zend_Gdata_App_InvalidArgumentException - */ - public function setAgreedToTerms($value) - { - if (!(is_bool($value))) { - #require_once('Zend/Gdata/App/InvalidArgumentException.php'); - throw new Zend_Gdata_App_InvalidArgumentException('Expected boolean for $value.'); - } - $this->_agreedToTerms = $value; - return $this; - } - - /** - * Get the value for this element's suspended attribute. - * - * @see setSuspended - * @return boolean The requested attribute. - * @throws Zend_Gdata_App_InvalidArgumentException - */ - public function getSuspended() - { - if (!(is_bool($this->_suspended))) { - #require_once('Zend/Gdata/App/InvalidArgumentException.php'); - throw new Zend_Gdata_App_InvalidArgumentException('Expected boolean for suspended.'); - } - return $this->_suspended; - } - - /** - * Set the value for this element's suspended attribute. If true, the - * user will not be able to login to this domain until unsuspended. - * - * @param boolean $value The desired value for this attribute. - * @return Zend_Gdata_Gapps_Extension_Login Provides a fluent interface. - * @throws Zend_Gdata_App_InvalidArgumentException - */ - public function setSuspended($value) - { - if (!(is_bool($value))) { - #require_once('Zend/Gdata/App/InvalidArgumentException.php'); - throw new Zend_Gdata_App_InvalidArgumentException('Expected boolean for $value.'); - } - $this->_suspended = $value; - return $this; - } - - /** - * Get the value for this element's changePasswordAtNextLogin attribute. - * - * @see setChangePasswordAtNextLogin - * @return boolean The requested attribute. - * @throws Zend_Gdata_App_InvalidArgumentException - */ - public function getChangePasswordAtNextLogin() - { - if (!(is_bool($this->_changePasswordAtNextLogin))) { - #require_once('Zend/Gdata/App/InvalidArgumentException.php'); - throw new Zend_Gdata_App_InvalidArgumentException('Expected boolean for changePasswordAtNextLogin.'); - } - return $this->_changePasswordAtNextLogin; - } - - /** - * Set the value for this element's changePasswordAtNextLogin attribute. - * If true, the user will be forced to set a new password the next - * time they login. - * - * @param boolean $value The desired value for this attribute. - * @return Zend_Gdata_Gapps_Extension_Login Provides a fluent interface. - * @throws Zend_Gdata_App_InvalidArgumentException - */ - public function setChangePasswordAtNextLogin($value) - { - if (!(is_bool($value))) { - #require_once('Zend/Gdata/App/InvalidArgumentException.php'); - throw new Zend_Gdata_App_InvalidArgumentException('Expected boolean for $value.'); - } - $this->_changePasswordAtNextLogin = $value; - return $this; - } - - /** - * Magic toString method allows using this directly via echo - * Works best in PHP >= 4.2.0 - */ - public function __toString() - { - return "Username: " . $this->getUsername() . - "\nPassword: " . (($this->getPassword() === null) ? "NOT SET" : "SET") . - "\nPassword Hash Function: " . $this->getHashFunctionName() . - "\nAdministrator: " . ($this->getAdmin() ? "Yes" : "No") . - "\nAgreed To Terms: " . ($this->getAgreedToTerms() ? "Yes" : "No") . - "\nSuspended: " . ($this->getSuspended() ? "Yes" : "No"); - } -} diff --git a/library/Zend/Gdata/Gapps/Extension/Name.php b/library/Zend/Gdata/Gapps/Extension/Name.php deleted file mode 100644 index 82c176604d..0000000000 --- a/library/Zend/Gdata/Gapps/Extension/Name.php +++ /dev/null @@ -1,181 +0,0 @@ -registerAllNamespaces(Zend_Gdata_Gapps::$namespaces); - parent::__construct(); - $this->_familyName = $familyName; - $this->_givenName = $givenName; - } - - /** - * Retrieves a DOMElement which corresponds to this element and all - * child properties. This is used to build an entry back into a DOM - * and eventually XML text for sending to the server upon updates, or - * for application storage/persistence. - * - * @param DOMDocument $doc The DOMDocument used to construct DOMElements - * @return DOMElement The DOMElement representing this element and all - * child properties. - */ - public function getDOM($doc = null, $majorVersion = 1, $minorVersion = null) - { - $element = parent::getDOM($doc, $majorVersion, $minorVersion); - if ($this->_familyName !== null) { - $element->setAttribute('familyName', $this->_familyName); - } - if ($this->_givenName !== null) { - $element->setAttribute('givenName', $this->_givenName); - } - return $element; - } - - /** - * Given a DOMNode representing an attribute, tries to map the data into - * instance members. If no mapping is defined, the name and value are - * stored in an array. - * - * @param DOMNode $attribute The DOMNode attribute needed to be handled - */ - protected function takeAttributeFromDOM($attribute) - { - switch ($attribute->localName) { - case 'familyName': - $this->_familyName = $attribute->nodeValue; - break; - case 'givenName': - $this->_givenName = $attribute->nodeValue; - break; - default: - parent::takeAttributeFromDOM($attribute); - } - } - - /** - * Get the value for this element's familyName attribute. - * - * @see setFamilyName - * @return string The requested attribute. - */ - public function getFamilyName() - { - return $this->_familyName; - } - - /** - * Set the value for this element's familyName attribute. This - * represents a user's family name. - * - * @param string $value The desired value for this attribute. - * @return Zend_Gdata_Gapps_Extension_Name Provides a fluent interface.. - */ - public function setFamilyName($value) - { - $this->_familyName = $value; - return $this; - } - - /** - * Get the value for this element's givenName attribute. - * - * @see setGivenName - * @return string The requested attribute. - */ - public function getGivenName() - { - return $this->_givenName; - } - - /** - * Set the value for this element's givenName attribute. This - * represents a user's given name. - * - * @param string $value The desired value for this attribute. - * @return Zend_Gdata_Gapps_Extension_Name Provides a fluent interface. - */ - public function setGivenName($value) - { - $this->_givenName = $value; - return $this; - } - - /** - * Magic toString method allows using this directly via echo - * Works best in PHP >= 4.2.0 - */ - public function __toString() - { - return $this->getGivenName() . ' ' . $this->getFamilyName(); - } - -} diff --git a/library/Zend/Gdata/Gapps/Extension/Nickname.php b/library/Zend/Gdata/Gapps/Extension/Nickname.php deleted file mode 100644 index 8db8ae6592..0000000000 --- a/library/Zend/Gdata/Gapps/Extension/Nickname.php +++ /dev/null @@ -1,142 +0,0 @@ -registerAllNamespaces(Zend_Gdata_Gapps::$namespaces); - parent::__construct(); - $this->_name = $name; - } - - /** - * Retrieves a DOMElement which corresponds to this element and all - * child properties. This is used to build an entry back into a DOM - * and eventually XML text for sending to the server upon updates, or - * for application storage/persistence. - * - * @param DOMDocument $doc The DOMDocument used to construct DOMElements - * @return DOMElement The DOMElement representing this element and all - * child properties. - */ - public function getDOM($doc = null, $majorVersion = 1, $minorVersion = null) - { - $element = parent::getDOM($doc, $majorVersion, $minorVersion); - if ($this->_name !== null) { - $element->setAttribute('name', $this->_name); - } - return $element; - } - - /** - * Given a DOMNode representing an attribute, tries to map the data into - * instance members. If no mapping is defined, the name and value are - * stored in an array. - * - * @param DOMNode $attribute The DOMNode attribute needed to be handled - */ - protected function takeAttributeFromDOM($attribute) - { - switch ($attribute->localName) { - case 'name': - $this->_name = $attribute->nodeValue; - break; - default: - parent::takeAttributeFromDOM($attribute); - } - } - - /** - * Get the value for this element's name attribute. - * - * @see setName - * @return string The requested attribute. - */ - public function getName() - { - return $this->_name; - } - - /** - * Set the value for this element's name attribute. This name uniquely - * describes this nickname within the domain. Emails addressed to this - * name will be delivered to the user who owns this nickname. - * - * @param string $value The desired value for this attribute. - * @return Zend_Gdata_Gapps_Extension_Nickname Provides a fluent - * interface. - */ - public function setName($value) - { - $this->_name = $value; - return $this; - } - - /** - * Magic toString method allows using this directly via echo - * Works best in PHP >= 4.2.0 - */ - public function __toString() - { - return $this->getName(); - } - -} diff --git a/library/Zend/Gdata/Gapps/Extension/Property.php b/library/Zend/Gdata/Gapps/Extension/Property.php deleted file mode 100644 index dd1f98fb65..0000000000 --- a/library/Zend/Gdata/Gapps/Extension/Property.php +++ /dev/null @@ -1,179 +0,0 @@ -registerAllNamespaces(Zend_Gdata_Gapps::$namespaces); - parent::__construct(); - $this->_name = $name; - $this->_value = $value; - - } - - - /** - * Retrieves a DOMElement which corresponds to this element and all - * child properties. This is used to build an entry back into a DOM - * and eventually XML text for sending to the server upon updates, or - * for application storage/persistence. - * - * @param DOMDocument $doc The DOMDocument used to construct DOMElements - * @return DOMElement The DOMElement representing this element and all - * child properties. - */ - public function getDOM($doc = null, $majorVersion = 1, $minorVersion = null) - { - $element = parent::getDOM($doc, $majorVersion, $minorVersion); - if ($this->_name !== null) { - $element->setAttribute('name', $this->_name); - } - if ($this->_value !== null) { - $element->setAttribute('value', $this->_value); - } - - return $element; - - } - - /** - * Given a DOMNode representing an attribute, tries to map the data into - * instance members. If no mapping is defined, the name and value are - * stored in an array. - * - * @param DOMNode $attribute The DOMNode attribute needed to be handled - */ - protected function takeAttributeFromDOM($attribute) - { - switch ($attribute->localName) { - case 'name': - $this->_name = $attribute->nodeValue; - break; - case 'value': - $this->_value = $attribute->nodeValue; - break; - default: - parent::takeAttributeFromDOM($attribute); - } - } - - /** - * Get the value for this element's name attribute. - * - * @see setName - * @return string The requested attribute. - */ - public function getName() - { - return $this->_name; - } - - /** - * Set the value for this element's name attribute. - * @param string $value The desired value for this attribute. - * @return Zend_Gdata_Gapps_Extension_Property The element being modified. - */ - public function setName($value) - { - $this->_name = $value; - return $this; - } - - /** - * Get the value for this element's value attribute. - * - * @see setName - * @return string The requested attribute. - */ - public function getValue() - { - return $this->_value; - } - - /** - * Set the value for this element's value attribute. - * - * @param string $value The desired value for this attribute. - * @return Zend_Gdata_Gapps_Extension_Property The element being modified. - */ - public function setValue($value) - { - $this->_value = $value; - return $this; - } - - /** - * Magic toString method allows using this directly via echo - * Works best in PHP >= 4.2.0 - * - * @return string - */ - public function __toString() - { - return "Property Name: " . $this->getName() . - "\nProperty Value: " . $this->getValue(); - } -} diff --git a/library/Zend/Gdata/Gapps/Extension/Quota.php b/library/Zend/Gdata/Gapps/Extension/Quota.php deleted file mode 100644 index 9b3e5667fb..0000000000 --- a/library/Zend/Gdata/Gapps/Extension/Quota.php +++ /dev/null @@ -1,142 +0,0 @@ -registerAllNamespaces(Zend_Gdata_Gapps::$namespaces); - parent::__construct(); - $this->_limit = $limit; - } - - /** - * Retrieves a DOMElement which corresponds to this element and all - * child properties. This is used to build an entry back into a DOM - * and eventually XML text for sending to the server upon updates, or - * for application storage/persistence. - * - * @param DOMDocument $doc The DOMDocument used to construct DOMElements - * @return DOMElement The DOMElement representing this element and all - * child properties. - */ - public function getDOM($doc = null, $majorVersion = 1, $minorVersion = null) - { - $element = parent::getDOM($doc, $majorVersion, $minorVersion); - if ($this->_limit !== null) { - $element->setAttribute('limit', $this->_limit); - } - return $element; - } - - /** - * Given a DOMNode representing an attribute, tries to map the data into - * instance members. If no mapping is defined, the name and value are - * stored in an array. - * - * @param DOMNode $attribute The DOMNode attribute needed to be handled - */ - protected function takeAttributeFromDOM($attribute) - { - switch ($attribute->localName) { - case 'limit': - $this->_limit = $attribute->nodeValue; - break; - default: - parent::takeAttributeFromDOM($attribute); - } - } - - /** - * Get the value for this element's limit attribute. - * - * @see setLimit - * @return string The requested attribute. - */ - public function getLimit() - { - return $this->_limit; - } - - /** - * Set the value for this element's limit attribute. This is the amount - * of storage space, in bytes, that should be made available to - * the associated user. - * - * @param string $value The desired value for this attribute. - * @return Zend_Gdata_Gapps_Extension_Quota Provides a fluent interface. - */ - public function setLimit($value) - { - $this->_limit = $value; - return $this; - } - - /** - * Magic toString method allows using this directly via echo - * Works best in PHP >= 4.2.0 - */ - public function __toString() - { - return $this->getLimit(); - } - -} diff --git a/library/Zend/Gdata/Gapps/GroupEntry.php b/library/Zend/Gdata/Gapps/GroupEntry.php deleted file mode 100644 index 34190f7665..0000000000 --- a/library/Zend/Gdata/Gapps/GroupEntry.php +++ /dev/null @@ -1,158 +0,0 @@ - in the Google Data protocol. - * - * @category Zend - * @package Zend_Gdata - * @subpackage Gapps - * @copyright Copyright (c) 2005-2015 Zend Technologies USA Inc. (http://www.zend.com) - * @license http://framework.zend.com/license/new-bsd New BSD License - */ -class Zend_Gdata_Gapps_GroupEntry extends Zend_Gdata_Entry -{ - - protected $_entryClassName = 'Zend_Gdata_Gapps_GroupEntry'; - - /** - * element containing information about other items - * relevant to this entry. - * - * @var Zend_Gdata_Gapps_Extension_Property - */ - protected $_property = array(); - - /** - * Create a new instance. - * - * @param DOMElement $element (optional) DOMElement from which this - * object should be constructed. - */ - public function __construct($element = null) - { - $this->registerAllNamespaces(Zend_Gdata_Gapps::$namespaces); - parent::__construct($element); - } - - /** - * Retrieves a DOMElement which corresponds to this element and all - * child properties. This is used to build an entry back into a DOM - * and eventually XML text for application storage/persistence. - * - * @param DOMDocument $doc The DOMDocument used to construct DOMElements - * @return DOMElement The DOMElement representing this element and all - * child properties. - */ - public function getDOM($doc = null, $majorVersion = 1, $minorVersion = null) - { - $element = parent::getDOM($doc, $majorVersion, $minorVersion); - - foreach ($this->_property as $p) { - $element->appendChild($p->getDOM($element->ownerDocument)); - } - return $element; - } - - /** - * Creates individual Entry objects of the appropriate type and - * stores them as members of this entry based upon DOM data. - * - * @param DOMNode $child The DOMNode to process - */ - protected function takeChildFromDOM($child) - { - $absoluteNodeName = $child->namespaceURI . ':' . $child->localName; - - switch ($absoluteNodeName) { - - case $this->lookupNamespace('apps') . ':' . 'property'; - $property = new Zend_Gdata_Gapps_Extension_Property(); - $property->transferFromDOM($child); - $this->_property[] = $property; - break; - default: - parent::takeChildFromDOM($child); - break; - } - } - - /** - * Returns all property tags for this entry - * - * @param string $rel The rel value of the property to be found. If null, - * the array of properties is returned instead. - * @return mixed Either an array of Zend_Gdata_Gapps_Extension_Property - * objects if $rel is null, a single - * Zend_Gdata_Gapps_Extension_Property object if $rel is specified - * and a matching feed link is found, or null if $rel is - * specified and no matching property is found. - */ - public function getProperty($rel = null) - { - if ($rel == null) { - return $this->_property; - } else { - foreach ($this->_property as $p) { - if ($p->rel == $rel) { - return $p; - } - } - return null; - } - } - - /** - * Set the value of the property property for this object. - * - * @param array $value A collection of - * Zend_Gdata_Gapps_Extension_Property objects. - * @return Zend_Gdata_Gapps_GroupEntry Provides a fluent interface. - */ - public function setProperty($value) - { - $this->_property = $value; - return $this; - } - -} - diff --git a/library/Zend/Gdata/Gapps/GroupFeed.php b/library/Zend/Gdata/Gapps/GroupFeed.php deleted file mode 100644 index f0072c9c9b..0000000000 --- a/library/Zend/Gdata/Gapps/GroupFeed.php +++ /dev/null @@ -1,53 +0,0 @@ -setGroupId($groupId); - $this->setStartGroupId($startGroupId); - } - - /** - * Set the group id to query for. When set, only groups with a group id - * matching this value will be returned in search results. Set to - * null to disable filtering by group id. - * - * @see getGroupId - * @param string $value The group id to filter search results by, or null to - * disable. - */ - public function setGroupId($value) - { - $this->_groupId = $value; - } - - /** - * Get the group id to query for. If no group id is set, null will be - * returned. - * - * @param string $value The group id to filter search results by, or - * null if disabled. - */ - public function getGroupId() - { - return $this->_groupId; - } - - /** - * Set the member to query for. When set, only subscribers with an - * email address matching this value will be returned in search results. - * Set to null to disable filtering by username. - * - * @param string $value The member email address to filter search - * results by, or null to disable. - */ - public function setMember($value) - { - if ($value !== null) { - $this->_params['member'] = $value; - } - else { - unset($this->_params['member']); - } - } - - /** - * Get the member email address to query for. If no member is set, - * null will be returned. - * - * @see setMember - * @return string The member email address to filter search - * results by, or null if disabled. - */ - public function getMember() - { - if (array_key_exists('member', $this->_params)) { - return $this->_params['member']; - } else { - return null; - } - } - - - /** - * Sets the query parameter directOnly - * @param bool $value - */ - public function setDirectOnly($value) - { - if ($value !== null) { - if($value == true) { - $this->_params['directOnly'] = 'true'; - } else { - $this->_params['directOnly'] = 'false'; - } - } else { - unset($this->_params['directOnly']); - } - } - - /** - * - * @see setDirectOnly - * @return bool - */ - public function getDirectOnly() - { - if (array_key_exists('directOnly', $this->_params)) { - - if($this->_params['directOnly'] == 'true') { - return true; - } else { - return false; - } - } else { - return null; - } - } - - /** - * Set the first group id which should be displayed when retrieving - * a list of groups. - * - * @param string $value The first group id to be returned, or null to - * disable. - */ - public function setStartGroupId($value) - { - if ($value !== null) { - $this->_params['start'] = $value; - } else { - unset($this->_params['start']); - } - } - - /** - * Get the first group id which should be displayed when retrieving - * a list of groups. - * - * @see setStartGroupId - * @return string The first group id to be returned, or null if - * disabled. - */ - public function getStartGroupId() - { - if (array_key_exists('start', $this->_params)) { - return $this->_params['start']; - } else { - return null; - } - } - - /** - * Returns the query URL generated by this query instance. - * - * @return string The query URL for this instance. - */ - public function getQueryUrl() - { - - $uri = Zend_Gdata_Gapps::APPS_BASE_FEED_URI; - $uri .= Zend_Gdata_Gapps::APPS_GROUP_PATH; - $uri .= '/' . $this->_domain; - - if ($this->_groupId !== null) { - $uri .= '/' . $this->_groupId; - } - - if(array_key_exists('member', $this->_params)) { - $uri .= '/'; - } - - $uri .= $this->getQueryString(); - return $uri; - } - -} diff --git a/library/Zend/Gdata/Gapps/MemberEntry.php b/library/Zend/Gdata/Gapps/MemberEntry.php deleted file mode 100644 index 17eb7942bf..0000000000 --- a/library/Zend/Gdata/Gapps/MemberEntry.php +++ /dev/null @@ -1,159 +0,0 @@ - in the Google Data protocol. - * - * @category Zend - * @package Zend_Gdata - * @subpackage Gapps - * @copyright Copyright (c) 2005-2015 Zend Technologies USA Inc. (http://www.zend.com) - * @license http://framework.zend.com/license/new-bsd New BSD License - */ -class Zend_Gdata_Gapps_MemberEntry extends Zend_Gdata_Entry -{ - - protected $_entryClassName = 'Zend_Gdata_Gapps_MemberEntry'; - - /** - * element containing information about other items - * relevant to this entry. - * - * @var Zend_Gdata_Gapps_Extension_Property - */ - protected $_property = array(); - - /** - * Create a new instance. - * - * @param DOMElement $element (optional) DOMElement from which this - * object should be constructed. - */ - public function __construct($element = null) - { - $this->registerAllNamespaces(Zend_Gdata_Gapps::$namespaces); - parent::__construct($element); - } - - /** - * Retrieves a DOMElement which corresponds to this element and all - * child properties. This is used to build an entry back into a DOM - * and eventually XML text for application storage/persistence. - * - * @param DOMDocument $doc The DOMDocument used to construct DOMElements - * @return DOMElement The DOMElement representing this element and all - * child properties. - */ - public function getDOM($doc = null, $majorVersion = 1, $minorVersion = null) - { - $element = parent::getDOM($doc, $majorVersion, $minorVersion); - - foreach ($this->_property as $p) { - $element->appendChild($p->getDOM($element->ownerDocument)); - } - return $element; - } - - /** - * Creates individual Entry objects of the appropriate type and - * stores them as members of this entry based upon DOM data. - * - * @param DOMNode $child The DOMNode to process - */ - protected function takeChildFromDOM($child) - { - $absoluteNodeName = $child->namespaceURI . ':' . $child->localName; - - switch ($absoluteNodeName) { - - case $this->lookupNamespace('apps') . ':' . 'property'; - $property = new Zend_Gdata_Gapps_Extension_Property(); - $property->transferFromDOM($child); - $this->_property[] = $property; - break; - default: - parent::takeChildFromDOM($child); - break; - } - } - - /** - * Returns all property tags for this entry - * - * @param string $rel The rel value of the property to be found. If null, - * the array of properties is returned instead. - * @return mixed Either an array of Zend_Gdata_Gapps_Extension_Property - * objects if $rel is null, a single - * Zend_Gdata_Gapps_Extension_Property object if $rel is specified - * and a matching feed link is found, or null if $rel is - * specified and no matching property is found. - */ - public function getProperty($rel = null) - { - if ($rel == null) { - return $this->_property; - } else { - foreach ($this->_property as $p) { - if ($p->rel == $rel) { - return $p; - } - } - return null; - } - } - - /** - * Set the value of the property property for this object. - * - * @param array $value A collection of - * Zend_Gdata_Gapps_Extension_Property objects. - * @return Zend_Gdata_Gapps_MemberEntry Provides a fluent interface. - */ - public function setProperty($value) - { - $this->_property = $value; - return $this; - } - -} - - diff --git a/library/Zend/Gdata/Gapps/MemberFeed.php b/library/Zend/Gdata/Gapps/MemberFeed.php deleted file mode 100644 index 7c63a4dbfd..0000000000 --- a/library/Zend/Gdata/Gapps/MemberFeed.php +++ /dev/null @@ -1,53 +0,0 @@ -setGroupId($groupId); - $this->setMemberId($memberId); - $this->setStartMemberId($startMemberId); - } - - /** - * Set the group id to query for. - * - * @see getGroupId - * @param string $value The group id to filter search results by, or null to - * disable. - */ - public function setGroupId($value) - { - $this->_groupId = $value; - } - - /** - * Get the group id to query for. If no group id is set, null will be - * returned. - * - * @param string $value The group id to filter search results by, or - * null if disabled. - * @return string The group id - */ - public function getGroupId() - { - return $this->_groupId; - } - - - /** - * Set the member id to query for. When set, only users with a member id - * matching this value will be returned in search results. Set to - * null to disable filtering by member id. - * - * @see getMemberId - * @param string $value The member id to filter search results by, or null to - * disable. - */ - public function setMemberId($value) - { - $this->_memberId = $value; - } - - /** - * Get the member id to query for. If no member id is set, null will be - * returned. - * - * @param string $value The member id to filter search results by, or - * null if disabled. - * @return The member id - */ - public function getMemberId() - { - return $this->_memberId; - } - - /** - * Set the first member id which should be displayed when retrieving - * a list of members. - * - * @param string $value The first member id to be returned, or null to - * disable. - */ - public function setStartMemberId($value) - { - if ($value !== null) { - $this->_params['start'] = $value; - } else { - unset($this->_params['start']); - } - } - - /** - * Get the first username which should be displayed when retrieving - * a list of users. - * - * @see setStartUsername - * @return string The first username to be returned, or null if - * disabled. - */ - public function getStartMemberId() - { - if (array_key_exists('start', $this->_params)) { - return $this->_params['start']; - } else { - return null; - } - } - - /** - * Returns the query URL generated by this query instance. - * - * @return string The query URL for this instance. - */ - public function getQueryUrl() - { - - $uri = Zend_Gdata_Gapps::APPS_BASE_FEED_URI; - $uri .= Zend_Gdata_Gapps::APPS_GROUP_PATH; - $uri .= '/' . $this->_domain; - if ($this->_groupId !== null) { - $uri .= '/' . $this->_groupId; - } else { - #require_once 'Zend/Gdata/App/InvalidArgumentException.php'; - throw new Zend_Gdata_App_InvalidArgumentException( - 'groupId must not be null'); - } - - $uri .= '/member'; - - if ($this->_memberId !== null) { - $uri .= '/' . $this->_memberId; - } - $uri .= $this->getQueryString(); - return $uri; - } - -} diff --git a/library/Zend/Gdata/Gapps/NicknameEntry.php b/library/Zend/Gdata/Gapps/NicknameEntry.php deleted file mode 100644 index 716a76394f..0000000000 --- a/library/Zend/Gdata/Gapps/NicknameEntry.php +++ /dev/null @@ -1,189 +0,0 @@ - in the Google Data protocol. - * - * @category Zend - * @package Zend_Gdata - * @subpackage Gapps - * @copyright Copyright (c) 2005-2015 Zend Technologies USA Inc. (http://www.zend.com) - * @license http://framework.zend.com/license/new-bsd New BSD License - */ -class Zend_Gdata_Gapps_NicknameEntry extends Zend_Gdata_Entry -{ - - protected $_entryClassName = 'Zend_Gdata_Gapps_NicknameEntry'; - - /** - * element used to hold information about the owner - * of this nickname, including their username. - * - * @var Zend_Gdata_Gapps_Extension_Login - */ - protected $_login = null; - - /** - * element used to hold the name of this nickname. - * - * @var Zend_Gdata_Gapps_Extension_Nickname - */ - protected $_nickname = null; - - /** - * Create a new instance. - * - * @param DOMElement $element (optional) DOMElement from which this - * object should be constructed. - */ - public function __construct($element = null) - { - $this->registerAllNamespaces(Zend_Gdata_Gapps::$namespaces); - parent::__construct($element); - } - - /** - * Retrieves a DOMElement which corresponds to this element and all - * child properties. This is used to build an entry back into a DOM - * and eventually XML text for application storage/persistence. - * - * @param DOMDocument $doc The DOMDocument used to construct DOMElements - * @return DOMElement The DOMElement representing this element and all - * child properties. - */ - public function getDOM($doc = null, $majorVersion = 1, $minorVersion = null) - { - $element = parent::getDOM($doc, $majorVersion, $minorVersion); - if ($this->_login !== null) { - $element->appendChild($this->_login->getDOM($element->ownerDocument)); - } - if ($this->_nickname !== null) { - $element->appendChild($this->_nickname->getDOM($element->ownerDocument)); - } - return $element; - } - - /** - * Creates individual Entry objects of the appropriate type and - * stores them as members of this entry based upon DOM data. - * - * @param DOMNode $child The DOMNode to process - */ - protected function takeChildFromDOM($child) - { - $absoluteNodeName = $child->namespaceURI . ':' . $child->localName; - - switch ($absoluteNodeName) { - case $this->lookupNamespace('apps') . ':' . 'login'; - $login = new Zend_Gdata_Gapps_Extension_Login(); - $login->transferFromDOM($child); - $this->_login = $login; - break; - case $this->lookupNamespace('apps') . ':' . 'nickname'; - $nickname = new Zend_Gdata_Gapps_Extension_Nickname(); - $nickname->transferFromDOM($child); - $this->_nickname = $nickname; - break; - default: - parent::takeChildFromDOM($child); - break; - } - } - - /** - * Get the value of the login property for this object. - * - * @see setLogin - * @return Zend_Gdata_Gapps_Extension_Login The requested object. - */ - public function getLogin() - { - return $this->_login; - } - - /** - * Set the value of the login property for this object. This property - * is used to store the username address of the current user. - * - * @param Zend_Gdata_Gapps_Extension_Login $value The desired value for - * this instance's login property. - * @return Zend_Gdata_Gapps_NicknameEntry Provides a fluent interface. - */ - public function setLogin($value) - { - $this->_login = $value; - return $this; - } - - /** - * Get the value of the nickname property for this object. - * - * @see setNickname - * @return Zend_Gdata_Gapps_Extension_Nickname The requested object. - */ - public function getNickname() - { - return $this->_nickname; - } - - /** - * Set the value of the nickname property for this object. This property - * is used to store the the name of the current nickname. - * - * @param Zend_Gdata_Gapps_Extension_Nickname $value The desired value for - * this instance's nickname property. - * @return Zend_Gdata_Gapps_NicknameEntry Provides a fluent interface. - */ - public function setNickname($value) - { - $this->_nickname = $value; - return $this; - } - -} diff --git a/library/Zend/Gdata/Gapps/NicknameFeed.php b/library/Zend/Gdata/Gapps/NicknameFeed.php deleted file mode 100644 index adb75b97bb..0000000000 --- a/library/Zend/Gdata/Gapps/NicknameFeed.php +++ /dev/null @@ -1,53 +0,0 @@ -setNickname($nickname); - $this->setUsername($username); - $this->setStartNickname($startNickname); - } - - /** - * Set the nickname to query for. When set, only users with a nickname - * matching this value will be returned in search results. Set to - * null to disable filtering by username. - * - * @param string $value The nickname to filter search results by, or null - * to disable. - */ - public function setNickname($value) - { - $this->_nickname = $value; - } - - /** - * Get the nickname to query for. If no nickname is set, null will be - * returned. - * - * @see setNickname - * @return string The nickname to filter search results by, or null if - * disabled. - */ - public function getNickname() - { - return $this->_nickname; - } - - /** - * Set the username to query for. When set, only users with a username - * matching this value will be returned in search results. Set to - * null to disable filtering by username. - * - * @param string $value The username to filter search results by, or null - * to disable. - */ - public function setUsername($value) - { - if ($value !== null) { - $this->_params['username'] = $value; - } - else { - unset($this->_params['username']); - } - } - - /** - * Get the username to query for. If no username is set, null will be - * returned. - * - * @see setUsername - * @return string The username to filter search results by, or null if - * disabled. - */ - public function getUsername() - { - if (array_key_exists('username', $this->_params)) { - return $this->_params['username']; - } else { - return null; - } - } - - /** - * Set the first nickname which should be displayed when retrieving - * a list of nicknames. - * - * @param string $value The first nickname to be returned, or null to - * disable. - */ - public function setStartNickname($value) - { - if ($value !== null) { - $this->_params['startNickname'] = $value; - } else { - unset($this->_params['startNickname']); - } - } - - /** - * Get the first nickname which should be displayed when retrieving - * a list of nicknames. - * - * @return string The first nickname to be returned, or null to - * disable. - */ - public function getStartNickname() - { - if (array_key_exists('startNickname', $this->_params)) { - return $this->_params['startNickname']; - } else { - return null; - } - } - - /** - * Returns the URL generated for this query, based on it's current - * parameters. - * - * @return string A URL generated based on the state of this query. - */ - public function getQueryUrl() - { - - $uri = $this->getBaseUrl(); - $uri .= Zend_Gdata_Gapps::APPS_NICKNAME_PATH; - if ($this->_nickname !== null) { - $uri .= '/' . $this->_nickname; - } - $uri .= $this->getQueryString(); - return $uri; - } - -} diff --git a/library/Zend/Gdata/Gapps/OwnerEntry.php b/library/Zend/Gdata/Gapps/OwnerEntry.php deleted file mode 100644 index fb06ec281a..0000000000 --- a/library/Zend/Gdata/Gapps/OwnerEntry.php +++ /dev/null @@ -1,158 +0,0 @@ - in the Google Data protocol. - * - * @category Zend - * @package Zend_Gdata - * @subpackage Gapps - * @copyright Copyright (c) 2005-2015 Zend Technologies USA Inc. (http://www.zend.com) - * @license http://framework.zend.com/license/new-bsd New BSD License - */ -class Zend_Gdata_Gapps_OwnerEntry extends Zend_Gdata_Entry -{ - - protected $_entryClassName = 'Zend_Gdata_Gapps_OwnerEntry'; - - /** - * element containing information about other items - * relevant to this entry. - * - * @var Zend_Gdata_Gapps_Extension_Property - */ - protected $_property = array(); - - /** - * Create a new instance. - * - * @param DOMElement $element (optional) DOMElement from which this - * object should be constructed. - */ - public function __construct($element = null) - { - $this->registerAllNamespaces(Zend_Gdata_Gapps::$namespaces); - parent::__construct($element); - } - - /** - * Retrieves a DOMElement which corresponds to this element and all - * child properties. This is used to build an entry back into a DOM - * and eventually XML text for application storage/persistence. - * - * @param DOMDocument $doc The DOMDocument used to construct DOMElements - * @return DOMElement The DOMElement representing this element and all - * child properties. - */ - public function getDOM($doc = null, $majorVersion = 1, $minorVersion = null) - { - $element = parent::getDOM($doc, $majorVersion, $minorVersion); - - foreach ($this->_property as $p) { - $element->appendChild($p->getDOM($element->ownerDocument)); - } - return $element; - } - - /** - * Creates individual Entry objects of the appropriate type and - * stores them as owners of this entry based upon DOM data. - * - * @param DOMNode $child The DOMNode to process - */ - protected function takeChildFromDOM($child) - { - $absoluteNodeName = $child->namespaceURI . ':' . $child->localName; - - switch ($absoluteNodeName) { - - case $this->lookupNamespace('apps') . ':' . 'property'; - $property = new Zend_Gdata_Gapps_Extension_Property(); - $property->transferFromDOM($child); - $this->_property[] = $property; - break; - default: - parent::takeChildFromDOM($child); - break; - } - } - - /** - * Returns all property tags for this entry - * - * @param string $rel The rel value of the property to be found. If null, - * the array of properties is returned instead. - * @return mixed Either an array of Zend_Gdata_Gapps_Extension_Property - * objects if $rel is null, a single - * Zend_Gdata_Gapps_Extension_Property object if $rel is specified - * and a matching feed link is found, or null if $rel is - * specified and no matching property is found. - */ - public function getProperty($rel = null) - { - if ($rel == null) { - return $this->_property; - } else { - foreach ($this->_property as $p) { - if ($p->rel == $rel) { - return $p; - } - } - return null; - } - } - - /** - * Set the value of the property property for this object. - * - * @param array $value A collection of - * Zend_Gdata_Gapps_Extension_Property objects. - * @return Zend_Gdata_Gapps_OwnerEntry Provides a fluent interface. - */ - public function setProperty($value) - { - $this->_property = $value; - return $this; - } - -} - diff --git a/library/Zend/Gdata/Gapps/OwnerFeed.php b/library/Zend/Gdata/Gapps/OwnerFeed.php deleted file mode 100644 index 3859ecc945..0000000000 --- a/library/Zend/Gdata/Gapps/OwnerFeed.php +++ /dev/null @@ -1,53 +0,0 @@ -setGroupId($groupId); - $this->setOwnerEmail($ownerEmail); - } - - /** - * Set the group id to query for. - * - * @see getGroupId - * @param string $value - */ - public function setGroupId($value) - { - $this->_groupId = $value; - } - - /** - * Get the group id to query for. - * - * @return string - * - */ - public function getGroupId() - { - return $this->_groupId; - } - - /** - * Set the owner email to query for. - * - * @see getOwnerEmail - * @param string $value - */ - public function setOwnerEmail($value) - { - $this->_ownerEmail = $value; - } - - /** - * Get the owner email to query for. - * - * @return string - * - */ - public function getOwnerEmail() - { - return $this->_ownerEmail; - } - - /** - * Returns the query URL generated by this query instance. - * - * @return string The query URL for this instance. - */ - public function getQueryUrl() - { - $uri = Zend_Gdata_Gapps::APPS_BASE_FEED_URI; - $uri .= Zend_Gdata_Gapps::APPS_GROUP_PATH; - $uri .= '/' . $this->_domain; - if ($this->_groupId !== null) { - $uri .= '/' . $this->_groupId; - } else { - #require_once 'Zend/Gdata/App/InvalidArgumentException.php'; - throw new Zend_Gdata_App_InvalidArgumentException( - 'groupId must not be null'); - } - - $uri .= '/owner'; - - if ($this->_ownerEmail !== null) { - $uri .= '/' . $this->_ownerEmail; - } - - $uri .= $this->getQueryString(); - return $uri; - } - -} diff --git a/library/Zend/Gdata/Gapps/Query.php b/library/Zend/Gdata/Gapps/Query.php deleted file mode 100644 index 839d8ad16c..0000000000 --- a/library/Zend/Gdata/Gapps/Query.php +++ /dev/null @@ -1,123 +0,0 @@ -_domain = $domain; - } - - /** - * Set domain for this service instance. This should be a fully qualified - * domain, such as 'foo.example.com'. - * - * This value is used when calculating URLs for retrieving and posting - * entries. If no value is specified, a URL will have to be manually - * constructed prior to using any methods which interact with the Google - * Apps provisioning service. - * - * @param string $value The domain to be used for this session. - */ - public function setDomain($value) - { - $this->_domain = $value; - } - - /** - * Get domain for this service instance. This should be a fully qualified - * domain, such as 'foo.example.com'. If no domain is set, null will be - * returned. - * - * @see setDomain - * @return string The domain to be used for this session, or null if not - * set. - */ - public function getDomain() - { - return $this->_domain; - } - - /** - * Returns the base URL used to access the Google Apps service, based - * on the current domain. The current domain can be temporarily - * overridden by providing a fully qualified domain as $domain. - * - * @see setDomain - * @param string $domain (optional) A fully-qualified domain to use - * instead of the default domain for this service instance. - */ - public function getBaseUrl($domain = null) - { - if ($domain !== null) { - return Zend_Gdata_Gapps::APPS_BASE_FEED_URI . '/' . $domain; - } - else if ($this->_domain !== null) { - return Zend_Gdata_Gapps::APPS_BASE_FEED_URI . '/' . $this->_domain; - } - else { - #require_once 'Zend/Gdata/App/InvalidArgumentException.php'; - throw new Zend_Gdata_App_InvalidArgumentException( - 'Domain must be specified.'); - } - } - -} diff --git a/library/Zend/Gdata/Gapps/ServiceException.php b/library/Zend/Gdata/Gapps/ServiceException.php deleted file mode 100644 index 6452875f4f..0000000000 --- a/library/Zend/Gdata/Gapps/ServiceException.php +++ /dev/null @@ -1,211 +0,0 @@ -setErrors($errors); - } - } - - /** - * Add a single Error object to the list of errors received by the - * server. - * - * @param Zend_Gdata_Gapps_Error $error An instance of an error returned - * by the server. The error's errorCode must be set. - * @throws Zend_Gdata_App_Exception - */ - public function addError($error) { - // Make sure that we don't try to index an error that doesn't - // contain an index value. - if ($error->getErrorCode() == null) { - #require_once 'Zend/Gdata/App/Exception.php'; - throw new Zend_Gdata_App_Exception("Error encountered without corresponding error code."); - } - - $this->_errors[$error->getErrorCode()] = $error; - } - - /** - * Set the list of errors as sent by the server inside of an - * AppsForYourDomainErrors tag. - * - * @param array $array An associative array containing a collection of - * Zend_Gdata_Gapps_Error objects. All errors must have their - * errorCode value set. - * @throws Zend_Gdata_App_Exception - */ - public function setErrors($array) { - $this->_errors = array(); - foreach ($array as $error) { - $this->addError($error); - } - } - - /** - * Get the list of errors as sent by the server inside of an - * AppsForYourDomainErrors tag. - * - * @return array An associative array containing a collection of - * Zend_Gdata_Gapps_Error objects, indexed by error code. - */ - public function getErrors() { - return $this->_errors; - } - - /** - * Return the Error object associated with a specific error code. - * - * @return Zend_Gdata_Gapps_Error The Error object requested, or null - * if not found. - */ - public function getError($errorCode) { - if (array_key_exists($errorCode, $this->_errors)) { - $result = $this->_errors[$errorCode]; - return $result; - } else { - return null; - } - } - - /** - * Check whether or not a particular error code was returned by the - * server. - * - * @param integer $errorCode The error code to check against. - * @return boolean Whether or not the supplied error code was returned - * by the server. - */ - public function hasError($errorCode) { - return array_key_exists($errorCode, $this->_errors); - } - - /** - * Import an AppsForYourDomain error from XML. - * - * @param string $string The XML data to be imported - * @return Zend_Gdata_Gapps_ServiceException Provides a fluent interface. - * @throws Zend_Gdata_App_Exception - */ - public function importFromString($string) { - if ($string) { - // Check to see if an AppsForYourDomainError exists - // - // track_errors is temporarily enabled so that if an error - // occurs while parsing the XML we can append it to an - // exception by referencing $php_errormsg - @ini_set('track_errors', 1); - $doc = new DOMDocument(); - $doc = @Zend_Xml_Security::scan($string, $doc); - @ini_restore('track_errors'); - - if (!$doc) { - #require_once 'Zend/Gdata/App/Exception.php'; - // $php_errormsg is automatically generated by PHP if - // an error occurs while calling loadXML(), above. - throw new Zend_Gdata_App_Exception("DOMDocument cannot parse XML: $php_errormsg"); - } - - // Ensure that the outermost node is an AppsForYourDomain error. - // If it isn't, something has gone horribly wrong. - $rootElement = $doc->getElementsByTagName($this->_rootElement)->item(0); - if (!$rootElement) { - #require_once 'Zend/Gdata/App/Exception.php'; - throw new Zend_Gdata_App_Exception('No root <' . $this->_rootElement . '> element found, cannot parse feed.'); - } - - foreach ($rootElement->childNodes as $errorNode) { - if (!($errorNode instanceof DOMText)) { - $error = new Zend_Gdata_Gapps_Error(); - $error->transferFromDom($errorNode); - $this->addError($error); - } - } - return $this; - } else { - #require_once 'Zend/Gdata/App/Exception.php'; - throw new Zend_Gdata_App_Exception('XML passed to transferFromXML cannot be null'); - } - - } - - /** - * Get a human readable version of this exception. - * - * @return string - */ - public function __toString() { - $result = "The server encountered the following errors processing the request:"; - foreach ($this->_errors as $error) { - $result .= "\n" . $error->__toString(); - } - return $result; - } -} diff --git a/library/Zend/Gdata/Gapps/UserEntry.php b/library/Zend/Gdata/Gapps/UserEntry.php deleted file mode 100644 index d238a306be..0000000000 --- a/library/Zend/Gdata/Gapps/UserEntry.php +++ /dev/null @@ -1,295 +0,0 @@ - in the Google Data protocol. - * - * @category Zend - * @package Zend_Gdata - * @subpackage Gapps - * @copyright Copyright (c) 2005-2015 Zend Technologies USA Inc. (http://www.zend.com) - * @license http://framework.zend.com/license/new-bsd New BSD License - */ -class Zend_Gdata_Gapps_UserEntry extends Zend_Gdata_Entry -{ - - protected $_entryClassName = 'Zend_Gdata_Gapps_UserEntry'; - - /** - * element containing information about this user's - * account, including their username and permissions. - * - * @var Zend_Gdata_Gapps_Extension_Login - */ - protected $_login = null; - - /** - * element containing the user's actual name. - * - * @var Zend_Gdata_Gapps_Extension_Name - */ - protected $_name = null; - - /** - * element describing any storage quotas in place for - * this user. - * - * @var Zend_Gdata_Gapps_Extension_Quota - */ - protected $_quota = null; - - /** - * element containing information about other feeds - * relevant to this entry. - * - * @var Zend_Gdata_Extension_FeedLink - */ - protected $_feedLink = array(); - - /** - * Create a new instance. - * - * @param DOMElement $element (optional) DOMElement from which this - * object should be constructed. - */ - public function __construct($element = null) - { - $this->registerAllNamespaces(Zend_Gdata_Gapps::$namespaces); - parent::__construct($element); - } - - /** - * Retrieves a DOMElement which corresponds to this element and all - * child properties. This is used to build an entry back into a DOM - * and eventually XML text for application storage/persistence. - * - * @param DOMDocument $doc The DOMDocument used to construct DOMElements - * @return DOMElement The DOMElement representing this element and all - * child properties. - */ - public function getDOM($doc = null, $majorVersion = 1, $minorVersion = null) - { - $element = parent::getDOM($doc, $majorVersion, $minorVersion); - if ($this->_login !== null) { - $element->appendChild($this->_login->getDOM($element->ownerDocument)); - } - if ($this->_name !== null) { - $element->appendChild($this->_name->getDOM($element->ownerDocument)); - } - if ($this->_quota !== null) { - $element->appendChild($this->_quota->getDOM($element->ownerDocument)); - } - foreach ($this->_feedLink as $feedLink) { - $element->appendChild($feedLink->getDOM($element->ownerDocument)); - } - return $element; - } - - /** - * Creates individual Entry objects of the appropriate type and - * stores them as members of this entry based upon DOM data. - * - * @param DOMNode $child The DOMNode to process - */ - protected function takeChildFromDOM($child) - { - $absoluteNodeName = $child->namespaceURI . ':' . $child->localName; - - switch ($absoluteNodeName) { - case $this->lookupNamespace('apps') . ':' . 'login'; - $login = new Zend_Gdata_Gapps_Extension_Login(); - $login->transferFromDOM($child); - $this->_login = $login; - break; - case $this->lookupNamespace('apps') . ':' . 'name'; - $name = new Zend_Gdata_Gapps_Extension_Name(); - $name->transferFromDOM($child); - $this->_name = $name; - break; - case $this->lookupNamespace('apps') . ':' . 'quota'; - $quota = new Zend_Gdata_Gapps_Extension_Quota(); - $quota->transferFromDOM($child); - $this->_quota = $quota; - break; - case $this->lookupNamespace('gd') . ':' . 'feedLink'; - $feedLink = new Zend_Gdata_Extension_FeedLink(); - $feedLink->transferFromDOM($child); - $this->_feedLink[] = $feedLink; - break; - default: - parent::takeChildFromDOM($child); - break; - } - } - - /** - * Get the value of the login property for this object. - * - * @see setLogin - * @return Zend_Gdata_Gapps_Extension_Login The requested object. - */ - public function getLogin() - { - return $this->_login; - } - - /** - * Set the value of the login property for this object. This property - * is used to store the username address of the current user. - * - * @param Zend_Gdata_Gapps_Extension_Login $value The desired value for - * this instance's login property. - * @return Zend_Gdata_Gapps_UserEntry Provides a fluent interface. - */ - public function setLogin($value) - { - $this->_login = $value; - return $this; - } - - /** - * Get the value of the name property for this object. - * - * @see setName - * @return Zend_Gdata_Gapps_Extension_Name The requested object. - */ - public function getName() - { - return $this->_name; - } - - /** - * Set the value of the name property for this object. This property - * is used to store the full name of the current user. - * - * @param Zend_Gdata_Gapps_Extension_Name $value The desired value for - * this instance's name property. - * @return Zend_Gdata_Gapps_UserEntry Provides a fluent interface. - */ - public function setName($value) - { - $this->_name = $value; - return $this; - } - - /** - * Get the value of the quota property for this object. - * - * @see setQuota - * @return Zend_Gdata_Gapps_Extension_Quota The requested object. - */ - public function getQuota() - { - return $this->_quota; - } - - /** - * Set the value of the quota property for this object. This property - * is used to store the amount of storage available for the current - * user. Quotas may not be modifiable depending on the domain used. - * - * @param Zend_Gdata_Gapps_Extension_Quota $value The desired value for - * this instance's quota property. - * @return Zend_Gdata_Gapps_UserEntry Provides a fluent interface. - */ - public function setQuota($value) - { - $this->_quota = $value; - return $this; - } - - /** - * Returns all feed links for this entry, or if a rel value is - * specified, the feed link associated with that value is returned. - * - * @param string $rel The rel value of the link to be found. If null, - * the array of links is returned instead. - * @return mixed Either an array of Zend_Gdata_Extension_FeedLink - * objects if $rel is null, a single - * Zend_Gdata_Extension_FeedLink object if $rel is specified - * and a matching feed link is found, or null if $rel is - * specified and no matching feed link is found. - */ - public function getFeedLink($rel = null) - { - if ($rel == null) { - return $this->_feedLink; - } else { - foreach ($this->_feedLink as $feedLink) { - if ($feedLink->rel == $rel) { - return $feedLink; - } - } - return null; - } - } - - /** - * Set the value of the feed link property for this object. This property - * is used to provide links to alternative feeds relevant to this entry. - * - * @param array $value A collection of - * Zend_Gdata_Gapps_Extension_FeedLink objects. - * @return Zend_Gdata_Gapps_EventEntry Provides a fluent interface. - */ - public function setFeedLink($value) - { - $this->_feedLink = $value; - return $this; - } - -} diff --git a/library/Zend/Gdata/Gapps/UserFeed.php b/library/Zend/Gdata/Gapps/UserFeed.php deleted file mode 100644 index d7c1050449..0000000000 --- a/library/Zend/Gdata/Gapps/UserFeed.php +++ /dev/null @@ -1,53 +0,0 @@ -setUsername($username); - $this->setStartUsername($startUsername); - } - - /** - * Set the username to query for. When set, only users with a username - * matching this value will be returned in search results. Set to - * null to disable filtering by username. - * - * @see getUsername - * @param string $value The username to filter search results by, or null to - * disable. - */ - public function setUsername($value) - { - $this->_username = $value; - } - - /** - * Get the username to query for. If no username is set, null will be - * returned. - * - * @param string $value The username to filter search results by, or - * null if disabled. - */ - public function getUsername() - { - return $this->_username; - } - - /** - * Set the first username which should be displayed when retrieving - * a list of users. - * - * @param string $value The first username to be returned, or null to - * disable. - */ - public function setStartUsername($value) - { - if ($value !== null) { - $this->_params['startUsername'] = $value; - } else { - unset($this->_params['startUsername']); - } - } - - /** - * Get the first username which should be displayed when retrieving - * a list of users. - * - * @see setStartUsername - * @return string The first username to be returned, or null if - * disabled. - */ - public function getStartUsername() - { - if (array_key_exists('startUsername', $this->_params)) { - return $this->_params['startUsername']; - } else { - return null; - } - } - - /** - * Returns the query URL generated by this query instance. - * - * @return string The query URL for this instance. - */ - public function getQueryUrl() - { - $uri = $this->getBaseUrl(); - $uri .= Zend_Gdata_Gapps::APPS_USER_PATH; - if ($this->_username !== null) { - $uri .= '/' . $this->_username; - } - $uri .= $this->getQueryString(); - return $uri; - } - -} diff --git a/library/Zend/Gdata/Gbase.php b/library/Zend/Gdata/Gbase.php deleted file mode 100644 index dd8f39c09f..0000000000 --- a/library/Zend/Gdata/Gbase.php +++ /dev/null @@ -1,78 +0,0 @@ -registerPackage('Zend_Gdata_Geo'); - $this->registerPackage('Zend_Gdata_Geo_Extension'); - parent::__construct($client, $applicationId); - } - -} diff --git a/library/Zend/Gdata/Geo/Entry.php b/library/Zend/Gdata/Geo/Entry.php deleted file mode 100755 index 85ec04b207..0000000000 --- a/library/Zend/Gdata/Geo/Entry.php +++ /dev/null @@ -1,97 +0,0 @@ -registerAllNamespaces(Zend_Gdata_Geo::$namespaces); - parent::__construct($element); - } - - public function getDOM($doc = null, $majorVersion = 1, $minorVersion = null) - { - $element = parent::getDOM($doc, $majorVersion, $minorVersion); - if ($this->_where != null) { - $element->appendChild($this->_where->getDOM($element->ownerDocument)); - } - return $element; - } - - protected function takeChildFromDOM($child) - { - $absoluteNodeName = $child->namespaceURI . ':' . $child->localName; - switch ($absoluteNodeName) { - case $this->lookupNamespace('georss') . ':' . 'where': - $where = new Zend_Gdata_Geo_Extension_GeoRssWhere(); - $where->transferFromDOM($child); - $this->_where = $where; - break; - default: - parent::takeChildFromDOM($child); - break; - } - } - - public function getWhere() - { - return $this->_where; - } - - public function setWhere($value) - { - $this->_where = $value; - return $this; - } - - -} diff --git a/library/Zend/Gdata/Geo/Extension/GeoRssWhere.php b/library/Zend/Gdata/Geo/Extension/GeoRssWhere.php deleted file mode 100755 index 81b33c6c90..0000000000 --- a/library/Zend/Gdata/Geo/Extension/GeoRssWhere.php +++ /dev/null @@ -1,135 +0,0 @@ -registerAllNamespaces(Zend_Gdata_Geo::$namespaces); - parent::__construct(); - $this->setPoint($point); - } - - /** - * Retrieves a DOMElement which corresponds to this element and all - * child properties. This is used to build an entry back into a DOM - * and eventually XML text for application storage/persistence. - * - * @param DOMDocument $doc The DOMDocument used to construct DOMElements - * @return DOMElement The DOMElement representing this element and all - * child properties. - */ - public function getDOM($doc = null, $majorVersion = 1, $minorVersion = null) - { - $element = parent::getDOM($doc, $majorVersion, $minorVersion); - if ($this->_point !== null) { - $element->appendChild($this->_point->getDOM($element->ownerDocument)); - } - return $element; - } - - /** - * Creates individual Entry objects of the appropriate type and - * stores them as members of this entry based upon DOM data. - * - * @param DOMNode $child The DOMNode to process - */ - protected function takeChildFromDOM($child) - { - $absoluteNodeName = $child->namespaceURI . ':' . $child->localName; - - switch ($absoluteNodeName) { - case $this->lookupNamespace('gml') . ':' . 'Point'; - $point = new Zend_Gdata_Geo_Extension_GmlPoint(); - $point->transferFromDOM($child); - $this->_point = $point; - break; - } - } - - /** - * Get the value for this element's point attribute. - * - * @see setPoint - * @return Zend_Gdata_Geo_Extension_GmlPoint The requested attribute. - */ - public function getPoint() - { - return $this->_point; - } - - /** - * Set the value for this element's point attribute. - * - * @param Zend_Gdata_Geo_Extension_GmlPoint $value The desired value for this attribute. - * @return Zend_Gdata_Geo_Extension_GeoRssWhere Provides a fluent interface - */ - public function setPoint($value) - { - $this->_point = $value; - return $this; - } - -} diff --git a/library/Zend/Gdata/Geo/Extension/GmlPoint.php b/library/Zend/Gdata/Geo/Extension/GmlPoint.php deleted file mode 100755 index d6b4e50b8b..0000000000 --- a/library/Zend/Gdata/Geo/Extension/GmlPoint.php +++ /dev/null @@ -1,136 +0,0 @@ -registerAllNamespaces(Zend_Gdata_Geo::$namespaces); - parent::__construct(); - $this->setPos($pos); - } - - /** - * Retrieves a DOMElement which corresponds to this element and all - * child properties. This is used to build an entry back into a DOM - * and eventually XML text for application storage/persistence. - * - * @param DOMDocument $doc The DOMDocument used to construct DOMElements - * @return DOMElement The DOMElement representing this element and all - * child properties. - */ - public function getDOM($doc = null, $majorVersion = 1, $minorVersion = null) - { - $element = parent::getDOM($doc, $majorVersion, $minorVersion); - if ($this->_pos !== null) { - $element->appendChild($this->_pos->getDOM($element->ownerDocument)); - } - return $element; - } - - /** - * Creates individual Entry objects of the appropriate type and - * stores them as members of this entry based upon DOM data. - * - * @param DOMNode $child The DOMNode to process - */ - protected function takeChildFromDOM($child) - { - $absoluteNodeName = $child->namespaceURI . ':' . $child->localName; - - switch ($absoluteNodeName) { - case $this->lookupNamespace('gml') . ':' . 'pos'; - $pos = new Zend_Gdata_Geo_Extension_GmlPos(); - $pos->transferFromDOM($child); - $this->_pos = $pos; - break; - } - } - - /** - * Get the value for this element's pos attribute. - * - * @see setPos - * @return Zend_Gdata_Geo_Extension_GmlPos The requested attribute. - */ - public function getPos() - { - return $this->_pos; - } - - /** - * Set the value for this element's distance attribute. - * - * @param Zend_Gdata_Geo_Extension_GmlPos $value The desired value for this attribute - * @return Zend_Gdata_Geo_Extension_GmlPoint Provides a fluent interface - */ - public function setPos($value) - { - $this->_pos = $value; - return $this; - } - - -} diff --git a/library/Zend/Gdata/Geo/Extension/GmlPos.php b/library/Zend/Gdata/Geo/Extension/GmlPos.php deleted file mode 100755 index 57e73ec9a7..0000000000 --- a/library/Zend/Gdata/Geo/Extension/GmlPos.php +++ /dev/null @@ -1,61 +0,0 @@ -registerAllNamespaces(Zend_Gdata_Geo::$namespaces); - parent::__construct(); - $this->setText($text); - } - -} diff --git a/library/Zend/Gdata/Geo/Feed.php b/library/Zend/Gdata/Geo/Feed.php deleted file mode 100755 index f29d2113c9..0000000000 --- a/library/Zend/Gdata/Geo/Feed.php +++ /dev/null @@ -1,64 +0,0 @@ -registerAllNamespaces(Zend_Gdata_Geo::$namespaces); - parent::__construct($element); - } - -} diff --git a/library/Zend/Gdata/Health.php b/library/Zend/Gdata/Health.php deleted file mode 100755 index 66b57d8698..0000000000 --- a/library/Zend/Gdata/Health.php +++ /dev/null @@ -1,89 +0,0 @@ -config['proxy_host']) { - #require_once 'Zend/Http/Client/Adapter/Exception.php'; - throw new Zend_Http_Client_Adapter_Exception('No proxy host set!'); - } - - // Make sure we're properly connected - if (! $this->socket) { - #require_once 'Zend/Http/Client/Adapter/Exception.php'; - throw new Zend_Http_Client_Adapter_Exception( - 'Trying to write but we are not connected'); - } - - $host = $this->config['proxy_host']; - $port = $this->config['proxy_port']; - - if ($this->connected_to[0] != $host || $this->connected_to[1] != $port) { - #require_once 'Zend/Http/Client/Adapter/Exception.php'; - throw new Zend_Http_Client_Adapter_Exception( - 'Trying to write but we are connected to the wrong proxy ' . - 'server'); - } - - // Add Proxy-Authorization header - if ($this->config['proxy_user'] && ! isset($headers['proxy-authorization'])) { - $headers['proxy-authorization'] = Zend_Http_Client::encodeAuthHeader( - $this->config['proxy_user'], $this->config['proxy_pass'], $this->config['proxy_auth'] - ); - } - - // if we are proxying HTTPS, preform CONNECT handshake with the proxy - if ($uri->getScheme() == 'https' && (! $this->negotiated)) { - $this->connectHandshake($uri->getHost(), $uri->getPort(), $http_ver, $headers); - $this->negotiated = true; - } - - // Save request method for later - $this->method = $method; - - // Build request headers - $request = "{$method} {$uri->__toString()} HTTP/{$http_ver}\r\n"; - - // Add all headers to the request string - foreach ($headers as $k => $v) { - if (is_string($k)) $v = "$k: $v"; - $request .= "$v\r\n"; - } - - $request .= "\r\n"; - - // Send the request headers - if (! @fwrite($this->socket, $request)) { - #require_once 'Zend/Http/Client/Adapter/Exception.php'; - throw new Zend_Http_Client_Adapter_Exception( - 'Error writing request to proxy server'); - } - - // Read from $body, write to socket - $chunk = $body->read(self::CHUNK_SIZE); - while ($chunk !== false) { - if (!@fwrite($this->socket, $chunk)) { - #require_once 'Zend/Http/Client/Adapter/Exception.php'; - throw new Zend_Http_Client_Adapter_Exception( - 'Error writing request to server' - ); - } - $chunk = $body->read(self::CHUNK_SIZE); - } - $body->closeFileHandle(); - - return 'Large upload, request is not cached.'; - } -} diff --git a/library/Zend/Gdata/HttpAdapterStreamingSocket.php b/library/Zend/Gdata/HttpAdapterStreamingSocket.php deleted file mode 100644 index 0739137de2..0000000000 --- a/library/Zend/Gdata/HttpAdapterStreamingSocket.php +++ /dev/null @@ -1,111 +0,0 @@ -socket) { - #require_once 'Zend/Http/Client/Adapter/Exception.php'; - throw new Zend_Http_Client_Adapter_Exception( - 'Trying to write but we are not connected'); - } - - $host = $uri->getHost(); - $host = (strtolower($uri->getScheme()) == 'https' ? $this->config['ssltransport'] : 'tcp') . '://' . $host; - if ($this->connected_to[0] != $host || $this->connected_to[1] != $uri->getPort()) { - #require_once 'Zend/Http/Client/Adapter/Exception.php'; - throw new Zend_Http_Client_Adapter_Exception( - 'Trying to write but we are connected to the wrong host'); - } - - // Save request method for later - $this->method = $method; - - // Build request headers - $path = $uri->getPath(); - if ($uri->getQuery()) $path .= '?' . $uri->getQuery(); - $request = "{$method} {$path} HTTP/{$http_ver}\r\n"; - foreach ($headers as $k => $v) { - if (is_string($k)) $v = ucfirst($k) . ": $v"; - $request .= "$v\r\n"; - } - - // Send the headers over - $request .= "\r\n"; - if (! @fwrite($this->socket, $request)) { - #require_once 'Zend/Http/Client/Adapter/Exception.php'; - throw new Zend_Http_Client_Adapter_Exception( - 'Error writing request to server'); - } - - - //read from $body, write to socket - $chunk = $body->read(self::CHUNK_SIZE); - while ($chunk !== FALSE) { - if (! @fwrite($this->socket, $chunk)) { - #require_once 'Zend/Http/Client/Adapter/Exception.php'; - throw new Zend_Http_Client_Adapter_Exception( - 'Error writing request to server'); - } - $chunk = $body->read(self::CHUNK_SIZE); - } - $body->closeFileHandle(); - return 'Large upload, request is not cached.'; - } -} diff --git a/library/Zend/Gdata/HttpClient.php b/library/Zend/Gdata/HttpClient.php deleted file mode 100644 index 958fe7eb02..0000000000 --- a/library/Zend/Gdata/HttpClient.php +++ /dev/null @@ -1,355 +0,0 @@ -setAuthSubPrivateKey($key, $passphrase); - fclose($fp); - } - - /** - * Sets the PEM formatted private key to be used for secure AuthSub auth. - * - * In order to call this method, openssl must be enabled in your PHP - * installation. Otherwise, a Zend_Gdata_App_InvalidArgumentException - * will be thrown. - * - * @param string $key The private key - * @param string $passphrase The optional private key passphrase - * @throws Zend_Gdata_App_InvalidArgumentException - * @return Zend_Gdata_HttpClient Provides a fluent interface - */ - public function setAuthSubPrivateKey($key, $passphrase = null) { - if ($key != null && !function_exists('openssl_pkey_get_private')) { - #require_once 'Zend/Gdata/App/InvalidArgumentException.php'; - throw new Zend_Gdata_App_InvalidArgumentException( - 'You cannot enable secure AuthSub if the openssl module ' . - 'is not enabled in your PHP installation.'); - } - $this->_authSubPrivateKeyId = openssl_pkey_get_private( - $key, $passphrase); - return $this; - } - - /** - * Gets the openssl private key id - * - * @return string The private key - */ - public function getAuthSubPrivateKeyId() { - return $this->_authSubPrivateKeyId; - } - - /** - * Gets the AuthSub token used for authentication - * - * @return string The token - */ - public function getAuthSubToken() { - return $this->_authSubToken; - } - - /** - * Sets the AuthSub token used for authentication - * - * @param string $token The token - * @return Zend_Gdata_HttpClient Provides a fluent interface - */ - public function setAuthSubToken($token) { - $this->_authSubToken = $token; - return $this; - } - - /** - * Gets the ClientLogin token used for authentication - * - * @return string The token - */ - public function getClientLoginToken() { - return $this->_clientLoginToken; - } - - /** - * Sets the ClientLogin token used for authentication - * - * @param string $token The token - * @return Zend_Gdata_HttpClient Provides a fluent interface - */ - public function setClientLoginToken($token) { - $this->_clientLoginToken = $token; - return $this; - } - - /** - * Filters the HTTP requests being sent to add the Authorization header. - * - * If both AuthSub and ClientLogin tokens are set, - * AuthSub takes precedence. If an AuthSub key is set, then - * secure AuthSub authentication is used, and the request is signed. - * Requests must be signed only with the private key corresponding to the - * public key registered with Google. If an AuthSub key is set, but - * openssl support is not enabled in the PHP installation, an exception is - * thrown. - * - * @param string $method The HTTP method - * @param string $url The URL - * @param array $headers An associate array of headers to be - * sent with the request or null - * @param string $body The body of the request or null - * @param string $contentType The MIME content type of the body or null - * @throws Zend_Gdata_App_Exception if there was a signing failure - * @return array The processed values in an associative array, - * using the same names as the params - */ - public function filterHttpRequest($method, $url, $headers = array(), $body = null, $contentType = null) { - if ($this->getAuthSubToken() != null) { - // AuthSub authentication - if ($this->getAuthSubPrivateKeyId() != null) { - // secure AuthSub - $time = time(); - $nonce = Zend_Crypt_Math::randInteger(0, 999999999); - $dataToSign = $method . ' ' . $url . ' ' . $time . ' ' . $nonce; - - // compute signature - $pKeyId = $this->getAuthSubPrivateKeyId(); - $signSuccess = openssl_sign($dataToSign, $signature, $pKeyId, - OPENSSL_ALGO_SHA1); - if (!$signSuccess) { - #require_once 'Zend/Gdata/App/Exception.php'; - throw new Zend_Gdata_App_Exception( - 'openssl_signing failure - returned false'); - } - // encode signature - $encodedSignature = base64_encode($signature); - - // final header - $headers['authorization'] = 'AuthSub token="' . $this->getAuthSubToken() . '" ' . - 'data="' . $dataToSign . '" ' . - 'sig="' . $encodedSignature . '" ' . - 'sigalg="rsa-sha1"'; - } else { - // AuthSub without secure tokens - $headers['authorization'] = 'AuthSub token="' . $this->getAuthSubToken() . '"'; - } - } elseif ($this->getClientLoginToken() != null) { - $headers['authorization'] = 'GoogleLogin auth=' . $this->getClientLoginToken(); - } - return array('method' => $method, 'url' => $url, 'body' => $body, 'headers' => $headers, 'contentType' => $contentType); - } - - /** - * Method for filtering the HTTP response, though no filtering is - * currently done. - * - * @param Zend_Http_Response $response The response object to filter - * @return Zend_Http_Response The filterd response object - */ - public function filterHttpResponse($response) { - return $response; - } - - /** - * Return the current connection adapter - * - * @return Zend_Http_Client_Adapter_Interface|string $adapter - */ - public function getAdapter() - { - return $this->adapter; - } - - /** - * Load the connection adapter - * - * @param Zend_Http_Client_Adapter_Interface $adapter - * @return void - */ - public function setAdapter($adapter) - { - if ($adapter == null) { - $this->adapter = $adapter; - } else { - parent::setAdapter($adapter); - } - } - - /** - * Set the streamingRequest variable which controls whether we are - * sending the raw (already encoded) POST data from a stream source. - * - * @param boolean $value The value to set. - * @return void - */ - public function setStreamingRequest($value) - { - $this->_streamingRequest = $value; - } - - /** - * Check whether the client is set to perform streaming requests. - * - * @return boolean True if yes, false otherwise. - */ - public function getStreamingRequest() - { - if ($this->_streamingRequest()) { - return true; - } else { - return false; - } - } - - /** - * Prepare the request body (for POST and PUT requests) - * - * @return string - * @throws Zend_Http_Client_Exception - */ - protected function _prepareBody() - { - if($this->_streamingRequest) { - $this->setHeaders(self::CONTENT_LENGTH, - $this->raw_post_data->getTotalSize()); - return $this->raw_post_data; - } - else { - return parent::_prepareBody(); - } - } - - /** - * Clear all custom parameters we set. - * - * @return Zend_Http_Client - */ - public function resetParameters($clearAll = false) - { - $this->_streamingRequest = false; - - return parent::resetParameters($clearAll); - } - - /** - * Set the raw (already encoded) POST data from a stream source. - * - * This is used to support POSTing from open file handles without - * caching the entire body into memory. It is a wrapper around - * Zend_Http_Client::setRawData(). - * - * @param string $data The request data - * @param string $enctype The encoding type - * @return Zend_Http_Client - */ - public function setRawDataStream($data, $enctype = null) - { - $this->_streamingRequest = true; - return $this->setRawData($data, $enctype); - } - -} diff --git a/library/Zend/Gdata/Kind/EventEntry.php b/library/Zend/Gdata/Kind/EventEntry.php deleted file mode 100644 index 99d0895281..0000000000 --- a/library/Zend/Gdata/Kind/EventEntry.php +++ /dev/null @@ -1,428 +0,0 @@ -_who != null) { - foreach ($this->_who as $who) { - $element->appendChild($who->getDOM($element->ownerDocument)); - } - } - if ($this->_when != null) { - foreach ($this->_when as $when) { - $element->appendChild($when->getDOM($element->ownerDocument)); - } - } - if ($this->_where != null) { - foreach ($this->_where as $where) { - $element->appendChild($where->getDOM($element->ownerDocument)); - } - } - if ($this->_recurrenceException != null) { - foreach ($this->_recurrenceException as $recurrenceException) { - $element->appendChild($recurrenceException->getDOM($element->ownerDocument)); - } - } - if ($this->_extendedProperty != null) { - foreach ($this->_extendedProperty as $extProp) { - $element->appendChild($extProp->getDOM($element->ownerDocument)); - } - } - - if ($this->_recurrence != null) { - $element->appendChild($this->_recurrence->getDOM($element->ownerDocument)); - } - if ($this->_eventStatus != null) { - $element->appendChild($this->_eventStatus->getDOM($element->ownerDocument)); - } - if ($this->_comments != null) { - $element->appendChild($this->_comments->getDOM($element->ownerDocument)); - } - if ($this->_transparency != null) { - $element->appendChild($this->_transparency->getDOM($element->ownerDocument)); - } - if ($this->_visibility != null) { - $element->appendChild($this->_visibility->getDOM($element->ownerDocument)); - } - if ($this->_originalEvent != null) { - $element->appendChild($this->_originalEvent->getDOM($element->ownerDocument)); - } - if ($this->_entryLink != null) { - $element->appendChild($this->_entryLink->getDOM($element->ownerDocument)); - } - - - return $element; - } - - protected function takeChildFromDOM($child) - { - $absoluteNodeName = $child->namespaceURI . ':' . $child->localName; - switch ($absoluteNodeName) { - case $this->lookupNamespace('gd') . ':' . 'where'; - $where = new Zend_Gdata_Extension_Where(); - $where->transferFromDOM($child); - $this->_where[] = $where; - break; - case $this->lookupNamespace('gd') . ':' . 'when'; - $when = new Zend_Gdata_Extension_When(); - $when->transferFromDOM($child); - $this->_when[] = $when; - break; - case $this->lookupNamespace('gd') . ':' . 'who'; - $who = new Zend_Gdata_Extension_Who(); - $who ->transferFromDOM($child); - $this->_who[] = $who; - break; - case $this->lookupNamespace('gd') . ':' . 'recurrence'; - $recurrence = new Zend_Gdata_Extension_Recurrence(); - $recurrence->transferFromDOM($child); - $this->_recurrence = $recurrence; - break; - case $this->lookupNamespace('gd') . ':' . 'eventStatus'; - $eventStatus = new Zend_Gdata_Extension_EventStatus(); - $eventStatus->transferFromDOM($child); - $this->_eventStatus = $eventStatus; - break; - case $this->lookupNamespace('gd') . ':' . 'comments'; - $comments = new Zend_Gdata_Extension_Comments(); - $comments->transferFromDOM($child); - $this->_comments = $comments; - break; - case $this->lookupNamespace('gd') . ':' . 'transparency'; - $transparency = new Zend_Gdata_Extension_Transparency(); - $transparency ->transferFromDOM($child); - $this->_transparency = $transparency; - break; - case $this->lookupNamespace('gd') . ':' . 'visibility'; - $visiblity = new Zend_Gdata_Extension_Visibility(); - $visiblity ->transferFromDOM($child); - $this->_visibility = $visiblity; - break; - case $this->lookupNamespace('gd') . ':' . 'recurrenceException'; - #require_once 'Zend/Gdata/Extension/RecurrenceException.php'; - $recurrenceException = new Zend_Gdata_Extension_RecurrenceException(); - $recurrenceException ->transferFromDOM($child); - $this->_recurrenceException[] = $recurrenceException; - break; - case $this->lookupNamespace('gd') . ':' . 'originalEvent'; - $originalEvent = new Zend_Gdata_Extension_OriginalEvent(); - $originalEvent ->transferFromDOM($child); - $this->_originalEvent = $originalEvent; - break; - case $this->lookupNamespace('gd') . ':' . 'extendedProperty'; - $extProp = new Zend_Gdata_Extension_ExtendedProperty(); - $extProp->transferFromDOM($child); - $this->_extendedProperty[] = $extProp; - break; - case $this->lookupNamespace('gd') . ':' . 'entryLink': - $entryLink = new Zend_Gdata_Extension_EntryLink(); - $entryLink->transferFromDOM($child); - $this->_entryLink = $entryLink; - break; - - default: - parent::takeChildFromDOM($child); - break; - } - } - - public function getWhen() - { - return $this->_when; - } - - /** - * @param array $value - * @return Zend_Gdata_Kind_EventEntry Provides a fluent interface - */ - public function setWhen($value) - { - $this->_when = $value; - return $this; - } - - public function getWhere() - { - return $this->_where; - } - - /** - * @param array $value - * @return Zend_Gdata_Kind_EventEntry Provides a fluent interface - */ - public function setWhere($value) - { - $this->_where = $value; - return $this; - } - - public function getWho() - { - return $this->_who; - } - - /** - * @param array $value - * @return Zend_Gdata_Kind_EventEntry Provides a fluent interface - */ - public function setWho($value) - { - $this->_who = $value; - return $this; - } - - public function getRecurrence() - { - return $this->_recurrence; - } - - /** - * @param array $value - * @return Zend_Gdata_Kind_EventEntry Provides a fluent interface - */ - public function setRecurrence($value) - { - $this->_recurrence = $value; - return $this; - } - - public function getEventStatus() - { - return $this->_eventStatus; - } - - /** - * @param array $value - * @return Zend_Gdata_Kind_EventEntry Provides a fluent interface - */ - public function setEventStatus($value) - { - $this->_eventStatus = $value; - return $this; - } - - public function getComments() - { - return $this->_comments; - } - - /** - * @param array $value - * @return Zend_Gdata_Kind_EventEntry Provides a fluent interface - */ - public function setComments($value) - { - $this->_comments = $value; - return $this; - } - - public function getTransparency() - { - return $this->_transparency; - } - - /** - * @param Zend_Gdata_Transparency $value - * @return Zend_Gdata_Kind_EventEntry Provides a fluent interface - */ - public function setTransparency($value) - { - $this->_transparency = $value; - return $this; - } - - public function getVisibility() - { - return $this->_visibility; - } - - /** - * @param Zend_Gdata_Visibility $value - * @return Zend_Gdata_Kind_EventEntry Provides a fluent interface - */ - public function setVisibility($value) - { - $this->_visibility = $value; - return $this; - } - - public function getRecurrenceExcption() - { - return $this->_recurrenceException; - } - - /** - * @param array $value - * @return Zend_Gdata_Kind_EventEntry Provides a fluent interface - */ - public function setRecurrenceException($value) - { - $this->_recurrenceException = $value; - return $this; - } - - public function getExtendedProperty() - { - return $this->_extendedProperty; - } - - /** - * @param array $value - * @return Zend_Gdata_Kind_EventEntry Provides a fluent interface - */ - public function setExtendedProperty($value) - { - $this->_extendedProperty = $value; - return $this; - } - - public function getOriginalEvent() - { - return $this->_originalEvent; - } - - /** - * @param Zend_Gdata_Extension_OriginalEvent $value - * @return Zend_Gdata_Kind_EventEntry Provides a fluent interface - */ - public function setOriginalEvent($value) - { - $this->_originalEvent = $value; - return $this; - } - - /** - * Get this entry's EntryLink element. - * - * @return Zend_Gdata_Extension_EntryLink The requested entry. - */ - public function getEntryLink() - { - return $this->_entryLink; - } - - /** - * Set the child's EntryLink element. - * - * @param Zend_Gdata_Extension_EntryLink $value The desired value for this attribute. - * @return Zend_Gdata_Extension_Who The element being modified. - */ - public function setEntryLink($value) - { - $this->_entryLink = $value; - return $this; - } - - -} diff --git a/library/Zend/Gdata/Media.php b/library/Zend/Gdata/Media.php deleted file mode 100755 index a68e962724..0000000000 --- a/library/Zend/Gdata/Media.php +++ /dev/null @@ -1,65 +0,0 @@ -registerPackage('Zend_Gdata_Media'); - $this->registerPackage('Zend_Gdata_Media_Extension'); - parent::__construct($client, $applicationId); - } - -} diff --git a/library/Zend/Gdata/Media/Entry.php b/library/Zend/Gdata/Media/Entry.php deleted file mode 100755 index 63f6bba5d8..0000000000 --- a/library/Zend/Gdata/Media/Entry.php +++ /dev/null @@ -1,134 +0,0 @@ -registerAllNamespaces(Zend_Gdata_Media::$namespaces); - parent::__construct($element); - } - - /** - * Retrieves a DOMElement which corresponds to this element and all - * child properties. This is used to build an entry back into a DOM - * and eventually XML text for application storage/persistence. - * - * @param DOMDocument $doc The DOMDocument used to construct DOMElements - * @return DOMElement The DOMElement representing this element and all - * child properties. - */ - public function getDOM($doc = null, $majorVersion = 1, $minorVersion = null) - { - $element = parent::getDOM($doc, $majorVersion, $minorVersion); - if ($this->_mediaGroup != null) { - $element->appendChild($this->_mediaGroup->getDOM($element->ownerDocument)); - } - return $element; - } - - /** - * Creates individual Entry objects of the appropriate type and - * stores them as members of this entry based upon DOM data. - * - * @param DOMNode $child The DOMNode to process - */ - protected function takeChildFromDOM($child) - { - $absoluteNodeName = $child->namespaceURI . ':' . $child->localName; - switch ($absoluteNodeName) { - case $this->lookupNamespace('media') . ':' . 'group': - $mediaGroup = new Zend_Gdata_Media_Extension_MediaGroup(); - $mediaGroup->transferFromDOM($child); - $this->_mediaGroup = $mediaGroup; - break; - default: - parent::takeChildFromDOM($child); - break; - } - } - - /** - * Returns the entry's mediaGroup object. - * - * @return Zend_Gdata_Media_Extension_MediaGroup - */ - public function getMediaGroup() - { - return $this->_mediaGroup; - } - - /** - * Sets the entry's mediaGroup object. - * - * @param Zend_Gdata_Media_Extension_MediaGroup $mediaGroup - * @return Zend_Gdata_Media_Entry Provides a fluent interface - */ - public function setMediaGroup($mediaGroup) - { - $this->_mediaGroup = $mediaGroup; - return $this; - } - - -} diff --git a/library/Zend/Gdata/Media/Extension/MediaCategory.php b/library/Zend/Gdata/Media/Extension/MediaCategory.php deleted file mode 100755 index 58167b974d..0000000000 --- a/library/Zend/Gdata/Media/Extension/MediaCategory.php +++ /dev/null @@ -1,148 +0,0 @@ -registerAllNamespaces(Zend_Gdata_Media::$namespaces); - parent::__construct(); - $this->_text = $text; - $this->_scheme = $scheme; - $this->_label = $label; - } - - /** - * Retrieves a DOMElement which corresponds to this element and all - * child properties. This is used to build an entry back into a DOM - * and eventually XML text for sending to the server upon updates, or - * for application storage/persistence. - * - * @param DOMDocument $doc The DOMDocument used to construct DOMElements - * @return DOMElement The DOMElement representing this element and all - * child properties. - */ - public function getDOM($doc = null, $majorVersion = 1, $minorVersion = null) - { - $element = parent::getDOM($doc, $majorVersion, $minorVersion); - if ($this->_scheme !== null) { - $element->setAttribute('scheme', $this->_scheme); - } - if ($this->_label !== null) { - $element->setAttribute('label', $this->_label); - } - return $element; - } - - /** - * Given a DOMNode representing an attribute, tries to map the data into - * instance members. If no mapping is defined, the name and value are - * stored in an array. - * - * @param DOMNode $attribute The DOMNode attribute needed to be handled - */ - protected function takeAttributeFromDOM($attribute) - { - switch ($attribute->localName) { - case 'scheme': - $this->_scheme = $attribute->nodeValue; - break; - case 'label': - $this->_label = $attribute->nodeValue; - break; - default: - parent::takeAttributeFromDOM($attribute); - } - } - - /** - * Returns the URI that identifies the categorization scheme - * Optional. - * - * @return string URI that identifies the categorization scheme - */ - public function getScheme() - { - return $this->_scheme; - } - - /** - * @param string $value URI that identifies the categorization scheme - * @return Zend_Gdata_Media_Extension_MediaCategory Provides a fluent interface - */ - public function setScheme($value) - { - $this->_scheme = $value; - return $this; - } - - /** - * @return string Human-readable label to be displayed in applications - */ - public function getLabel() - { - return $this->_label; - } - - /** - * @param string $value Human-readable label to be displayed in applications - * @return Zend_Gdata_Media_Extension_MediaCategory Provides a fluent interface - */ - public function setLabel($value) - { - $this->_label = $value; - return $this; - } - -} diff --git a/library/Zend/Gdata/Media/Extension/MediaContent.php b/library/Zend/Gdata/Media/Extension/MediaContent.php deleted file mode 100755 index 3685a5b9a5..0000000000 --- a/library/Zend/Gdata/Media/Extension/MediaContent.php +++ /dev/null @@ -1,522 +0,0 @@ -registerAllNamespaces(Zend_Gdata_Media::$namespaces); - parent::__construct(); - $this->_url = $url; - $this->_fileSize = $fileSize; - $this->_type = $type; - $this->_medium = $medium; - $this->_isDefault = $isDefault; - $this->_expression = $expression; - $this->_bitrate = $bitrate; - $this->_framerate = $framerate; - $this->_samplingrate = $samplingrate; - $this->_channels = $channels; - $this->_duration = $duration; - $this->_height = $height; - $this->_width = $width; - $this->_lang = $lang; - } - - - /** - * Retrieves a DOMElement which corresponds to this element and all - * child properties. This is used to build an entry back into a DOM - * and eventually XML text for sending to the server upon updates, or - * for application storage/persistence. - * - * @param DOMDocument $doc The DOMDocument used to construct DOMElements - * @return DOMElement The DOMElement representing this element and all - * child properties. - */ - public function getDOM($doc = null, $majorVersion = 1, $minorVersion = null) - { - $element = parent::getDOM($doc, $majorVersion, $minorVersion); - if ($this->_url !== null) { - $element->setAttribute('url', $this->_url); - } - if ($this->_fileSize !== null) { - $element->setAttribute('fileSize', $this->_fileSize); - } - if ($this->_type !== null) { - $element->setAttribute('type', $this->_type); - } - if ($this->_medium !== null) { - $element->setAttribute('medium', $this->_medium); - } - if ($this->_isDefault !== null) { - $element->setAttribute('isDefault', $this->_isDefault); - } - if ($this->_expression !== null) { - $element->setAttribute('expression', $this->_expression); - } - if ($this->_bitrate !== null) { - $element->setAttribute('bitrate', $this->_bitrate); - } - if ($this->_framerate !== null) { - $element->setAttribute('framerate', $this->_framerate); - } - if ($this->_samplingrate !== null) { - $element->setAttribute('samplingrate', $this->_samplingrate); - } - if ($this->_channels !== null) { - $element->setAttribute('channels', $this->_channels); - } - if ($this->_duration !== null) { - $element->setAttribute('duration', $this->_duration); - } - if ($this->_height !== null) { - $element->setAttribute('height', $this->_height); - } - if ($this->_width !== null) { - $element->setAttribute('width', $this->_width); - } - if ($this->_lang !== null) { - $element->setAttribute('lang', $this->_lang); - } - return $element; - } - - /** - * Given a DOMNode representing an attribute, tries to map the data into - * instance members. If no mapping is defined, the name and value are - * stored in an array. - * - * @param DOMNode $attribute The DOMNode attribute needed to be handled - */ - protected function takeAttributeFromDOM($attribute) - { - switch ($attribute->localName) { - case 'url': - $this->_url = $attribute->nodeValue; - break; - case 'fileSize': - $this->_fileSize = $attribute->nodeValue; - break; - case 'type': - $this->_type = $attribute->nodeValue; - break; - case 'medium': - $this->_medium = $attribute->nodeValue; - break; - case 'isDefault': - $this->_isDefault = $attribute->nodeValue; - break; - case 'expression': - $this->_expression = $attribute->nodeValue; - break; - case 'bitrate': - $this->_bitrate = $attribute->nodeValue; - break; - case 'framerate': - $this->_framerate = $attribute->nodeValue; - break; - case 'samplingrate': - $this->_samplingrate = $attribute->nodeValue; - break; - case 'channels': - $this->_channels = $attribute->nodeValue; - break; - case 'duration': - $this->_duration = $attribute->nodeValue; - break; - case 'height': - $this->_height = $attribute->nodeValue; - break; - case 'width': - $this->_width = $attribute->nodeValue; - break; - case 'lang': - $this->_lang = $attribute->nodeValue; - break; - default: - parent::takeAttributeFromDOM($attribute); - } - } - - /** - * Returns the URL representing this MediaContent object - * - * @return string The URL representing this MediaContent object. - */ - public function __toString() - { - return $this->getUrl(); - } - - /** - * @return string The direct URL to the media object - */ - public function getUrl() - { - return $this->_url; - } - - /** - * @param string $value The direct URL to the media object - * @return Zend_Gdata_Media_Extension_MediaContent Provides a fluent interface - */ - public function setUrl($value) - { - $this->_url = $value; - return $this; - } - - /** - * @return int The size of the media in bytes - */ - public function getFileSize() - { - return $this->_fileSize; - } - - /** - * @param int $value - * @return Zend_Gdata_Media_Extension_MediaContent Provides a fluent interface - */ - public function setFileSize($value) - { - $this->_fileSize = $value; - return $this; - } - - /** - * @return string - */ - public function getType() - { - return $this->_type; - } - - /** - * @param string $value - * @return Zend_Gdata_Media_Extension_MediaContent Provides a fluent interface - */ - public function setType($value) - { - $this->_type = $value; - return $this; - } - - /** - * @return string - */ - public function getMedium() - { - return $this->_medium; - } - - /** - * @param string $value - * @return Zend_Gdata_Media_Extension_MediaContent Provides a fluent interface - */ - public function setMedium($value) - { - $this->_medium = $value; - return $this; - } - - /** - * @return bool - */ - public function getIsDefault() - { - return $this->_isDefault; - } - - /** - * @param bool $value - * @return Zend_Gdata_Media_Extension_MediaContent Provides a fluent interface - */ - public function setIsDefault($value) - { - $this->_isDefault = $value; - return $this; - } - - /** - * @return string - */ - public function getExpression() - { - return $this->_expression; - } - - /** - * @param string - * @return Zend_Gdata_Media_Extension_MediaContent Provides a fluent interface - */ - public function setExpression($value) - { - $this->_expression = $value; - return $this; - } - - /** - * @return int - */ - public function getBitrate() - { - return $this->_bitrate; - } - - /** - * @param int - * @return Zend_Gdata_Media_Extension_MediaContent Provides a fluent interface - */ - public function setBitrate($value) - { - $this->_bitrate = $value; - return $this; - } - - /** - * @return int - */ - public function getFramerate() - { - return $this->_framerate; - } - - /** - * @param int - * @return Zend_Gdata_Media_Extension_MediaContent Provides a fluent interface - */ - public function setFramerate($value) - { - $this->_framerate = $value; - return $this; - } - - /** - * @return int - */ - public function getSamplingrate() - { - return $this->_samplingrate; - } - - /** - * @param int - * @return Zend_Gdata_Media_Extension_MediaContent Provides a fluent interface - */ - public function setSamplingrate($value) - { - $this->_samplingrate = $value; - return $this; - } - - /** - * @return int - */ - public function getChannels() - { - return $this->_channels; - } - - /** - * @param int - * @return Zend_Gdata_Media_Extension_MediaContent Provides a fluent interface - */ - public function setChannels($value) - { - $this->_channels = $value; - return $this; - } - - /** - * @return int - */ - public function getDuration() - { - return $this->_duration; - } - - /** - * - * @param int - * @return Zend_Gdata_Media_Extension_MediaContent Provides a fluent interface - */ - public function setDuration($value) - { - $this->_duration = $value; - return $this; - } - - /** - * @return int - */ - public function getHeight() - { - return $this->_height; - } - - /** - * @param int - * @return Zend_Gdata_Media_Extension_MediaContent Provides a fluent interface - */ - public function setHeight($value) - { - $this->_height = $value; - return $this; - } - - /** - * @return int - */ - public function getWidth() - { - return $this->_width; - } - - /** - * @param int - * @return Zend_Gdata_Media_Extension_MediaContent Provides a fluent interface - */ - public function setWidth($value) - { - $this->_width = $value; - return $this; - } - - /** - * @return string - */ - public function getLang() - { - return $this->_lang; - } - - /** - * @param string - * @return Zend_Gdata_Media_Extension_MediaContent Provides a fluent interface - */ - public function setLang($value) - { - $this->_lang = $value; - return $this; - } - -} diff --git a/library/Zend/Gdata/Media/Extension/MediaCopyright.php b/library/Zend/Gdata/Media/Extension/MediaCopyright.php deleted file mode 100755 index e1ddc1b398..0000000000 --- a/library/Zend/Gdata/Media/Extension/MediaCopyright.php +++ /dev/null @@ -1,116 +0,0 @@ -registerAllNamespaces(Zend_Gdata_Media::$namespaces); - parent::__construct(); - $this->_text = $text; - $this->_url = $url; - } - - /** - * Retrieves a DOMElement which corresponds to this element and all - * child properties. This is used to build an entry back into a DOM - * and eventually XML text for sending to the server upon updates, or - * for application storage/persistence. - * - * @param DOMDocument $doc The DOMDocument used to construct DOMElements - * @return DOMElement The DOMElement representing this element and all - * child properties. - */ - public function getDOM($doc = null, $majorVersion = 1, $minorVersion = null) - { - $element = parent::getDOM($doc, $majorVersion, $minorVersion); - if ($this->_url !== null) { - $element->setAttribute('url', $this->_url); - } - return $element; - } - - /** - * Given a DOMNode representing an attribute, tries to map the data into - * instance members. If no mapping is defined, the name and value are - * stored in an array. - * - * @param DOMNode $attribute The DOMNode attribute needed to be handled - */ - protected function takeAttributeFromDOM($attribute) - { - switch ($attribute->localName) { - case 'url': - $this->_url = $attribute->nodeValue; - break; - default: - parent::takeAttributeFromDOM($attribute); - } - } - - /** - * @return string - */ - public function getUrl() - { - return $this->_url; - } - - /** - * @param string $value - * @return Zend_Gdata_Media_Extension_MediaCopyright Provides a fluent interface - */ - public function setUrl($value) - { - $this->_url = $value; - return $this; - } - -} diff --git a/library/Zend/Gdata/Media/Extension/MediaCredit.php b/library/Zend/Gdata/Media/Extension/MediaCredit.php deleted file mode 100755 index 92382b54c6..0000000000 --- a/library/Zend/Gdata/Media/Extension/MediaCredit.php +++ /dev/null @@ -1,149 +0,0 @@ -registerAllNamespaces(Zend_Gdata_Media::$namespaces); - parent::__construct(); - $this->_text = $text; - $this->_role = $role; - $this->_scheme = $scheme; - } - - /** - * Retrieves a DOMElement which corresponds to this element and all - * child properties. This is used to build an entry back into a DOM - * and eventually XML text for sending to the server upon updates, or - * for application storage/persistence. - * - * @param DOMDocument $doc The DOMDocument used to construct DOMElements - * @return DOMElement The DOMElement representing this element and all - * child properties. - */ - public function getDOM($doc = null, $majorVersion = 1, $minorVersion = null) - { - $element = parent::getDOM($doc, $majorVersion, $minorVersion); - if ($this->_role !== null) { - $element->setAttribute('role', $this->_role); - } - if ($this->_scheme !== null) { - $element->setAttribute('scheme', $this->_scheme); - } - return $element; - } - - /** - * Given a DOMNode representing an attribute, tries to map the data into - * instance members. If no mapping is defined, the name and value are - * stored in an array. - * - * @param DOMNode $attribute The DOMNode attribute needed to be handled - */ - protected function takeAttributeFromDOM($attribute) - { - switch ($attribute->localName) { - case 'role': - $this->_role = $attribute->nodeValue; - break; - case 'scheme': - $this->_scheme = $attribute->nodeValue; - break; - default: - parent::takeAttributeFromDOM($attribute); - } - } - - /** - * @return string - */ - public function getRole() - { - return $this->_role; - } - - /** - * @param string $value - * @return Zend_Gdata_Media_Extension_MediaCredit Provides a fluent interface - */ - public function setRole($value) - { - $this->_role = $value; - return $this; - } - - /** - * @return string - */ - public function getScheme() - { - return $this->_scheme; - } - - /** - * @param string $value - * @return Zend_Gdata_Media_Extension_MediaCredit Provides a fluent interface - */ - public function setScheme($value) - { - $this->_scheme = $value; - return $this; - } - -} diff --git a/library/Zend/Gdata/Media/Extension/MediaDescription.php b/library/Zend/Gdata/Media/Extension/MediaDescription.php deleted file mode 100755 index 9a0277e3f1..0000000000 --- a/library/Zend/Gdata/Media/Extension/MediaDescription.php +++ /dev/null @@ -1,116 +0,0 @@ -registerAllNamespaces(Zend_Gdata_Media::$namespaces); - parent::__construct(); - $this->_type = $type; - $this->_text = $text; - } - - /** - * Retrieves a DOMElement which corresponds to this element and all - * child properties. This is used to build an entry back into a DOM - * and eventually XML text for sending to the server upon updates, or - * for application storage/persistence. - * - * @param DOMDocument $doc The DOMDocument used to construct DOMElements - * @return DOMElement The DOMElement representing this element and all - * child properties. - */ - public function getDOM($doc = null, $majorVersion = 1, $minorVersion = null) - { - $element = parent::getDOM($doc, $majorVersion, $minorVersion); - if ($this->_type !== null) { - $element->setAttribute('type', $this->_type); - } - return $element; - } - - /** - * Given a DOMNode representing an attribute, tries to map the data into - * instance members. If no mapping is defined, the name and value are - * stored in an array. - * - * @param DOMNode $attribute The DOMNode attribute needed to be handled - */ - protected function takeAttributeFromDOM($attribute) - { - switch ($attribute->localName) { - case 'type': - $this->_type = $attribute->nodeValue; - break; - default: - parent::takeAttributeFromDOM($attribute); - } - } - - /** - * @return string - */ - public function getType() - { - return $this->_type; - } - - /** - * @param string $value - * @return Zend_Gdata_Media_Extension_MediaDescription Provides a fluent interface - */ - public function setType($value) - { - $this->_type = $value; - return $this; - } - -} diff --git a/library/Zend/Gdata/Media/Extension/MediaGroup.php b/library/Zend/Gdata/Media/Extension/MediaGroup.php deleted file mode 100755 index b0b77206e0..0000000000 --- a/library/Zend/Gdata/Media/Extension/MediaGroup.php +++ /dev/null @@ -1,566 +0,0 @@ -registerAllNamespaces(Zend_Gdata_Media::$namespaces); - parent::__construct($element); - } - - /** - * Retrieves a DOMElement which corresponds to this element and all - * child properties. This is used to build an entry back into a DOM - * and eventually XML text for sending to the server upon updates, or - * for application storage/persistence. - * - * @param DOMDocument $doc The DOMDocument used to construct DOMElements - * @return DOMElement The DOMElement representing this element and all - * child properties. - */ - public function getDOM($doc = null, $majorVersion = 1, $minorVersion = null) - { - $element = parent::getDOM($doc, $majorVersion, $minorVersion); - foreach ($this->_content as $content) { - $element->appendChild($content->getDOM($element->ownerDocument)); - } - foreach ($this->_category as $category) { - $element->appendChild($category->getDOM($element->ownerDocument)); - } - foreach ($this->_credit as $credit) { - $element->appendChild($credit->getDOM($element->ownerDocument)); - } - foreach ($this->_player as $player) { - $element->appendChild($player->getDOM($element->ownerDocument)); - } - foreach ($this->_rating as $rating) { - $element->appendChild($rating->getDOM($element->ownerDocument)); - } - foreach ($this->_restriction as $restriction) { - $element->appendChild($restriction->getDOM($element->ownerDocument)); - } - foreach ($this->_mediaText as $text) { - $element->appendChild($text->getDOM($element->ownerDocument)); - } - foreach ($this->_thumbnail as $thumbnail) { - $element->appendChild($thumbnail->getDOM($element->ownerDocument)); - } - if ($this->_copyright != null) { - $element->appendChild( - $this->_copyright->getDOM($element->ownerDocument)); - } - if ($this->_description != null) { - $element->appendChild( - $this->_description->getDOM($element->ownerDocument)); - } - foreach ($this->_hash as $hash) { - $element->appendChild($hash->getDOM($element->ownerDocument)); - } - if ($this->_keywords != null) { - $element->appendChild( - $this->_keywords->getDOM($element->ownerDocument)); - } - if ($this->_title != null) { - $element->appendChild( - $this->_title->getDOM($element->ownerDocument)); - } - return $element; - } - - /** - * Creates individual Entry objects of the appropriate type and - * stores them in the $_entry array based upon DOM data. - * - * @param DOMNode $child The DOMNode to process - */ - protected function takeChildFromDOM($child) - { - $absoluteNodeName = $child->namespaceURI . ':' . $child->localName; - switch ($absoluteNodeName) { - case $this->lookupNamespace('media') . ':' . 'content'; - $content = new Zend_Gdata_Media_Extension_MediaContent(); - $content->transferFromDOM($child); - $this->_content[] = $content; - break; - case $this->lookupNamespace('media') . ':' . 'category'; - $category = new Zend_Gdata_Media_Extension_MediaCategory(); - $category->transferFromDOM($child); - $this->_category[] = $category; - break; - case $this->lookupNamespace('media') . ':' . 'copyright'; - $copyright = new Zend_Gdata_Media_Extension_MediaCopyright(); - $copyright->transferFromDOM($child); - $this->_copyright = $copyright; - break; - case $this->lookupNamespace('media') . ':' . 'credit'; - $credit = new Zend_Gdata_Media_Extension_MediaCredit(); - $credit->transferFromDOM($child); - $this->_credit[] = $credit; - break; - case $this->lookupNamespace('media') . ':' . 'description'; - $description = new Zend_Gdata_Media_Extension_MediaDescription(); - $description->transferFromDOM($child); - $this->_description = $description; - break; - case $this->lookupNamespace('media') . ':' . 'hash'; - $hash = new Zend_Gdata_Media_Extension_MediaHash(); - $hash->transferFromDOM($child); - $this->_hash[] = $hash; - break; - case $this->lookupNamespace('media') . ':' . 'keywords'; - $keywords = new Zend_Gdata_Media_Extension_MediaKeywords(); - $keywords->transferFromDOM($child); - $this->_keywords = $keywords; - break; - case $this->lookupNamespace('media') . ':' . 'player'; - $player = new Zend_Gdata_Media_Extension_MediaPlayer(); - $player->transferFromDOM($child); - $this->_player[] = $player; - break; - case $this->lookupNamespace('media') . ':' . 'rating'; - $rating = new Zend_Gdata_Media_Extension_MediaRating(); - $rating->transferFromDOM($child); - $this->_rating[] = $rating; - break; - case $this->lookupNamespace('media') . ':' . 'restriction'; - $restriction = new Zend_Gdata_Media_Extension_MediaRestriction(); - $restriction->transferFromDOM($child); - $this->_restriction[] = $restriction; - break; - case $this->lookupNamespace('media') . ':' . 'text'; - $text = new Zend_Gdata_Media_Extension_MediaText(); - $text->transferFromDOM($child); - $this->_mediaText[] = $text; - break; - case $this->lookupNamespace('media') . ':' . 'thumbnail'; - $thumbnail = new Zend_Gdata_Media_Extension_MediaThumbnail(); - $thumbnail->transferFromDOM($child); - $this->_thumbnail[] = $thumbnail; - break; - case $this->lookupNamespace('media') . ':' . 'title'; - $title = new Zend_Gdata_Media_Extension_MediaTitle(); - $title->transferFromDOM($child); - $this->_title = $title; - break; - default: - parent::takeChildFromDOM($child); - break; - } - } - - /** - * @return array - */ - public function getContent() - { - return $this->_content; - } - - /** - * @param array $value - * @return Zend_Gdata_Media_MediaGroup Provides a fluent interface - */ - public function setContent($value) - { - $this->_content = $value; - return $this; - } - - /** - * @return array - */ - public function getCategory() - { - return $this->_category; - } - - /** - * @param array $value - * @return Zend_Gdata_Media_Extension_MediaGroup - */ - public function setCategory($value) - { - $this->_category = $value; - return $this; - } - - /** - * @return Zend_Gdata_Media_Extension_MediaCopyright - */ - public function getCopyright() - { - return $this->_copyright; - } - - /** - * @param Zend_Gdata_Media_Extension_MediaCopyright $value - * @return Zend_Gdata_Media_Extension_MediaGroup - */ - public function setCopyright($value) - { - $this->_copyright = $value; - return $this; - } - - /** - * @return array - */ - public function getCredit() - { - return $this->_credit; - } - - /** - * @param array $value - * @return Zend_Gdata_Media_Extension_MediaGroup - */ - public function setCredit($value) - { - $this->_credit = $value; - return $this; - } - - /** - * @return Zend_Gdata_Media_Extension_MediaTitle - */ - public function getTitle() - { - return $this->_title; - } - - /** - * @param Zend_Gdata_Media_Extension_MediaTitle $value - * @return Zend_Gdata_Media_Extension_MediaGroup - */ - public function setTitle($value) - { - $this->_title = $value; - return $this; - } - - /** - * @return Zend_Gdata_Media_Extension_MediaDescription - */ - public function getDescription() - { - return $this->_description; - } - - /** - * @param Zend_Gdata_Media_Extension_MediaDescription $value - * @return Zend_Gdata_Media_Extension_MediaGroup - */ - public function setDescription($value) - { - $this->_description = $value; - return $this; - } - - /** - * @return array - */ - public function getHash() - { - return $this->_hash; - } - - /** - * @param array $value - * @return Zend_Gdata_Media_Extension_MediaGroup - */ - public function setHash($value) - { - $this->_hash = $value; - return $this; - } - - /** - * @return Zend_Gdata_Media_Extension_MediaKeywords - */ - public function getKeywords() - { - return $this->_keywords; - } - - /** - * @param array $value - * @return Zend_Gdata_Media_Extension_MediaGroup Provides a fluent interface - */ - public function setKeywords($value) - { - $this->_keywords = $value; - return $this; - } - - /** - * @return array - */ - public function getPlayer() - { - return $this->_player; - } - - /** - * @param array - * @return Zend_Gdata_Media_Extension_MediaGroup - */ - public function setPlayer($value) - { - $this->_player = $value; - return $this; - } - - /** - * @return array - */ - public function getRating() - { - return $this->_rating; - } - - /** - * @param array - * @return Zend_Gdata_Media_Extension_MediaGroup - */ - public function setRating($value) - { - $this->_rating = $value; - return $this; - } - - /** - * @return array - */ - public function getRestriction() - { - return $this->_restriction; - } - - /** - * @param array - * @return Zend_Gdata_Media_Extension_MediaGroup - */ - public function setRestriction($value) - { - $this->_restriction = $value; - return $this; - } - - /** - * @return array - */ - public function getThumbnail() - { - return $this->_thumbnail; - } - - /** - * @param array - * @return Zend_Gdata_Media_Extension_MediaGroup - */ - public function setThumbnail($value) - { - $this->_thumbnail = $value; - return $this; - } - - /** - * @return array - */ - public function getMediaText() - { - return $this->_mediaText; - } - - /** - * @param array - * @return Zend_Gdata_Media_Extension_MediaGroup - */ - public function setMediaText($value) - { - $this->_mediaText = $value; - return $this; - } - -} diff --git a/library/Zend/Gdata/Media/Extension/MediaHash.php b/library/Zend/Gdata/Media/Extension/MediaHash.php deleted file mode 100755 index 41ea42f2c2..0000000000 --- a/library/Zend/Gdata/Media/Extension/MediaHash.php +++ /dev/null @@ -1,115 +0,0 @@ -registerAllNamespaces(Zend_Gdata_Media::$namespaces); - parent::__construct(); - $this->_text = $text; - $this->_algo = $algo; - } - - /** - * Retrieves a DOMElement which corresponds to this element and all - * child properties. This is used to build an entry back into a DOM - * and eventually XML text for sending to the server upon updates, or - * for application storage/persistence. - * - * @param DOMDocument $doc The DOMDocument used to construct DOMElements - * @return DOMElement The DOMElement representing this element and all - * child properties. - */ - public function getDOM($doc = null, $majorVersion = 1, $minorVersion = null) - { - $element = parent::getDOM($doc, $majorVersion, $minorVersion); - if ($this->_algo !== null) { - $element->setAttribute('algo', $this->_algo); - } - return $element; - } - - /** - * Given a DOMNode representing an attribute, tries to map the data into - * instance members. If no mapping is defined, the name and value are - * stored in an array. - * - * @param DOMNode $attribute The DOMNode attribute needed to be handled - * @throws Zend_Gdata_App_InvalidArgumentException - */ - protected function takeAttributeFromDOM($attribute) - { - switch ($attribute->localName) { - case 'algo': - $this->_algo = $attribute->nodeValue; - break; - default: - parent::takeAttributeFromDOM($attribute); - } - } - - /** - * @return string The algo - */ - public function getAlgo() - { - return $this->_algo; - } - - /** - * @param string $value - * @return Zend_Gdata_Media_Extension_MediaHash Provides a fluent interface - */ - public function setAlgo($value) - { - $this->_algo = $value; - return $this; - } - -} diff --git a/library/Zend/Gdata/Media/Extension/MediaKeywords.php b/library/Zend/Gdata/Media/Extension/MediaKeywords.php deleted file mode 100755 index 79cc7c2482..0000000000 --- a/library/Zend/Gdata/Media/Extension/MediaKeywords.php +++ /dev/null @@ -1,52 +0,0 @@ -registerAllNamespaces(Zend_Gdata_Media::$namespaces); - parent::__construct(); - } - -} diff --git a/library/Zend/Gdata/Media/Extension/MediaPlayer.php b/library/Zend/Gdata/Media/Extension/MediaPlayer.php deleted file mode 100755 index da30110417..0000000000 --- a/library/Zend/Gdata/Media/Extension/MediaPlayer.php +++ /dev/null @@ -1,178 +0,0 @@ -registerAllNamespaces(Zend_Gdata_Media::$namespaces); - parent::__construct(); - $this->_url = $url; - $this->_width = $width; - $this->_height = $height; - } - - /** - * Retrieves a DOMElement which corresponds to this element and all - * child properties. This is used to build an entry back into a DOM - * and eventually XML text for sending to the server upon updates, or - * for application storage/persistence. - * - * @param DOMDocument $doc The DOMDocument used to construct DOMElements - * @return DOMElement The DOMElement representing this element and all - * child properties. - */ - public function getDOM($doc = null, $majorVersion = 1, $minorVersion = null) - { - $element = parent::getDOM($doc, $majorVersion, $minorVersion); - if ($this->_url !== null) { - $element->setAttribute('url', $this->_url); - } - if ($this->_width !== null) { - $element->setAttribute('width', $this->_width); - } - if ($this->_height !== null) { - $element->setAttribute('height', $this->_height); - } - return $element; - } - - /** - * Given a DOMNode representing an attribute, tries to map the data into - * instance members. If no mapping is defined, the name and value are - * stored in an array. - * - * @param DOMNode $attribute The DOMNode attribute needed to be handled - */ - protected function takeAttributeFromDOM($attribute) - { - switch ($attribute->localName) { - case 'url': - $this->_url = $attribute->nodeValue; - break; - case 'width': - $this->_width = $attribute->nodeValue; - break; - case 'height': - $this->_height = $attribute->nodeValue; - break; - default: - parent::takeAttributeFromDOM($attribute); - } - } - - /** - * @return string - */ - public function getUrl() - { - return $this->_url; - } - - /** - * @param string $value - * @return Zend_Gdata_Media_Extension_MediaPlayer Provides a fluent interface - */ - public function setUrl($value) - { - $this->_url = $value; - return $this; - } - - /** - * @return int - */ - public function getWidth() - { - return $this->_width; - } - - /** - * @param int $value - * @return Zend_Gdata_Media_Extension_MediaPlayer Provides a fluent interface - */ - public function setWidth($value) - { - $this->_width = $value; - return $this; - } - - /** - * @return int - */ - public function getHeight() - { - return $this->_height; - } - - /** - * @param int $value - * @return Zend_Gdata_Media_Extension_MediaPlayer Provides a fluent interface - */ - public function setHeight($value) - { - $this->_height = $value; - return $this; - } - -} diff --git a/library/Zend/Gdata/Media/Extension/MediaRating.php b/library/Zend/Gdata/Media/Extension/MediaRating.php deleted file mode 100755 index c95ab1a87f..0000000000 --- a/library/Zend/Gdata/Media/Extension/MediaRating.php +++ /dev/null @@ -1,118 +0,0 @@ -registerAllNamespaces(Zend_Gdata_Media::$namespaces); - parent::__construct(); - $this->_scheme = $scheme; - $this->_text = $text; - } - - /** - * Retrieves a DOMElement which corresponds to this element and all - * child properties. This is used to build an entry back into a DOM - * and eventually XML text for sending to the server upon updates, or - * for application storage/persistence. - * - * @param DOMDocument $doc The DOMDocument used to construct DOMElements - * @return DOMElement The DOMElement representing this element and all - * child properties. - */ - public function getDOM($doc = null, $majorVersion = 1, $minorVersion = null) - { - $element = parent::getDOM($doc, $majorVersion, $minorVersion); - if ($this->_scheme !== null) { - $element->setAttribute('scheme', $this->_scheme); - } - return $element; - } - - /** - * Given a DOMNode representing an attribute, tries to map the data into - * instance members. If no mapping is defined, the name and value are - * stored in an array. - * - * @param DOMNode $attribute The DOMNode attribute needed to be handled - */ - protected function takeAttributeFromDOM($attribute) - { - switch ($attribute->localName) { - case 'scheme': - $this->_scheme = $attribute->nodeValue; - break; - default: - parent::takeAttributeFromDOM($attribute); - } - } - - /** - * @return string - */ - public function getScheme() - { - return $this->_scheme; - } - - /** - * @param string $value - * @return Zend_Gdata_Media_Extension_MediaRating Provides a fluent interface - */ - public function setScheme($value) - { - $this->_scheme = $value; - return $this; - } - -} diff --git a/library/Zend/Gdata/Media/Extension/MediaRestriction.php b/library/Zend/Gdata/Media/Extension/MediaRestriction.php deleted file mode 100755 index 9e86bbbce9..0000000000 --- a/library/Zend/Gdata/Media/Extension/MediaRestriction.php +++ /dev/null @@ -1,149 +0,0 @@ -registerAllNamespaces(Zend_Gdata_Media::$namespaces); - parent::__construct(); - $this->_text = $text; - $this->_relationship = $relationship; - $this->_type = $type; - } - - /** - * Retrieves a DOMElement which corresponds to this element and all - * child properties. This is used to build an entry back into a DOM - * and eventually XML text for sending to the server upon updates, or - * for application storage/persistence. - * - * @param DOMDocument $doc The DOMDocument used to construct DOMElements - * @return DOMElement The DOMElement representing this element and all - * child properties. - */ - public function getDOM($doc = null, $majorVersion = 1, $minorVersion = null) - { - $element = parent::getDOM($doc, $majorVersion, $minorVersion); - if ($this->_relationship !== null) { - $element->setAttribute('relationship', $this->_relationship); - } - if ($this->_type !== null) { - $element->setAttribute('type', $this->_type); - } - return $element; - } - - /** - * Given a DOMNode representing an attribute, tries to map the data into - * instance members. If no mapping is defined, the name and value are - * stored in an array. - * - * @param DOMNode $attribute The DOMNode attribute needed to be handled - */ - protected function takeAttributeFromDOM($attribute) - { - switch ($attribute->localName) { - case 'relationship': - $this->_relationship = $attribute->nodeValue; - break; - case 'type': - $this->_type = $attribute->nodeValue; - break; - default: - parent::takeAttributeFromDOM($attribute); - } - } - - /** - * @return string - */ - public function getRelationship() - { - return $this->_relationship; - } - - /** - * @param string $value - * @return Zend_Gdata_Media_Extension_MediaRestriction Provides a fluent interface - */ - public function setRelationship($value) - { - $this->_relationship = $value; - return $this; - } - - /** - * @return string - */ - public function getType() - { - return $this->_type; - } - - /** - * @param string $value - * @return Zend_Gdata_Media_Extension_MediaRestriction Provides a fluent interface - */ - public function setType($value) - { - $this->_type = $value; - return $this; - } - -} diff --git a/library/Zend/Gdata/Media/Extension/MediaText.php b/library/Zend/Gdata/Media/Extension/MediaText.php deleted file mode 100755 index 65860ce07f..0000000000 --- a/library/Zend/Gdata/Media/Extension/MediaText.php +++ /dev/null @@ -1,211 +0,0 @@ -registerAllNamespaces(Zend_Gdata_Media::$namespaces); - parent::__construct(); - $this->_text = $text; - $this->_type = $type; - $this->_lang = $lang; - $this->_start = $start; - $this->_end = $end; - } - - /** - * Retrieves a DOMElement which corresponds to this element and all - * child properties. This is used to build an entry back into a DOM - * and eventually XML text for sending to the server upon updates, or - * for application storage/persistence. - * - * @param DOMDocument $doc The DOMDocument used to construct DOMElements - * @return DOMElement The DOMElement representing this element and all - * child properties. - */ - public function getDOM($doc = null, $majorVersion = 1, $minorVersion = null) - { - $element = parent::getDOM($doc, $majorVersion, $minorVersion); - if ($this->_type !== null) { - $element->setAttribute('type', $this->_type); - } - if ($this->_lang !== null) { - $element->setAttribute('lang', $this->_lang); - } - if ($this->_start !== null) { - $element->setAttribute('start', $this->_start); - } - if ($this->_end !== null) { - $element->setAttribute('end', $this->_end); - } - return $element; - } - - /** - * Given a DOMNode representing an attribute, tries to map the data into - * instance members. If no mapping is defined, the name and value are - * stored in an array. - * - * @param DOMNode $attribute The DOMNode attribute needed to be handled - */ - protected function takeAttributeFromDOM($attribute) - { - switch ($attribute->localName) { - case 'type': - $this->_type = $attribute->nodeValue; - break; - case 'lang': - $this->_lang = $attribute->nodeValue; - break; - case 'start': - $this->_start = $attribute->nodeValue; - break; - case 'end': - $this->_end = $attribute->nodeValue; - break; - default: - parent::takeAttributeFromDOM($attribute); - } - } - - /** - * @return string - */ - public function getType() - { - return $this->_type; - } - - /** - * @param string $value - * @return Zend_Gdata_Media_Extension_MediaText Provides a fluent interface - */ - public function setType($value) - { - $this->_type = $value; - return $this; - } - - /** - * @return string - */ - public function getLang() - { - return $this->_lang; - } - - /** - * @param string $value - * @return Zend_Gdata_Media_Extension_MediaText Provides a fluent interface - */ - public function setLang($value) - { - $this->_lang = $value; - return $this; - } - - /** - * @return string - */ - public function getStart() - { - return $this->_start; - } - - /** - * @param string $value - * @return Zend_Gdata_Media_Extension_MediaText Provides a fluent interface - */ - public function setStart($value) - { - $this->_start = $value; - return $this; - } - - /** - * @return string - */ - public function getEnd() - { - return $this->_end; - } - - /** - * @param string $value - * @return Zend_Gdata_Media_Extension_MediaText Provides a fluent interface - */ - public function setEnd($value) - { - $this->_end = $value; - return $this; - } -} diff --git a/library/Zend/Gdata/Media/Extension/MediaThumbnail.php b/library/Zend/Gdata/Media/Extension/MediaThumbnail.php deleted file mode 100755 index d9cac179e7..0000000000 --- a/library/Zend/Gdata/Media/Extension/MediaThumbnail.php +++ /dev/null @@ -1,210 +0,0 @@ -registerAllNamespaces(Zend_Gdata_Media::$namespaces); - parent::__construct(); - $this->_url = $url; - $this->_width = $width; - $this->_height = $height; - $this->_time = $time ; - } - - /** - * Retrieves a DOMElement which corresponds to this element and all - * child properties. This is used to build an entry back into a DOM - * and eventually XML text for sending to the server upon updates, or - * for application storage/persistence. - * - * @param DOMDocument $doc The DOMDocument used to construct DOMElements - * @return DOMElement The DOMElement representing this element and all - * child properties. - */ - public function getDOM($doc = null, $majorVersion = 1, $minorVersion = null) - { - $element = parent::getDOM($doc, $majorVersion, $minorVersion); - if ($this->_url !== null) { - $element->setAttribute('url', $this->_url); - } - if ($this->_width !== null) { - $element->setAttribute('width', $this->_width); - } - if ($this->_height !== null) { - $element->setAttribute('height', $this->_height); - } - if ($this->_time !== null) { - $element->setAttribute('time', $this->_time); - } - return $element; - } - - /** - * Given a DOMNode representing an attribute, tries to map the data into - * instance members. If no mapping is defined, the name and value are - * stored in an array. - * - * @param DOMNode $attribute The DOMNode attribute needed to be handled - */ - protected function takeAttributeFromDOM($attribute) - { - switch ($attribute->localName) { - case 'url': - $this->_url = $attribute->nodeValue; - break; - case 'width': - $this->_width = $attribute->nodeValue; - break; - case 'height': - $this->_height = $attribute->nodeValue; - break; - case 'time': - $this->_time = $attribute->nodeValue; - break; - default: - parent::takeAttributeFromDOM($attribute); - } - } - - /** - * @return string - */ - public function getUrl() - { - return $this->_url; - } - - /** - * @param string $value - * @return Zend_Gdata_Media_Extension_MediaThumbnail Provides a fluent interface - */ - public function setUrl($value) - { - $this->_url = $value; - return $this; - } - - /** - * @return int - */ - public function getWidth() - { - return $this->_width; - } - - /** - * @param int $value - * @return Zend_Gdata_Media_Extension_MediaThumbnail Provides a fluent interface - */ - public function setWidth($value) - { - $this->_width = $value; - return $this; - } - - /** - * @return int - */ - public function getHeight() - { - return $this->_height; - } - - /** - * @param int $value - * @return Zend_Gdata_Media_Extension_MediaThumbnail Provides a fluent interface - */ - public function setHeight($value) - { - $this->_height = $value; - return $this; - } - - /** - * @return string - */ - public function getTime() - { - return $this->_time; - } - - /** - * @param string $value - * @return Zend_Gdata_Media_Extension_MediaThumbnail Provides a fluent interface - */ - public function setTime($value) - { - $this->_time = $value; - return $this; - } - -} diff --git a/library/Zend/Gdata/Media/Extension/MediaTitle.php b/library/Zend/Gdata/Media/Extension/MediaTitle.php deleted file mode 100755 index 7b6dc2b46d..0000000000 --- a/library/Zend/Gdata/Media/Extension/MediaTitle.php +++ /dev/null @@ -1,118 +0,0 @@ -registerAllNamespaces(Zend_Gdata_Media::$namespaces); - parent::__construct(); - $this->_type = $type; - $this->_text = $text; - } - - /** - * Retrieves a DOMElement which corresponds to this element and all - * child properties. This is used to build an entry back into a DOM - * and eventually XML text for sending to the server upon updates, or - * for application storage/persistence. - * - * @param DOMDocument $doc The DOMDocument used to construct DOMElements - * @return DOMElement The DOMElement representing this element and all - * child properties. - */ - public function getDOM($doc = null, $majorVersion = 1, $minorVersion = null) - { - $element = parent::getDOM($doc, $majorVersion, $minorVersion); - if ($this->_type !== null) { - $element->setAttribute('type', $this->_type); - } - return $element; - } - - /** - * Given a DOMNode representing an attribute, tries to map the data into - * instance members. If no mapping is defined, the name and value are - * stored in an array. - * - * @param DOMNode $attribute The DOMNode attribute needed to be handled - */ - protected function takeAttributeFromDOM($attribute) - { - switch ($attribute->localName) { - case 'type': - $this->_type = $attribute->nodeValue; - break; - default: - parent::takeAttributeFromDOM($attribute); - } - } - - /** - * @return string - */ - public function getType() - { - return $this->_type; - } - - /** - * @param string $value - * @return Zend_Gdata_Media_Extension_MediaTitle Provides a fluent interface - */ - public function setType($value) - { - $this->_type = $value; - return $this; - } - -} diff --git a/library/Zend/Gdata/Media/Feed.php b/library/Zend/Gdata/Media/Feed.php deleted file mode 100755 index 06492c700d..0000000000 --- a/library/Zend/Gdata/Media/Feed.php +++ /dev/null @@ -1,70 +0,0 @@ -registerAllNamespaces(Zend_Gdata_Media::$namespaces); - parent::__construct($element); - } - -} diff --git a/library/Zend/Gdata/MediaMimeStream.php b/library/Zend/Gdata/MediaMimeStream.php deleted file mode 100644 index 497c4db3be..0000000000 --- a/library/Zend/Gdata/MediaMimeStream.php +++ /dev/null @@ -1,190 +0,0 @@ - 1. - */ - public function __construct($xmlString = null, $filePath = null, - $fileContentType = null) - { - if (!file_exists($filePath) || !is_readable($filePath)) { - #require_once 'Zend/Gdata/App/IOException.php'; - throw new Zend_Gdata_App_IOException('File to be uploaded at ' . - $filePath . ' does not exist or is not readable.'); - } - - $this->_fileHandle = fopen($filePath, 'rb', TRUE); - $this->_boundaryString = '=_' . md5(microtime(1) . rand(1,20)); - $entry = $this->wrapEntry($xmlString, $fileContentType); - $closingBoundary = new Zend_Gdata_MimeBodyString("\r\n--{$this->_boundaryString}--\r\n"); - $file = new Zend_Gdata_MimeFile($this->_fileHandle); - $this->_parts = array($entry, $file, $closingBoundary); - - $fileSize = filesize($filePath); - $this->_totalSize = $entry->getSize() + $fileSize - + $closingBoundary->getSize(); - - } - - /** - * Sandwiches the entry body into a MIME message - * - * @return void - */ - private function wrapEntry($entry, $fileMimeType) - { - $wrappedEntry = "--{$this->_boundaryString}\r\n"; - $wrappedEntry .= "Content-Type: application/atom+xml\r\n\r\n"; - $wrappedEntry .= $entry; - $wrappedEntry .= "\r\n--{$this->_boundaryString}\r\n"; - $wrappedEntry .= "Content-Type: $fileMimeType\r\n\r\n"; - return new Zend_Gdata_MimeBodyString($wrappedEntry); - } - - /** - * Read a specific chunk of the the MIME multipart message. - * - * @param integer $bufferSize The size of the chunk that is to be read, - * must be lower than MAX_BUFFER_SIZE. - * @return string A corresponding piece of the message. This could be - * binary or regular text. - */ - public function read($bytesRequested) - { - if($this->_currentPart >= count($this->_parts)) { - return FALSE; - } - - $activePart = $this->_parts[$this->_currentPart]; - $buffer = $activePart->read($bytesRequested); - - while(strlen($buffer) < $bytesRequested) { - $this->_currentPart += 1; - $nextBuffer = $this->read($bytesRequested - strlen($buffer)); - if($nextBuffer === FALSE) { - break; - } - $buffer .= $nextBuffer; - } - - return $buffer; - } - - /** - * Return the total size of the mime message. - * - * @return integer Total size of the message to be sent. - */ - public function getTotalSize() - { - return $this->_totalSize; - } - - /** - * Close the internal file that we are streaming to the socket. - * - * @return void - */ - public function closeFileHandle() - { - if ($this->_fileHandle !== null) { - fclose($this->_fileHandle); - } - } - - /** - * Return a Content-type header that includes the current boundary string. - * - * @return string A valid HTTP Content-Type header. - */ - public function getContentType() - { - return 'multipart/related;boundary="' . - $this->_boundaryString . '"' . "\r\n"; - } - -} diff --git a/library/Zend/Gdata/MimeBodyString.php b/library/Zend/Gdata/MimeBodyString.php deleted file mode 100644 index acbeac50db..0000000000 --- a/library/Zend/Gdata/MimeBodyString.php +++ /dev/null @@ -1,92 +0,0 @@ -_sourceString = $sourceString; - $this->_bytesRead = 0; - } - - /** - * Read the next chunk of the string. - * - * @param integer $bytesRequested The size of the chunk that is to be read. - * @return string A corresponding piece of the string. - */ - public function read($bytesRequested) - { - $len = strlen($this->_sourceString); - if($this->_bytesRead == $len) { - return FALSE; - } else if($bytesRequested > $len - $this->_bytesRead) { - $bytesRequested = $len - $this->_bytesRead; - } - - $buffer = substr($this->_sourceString, $this->_bytesRead, $bytesRequested); - $this->_bytesRead += $bytesRequested; - - return $buffer; - } - - /** - * The length of the string. - * - * @return int The length of the string contained in the object. - */ - public function getSize() - { - return strlen($this->_sourceString); - } - - -} diff --git a/library/Zend/Gdata/MimeFile.php b/library/Zend/Gdata/MimeFile.php deleted file mode 100644 index 853d121a4b..0000000000 --- a/library/Zend/Gdata/MimeFile.php +++ /dev/null @@ -1,66 +0,0 @@ -_fileHandle = $fileHandle; - } - - /** - * Read the next chunk of the file. - * - * @param integer $bytesRequested The size of the chunk that is to be read. - * @return string A corresponding piece of the message. This could be - * binary or regular text. - */ - public function read($bytesRequested) - { - return fread($this->_fileHandle, $bytesRequested); - } - -} diff --git a/library/Zend/Gdata/Photos.php b/library/Zend/Gdata/Photos.php deleted file mode 100755 index 8b19c8c68b..0000000000 --- a/library/Zend/Gdata/Photos.php +++ /dev/null @@ -1,576 +0,0 @@ -registerPackage('Zend_Gdata_Photos'); - $this->registerPackage('Zend_Gdata_Photos_Extension'); - parent::__construct($client, $applicationId); - $this->_httpClient->setParameterPost('service', self::AUTH_SERVICE_NAME); - } - - /** - * Retrieve a UserFeed containing AlbumEntries, PhotoEntries and - * TagEntries associated with a given user. - * - * @param string $userName The userName of interest - * @param mixed $location (optional) The location for the feed, as a URL - * or Query. If not provided, a default URL will be used instead. - * @return Zend_Gdata_Photos_UserFeed - * @throws Zend_Gdata_App_Exception - * @throws Zend_Gdata_App_HttpException - */ - public function getUserFeed($userName = null, $location = null) - { - if ($location instanceof Zend_Gdata_Photos_UserQuery) { - $location->setType('feed'); - if ($userName !== null) { - $location->setUser($userName); - } - $uri = $location->getQueryUrl(); - } else if ($location instanceof Zend_Gdata_Query) { - if ($userName !== null) { - $location->setUser($userName); - } - $uri = $location->getQueryUrl(); - } else if ($location !== null) { - $uri = $location; - } else if ($userName !== null) { - $uri = self::PICASA_BASE_FEED_URI . '/' . - self::DEFAULT_PROJECTION . '/' . self::USER_PATH . '/' . - $userName; - } else { - $uri = self::PICASA_BASE_FEED_URI . '/' . - self::DEFAULT_PROJECTION . '/' . self::USER_PATH . '/' . - self::DEFAULT_USER; - } - - return parent::getFeed($uri, 'Zend_Gdata_Photos_UserFeed'); - } - - /** - * Retreive AlbumFeed object containing multiple PhotoEntry or TagEntry - * objects. - * - * @param mixed $location (optional) The location for the feed, as a URL or Query. - * @return Zend_Gdata_Photos_AlbumFeed - * @throws Zend_Gdata_App_Exception - * @throws Zend_Gdata_App_HttpException - */ - public function getAlbumFeed($location = null) - { - if ($location === null) { - #require_once 'Zend/Gdata/App/InvalidArgumentException.php'; - throw new Zend_Gdata_App_InvalidArgumentException( - 'Location must not be null'); - } else if ($location instanceof Zend_Gdata_Photos_UserQuery) { - $location->setType('feed'); - $uri = $location->getQueryUrl(); - } else if ($location instanceof Zend_Gdata_Query) { - $uri = $location->getQueryUrl(); - } else { - $uri = $location; - } - return parent::getFeed($uri, 'Zend_Gdata_Photos_AlbumFeed'); - } - - /** - * Retreive PhotoFeed object containing comments and tags associated - * with a given photo. - * - * @param mixed $location (optional) The location for the feed, as a URL - * or Query. If not specified, the community search feed will - * be returned instead. - * @return Zend_Gdata_Photos_PhotoFeed - * @throws Zend_Gdata_App_Exception - * @throws Zend_Gdata_App_HttpException - */ - public function getPhotoFeed($location = null) - { - if ($location === null) { - $uri = self::PICASA_BASE_FEED_URI . '/' . - self::DEFAULT_PROJECTION . '/' . - self::COMMUNITY_SEARCH_PATH; - } else if ($location instanceof Zend_Gdata_Photos_UserQuery) { - $location->setType('feed'); - $uri = $location->getQueryUrl(); - } else if ($location instanceof Zend_Gdata_Query) { - $uri = $location->getQueryUrl(); - } else { - $uri = $location; - } - return parent::getFeed($uri, 'Zend_Gdata_Photos_PhotoFeed'); - } - - /** - * Retreive a single UserEntry object. - * - * @param mixed $location The location for the feed, as a URL or Query. - * @return Zend_Gdata_Photos_UserEntry - * @throws Zend_Gdata_App_Exception - * @throws Zend_Gdata_App_HttpException - */ - public function getUserEntry($location) - { - if ($location === null) { - #require_once 'Zend/Gdata/App/InvalidArgumentException.php'; - throw new Zend_Gdata_App_InvalidArgumentException( - 'Location must not be null'); - } else if ($location instanceof Zend_Gdata_Photos_UserQuery) { - $location->setType('entry'); - $uri = $location->getQueryUrl(); - } else if ($location instanceof Zend_Gdata_Query) { - $uri = $location->getQueryUrl(); - } else { - $uri = $location; - } - return parent::getEntry($uri, 'Zend_Gdata_Photos_UserEntry'); - } - - /** - * Retreive a single AlbumEntry object. - * - * @param mixed $location The location for the feed, as a URL or Query. - * @return Zend_Gdata_Photos_AlbumEntry - * @throws Zend_Gdata_App_Exception - * @throws Zend_Gdata_App_HttpException - */ - public function getAlbumEntry($location) - { - if ($location === null) { - #require_once 'Zend/Gdata/App/InvalidArgumentException.php'; - throw new Zend_Gdata_App_InvalidArgumentException( - 'Location must not be null'); - } else if ($location instanceof Zend_Gdata_Photos_UserQuery) { - $location->setType('entry'); - $uri = $location->getQueryUrl(); - } else if ($location instanceof Zend_Gdata_Query) { - $uri = $location->getQueryUrl(); - } else { - $uri = $location; - } - return parent::getEntry($uri, 'Zend_Gdata_Photos_AlbumEntry'); - } - - /** - * Retreive a single PhotoEntry object. - * - * @param mixed $location The location for the feed, as a URL or Query. - * @return Zend_Gdata_Photos_PhotoEntry - * @throws Zend_Gdata_App_Exception - * @throws Zend_Gdata_App_HttpException - */ - public function getPhotoEntry($location) - { - if ($location === null) { - #require_once 'Zend/Gdata/App/InvalidArgumentException.php'; - throw new Zend_Gdata_App_InvalidArgumentException( - 'Location must not be null'); - } else if ($location instanceof Zend_Gdata_Photos_UserQuery) { - $location->setType('entry'); - $uri = $location->getQueryUrl(); - } else if ($location instanceof Zend_Gdata_Query) { - $uri = $location->getQueryUrl(); - } else { - $uri = $location; - } - return parent::getEntry($uri, 'Zend_Gdata_Photos_PhotoEntry'); - } - - /** - * Retreive a single TagEntry object. - * - * @param mixed $location The location for the feed, as a URL or Query. - * @return Zend_Gdata_Photos_TagEntry - * @throws Zend_Gdata_App_Exception - * @throws Zend_Gdata_App_HttpException - */ - public function getTagEntry($location) - { - if ($location === null) { - #require_once 'Zend/Gdata/App/InvalidArgumentException.php'; - throw new Zend_Gdata_App_InvalidArgumentException( - 'Location must not be null'); - } else if ($location instanceof Zend_Gdata_Photos_UserQuery) { - $location->setType('entry'); - $uri = $location->getQueryUrl(); - } else if ($location instanceof Zend_Gdata_Query) { - $uri = $location->getQueryUrl(); - } else { - $uri = $location; - } - return parent::getEntry($uri, 'Zend_Gdata_Photos_TagEntry'); - } - - /** - * Retreive a single CommentEntry object. - * - * @param mixed $location The location for the feed, as a URL or Query. - * @return Zend_Gdata_Photos_CommentEntry - * @throws Zend_Gdata_App_Exception - * @throws Zend_Gdata_App_HttpException - */ - public function getCommentEntry($location) - { - if ($location === null) { - #require_once 'Zend/Gdata/App/InvalidArgumentException.php'; - throw new Zend_Gdata_App_InvalidArgumentException( - 'Location must not be null'); - } else if ($location instanceof Zend_Gdata_Photos_UserQuery) { - $location->setType('entry'); - $uri = $location->getQueryUrl(); - } else if ($location instanceof Zend_Gdata_Query) { - $uri = $location->getQueryUrl(); - } else { - $uri = $location; - } - return parent::getEntry($uri, 'Zend_Gdata_Photos_CommentEntry'); - } - - /** - * Create a new album from a AlbumEntry. - * - * @param Zend_Gdata_Photos_AlbumEntry $album The album entry to - * insert. - * @param string $url (optional) The URI that the album should be - * uploaded to. If null, the default album creation URI for - * this domain will be used. - * @return Zend_Gdata_Photos_AlbumEntry The inserted album entry as - * returned by the server. - * @throws Zend_Gdata_App_Exception - * @throws Zend_Gdata_App_HttpException - */ - public function insertAlbumEntry($album, $uri = null) - { - if ($uri === null) { - $uri = self::PICASA_BASE_FEED_URI . '/' . - self::DEFAULT_PROJECTION . '/' . self::USER_PATH . '/' . - self::DEFAULT_USER; - } - $newEntry = $this->insertEntry($album, $uri, 'Zend_Gdata_Photos_AlbumEntry'); - return $newEntry; - } - - /** - * Create a new photo from a PhotoEntry. - * - * @param Zend_Gdata_Photos_PhotoEntry $photo The photo to insert. - * @param string $url The URI that the photo should be uploaded - * to. Alternatively, an AlbumEntry can be provided and the - * photo will be added to that album. - * @return Zend_Gdata_Photos_PhotoEntry The inserted photo entry - * as returned by the server. - * @throws Zend_Gdata_App_Exception - * @throws Zend_Gdata_App_HttpException - */ - public function insertPhotoEntry($photo, $uri = null) - { - if ($uri instanceof Zend_Gdata_Photos_AlbumEntry) { - $uri = $uri->getLink(self::FEED_LINK_PATH)->href; - } - if ($uri === null) { - #require_once 'Zend/Gdata/App/InvalidArgumentException.php'; - throw new Zend_Gdata_App_InvalidArgumentException( - 'URI must not be null'); - } - $newEntry = $this->insertEntry($photo, $uri, 'Zend_Gdata_Photos_PhotoEntry'); - return $newEntry; - } - - /** - * Create a new tag from a TagEntry. - * - * @param Zend_Gdata_Photos_TagEntry $tag The tag entry to insert. - * @param string $url The URI where the tag should be - * uploaded to. Alternatively, a PhotoEntry can be provided and - * the tag will be added to that photo. - * @return Zend_Gdata_Photos_TagEntry The inserted tag entry as returned - * by the server. - * @throws Zend_Gdata_App_Exception - * @throws Zend_Gdata_App_HttpException - */ - public function insertTagEntry($tag, $uri = null) - { - if ($uri instanceof Zend_Gdata_Photos_PhotoEntry) { - $uri = $uri->getLink(self::FEED_LINK_PATH)->href; - } - if ($uri === null) { - #require_once 'Zend/Gdata/App/InvalidArgumentException.php'; - throw new Zend_Gdata_App_InvalidArgumentException( - 'URI must not be null'); - } - $newEntry = $this->insertEntry($tag, $uri, 'Zend_Gdata_Photos_TagEntry'); - return $newEntry; - } - - /** - * Create a new comment from a CommentEntry. - * - * @param Zend_Gdata_Photos_CommentEntry $comment The comment entry to - * insert. - * @param string $url The URI where the comment should be uploaded to. - * Alternatively, a PhotoEntry can be provided and - * the comment will be added to that photo. - * @return Zend_Gdata_Photos_CommentEntry The inserted comment entry - * as returned by the server. - * @throws Zend_Gdata_App_Exception - * @throws Zend_Gdata_App_HttpException - */ - public function insertCommentEntry($comment, $uri = null) - { - if ($uri instanceof Zend_Gdata_Photos_PhotoEntry) { - $uri = $uri->getLink(self::FEED_LINK_PATH)->href; - } - if ($uri === null) { - #require_once 'Zend/Gdata/App/InvalidArgumentException.php'; - throw new Zend_Gdata_App_InvalidArgumentException( - 'URI must not be null'); - } - $newEntry = $this->insertEntry($comment, $uri, 'Zend_Gdata_Photos_CommentEntry'); - return $newEntry; - } - - /** - * Delete an AlbumEntry. - * - * @param Zend_Gdata_Photos_AlbumEntry $album The album entry to - * delete. - * @param boolean $catch Whether to catch an exception when - * modified and re-delete or throw - * @return void. - * @throws Zend_Gdata_App_Exception - * @throws Zend_Gdata_App_HttpException - */ - public function deleteAlbumEntry($album, $catch) - { - if ($catch) { - try { - $this->delete($album); - } catch (Zend_Gdata_App_HttpException $e) { - if ($e->getResponse()->getStatus() === 409) { - $entry = new Zend_Gdata_Photos_AlbumEntry($e->getResponse()->getBody()); - $this->delete($entry->getLink('edit')->href); - } else { - throw $e; - } - } - } else { - $this->delete($album); - } - } - - /** - * Delete a PhotoEntry. - * - * @param Zend_Gdata_Photos_PhotoEntry $photo The photo entry to - * delete. - * @param boolean $catch Whether to catch an exception when - * modified and re-delete or throw - * @return void. - * @throws Zend_Gdata_App_Exception - * @throws Zend_Gdata_App_HttpException - */ - public function deletePhotoEntry($photo, $catch) - { - if ($catch) { - try { - $this->delete($photo); - } catch (Zend_Gdata_App_HttpException $e) { - if ($e->getResponse()->getStatus() === 409) { - $entry = new Zend_Gdata_Photos_PhotoEntry($e->getResponse()->getBody()); - $this->delete($entry->getLink('edit')->href); - } else { - throw $e; - } - } - } else { - $this->delete($photo); - } - } - - /** - * Delete a CommentEntry. - * - * @param Zend_Gdata_Photos_CommentEntry $comment The comment entry to - * delete. - * @param boolean $catch Whether to catch an exception when - * modified and re-delete or throw - * @return void. - * @throws Zend_Gdata_App_Exception - * @throws Zend_Gdata_App_HttpException - */ - public function deleteCommentEntry($comment, $catch) - { - if ($catch) { - try { - $this->delete($comment); - } catch (Zend_Gdata_App_HttpException $e) { - if ($e->getResponse()->getStatus() === 409) { - $entry = new Zend_Gdata_Photos_CommentEntry($e->getResponse()->getBody()); - $this->delete($entry->getLink('edit')->href); - } else { - throw $e; - } - } - } else { - $this->delete($comment); - } - } - - /** - * Delete a TagEntry. - * - * @param Zend_Gdata_Photos_TagEntry $tag The tag entry to - * delete. - * @param boolean $catch Whether to catch an exception when - * modified and re-delete or throw - * @return void. - * @throws Zend_Gdata_App_Exception - * @throws Zend_Gdata_App_HttpException - */ - public function deleteTagEntry($tag, $catch) - { - if ($catch) { - try { - $this->delete($tag); - } catch (Zend_Gdata_App_HttpException $e) { - if ($e->getResponse()->getStatus() === 409) { - $entry = new Zend_Gdata_Photos_TagEntry($e->getResponse()->getBody()); - $this->delete($entry->getLink('edit')->href); - } else { - throw $e; - } - } - } else { - $this->delete($tag); - } - } - -} diff --git a/library/Zend/Gdata/Photos/AlbumEntry.php b/library/Zend/Gdata/Photos/AlbumEntry.php deleted file mode 100755 index 7fe25a4f53..0000000000 --- a/library/Zend/Gdata/Photos/AlbumEntry.php +++ /dev/null @@ -1,610 +0,0 @@ - in the Google Data protocol. - * - * @category Zend - * @package Zend_Gdata - * @subpackage Photos - * @copyright Copyright (c) 2005-2015 Zend Technologies USA Inc. (http://www.zend.com) - * @license http://framework.zend.com/license/new-bsd New BSD License - */ -class Zend_Gdata_Photos_AlbumEntry extends Zend_Gdata_Entry -{ - - protected $_entryClassName = 'Zend_Gdata_Photos_AlbumEntry'; - - /** - * gphoto:id element - * - * @var Zend_Gdata_Photos_Extension_Id - */ - protected $_gphotoId = null; - - /** - * gphoto:access element - * - * @var Zend_Gdata_Photos_Extension_Access - */ - protected $_gphotoAccess = null; - - /** - * gphoto:location element - * - * @var Zend_Gdata_Photos_Extension_Location - */ - protected $_gphotoLocation = null; - - /** - * gphoto:user element - * - * @var Zend_Gdata_Photos_Extension_User - */ - protected $_gphotoUser = null; - - /** - * gphoto:nickname element - * - * @var Zend_Gdata_Photos_Extension_Nickname - */ - protected $_gphotoNickname = null; - - /** - * gphoto:timestamp element - * - * @var Zend_Gdata_Photos_Extension_Timestamp - */ - protected $_gphotoTimestamp = null; - - /** - * gphoto:name element - * - * @var Zend_Gdata_Photos_Extension_Name - */ - protected $_gphotoName = null; - - /** - * gphoto:numphotos element - * - * @var Zend_Gdata_Photos_Extension_NumPhotos - */ - protected $_gphotoNumPhotos = null; - - /** - * gphoto:commentCount element - * - * @var Zend_Gdata_Photos_Extension_CommentCount - */ - protected $_gphotoCommentCount = null; - - /** - * gphoto:commentingEnabled element - * - * @var Zend_Gdata_Photos_Extension_CommentingEnabled - */ - protected $_gphotoCommentingEnabled = null; - - /** - * media:group element - * - * @var Zend_Gdata_Media_MediaGroup - */ - protected $_mediaGroup = null; - - /** - * georss:where element - * - * @var Zend_Gdata_Geo_Extension_GeoRssWhere - */ - protected $_geoRssWhere = null; - - /** - * Create a new instance. - * - * @param DOMElement $element (optional) DOMElement from which this - * object should be constructed. - */ - public function __construct($element = null) - { - $this->registerAllNamespaces(Zend_Gdata_Photos::$namespaces); - parent::__construct($element); - - $category = new Zend_Gdata_App_Extension_Category( - 'http://schemas.google.com/photos/2007#album', - 'http://schemas.google.com/g/2005#kind'); - $this->setCategory(array($category)); - } - - /** - * Retrieves a DOMElement which corresponds to this element and all - * child properties. This is used to build an entry back into a DOM - * and eventually XML text for application storage/persistence. - * - * @param DOMDocument $doc The DOMDocument used to construct DOMElements - * @return DOMElement The DOMElement representing this element and all - * child properties. - */ - public function getDOM($doc = null, $majorVersion = 1, $minorVersion = null) - { - $element = parent::getDOM($doc, $majorVersion, $minorVersion); - if ($this->_gphotoTimestamp !== null) { - $element->appendChild($this->_gphotoTimestamp->getDOM($element->ownerDocument)); - } - if ($this->_gphotoUser !== null) { - $element->appendChild($this->_gphotoUser->getDOM($element->ownerDocument)); - } - if ($this->_gphotoNickname !== null) { - $element->appendChild($this->_gphotoNickname->getDOM($element->ownerDocument)); - } - if ($this->_gphotoAccess !== null) { - $element->appendChild($this->_gphotoAccess->getDOM($element->ownerDocument)); - } - if ($this->_gphotoLocation !== null) { - $element->appendChild($this->_gphotoLocation->getDOM($element->ownerDocument)); - } - if ($this->_gphotoName !== null) { - $element->appendChild($this->_gphotoName->getDOM($element->ownerDocument)); - } - if ($this->_gphotoNumPhotos !== null) { - $element->appendChild($this->_gphotoNumPhotos->getDOM($element->ownerDocument)); - } - if ($this->_gphotoCommentCount !== null) { - $element->appendChild($this->_gphotoCommentCount->getDOM($element->ownerDocument)); - } - if ($this->_gphotoCommentingEnabled !== null) { - $element->appendChild($this->_gphotoCommentingEnabled->getDOM($element->ownerDocument)); - } - if ($this->_gphotoId !== null) { - $element->appendChild($this->_gphotoId->getDOM($element->ownerDocument)); - } - if ($this->_mediaGroup !== null) { - $element->appendChild($this->_mediaGroup->getDOM($element->ownerDocument)); - } - return $element; - } - - /** - * Creates individual Entry objects of the appropriate type and - * stores them as members of this entry based upon DOM data. - * - * @param DOMNode $child The DOMNode to process - */ - protected function takeChildFromDOM($child) - { - $absoluteNodeName = $child->namespaceURI . ':' . $child->localName; - - switch ($absoluteNodeName) { - case $this->lookupNamespace('gphoto') . ':' . 'access'; - $access = new Zend_Gdata_Photos_Extension_Access(); - $access->transferFromDOM($child); - $this->_gphotoAccess = $access; - break; - case $this->lookupNamespace('gphoto') . ':' . 'location'; - $location = new Zend_Gdata_Photos_Extension_Location(); - $location->transferFromDOM($child); - $this->_gphotoLocation = $location; - break; - case $this->lookupNamespace('gphoto') . ':' . 'name'; - $name = new Zend_Gdata_Photos_Extension_Name(); - $name->transferFromDOM($child); - $this->_gphotoName = $name; - break; - case $this->lookupNamespace('gphoto') . ':' . 'numphotos'; - $numPhotos = new Zend_Gdata_Photos_Extension_NumPhotos(); - $numPhotos->transferFromDOM($child); - $this->_gphotoNumPhotos = $numPhotos; - break; - case $this->lookupNamespace('gphoto') . ':' . 'commentCount'; - $commentCount = new Zend_Gdata_Photos_Extension_CommentCount(); - $commentCount->transferFromDOM($child); - $this->_gphotoCommentCount = $commentCount; - break; - case $this->lookupNamespace('gphoto') . ':' . 'commentingEnabled'; - $commentingEnabled = new Zend_Gdata_Photos_Extension_CommentingEnabled(); - $commentingEnabled->transferFromDOM($child); - $this->_gphotoCommentingEnabled = $commentingEnabled; - break; - case $this->lookupNamespace('gphoto') . ':' . 'id'; - $id = new Zend_Gdata_Photos_Extension_Id(); - $id->transferFromDOM($child); - $this->_gphotoId = $id; - break; - case $this->lookupNamespace('gphoto') . ':' . 'user'; - $user = new Zend_Gdata_Photos_Extension_User(); - $user->transferFromDOM($child); - $this->_gphotoUser = $user; - break; - case $this->lookupNamespace('gphoto') . ':' . 'timestamp'; - $timestamp = new Zend_Gdata_Photos_Extension_Timestamp(); - $timestamp->transferFromDOM($child); - $this->_gphotoTimestamp = $timestamp; - break; - case $this->lookupNamespace('gphoto') . ':' . 'nickname'; - $nickname = new Zend_Gdata_Photos_Extension_Nickname(); - $nickname->transferFromDOM($child); - $this->_gphotoNickname = $nickname; - break; - case $this->lookupNamespace('georss') . ':' . 'where'; - $geoRssWhere = new Zend_Gdata_Geo_Extension_GeoRssWhere(); - $geoRssWhere->transferFromDOM($child); - $this->_geoRssWhere = $geoRssWhere; - break; - case $this->lookupNamespace('media') . ':' . 'group'; - $mediaGroup = new Zend_Gdata_Media_Extension_MediaGroup(); - $mediaGroup->transferFromDOM($child); - $this->_mediaGroup = $mediaGroup; - break; - default: - parent::takeChildFromDOM($child); - break; - } - } - - /** - * Get the value for this element's gphoto:access attribute. - * - * @see setGphotoAccess - * @return string The requested attribute. - */ - public function getGphotoAccess() - { - return $this->_gphotoAccess; - } - - /** - * Set the value for this element's gphoto:access attribute. - * - * @param string $value The desired value for this attribute. - * @return Zend_Gdata_Photos_Extension_Access The element being modified. - */ - public function setGphotoAccess($value) - { - $this->_gphotoAccess = $value; - return $this; - } - - /** - * Get the value for this element's gphoto:location attribute. - * - * @see setGphotoLocation - * @return string The requested attribute. - */ - public function getGphotoLocation() - { - return $this->_gphotoLocation; - } - - /** - * Set the value for this element's gphoto:location attribute. - * - * @param string $value The desired value for this attribute. - * @return Zend_Gdata_Photos_Extension_Location The element being modified. - */ - public function setGphotoLocation($value) - { - $this->_location = $value; - return $this; - } - - /** - * Get the value for this element's gphoto:name attribute. - * - * @see setGphotoName - * @return string The requested attribute. - */ - public function getGphotoName() - { - return $this->_gphotoName; - } - - /** - * Set the value for this element's gphoto:name attribute. - * - * @param string $value The desired value for this attribute. - * @return Zend_Gdata_Photos_Extension_Name The element being modified. - */ - public function setGphotoName($value) - { - $this->_gphotoName = $value; - return $this; - } - - /** - * Get the value for this element's gphoto:numphotos attribute. - * - * @see setGphotoNumPhotos - * @return string The requested attribute. - */ - public function getGphotoNumPhotos() - { - return $this->_gphotoNumPhotos; - } - - /** - * Set the value for this element's gphoto:numphotos attribute. - * - * @param string $value The desired value for this attribute. - * @return Zend_Gdata_Photos_Extension_NumPhotos The element being modified. - */ - public function setGphotoNumPhotos($value) - { - $this->_gphotoNumPhotos = $value; - return $this; - } - - /** - * Get the value for this element's gphoto:commentCount attribute. - * - * @see setGphotoCommentCount - * @return string The requested attribute. - */ - public function getGphotoCommentCount() - { - return $this->_gphotoCommentCount; - } - - /** - * Set the value for this element's gphoto:commentCount attribute. - * - * @param string $value The desired value for this attribute. - * @return Zend_Gdata_Photos_Extension_CommentCount The element being modified. - */ - public function setGphotoCommentCount($value) - { - $this->_gphotoCommentCount = $value; - return $this; - } - - /** - * Get the value for this element's gphoto:commentingEnabled attribute. - * - * @see setGphotoCommentingEnabled - * @return string The requested attribute. - */ - public function getGphotoCommentingEnabled() - { - return $this->_gphotoCommentingEnabled; - } - - /** - * Set the value for this element's gphoto:commentingEnabled attribute. - * - * @param string $value The desired value for this attribute. - * @return Zend_Gdata_Photos_Extension_CommentingEnabled The element being modified. - */ - public function setGphotoCommentingEnabled($value) - { - $this->_gphotoCommentingEnabled = $value; - return $this; - } - - /** - * Get the value for this element's gphoto:id attribute. - * - * @see setGphotoId - * @return string The requested attribute. - */ - public function getGphotoId() - { - return $this->_gphotoId; - } - - /** - * Set the value for this element's gphoto:id attribute. - * - * @param string $value The desired value for this attribute. - * @return Zend_Gdata_Photos_Extension_Id The element being modified. - */ - public function setGphotoId($value) - { - $this->_gphotoId = $value; - return $this; - } - - /** - * Get the value for this element's georss:where attribute. - * - * @see setGeoRssWhere - * @return string The requested attribute. - */ - public function getGeoRssWhere() - { - return $this->_geoRssWhere; - } - - /** - * Set the value for this element's georss:where attribute. - * - * @param string $value The desired value for this attribute. - * @return Zend_Gdata_Geo_Extension_GeoRssWhere The element being modified. - */ - public function setGeoRssWhere($value) - { - $this->_geoRssWhere = $value; - return $this; - } - - /** - * Get the value for this element's media:group attribute. - * - * @see setMediaGroup - * @return string The requested attribute. - */ - public function getMediaGroup() - { - return $this->_mediaGroup; - } - - /** - * Set the value for this element's media:group attribute. - * - * @param string $value The desired value for this attribute. - * @return Zend_Gdata_Media_Extension_MediaGroup The element being modified. - */ - public function setMediaGroup($value) - { - $this->_mediaGroup = $value; - return $this; - } - - /** - * Get the value for this element's gphoto:user attribute. - * - * @see setGphotoUser - * @return string The requested attribute. - */ - public function getGphotoUser() - { - return $this->_gphotoUser; - } - - /** - * Set the value for this element's gphoto:user attribute. - * - * @param string $value The desired value for this attribute. - * @return Zend_Gdata_Photos_Extension_User The element being modified. - */ - public function setGphotoUser($value) - { - $this->_gphotoUser = $value; - return $this; - } - - /** - * Get the value for this element's gphoto:nickname attribute. - * - * @see setGphotoNickname - * @return string The requested attribute. - */ - public function getGphotoNickname() - { - return $this->_gphotoNickname; - } - - /** - * Set the value for this element's gphoto:nickname attribute. - * - * @param string $value The desired value for this attribute. - * @return Zend_Gdata_Photos_Extension_Nickname The element being modified. - */ - public function setGphotoNickname($value) - { - $this->_gphotoNickname = $value; - return $this; - } - - /** - * Get the value for this element's gphoto:timestamp attribute. - * - * @see setGphotoTimestamp - * @return string The requested attribute. - */ - public function getGphotoTimestamp() - { - return $this->_gphotoTimestamp; - } - - /** - * Set the value for this element's gphoto:timestamp attribute. - * - * @param string $value The desired value for this attribute. - * @return Zend_Gdata_Photos_Extension_Timestamp The element being modified. - */ - public function setGphotoTimestamp($value) - { - $this->_gphotoTimestamp = $value; - return $this; - } -} diff --git a/library/Zend/Gdata/Photos/AlbumFeed.php b/library/Zend/Gdata/Photos/AlbumFeed.php deleted file mode 100755 index 12291c7a3a..0000000000 --- a/library/Zend/Gdata/Photos/AlbumFeed.php +++ /dev/null @@ -1,509 +0,0 @@ - 'Zend_Gdata_Photos_PhotoEntry', - 'http://schemas.google.com/photos/2007#comment' => 'Zend_Gdata_Photos_CommentEntry', - 'http://schemas.google.com/photos/2007#tag' => 'Zend_Gdata_Photos_TagEntry' - ); - - public function __construct($element = null) - { - $this->registerAllNamespaces(Zend_Gdata_Photos::$namespaces); - parent::__construct($element); - } - - public function getDOM($doc = null, $majorVersion = 1, $minorVersion = null) - { - $element = parent::getDOM($doc, $majorVersion, $minorVersion); - if ($this->_gphotoId != null) { - $element->appendChild($this->_gphotoId->getDOM($element->ownerDocument)); - } - if ($this->_gphotoUser != null) { - $element->appendChild($this->_gphotoUser->getDOM($element->ownerDocument)); - } - if ($this->_gphotoNickname != null) { - $element->appendChild($this->_gphotoNickname->getDOM($element->ownerDocument)); - } - if ($this->_gphotoName != null) { - $element->appendChild($this->_gphotoName->getDOM($element->ownerDocument)); - } - if ($this->_gphotoLocation != null) { - $element->appendChild($this->_gphotoLocation->getDOM($element->ownerDocument)); - } - if ($this->_gphotoAccess != null) { - $element->appendChild($this->_gphotoAccess->getDOM($element->ownerDocument)); - } - if ($this->_gphotoTimestamp != null) { - $element->appendChild($this->_gphotoTimestamp->getDOM($element->ownerDocument)); - } - if ($this->_gphotoNumPhotos != null) { - $element->appendChild($this->_gphotoNumPhotos->getDOM($element->ownerDocument)); - } - if ($this->_gphotoCommentingEnabled != null) { - $element->appendChild($this->_gphotoCommentingEnabled->getDOM($element->ownerDocument)); - } - if ($this->_gphotoCommentCount != null) { - $element->appendChild($this->_gphotoCommentCount->getDOM($element->ownerDocument)); - } - - return $element; - } - - protected function takeChildFromDOM($child) - { - $absoluteNodeName = $child->namespaceURI . ':' . $child->localName; - - switch ($absoluteNodeName) { - case $this->lookupNamespace('gphoto') . ':' . 'id'; - $id = new Zend_Gdata_Photos_Extension_Id(); - $id->transferFromDOM($child); - $this->_gphotoId = $id; - break; - case $this->lookupNamespace('gphoto') . ':' . 'user'; - $user = new Zend_Gdata_Photos_Extension_User(); - $user->transferFromDOM($child); - $this->_gphotoUser = $user; - break; - case $this->lookupNamespace('gphoto') . ':' . 'nickname'; - $nickname = new Zend_Gdata_Photos_Extension_Nickname(); - $nickname->transferFromDOM($child); - $this->_gphotoNickname = $nickname; - break; - case $this->lookupNamespace('gphoto') . ':' . 'name'; - $name = new Zend_Gdata_Photos_Extension_Name(); - $name->transferFromDOM($child); - $this->_gphotoName = $name; - break; - case $this->lookupNamespace('gphoto') . ':' . 'location'; - $location = new Zend_Gdata_Photos_Extension_Location(); - $location->transferFromDOM($child); - $this->_gphotoLocation = $location; - break; - case $this->lookupNamespace('gphoto') . ':' . 'access'; - $access = new Zend_Gdata_Photos_Extension_Access(); - $access->transferFromDOM($child); - $this->_gphotoAccess = $access; - break; - case $this->lookupNamespace('gphoto') . ':' . 'timestamp'; - $timestamp = new Zend_Gdata_Photos_Extension_Timestamp(); - $timestamp->transferFromDOM($child); - $this->_gphotoTimestamp = $timestamp; - break; - case $this->lookupNamespace('gphoto') . ':' . 'numphotos'; - $numphotos = new Zend_Gdata_Photos_Extension_NumPhotos(); - $numphotos->transferFromDOM($child); - $this->_gphotoNumPhotos = $numphotos; - break; - case $this->lookupNamespace('gphoto') . ':' . 'commentingEnabled'; - $commentingEnabled = new Zend_Gdata_Photos_Extension_CommentingEnabled(); - $commentingEnabled->transferFromDOM($child); - $this->_gphotoCommentingEnabled = $commentingEnabled; - break; - case $this->lookupNamespace('gphoto') . ':' . 'commentCount'; - $commentCount = new Zend_Gdata_Photos_Extension_CommentCount(); - $commentCount->transferFromDOM($child); - $this->_gphotoCommentCount = $commentCount; - break; - case $this->lookupNamespace('atom') . ':' . 'entry': - $entryClassName = $this->_entryClassName; - $tmpEntry = new Zend_Gdata_App_Entry($child); - $categories = $tmpEntry->getCategory(); - foreach ($categories as $category) { - if ($category->scheme == Zend_Gdata_Photos::KIND_PATH && - $this->_entryKindClassMapping[$category->term] != "") { - $entryClassName = $this->_entryKindClassMapping[$category->term]; - break; - } else { - #require_once 'Zend/Gdata/App/Exception.php'; - throw new Zend_Gdata_App_Exception('Entry is missing kind declaration.'); - } - } - - $newEntry = new $entryClassName($child); - $newEntry->setHttpClient($this->getHttpClient()); - $this->_entry[] = $newEntry; - break; - default: - parent::takeChildFromDOM($child); - break; - } - } - - /** - * Get the value for this element's gphoto:user attribute. - * - * @see setGphotoUser - * @return string The requested attribute. - */ - public function getGphotoUser() - { - return $this->_gphotoUser; - } - - /** - * Set the value for this element's gphoto:user attribute. - * - * @param string $value The desired value for this attribute. - * @return Zend_Gdata_Photos_Extension_User The element being modified. - */ - public function setGphotoUser($value) - { - $this->_gphotoUser = $value; - return $this; - } - - /** - * Get the value for this element's gphoto:access attribute. - * - * @see setGphotoAccess - * @return string The requested attribute. - */ - public function getGphotoAccess() - { - return $this->_gphotoAccess; - } - - /** - * Set the value for this element's gphoto:access attribute. - * - * @param string $value The desired value for this attribute. - * @return Zend_Gdata_Photos_Extension_Access The element being modified. - */ - public function setGphotoAccess($value) - { - $this->_gphotoAccess = $value; - return $this; - } - - /** - * Get the value for this element's gphoto:location attribute. - * - * @see setGphotoLocation - * @return string The requested attribute. - */ - public function getGphotoLocation() - { - return $this->_gphotoLocation; - } - - /** - * Set the value for this element's gphoto:location attribute. - * - * @param string $value The desired value for this attribute. - * @return Zend_Gdata_Photos_Extension_Location The element being modified. - */ - public function setGphotoLocation($value) - { - $this->_gphotoLocation = $value; - return $this; - } - - /** - * Get the value for this element's gphoto:name attribute. - * - * @see setGphotoName - * @return string The requested attribute. - */ - public function getGphotoName() - { - return $this->_gphotoName; - } - - /** - * Set the value for this element's gphoto:name attribute. - * - * @param string $value The desired value for this attribute. - * @return Zend_Gdata_Photos_Extension_Name The element being modified. - */ - public function setGphotoName($value) - { - $this->_gphotoName = $value; - return $this; - } - - /** - * Get the value for this element's gphoto:numphotos attribute. - * - * @see setGphotoNumPhotos - * @return string The requested attribute. - */ - public function getGphotoNumPhotos() - { - return $this->_gphotoNumPhotos; - } - - /** - * Set the value for this element's gphoto:numphotos attribute. - * - * @param string $value The desired value for this attribute. - * @return Zend_Gdata_Photos_Extension_NumPhotos The element being modified. - */ - public function setGphotoNumPhotos($value) - { - $this->_gphotoNumPhotos = $value; - return $this; - } - - /** - * Get the value for this element's gphoto:commentCount attribute. - * - * @see setGphotoCommentCount - * @return string The requested attribute. - */ - public function getGphotoCommentCount() - { - return $this->_gphotoCommentCount; - } - - /** - * Set the value for this element's gphoto:commentCount attribute. - * - * @param string $value The desired value for this attribute. - * @return Zend_Gdata_Photos_Extension_CommentCount The element being modified. - */ - public function setGphotoCommentCount($value) - { - $this->_gphotoCommentCount = $value; - return $this; - } - - /** - * Get the value for this element's gphoto:commentingEnabled attribute. - * - * @see setGphotoCommentingEnabled - * @return string The requested attribute. - */ - public function getGphotoCommentingEnabled() - { - return $this->_gphotoCommentingEnabled; - } - - /** - * Set the value for this element's gphoto:commentingEnabled attribute. - * - * @param string $value The desired value for this attribute. - * @return Zend_Gdata_Photos_Extension_CommentingEnabled The element being modified. - */ - public function setGphotoCommentingEnabled($value) - { - $this->_gphotoCommentingEnabled = $value; - return $this; - } - - /** - * Get the value for this element's gphoto:id attribute. - * - * @see setGphotoId - * @return string The requested attribute. - */ - public function getGphotoId() - { - return $this->_gphotoId; - } - - /** - * Set the value for this element's gphoto:id attribute. - * - * @param string $value The desired value for this attribute. - * @return Zend_Gdata_Photos_Extension_Id The element being modified. - */ - public function setGphotoId($value) - { - $this->_gphotoId = $value; - return $this; - } - - /** - * Get the value for this element's georss:where attribute. - * - * @see setGeoRssWhere - * @return string The requested attribute. - */ - public function getGeoRssWhere() - { - return $this->_geoRssWhere; - } - - /** - * Set the value for this element's georss:where attribute. - * - * @param string $value The desired value for this attribute. - * @return Zend_Gdata_Geo_Extension_GeoRssWhere The element being modified. - */ - public function setGeoRssWhere($value) - { - $this->_geoRssWhere = $value; - return $this; - } - - /** - * Get the value for this element's gphoto:nickname attribute. - * - * @see setGphotoNickname - * @return string The requested attribute. - */ - public function getGphotoNickname() - { - return $this->_gphotoNickname; - } - - /** - * Set the value for this element's gphoto:nickname attribute. - * - * @param string $value The desired value for this attribute. - * @return Zend_Gdata_Photos_Extension_Nickname The element being modified. - */ - public function setGphotoNickname($value) - { - $this->_gphotoNickname = $value; - return $this; - } - - /** - * Get the value for this element's gphoto:timestamp attribute. - * - * @see setGphotoTimestamp - * @return string The requested attribute. - */ - public function getGphotoTimestamp() - { - return $this->_gphotoTimestamp; - } - - /** - * Set the value for this element's gphoto:timestamp attribute. - * - * @param string $value The desired value for this attribute. - * @return Zend_Gdata_Photos_Extension_Timestamp The element being modified. - */ - public function setGphotoTimestamp($value) - { - $this->_gphotoTimestamp = $value; - return $this; - } - -} diff --git a/library/Zend/Gdata/Photos/AlbumQuery.php b/library/Zend/Gdata/Photos/AlbumQuery.php deleted file mode 100755 index eb460a9686..0000000000 --- a/library/Zend/Gdata/Photos/AlbumQuery.php +++ /dev/null @@ -1,149 +0,0 @@ -_albumId = null; - $this->_albumName = $value; - - return $this; - } - - /** - * Get the album name which is to be returned. - * - * @see setAlbumName - * @return string The name of the album to retrieve. - */ - public function getAlbumName() - { - return $this->_albumName; - } - - /** - * Set the album ID to query for. When set, this album's photographs - * be returned. If not set or null, the default user's feed will be - * returned instead. - * - * NOTE: Album and AlbumId are mutually exclusive. Setting one will - * automatically set the other to null. - * - * @param string $value The ID of the album to retrieve, or null to - * clear. - * @return Zend_Gdata_Photos_AlbumQuery The query object. - */ - public function setAlbumId($value) - { - $this->_albumName = null; - $this->_albumId = $value; - - return $this; - } - - /** - * Get the album ID which is to be returned. - * - * @see setAlbum - * @return string The ID of the album to retrieve. - */ - public function getAlbumId() - { - return $this->_albumId; - } - - /** - * Returns the URL generated for this query, based on it's current - * parameters. - * - * @return string A URL generated based on the state of this query. - * @throws Zend_Gdata_App_InvalidArgumentException - */ - public function getQueryUrl($incomingUri = '') - { - $uri = ''; - if ($this->getAlbumName() !== null && $this->getAlbumId() === null) { - $uri .= '/album/' . $this->getAlbumName(); - } elseif ($this->getAlbumName() === null && $this->getAlbumId() !== null) { - $uri .= '/albumid/' . $this->getAlbumId(); - } elseif ($this->getAlbumName() !== null && $this->getAlbumId() !== null) { - #require_once 'Zend/Gdata/App/InvalidArgumentException.php'; - throw new Zend_Gdata_App_InvalidArgumentException( - 'AlbumName and AlbumId cannot both be non-null'); - } else { - #require_once 'Zend/Gdata/App/InvalidArgumentException.php'; - throw new Zend_Gdata_App_InvalidArgumentException( - 'AlbumName and AlbumId cannot both be null'); - } - $uri .= $incomingUri; - return parent::getQueryUrl($uri); - } - -} diff --git a/library/Zend/Gdata/Photos/CommentEntry.php b/library/Zend/Gdata/Photos/CommentEntry.php deleted file mode 100755 index 931f3704a4..0000000000 --- a/library/Zend/Gdata/Photos/CommentEntry.php +++ /dev/null @@ -1,195 +0,0 @@ - in the Google Data protocol. - * - * @category Zend - * @package Zend_Gdata - * @subpackage Photos - * @copyright Copyright (c) 2005-2015 Zend Technologies USA Inc. (http://www.zend.com) - * @license http://framework.zend.com/license/new-bsd New BSD License - */ -class Zend_Gdata_Photos_CommentEntry extends Zend_Gdata_Entry -{ - - protected $_entryClassName = 'Zend_Gdata_Photos_CommentEntry'; - - /** - * gphoto:id element - * - * @var Zend_Gdata_Photos_Extension_Id - */ - protected $_gphotoId = null; - - /** - * gphoto:photoid element, differs from gphoto:id as this is an - * actual identification number unique exclusively to photo entries, - * whereas gphoto:id can refer to all gphoto objects - * - * @var Zend_Gdata_Photos_Extension_PhotoId - */ - protected $_gphotoPhotoId = null; - - /** - * Create a new instance. - * - * @param DOMElement $element (optional) DOMElement from which this - * object should be constructed. - */ - public function __construct($element = null) - { - $this->registerAllNamespaces(Zend_Gdata_Photos::$namespaces); - parent::__construct($element); - - $category = new Zend_Gdata_App_Extension_Category( - 'http://schemas.google.com/photos/2007#comment', - 'http://schemas.google.com/g/2005#kind'); - $this->setCategory(array($category)); - } - - /** - * Retrieves a DOMElement which corresponds to this element and all - * child properties. This is used to build an entry back into a DOM - * and eventually XML text for application storage/persistence. - * - * @param DOMDocument $doc The DOMDocument used to construct DOMElements - * @return DOMElement The DOMElement representing this element and all - * child properties. - */ - public function getDOM($doc = null, $majorVersion = 1, $minorVersion = null) - { - $element = parent::getDOM($doc, $majorVersion, $minorVersion); - if ($this->_gphotoId !== null) { - $element->appendChild($this->_gphotoId->getDOM($element->ownerDocument)); - } - if ($this->_gphotoPhotoId !== null) { - $element->appendChild($this->_gphotoPhotoId->getDOM($element->ownerDocument)); - } - return $element; - } - - /** - * Creates individual Entry objects of the appropriate type and - * stores them as members of this entry based upon DOM data. - * - * @param DOMNode $child The DOMNode to process - */ - protected function takeChildFromDOM($child) - { - $absoluteNodeName = $child->namespaceURI . ':' . $child->localName; - - switch ($absoluteNodeName) { - case $this->lookupNamespace('gphoto') . ':' . 'id'; - $id = new Zend_Gdata_Photos_Extension_Id(); - $id->transferFromDOM($child); - $this->_gphotoId = $id; - break; - case $this->lookupNamespace('gphoto') . ':' . 'photoid'; - $photoid = new Zend_Gdata_Photos_Extension_PhotoId(); - $photoid->transferFromDOM($child); - $this->_gphotoPhotoId = $photoid; - break; - default: - parent::takeChildFromDOM($child); - break; - } - } - - /** - * Get the value for this element's gphoto:photoid attribute. - * - * @see setGphotoPhotoId - * @return string The requested attribute. - */ - public function getGphotoPhotoId() - { - return $this->_gphotoPhotoId; - } - - /** - * Set the value for this element's gphoto:photoid attribute. - * - * @param string $value The desired value for this attribute. - * @return Zend_Gdata_Photos_Extension_PhotoId The element being modified. - */ - public function setGphotoPhotoId($value) - { - $this->_gphotoPhotoId = $value; - return $this; - } - - /** - * Get the value for this element's gphoto:id attribute. - * - * @see setGphotoId - * @return string The requested attribute. - */ - public function getGphotoId() - { - return $this->_gphotoId; - } - - /** - * Set the value for this element's gphoto:id attribute. - * - * @param string $value The desired value for this attribute. - * @return Zend_Gdata_Photos_Extension_Id The element being modified. - */ - public function setGphotoId($value) - { - $this->_gphotoId = $value; - return $this; - } -} diff --git a/library/Zend/Gdata/Photos/Extension/Access.php b/library/Zend/Gdata/Photos/Extension/Access.php deleted file mode 100755 index b101d4e111..0000000000 --- a/library/Zend/Gdata/Photos/Extension/Access.php +++ /dev/null @@ -1,63 +0,0 @@ -registerAllNamespaces(Zend_Gdata_Photos::$namespaces); - parent::__construct(); - $this->setText($text); - } - -} diff --git a/library/Zend/Gdata/Photos/Extension/AlbumId.php b/library/Zend/Gdata/Photos/Extension/AlbumId.php deleted file mode 100755 index a5f35c984f..0000000000 --- a/library/Zend/Gdata/Photos/Extension/AlbumId.php +++ /dev/null @@ -1,63 +0,0 @@ -registerAllNamespaces(Zend_Gdata_Photos::$namespaces); - parent::__construct(); - $this->setText($text); - } - -} diff --git a/library/Zend/Gdata/Photos/Extension/BytesUsed.php b/library/Zend/Gdata/Photos/Extension/BytesUsed.php deleted file mode 100755 index 131139f343..0000000000 --- a/library/Zend/Gdata/Photos/Extension/BytesUsed.php +++ /dev/null @@ -1,62 +0,0 @@ -registerAllNamespaces(Zend_Gdata_Photos::$namespaces); - parent::__construct(); - $this->setText($text); - } - -} diff --git a/library/Zend/Gdata/Photos/Extension/Checksum.php b/library/Zend/Gdata/Photos/Extension/Checksum.php deleted file mode 100755 index 8f388dd40f..0000000000 --- a/library/Zend/Gdata/Photos/Extension/Checksum.php +++ /dev/null @@ -1,63 +0,0 @@ -registerAllNamespaces(Zend_Gdata_Photos::$namespaces); - parent::__construct(); - $this->setText($text); - } - -} diff --git a/library/Zend/Gdata/Photos/Extension/Client.php b/library/Zend/Gdata/Photos/Extension/Client.php deleted file mode 100755 index 63e8a6caa5..0000000000 --- a/library/Zend/Gdata/Photos/Extension/Client.php +++ /dev/null @@ -1,63 +0,0 @@ -registerAllNamespaces(Zend_Gdata_Photos::$namespaces); - parent::__construct(); - $this->setText($text); - } - -} diff --git a/library/Zend/Gdata/Photos/Extension/CommentCount.php b/library/Zend/Gdata/Photos/Extension/CommentCount.php deleted file mode 100755 index 0c6310452b..0000000000 --- a/library/Zend/Gdata/Photos/Extension/CommentCount.php +++ /dev/null @@ -1,63 +0,0 @@ -registerAllNamespaces(Zend_Gdata_Photos::$namespaces); - parent::__construct(); - $this->setText($text); - } - -} diff --git a/library/Zend/Gdata/Photos/Extension/CommentingEnabled.php b/library/Zend/Gdata/Photos/Extension/CommentingEnabled.php deleted file mode 100755 index aefd21a856..0000000000 --- a/library/Zend/Gdata/Photos/Extension/CommentingEnabled.php +++ /dev/null @@ -1,64 +0,0 @@ -registerAllNamespaces(Zend_Gdata_Photos::$namespaces); - parent::__construct(); - $this->setText($text); - } - -} diff --git a/library/Zend/Gdata/Photos/Extension/Height.php b/library/Zend/Gdata/Photos/Extension/Height.php deleted file mode 100755 index bb482aa778..0000000000 --- a/library/Zend/Gdata/Photos/Extension/Height.php +++ /dev/null @@ -1,62 +0,0 @@ -registerAllNamespaces(Zend_Gdata_Photos::$namespaces); - parent::__construct(); - $this->setText($text); - } - -} diff --git a/library/Zend/Gdata/Photos/Extension/Id.php b/library/Zend/Gdata/Photos/Extension/Id.php deleted file mode 100755 index d87af118c5..0000000000 --- a/library/Zend/Gdata/Photos/Extension/Id.php +++ /dev/null @@ -1,62 +0,0 @@ -registerAllNamespaces(Zend_Gdata_Photos::$namespaces); - parent::__construct(); - $this->setText($text); - } - -} diff --git a/library/Zend/Gdata/Photos/Extension/Location.php b/library/Zend/Gdata/Photos/Extension/Location.php deleted file mode 100755 index 6c23a2b15a..0000000000 --- a/library/Zend/Gdata/Photos/Extension/Location.php +++ /dev/null @@ -1,62 +0,0 @@ -registerAllNamespaces(Zend_Gdata_Photos::$namespaces); - parent::__construct(); - $this->setText($text); - } - -} diff --git a/library/Zend/Gdata/Photos/Extension/MaxPhotosPerAlbum.php b/library/Zend/Gdata/Photos/Extension/MaxPhotosPerAlbum.php deleted file mode 100755 index 44b6f85a23..0000000000 --- a/library/Zend/Gdata/Photos/Extension/MaxPhotosPerAlbum.php +++ /dev/null @@ -1,63 +0,0 @@ -registerAllNamespaces(Zend_Gdata_Photos::$namespaces); - parent::__construct(); - $this->setText($text); - } - -} diff --git a/library/Zend/Gdata/Photos/Extension/Name.php b/library/Zend/Gdata/Photos/Extension/Name.php deleted file mode 100755 index 021f845c80..0000000000 --- a/library/Zend/Gdata/Photos/Extension/Name.php +++ /dev/null @@ -1,62 +0,0 @@ -registerAllNamespaces(Zend_Gdata_Photos::$namespaces); - parent::__construct(); - $this->setText($text); - } - -} diff --git a/library/Zend/Gdata/Photos/Extension/Nickname.php b/library/Zend/Gdata/Photos/Extension/Nickname.php deleted file mode 100755 index a1590ba084..0000000000 --- a/library/Zend/Gdata/Photos/Extension/Nickname.php +++ /dev/null @@ -1,62 +0,0 @@ -registerAllNamespaces(Zend_Gdata_Photos::$namespaces); - parent::__construct(); - $this->setText($text); - } - -} diff --git a/library/Zend/Gdata/Photos/Extension/NumPhotos.php b/library/Zend/Gdata/Photos/Extension/NumPhotos.php deleted file mode 100755 index 6de5b91e06..0000000000 --- a/library/Zend/Gdata/Photos/Extension/NumPhotos.php +++ /dev/null @@ -1,62 +0,0 @@ -registerAllNamespaces(Zend_Gdata_Photos::$namespaces); - parent::__construct(); - $this->setText($text); - } - -} diff --git a/library/Zend/Gdata/Photos/Extension/NumPhotosRemaining.php b/library/Zend/Gdata/Photos/Extension/NumPhotosRemaining.php deleted file mode 100755 index f7dc830d87..0000000000 --- a/library/Zend/Gdata/Photos/Extension/NumPhotosRemaining.php +++ /dev/null @@ -1,62 +0,0 @@ -registerAllNamespaces(Zend_Gdata_Photos::$namespaces); - parent::__construct(); - $this->setText($text); - } - -} diff --git a/library/Zend/Gdata/Photos/Extension/PhotoId.php b/library/Zend/Gdata/Photos/Extension/PhotoId.php deleted file mode 100755 index fc95cfe277..0000000000 --- a/library/Zend/Gdata/Photos/Extension/PhotoId.php +++ /dev/null @@ -1,61 +0,0 @@ -registerAllNamespaces(Zend_Gdata_Photos::$namespaces); - parent::__construct(); - $this->setText($text); - } - -} diff --git a/library/Zend/Gdata/Photos/Extension/Position.php b/library/Zend/Gdata/Photos/Extension/Position.php deleted file mode 100755 index d1a0b30583..0000000000 --- a/library/Zend/Gdata/Photos/Extension/Position.php +++ /dev/null @@ -1,62 +0,0 @@ -registerAllNamespaces(Zend_Gdata_Photos::$namespaces); - parent::__construct(); - $this->setText($text); - } - -} diff --git a/library/Zend/Gdata/Photos/Extension/QuotaCurrent.php b/library/Zend/Gdata/Photos/Extension/QuotaCurrent.php deleted file mode 100755 index 031868a4fe..0000000000 --- a/library/Zend/Gdata/Photos/Extension/QuotaCurrent.php +++ /dev/null @@ -1,62 +0,0 @@ -registerAllNamespaces(Zend_Gdata_Photos::$namespaces); - parent::__construct(); - $this->setText($text); - } - -} diff --git a/library/Zend/Gdata/Photos/Extension/QuotaLimit.php b/library/Zend/Gdata/Photos/Extension/QuotaLimit.php deleted file mode 100755 index 32b17d8f88..0000000000 --- a/library/Zend/Gdata/Photos/Extension/QuotaLimit.php +++ /dev/null @@ -1,63 +0,0 @@ -registerAllNamespaces(Zend_Gdata_Photos::$namespaces); - parent::__construct(); - $this->setText($text); - } - -} diff --git a/library/Zend/Gdata/Photos/Extension/Rotation.php b/library/Zend/Gdata/Photos/Extension/Rotation.php deleted file mode 100755 index cdcc57c490..0000000000 --- a/library/Zend/Gdata/Photos/Extension/Rotation.php +++ /dev/null @@ -1,63 +0,0 @@ -registerAllNamespaces(Zend_Gdata_Photos::$namespaces); - parent::__construct(); - $this->setText($text); - } - -} diff --git a/library/Zend/Gdata/Photos/Extension/Size.php b/library/Zend/Gdata/Photos/Extension/Size.php deleted file mode 100755 index ff97aa5735..0000000000 --- a/library/Zend/Gdata/Photos/Extension/Size.php +++ /dev/null @@ -1,62 +0,0 @@ -registerAllNamespaces(Zend_Gdata_Photos::$namespaces); - parent::__construct(); - $this->setText($text); - } - -} diff --git a/library/Zend/Gdata/Photos/Extension/Thumbnail.php b/library/Zend/Gdata/Photos/Extension/Thumbnail.php deleted file mode 100755 index da30295066..0000000000 --- a/library/Zend/Gdata/Photos/Extension/Thumbnail.php +++ /dev/null @@ -1,62 +0,0 @@ -registerAllNamespaces(Zend_Gdata_Photos::$namespaces); - parent::__construct(); - $this->setText($text); - } - -} diff --git a/library/Zend/Gdata/Photos/Extension/Timestamp.php b/library/Zend/Gdata/Photos/Extension/Timestamp.php deleted file mode 100755 index 6a0d56c2ff..0000000000 --- a/library/Zend/Gdata/Photos/Extension/Timestamp.php +++ /dev/null @@ -1,63 +0,0 @@ -registerAllNamespaces(Zend_Gdata_Photos::$namespaces); - parent::__construct(); - $this->setText($text); - } - -} diff --git a/library/Zend/Gdata/Photos/Extension/User.php b/library/Zend/Gdata/Photos/Extension/User.php deleted file mode 100755 index 42f103fa46..0000000000 --- a/library/Zend/Gdata/Photos/Extension/User.php +++ /dev/null @@ -1,62 +0,0 @@ -registerAllNamespaces(Zend_Gdata_Photos::$namespaces); - parent::__construct(); - $this->setText($text); - } - -} diff --git a/library/Zend/Gdata/Photos/Extension/Version.php b/library/Zend/Gdata/Photos/Extension/Version.php deleted file mode 100755 index 58da5922c5..0000000000 --- a/library/Zend/Gdata/Photos/Extension/Version.php +++ /dev/null @@ -1,63 +0,0 @@ -registerAllNamespaces(Zend_Gdata_Photos::$namespaces); - parent::__construct(); - $this->setText($text); - } - -} diff --git a/library/Zend/Gdata/Photos/Extension/Weight.php b/library/Zend/Gdata/Photos/Extension/Weight.php deleted file mode 100755 index 195c0a792a..0000000000 --- a/library/Zend/Gdata/Photos/Extension/Weight.php +++ /dev/null @@ -1,63 +0,0 @@ -registerAllNamespaces(Zend_Gdata_Photos::$namespaces); - parent::__construct(); - $this->setText($text); - } - -} diff --git a/library/Zend/Gdata/Photos/Extension/Width.php b/library/Zend/Gdata/Photos/Extension/Width.php deleted file mode 100755 index e660f9fc64..0000000000 --- a/library/Zend/Gdata/Photos/Extension/Width.php +++ /dev/null @@ -1,62 +0,0 @@ -registerAllNamespaces(Zend_Gdata_Photos::$namespaces); - parent::__construct(); - $this->setText($text); - } - -} diff --git a/library/Zend/Gdata/Photos/PhotoEntry.php b/library/Zend/Gdata/Photos/PhotoEntry.php deleted file mode 100755 index f261ffdbea..0000000000 --- a/library/Zend/Gdata/Photos/PhotoEntry.php +++ /dev/null @@ -1,691 +0,0 @@ - in the Google Data protocol. - * - * @category Zend - * @package Zend_Gdata - * @subpackage Photos - * @copyright Copyright (c) 2005-2015 Zend Technologies USA Inc. (http://www.zend.com) - * @license http://framework.zend.com/license/new-bsd New BSD License - */ -class Zend_Gdata_Photos_PhotoEntry extends Zend_Gdata_Media_Entry -{ - - protected $_entryClassName = 'Zend_Gdata_Photos_PhotoEntry'; - - /** - * gphoto:id element - * - * @var Zend_Gdata_Photos_Extension_Id - */ - protected $_gphotoId = null; - - /** - * gphoto:albumid element - * - * @var Zend_Gdata_Photos_Extension_AlbumId - */ - protected $_gphotoAlbumId = null; - - /** - * gphoto:version element - * - * @var Zend_Gdata_Photos_Extension_Version - */ - protected $_gphotoVersion = null; - - /** - * gphoto:width element - * - * @var Zend_Gdata_Photos_Extension_Width - */ - protected $_gphotoWidth = null; - - /** - * gphoto:height element - * - * @var Zend_Gdata_Photos_Extension_Height - */ - protected $_gphotoHeight = null; - - /** - * gphoto:size element - * - * @var Zend_Gdata_Photos_Extension_Size - */ - protected $_gphotoSize = null; - - /** - * gphoto:client element - * - * @var Zend_Gdata_Photos_Extension_Client - */ - protected $_gphotoClient = null; - - /** - * gphoto:checksum element - * - * @var Zend_Gdata_Photos_Extension_Checksum - */ - protected $_gphotoChecksum = null; - - /** - * gphoto:timestamp element - * - * @var Zend_Gdata_Photos_Extension_Timestamp - */ - protected $_gphotoTimestamp = null; - - /** - * gphoto:commentCount element - * - * @var Zend_Gdata_Photos_Extension_CommentCount - */ - protected $_gphotoCommentCount = null; - - /** - * gphoto:commentingEnabled element - * - * @var Zend_Gdata_Photos_Extension_CommentingEnabled - */ - protected $_gphotoCommentingEnabled = null; - - /** - * exif:tags element - * - * @var Zend_Gdata_Exif_Extension_Tags - */ - protected $_exifTags = null; - - /** - * georss:where element - * - * @var Zend_Gdata_Geo_Extension_GeoRssWhere - */ - protected $_geoRssWhere = null; - - /** - * Create a new instance. - * - * @param DOMElement $element (optional) DOMElement from which this - * object should be constructed. - */ - public function __construct($element = null) - { - $this->registerAllNamespaces(Zend_Gdata_Photos::$namespaces); - parent::__construct($element); - - $category = new Zend_Gdata_App_Extension_Category( - 'http://schemas.google.com/photos/2007#photo', - 'http://schemas.google.com/g/2005#kind'); - $this->setCategory(array($category)); - } - - /** - * Retrieves a DOMElement which corresponds to this element and all - * child properties. This is used to build an entry back into a DOM - * and eventually XML text for application storage/persistence. - * - * @param DOMDocument $doc The DOMDocument used to construct DOMElements - * @return DOMElement The DOMElement representing this element and all - * child properties. - */ - public function getDOM($doc = null, $majorVersion = 1, $minorVersion = null) - { - $element = parent::getDOM($doc, $majorVersion, $minorVersion); - if ($this->_gphotoAlbumId !== null) { - $element->appendChild($this->_gphotoAlbumId->getDOM($element->ownerDocument)); - } - if ($this->_gphotoId !== null) { - $element->appendChild($this->_gphotoId->getDOM($element->ownerDocument)); - } - if ($this->_gphotoVersion !== null) { - $element->appendChild($this->_gphotoVersion->getDOM($element->ownerDocument)); - } - if ($this->_gphotoWidth !== null) { - $element->appendChild($this->_gphotoWidth->getDOM($element->ownerDocument)); - } - if ($this->_gphotoHeight !== null) { - $element->appendChild($this->_gphotoHeight->getDOM($element->ownerDocument)); - } - if ($this->_gphotoSize !== null) { - $element->appendChild($this->_gphotoSize->getDOM($element->ownerDocument)); - } - if ($this->_gphotoClient !== null) { - $element->appendChild($this->_gphotoClient->getDOM($element->ownerDocument)); - } - if ($this->_gphotoChecksum !== null) { - $element->appendChild($this->_gphotoChecksum->getDOM($element->ownerDocument)); - } - if ($this->_gphotoTimestamp !== null) { - $element->appendChild($this->_gphotoTimestamp->getDOM($element->ownerDocument)); - } - if ($this->_gphotoCommentingEnabled !== null) { - $element->appendChild($this->_gphotoCommentingEnabled->getDOM($element->ownerDocument)); - } - if ($this->_gphotoCommentCount !== null) { - $element->appendChild($this->_gphotoCommentCount->getDOM($element->ownerDocument)); - } - if ($this->_exifTags !== null) { - $element->appendChild($this->_exifTags->getDOM($element->ownerDocument)); - } - if ($this->_geoRssWhere !== null) { - $element->appendChild($this->_geoRssWhere->getDOM($element->ownerDocument)); - } - return $element; - } - - /** - * Creates individual Entry objects of the appropriate type and - * stores them as members of this entry based upon DOM data. - * - * @param DOMNode $child The DOMNode to process - */ - protected function takeChildFromDOM($child) - { - $absoluteNodeName = $child->namespaceURI . ':' . $child->localName; - - switch ($absoluteNodeName) { - case $this->lookupNamespace('gphoto') . ':' . 'albumid'; - $albumId = new Zend_Gdata_Photos_Extension_AlbumId(); - $albumId->transferFromDOM($child); - $this->_gphotoAlbumId = $albumId; - break; - case $this->lookupNamespace('gphoto') . ':' . 'id'; - $id = new Zend_Gdata_Photos_Extension_Id(); - $id->transferFromDOM($child); - $this->_gphotoId = $id; - break; - case $this->lookupNamespace('gphoto') . ':' . 'version'; - $version = new Zend_Gdata_Photos_Extension_Version(); - $version->transferFromDOM($child); - $this->_gphotoVersion = $version; - break; - case $this->lookupNamespace('gphoto') . ':' . 'width'; - $width = new Zend_Gdata_Photos_Extension_Width(); - $width->transferFromDOM($child); - $this->_gphotoWidth = $width; - break; - case $this->lookupNamespace('gphoto') . ':' . 'height'; - $height = new Zend_Gdata_Photos_Extension_Height(); - $height->transferFromDOM($child); - $this->_gphotoHeight = $height; - break; - case $this->lookupNamespace('gphoto') . ':' . 'size'; - $size = new Zend_Gdata_Photos_Extension_Size(); - $size->transferFromDOM($child); - $this->_gphotoSize = $size; - break; - case $this->lookupNamespace('gphoto') . ':' . 'client'; - $client = new Zend_Gdata_Photos_Extension_Client(); - $client->transferFromDOM($child); - $this->_gphotoClient = $client; - break; - case $this->lookupNamespace('gphoto') . ':' . 'checksum'; - $checksum = new Zend_Gdata_Photos_Extension_Checksum(); - $checksum->transferFromDOM($child); - $this->_gphotoChecksum = $checksum; - break; - case $this->lookupNamespace('gphoto') . ':' . 'timestamp'; - $timestamp = new Zend_Gdata_Photos_Extension_Timestamp(); - $timestamp->transferFromDOM($child); - $this->_gphotoTimestamp = $timestamp; - break; - case $this->lookupNamespace('gphoto') . ':' . 'commentingEnabled'; - $commentingEnabled = new Zend_Gdata_Photos_Extension_CommentingEnabled(); - $commentingEnabled->transferFromDOM($child); - $this->_gphotoCommentingEnabled = $commentingEnabled; - break; - case $this->lookupNamespace('gphoto') . ':' . 'commentCount'; - $commentCount = new Zend_Gdata_Photos_Extension_CommentCount(); - $commentCount->transferFromDOM($child); - $this->_gphotoCommentCount = $commentCount; - break; - case $this->lookupNamespace('exif') . ':' . 'tags'; - $exifTags = new Zend_Gdata_Exif_Extension_Tags(); - $exifTags->transferFromDOM($child); - $this->_exifTags = $exifTags; - break; - case $this->lookupNamespace('georss') . ':' . 'where'; - $geoRssWhere = new Zend_Gdata_Geo_Extension_GeoRssWhere(); - $geoRssWhere->transferFromDOM($child); - $this->_geoRssWhere = $geoRssWhere; - break; - default: - parent::takeChildFromDOM($child); - break; - - } - } - - /** - * Get the value for this element's gphoto:albumid attribute. - * - * @see setGphotoAlbumId - * @return string The requested attribute. - */ - public function getGphotoAlbumId() - { - return $this->_gphotoAlbumId; - } - - /** - * Set the value for this element's gphoto:albumid attribute. - * - * @param string $value The desired value for this attribute. - * @return Zend_Gdata_Photos_Extension_AlbumId The element being modified. - */ - public function setGphotoAlbumId($value) - { - $this->_gphotoAlbumId = $value; - return $this; - } - - /** - * Get the value for this element's gphoto:id attribute. - * - * @see setGphotoId - * @return string The requested attribute. - */ - public function getGphotoId() - { - return $this->_gphotoId; - } - - /** - * Set the value for this element's gphoto:id attribute. - * - * @param string $value The desired value for this attribute. - * @return Zend_Gdata_Photos_Extension_Id The element being modified. - */ - public function setGphotoId($value) - { - $this->_gphotoId = $value; - return $this; - } - - /** - * Get the value for this element's gphoto:version attribute. - * - * @see setGphotoVersion - * @return string The requested attribute. - */ - public function getGphotoVersion() - { - return $this->_gphotoVersion; - } - - /** - * Set the value for this element's gphoto:version attribute. - * - * @param string $value The desired value for this attribute. - * @return Zend_Gdata_Photos_Extension_Version The element being modified. - */ - public function setGphotoVersion($value) - { - $this->_gphotoVersion = $value; - return $this; - } - - /** - * Get the value for this element's gphoto:width attribute. - * - * @see setGphotoWidth - * @return string The requested attribute. - */ - public function getGphotoWidth() - { - return $this->_gphotoWidth; - } - - /** - * Set the value for this element's gphoto:width attribute. - * - * @param string $value The desired value for this attribute. - * @return Zend_Gdata_Photos_Extension_Width The element being modified. - */ - public function setGphotoWidth($value) - { - $this->_gphotoWidth = $value; - return $this; - } - - /** - * Get the value for this element's gphoto:height attribute. - * - * @see setGphotoHeight - * @return string The requested attribute. - */ - public function getGphotoHeight() - { - return $this->_gphotoHeight; - } - - /** - * Set the value for this element's gphoto:height attribute. - * - * @param string $value The desired value for this attribute. - * @return Zend_Gdata_Photos_Extension_Height The element being modified. - */ - public function setGphotoHeight($value) - { - $this->_gphotoHeight = $value; - return $this; - } - - /** - * Get the value for this element's gphoto:size attribute. - * - * @see setGphotoSize - * @return string The requested attribute. - */ - public function getGphotoSize() - { - return $this->_gphotoSize; - } - - /** - * Set the value for this element's gphoto:size attribute. - * - * @param string $value The desired value for this attribute. - * @return Zend_Gdata_Photos_Extension_Size The element being modified. - */ - public function setGphotoSize($value) - { - $this->_gphotoSize = $value; - return $this; - } - - /** - * Get the value for this element's gphoto:client attribute. - * - * @see setGphotoClient - * @return string The requested attribute. - */ - public function getGphotoClient() - { - return $this->_gphotoClient; - } - - /** - * Set the value for this element's gphoto:client attribute. - * - * @param string $value The desired value for this attribute. - * @return Zend_Gdata_Photos_Extension_Client The element being modified. - */ - public function setGphotoClient($value) - { - $this->_gphotoClient = $value; - return $this; - } - - /** - * Get the value for this element's gphoto:checksum attribute. - * - * @see setGphotoChecksum - * @return string The requested attribute. - */ - public function getGphotoChecksum() - { - return $this->_gphotoChecksum; - } - - /** - * Set the value for this element's gphoto:checksum attribute. - * - * @param string $value The desired value for this attribute. - * @return Zend_Gdata_Photos_Extension_Checksum The element being modified. - */ - public function setGphotoChecksum($value) - { - $this->_gphotoChecksum = $value; - return $this; - } - - /** - * Get the value for this element's gphoto:timestamp attribute. - * - * @see setGphotoTimestamp - * @return string The requested attribute. - */ - public function getGphotoTimestamp() - { - return $this->_gphotoTimestamp; - } - - /** - * Set the value for this element's gphoto:timestamp attribute. - * - * @param string $value The desired value for this attribute. - * @return Zend_Gdata_Photos_Extension_Timestamp The element being modified. - */ - public function setGphotoTimestamp($value) - { - $this->_gphotoTimestamp = $value; - return $this; - } - - /** - * Get the value for this element's gphoto:commentCount attribute. - * - * @see setGphotoCommentCount - * @return string The requested attribute. - */ - public function getGphotoCommentCount() - { - return $this->_gphotoCommentCount; - } - - /** - * Set the value for this element's gphoto:commentCount attribute. - * - * @param string $value The desired value for this attribute. - * @return Zend_Gdata_Photos_Extension_CommentCount The element being modified. - */ - public function setGphotoCommentCount($value) - { - $this->_gphotoCommentCount = $value; - return $this; - } - - /** - * Get the value for this element's gphoto:commentingEnabled attribute. - * - * @see setGphotoCommentingEnabled - * @return string The requested attribute. - */ - public function getGphotoCommentingEnabled() - { - return $this->_gphotoCommentingEnabled; - } - - /** - * Set the value for this element's gphoto:commentingEnabled attribute. - * - * @param string $value The desired value for this attribute. - * @return Zend_Gdata_Photos_Extension_CommentingEnabled The element being modified. - */ - public function setGphotoCommentingEnabled($value) - { - $this->_gphotoCommentingEnabled = $value; - return $this; - } - - /** - * Get the value for this element's exif:tags attribute. - * - * @see setExifTags - * @return string The requested attribute. - */ - public function getExifTags() - { - return $this->_exifTags; - } - - /** - * Set the value for this element's exif:tags attribute. - * - * @param string $value The desired value for this attribute. - * @return Zend_Gdata_Exif_Extension_Tags The element being modified. - */ - public function setExifTags($value) - { - $this->_exifTags = $value; - return $this; - } - - /** - * Get the value for this element's georss:where attribute. - * - * @see setGeoRssWhere - * @return string The requested attribute. - */ - public function getGeoRssWhere() - { - return $this->_geoRssWhere; - } - - /** - * Set the value for this element's georss:where attribute. - * - * @param string $value The desired value for this attribute. - * @return Zend_Gdata_Geo_Extension_GeoRssWhere The element being modified. - */ - public function setGeoRssWhere($value) - { - $this->_geoRssWhere = $value; - return $this; - } - - /** - * Get the value for this element's media:group attribute. - * - * @see setMediaGroup - * @return string The requested attribute. - */ - public function getMediaGroup() - { - return $this->_mediaGroup; - } - - /** - * Set the value for this element's media:group attribute. - * - * @param string $value The desired value for this attribute. - * @return Zend_Gdata_Media_Extension_MediaGroup The element being modified. - */ - public function setMediaGroup($value) - { - $this->_mediaGroup = $value; - return $this; - } - -} diff --git a/library/Zend/Gdata/Photos/PhotoFeed.php b/library/Zend/Gdata/Photos/PhotoFeed.php deleted file mode 100755 index 59a553958b..0000000000 --- a/library/Zend/Gdata/Photos/PhotoFeed.php +++ /dev/null @@ -1,559 +0,0 @@ - 'Zend_Gdata_Photos_CommentEntry', - 'http://schemas.google.com/photos/2007#tag' => 'Zend_Gdata_Photos_TagEntry' - ); - - public function __construct($element = null) - { - $this->registerAllNamespaces(Zend_Gdata_Photos::$namespaces); - parent::__construct($element); - } - - public function getDOM($doc = null, $majorVersion = 1, $minorVersion = null) - { - $element = parent::getDOM($doc, $majorVersion, $minorVersion); - if ($this->_gphotoId != null) { - $element->appendChild($this->_gphotoId->getDOM($element->ownerDocument)); - } - if ($this->_gphotoVersion != null) { - $element->appendChild($this->_gphotoVersion->getDOM($element->ownerDocument)); - } - if ($this->_gphotoWidth != null) { - $element->appendChild($this->_gphotoWidth->getDOM($element->ownerDocument)); - } - if ($this->_gphotoHeight != null) { - $element->appendChild($this->_gphotoHeight->getDOM($element->ownerDocument)); - } - if ($this->_gphotoSize != null) { - $element->appendChild($this->_gphotoSize->getDOM($element->ownerDocument)); - } - if ($this->_gphotoClient != null) { - $element->appendChild($this->_gphotoClient->getDOM($element->ownerDocument)); - } - if ($this->_gphotoChecksum != null) { - $element->appendChild($this->_gphotoChecksum->getDOM($element->ownerDocument)); - } - if ($this->_gphotoTimestamp != null) { - $element->appendChild($this->_gphotoTimestamp->getDOM($element->ownerDocument)); - } - if ($this->_gphotoCommentingEnabled != null) { - $element->appendChild($this->_gphotoCommentingEnabled->getDOM($element->ownerDocument)); - } - if ($this->_gphotoCommentCount != null) { - $element->appendChild($this->_gphotoCommentCount->getDOM($element->ownerDocument)); - } - if ($this->_mediaGroup != null) { - $element->appendChild($this->_mediaGroup->getDOM($element->ownerDocument)); - } - - return $element; - } - - protected function takeChildFromDOM($child) - { - $absoluteNodeName = $child->namespaceURI . ':' . $child->localName; - - switch ($absoluteNodeName) { - case $this->lookupNamespace('gphoto') . ':' . 'id'; - $id = new Zend_Gdata_Photos_Extension_Id(); - $id->transferFromDOM($child); - $this->_gphotoId = $id; - break; - case $this->lookupNamespace('gphoto') . ':' . 'version'; - $version = new Zend_Gdata_Photos_Extension_Version(); - $version->transferFromDOM($child); - $this->_gphotoVersion = $version; - break; - case $this->lookupNamespace('gphoto') . ':' . 'albumid'; - $albumid = new Zend_Gdata_Photos_Extension_AlbumId(); - $albumid->transferFromDOM($child); - $this->_gphotoAlbumId = $albumid; - break; - case $this->lookupNamespace('gphoto') . ':' . 'width'; - $width = new Zend_Gdata_Photos_Extension_Width(); - $width->transferFromDOM($child); - $this->_gphotoWidth = $width; - break; - case $this->lookupNamespace('gphoto') . ':' . 'height'; - $height = new Zend_Gdata_Photos_Extension_Height(); - $height->transferFromDOM($child); - $this->_gphotoHeight = $height; - break; - case $this->lookupNamespace('gphoto') . ':' . 'size'; - $size = new Zend_Gdata_Photos_Extension_Size(); - $size->transferFromDOM($child); - $this->_gphotoSize = $size; - break; - case $this->lookupNamespace('gphoto') . ':' . 'client'; - $client = new Zend_Gdata_Photos_Extension_Client(); - $client->transferFromDOM($child); - $this->_gphotoClient = $client; - break; - case $this->lookupNamespace('gphoto') . ':' . 'checksum'; - $checksum = new Zend_Gdata_Photos_Extension_Checksum(); - $checksum->transferFromDOM($child); - $this->_gphotoChecksum = $checksum; - break; - case $this->lookupNamespace('gphoto') . ':' . 'timestamp'; - $timestamp = new Zend_Gdata_Photos_Extension_Timestamp(); - $timestamp->transferFromDOM($child); - $this->_gphotoTimestamp = $timestamp; - break; - case $this->lookupNamespace('gphoto') . ':' . 'commentingEnabled'; - $commentingEnabled = new Zend_Gdata_Photos_Extension_CommentingEnabled(); - $commentingEnabled->transferFromDOM($child); - $this->_gphotoCommentingEnabled = $commentingEnabled; - break; - case $this->lookupNamespace('gphoto') . ':' . 'commentCount'; - $commentCount = new Zend_Gdata_Photos_Extension_CommentCount(); - $commentCount->transferFromDOM($child); - $this->_gphotoCommentCount = $commentCount; - break; - case $this->lookupNamespace('media') . ':' . 'group'; - $mediaGroup = new Zend_Gdata_Media_Extension_MediaGroup(); - $mediaGroup->transferFromDOM($child); - $this->_mediaGroup = $mediaGroup; - break; - case $this->lookupNamespace('atom') . ':' . 'entry': - $entryClassName = $this->_entryClassName; - $tmpEntry = new Zend_Gdata_App_Entry($child); - $categories = $tmpEntry->getCategory(); - foreach ($categories as $category) { - if ($category->scheme == Zend_Gdata_Photos::KIND_PATH && - $this->_entryKindClassMapping[$category->term] != "") { - $entryClassName = $this->_entryKindClassMapping[$category->term]; - break; - } else { - #require_once 'Zend/Gdata/App/Exception.php'; - throw new Zend_Gdata_App_Exception('Entry is missing kind declaration.'); - } - } - - $newEntry = new $entryClassName($child); - $newEntry->setHttpClient($this->getHttpClient()); - $this->_entry[] = $newEntry; - break; - default: - parent::takeChildFromDOM($child); - break; - } - } - - /** - * Get the value for this element's gphoto:id attribute. - * - * @see setGphotoId - * @return string The requested attribute. - */ - public function getGphotoId() - { - return $this->_gphotoId; - } - - /** - * Set the value for this element's gphoto:id attribute. - * - * @param string $value The desired value for this attribute. - * @return Zend_Gdata_Photos_Extension_Id The element being modified. - */ - public function setGphotoId($value) - { - $this->_gphotoId = $value; - return $this; - } - - /** - * Get the value for this element's gphoto:version attribute. - * - * @see setGphotoVersion - * @return string The requested attribute. - */ - public function getGphotoVersion() - { - return $this->_gphotoVersion; - } - - /** - * Set the value for this element's gphoto:version attribute. - * - * @param string $value The desired value for this attribute. - * @return Zend_Gdata_Photos_Extension_Version The element being modified. - */ - public function setGphotoVersion($value) - { - $this->_gphotoVersion = $value; - return $this; - } - - /** - * Get the value for this element's gphoto:albumid attribute. - * - * @see setGphotoAlbumId - * @return string The requested attribute. - */ - public function getGphotoAlbumId() - { - return $this->_gphotoAlbumId; - } - - /** - * Set the value for this element's gphoto:albumid attribute. - * - * @param string $value The desired value for this attribute. - * @return Zend_Gdata_Photos_Extension_AlbumId The element being modified. - */ - public function setGphotoAlbumId($value) - { - $this->_gphotoAlbumId = $value; - return $this; - } - - /** - * Get the value for this element's gphoto:width attribute. - * - * @see setGphotoWidth - * @return string The requested attribute. - */ - public function getGphotoWidth() - { - return $this->_gphotoWidth; - } - - /** - * Set the value for this element's gphoto:width attribute. - * - * @param string $value The desired value for this attribute. - * @return Zend_Gdata_Photos_Extension_Width The element being modified. - */ - public function setGphotoWidth($value) - { - $this->_gphotoWidth = $value; - return $this; - } - - /** - * Get the value for this element's gphoto:height attribute. - * - * @see setGphotoHeight - * @return string The requested attribute. - */ - public function getGphotoHeight() - { - return $this->_gphotoHeight; - } - - /** - * Set the value for this element's gphoto:height attribute. - * - * @param string $value The desired value for this attribute. - * @return Zend_Gdata_Photos_Extension_Height The element being modified. - */ - public function setGphotoHeight($value) - { - $this->_gphotoHeight = $value; - return $this; - } - - /** - * Get the value for this element's gphoto:size attribute. - * - * @see setGphotoSize - * @return string The requested attribute. - */ - public function getGphotoSize() - { - return $this->_gphotoSize; - } - - /** - * Set the value for this element's gphoto:size attribute. - * - * @param string $value The desired value for this attribute. - * @return Zend_Gdata_Photos_Extension_Size The element being modified. - */ - public function setGphotoSize($value) - { - $this->_gphotoSize = $value; - return $this; - } - - /** - * Get the value for this element's gphoto:client attribute. - * - * @see setGphotoClient - * @return string The requested attribute. - */ - public function getGphotoClient() - { - return $this->_gphotoClient; - } - - /** - * Set the value for this element's gphoto:client attribute. - * - * @param string $value The desired value for this attribute. - * @return Zend_Gdata_Photos_Extension_Client The element being modified. - */ - public function setGphotoClient($value) - { - $this->_gphotoClient = $value; - return $this; - } - - /** - * Get the value for this element's gphoto:checksum attribute. - * - * @see setGphotoChecksum - * @return string The requested attribute. - */ - public function getGphotoChecksum() - { - return $this->_gphotoChecksum; - } - - /** - * Set the value for this element's gphoto:checksum attribute. - * - * @param string $value The desired value for this attribute. - * @return Zend_Gdata_Photos_Extension_Checksum The element being modified. - */ - public function setGphotoChecksum($value) - { - $this->_gphotoChecksum = $value; - return $this; - } - - /** - * Get the value for this element's gphoto:timestamp attribute. - * - * @see setGphotoTimestamp - * @return string The requested attribute. - */ - public function getGphotoTimestamp() - { - return $this->_gphotoTimestamp; - } - - /** - * Set the value for this element's gphoto:timestamp attribute. - * - * @param string $value The desired value for this attribute. - * @return Zend_Gdata_Photos_Extension_Timestamp The element being modified. - */ - public function setGphotoTimestamp($value) - { - $this->_gphotoTimestamp = $value; - return $this; - } - - /** - * Get the value for this element's gphoto:commentCount attribute. - * - * @see setGphotoCommentCount - * @return string The requested attribute. - */ - public function getGphotoCommentCount() - { - return $this->_gphotoCommentCount; - } - - /** - * Set the value for this element's gphoto:commentCount attribute. - * - * @param string $value The desired value for this attribute. - * @return Zend_Gdata_Photos_Extension_CommentCount The element being modified. - */ - public function setGphotoCommentCount($value) - { - $this->_gphotoCommentCount = $value; - return $this; - } - - /** - * Get the value for this element's gphoto:commentingEnabled attribute. - * - * @see setGphotoCommentingEnabled - * @return string The requested attribute. - */ - public function getGphotoCommentingEnabled() - { - return $this->_gphotoCommentingEnabled; - } - - /** - * Set the value for this element's gphoto:commentingEnabled attribute. - * - * @param string $value The desired value for this attribute. - * @return Zend_Gdata_Photos_Extension_CommentingEnabled The element being modified. - */ - public function setGphotoCommentingEnabled($value) - { - $this->_gphotoCommentingEnabled = $value; - return $this; - } - - /** - * Get the value for this element's media:group attribute. - * - * @see setMediaGroup - * @return string The requested attribute. - */ - public function getMediaGroup() - { - return $this->_mediaGroup; - } - - /** - * Set the value for this element's media:group attribute. - * - * @param string $value The desired value for this attribute. - * @return Zend_Gdata_Media_Extension_MediaGroup The element being modified. - */ - public function setMediaGroup($value) - { - $this->_mediaGroup = $value; - return $this; - } - -} diff --git a/library/Zend/Gdata/Photos/PhotoQuery.php b/library/Zend/Gdata/Photos/PhotoQuery.php deleted file mode 100755 index 0d6b410eb6..0000000000 --- a/library/Zend/Gdata/Photos/PhotoQuery.php +++ /dev/null @@ -1,98 +0,0 @@ -_photoId = $value; - } - - /** - * Get the photo ID which is to be returned. - * - * @see setPhoto - * @return string The ID of the photo to retrieve. - */ - public function getPhotoId() - { - return $this->_photoId; - } - - /** - * Returns the URL generated for this query, based on it's current - * parameters. - * - * @return string A URL generated based on the state of this query. - * @throws Zend_Gdata_App_InvalidArgumentException - */ - public function getQueryUrl($incomingUri = '') - { - $uri = ''; - if ($this->getPhotoId() !== null) { - $uri .= '/photoid/' . $this->getPhotoId(); - } else { - #require_once 'Zend/Gdata/App/InvalidArgumentException.php'; - throw new Zend_Gdata_App_InvalidArgumentException( - 'PhotoId cannot be null'); - } - $uri .= $incomingUri; - return parent::getQueryUrl($uri); - } - -} diff --git a/library/Zend/Gdata/Photos/TagEntry.php b/library/Zend/Gdata/Photos/TagEntry.php deleted file mode 100755 index 7707a28ebc..0000000000 --- a/library/Zend/Gdata/Photos/TagEntry.php +++ /dev/null @@ -1,140 +0,0 @@ - in the Google Data protocol. - * - * @category Zend - * @package Zend_Gdata - * @subpackage Photos - * @copyright Copyright (c) 2005-2015 Zend Technologies USA Inc. (http://www.zend.com) - * @license http://framework.zend.com/license/new-bsd New BSD License - */ -class Zend_Gdata_Photos_TagEntry extends Zend_Gdata_Entry -{ - - protected $_entryClassName = 'Zend_Gdata_Photos_TagEntry'; - - protected $_gphotoWeight = null; - - /** - * Create a new instance. - * - * @param DOMElement $element (optional) DOMElement from which this - * object should be constructed. - */ - public function __construct($element = null) - { - $this->registerAllNamespaces(Zend_Gdata_Photos::$namespaces); - parent::__construct($element); - - $category = new Zend_Gdata_App_Extension_Category( - 'http://schemas.google.com/photos/2007#tag', - 'http://schemas.google.com/g/2005#kind'); - $this->setCategory(array($category)); - } - - /** - * Retrieves a DOMElement which corresponds to this element and all - * child properties. This is used to build an entry back into a DOM - * and eventually XML text for application storage/persistence. - * - * @param DOMDocument $doc The DOMDocument used to construct DOMElements - * @return DOMElement The DOMElement representing this element and all - * child properties. - */ - public function getDOM($doc = null, $majorVersion = 1, $minorVersion = null) - { - $element = parent::getDOM($doc, $majorVersion, $minorVersion); - if ($this->_gphotoWeight !== null) { - $element->appendChild($this->_gphotoWeight->getDOM($element->ownerDocument)); - } - return $element; - } - - /** - * Creates individual Entry objects of the appropriate type and - * stores them as members of this entry based upon DOM data. - * - * @param DOMNode $child The DOMNode to process - */ - protected function takeChildFromDOM($child) - { - $absoluteNodeName = $child->namespaceURI . ':' . $child->localName; - - switch ($absoluteNodeName) { - case $this->lookupNamespace('gphoto') . ':' . 'weight'; - $weight = new Zend_Gdata_Photos_Extension_Weight(); - $weight->transferFromDOM($child); - $this->_gphotoWeight = $weight; - break; - default: - parent::takeChildFromDOM($child); - break; - } - } - - /** - * Get the value for this element's gphoto:weight attribute. - * - * @see setGphotoWeight - * @return string The requested attribute. - */ - public function getGphotoWeight() - { - return $this->_gphotoWeight; - } - - /** - * Set the value for this element's gphoto:weight attribute. - * - * @param string $value The desired value for this attribute. - * @return Zend_Gdata_Photos_Extension_Weight The element being modified. - */ - public function setGphotoWeight($value) - { - $this->_gphotoWeight = $value; - return $this; - } -} diff --git a/library/Zend/Gdata/Photos/UserEntry.php b/library/Zend/Gdata/Photos/UserEntry.php deleted file mode 100755 index 1babe6bb3f..0000000000 --- a/library/Zend/Gdata/Photos/UserEntry.php +++ /dev/null @@ -1,366 +0,0 @@ - in the Google Data protocol. - * - * @category Zend - * @package Zend_Gdata - * @subpackage Photos - * @copyright Copyright (c) 2005-2015 Zend Technologies USA Inc. (http://www.zend.com) - * @license http://framework.zend.com/license/new-bsd New BSD License - */ -class Zend_Gdata_Photos_UserEntry extends Zend_Gdata_Entry -{ - - protected $_entryClassName = 'Zend_Gdata_Photos_UserEntry'; - - /** - * gphoto:nickname element - * - * @var Zend_Gdata_Photos_Extension_Nickname - */ - protected $_gphotoNickname = null; - - /** - * gphoto:user element - * - * @var Zend_Gdata_Photos_Extension_User - */ - protected $_gphotoUser = null; - - /** - * gphoto:thumbnail element - * - * @var Zend_Gdata_Photos_Extension_Thumbnail - */ - protected $_gphotoThumbnail = null; - - /** - * gphoto:quotalimit element - * - * @var Zend_Gdata_Photos_Extension_QuotaLimit - */ - protected $_gphotoQuotaLimit = null; - - /** - * gphoto:quotacurrent element - * - * @var Zend_Gdata_Photos_Extension_QuotaCurrent - */ - protected $_gphotoQuotaCurrent = null; - - /** - * gphoto:maxPhotosPerAlbum element - * - * @var Zend_Gdata_Photos_Extension_MaxPhotosPerAlbum - */ - protected $_gphotoMaxPhotosPerAlbum = null; - - /** - * Create a new instance. - * - * @param DOMElement $element (optional) DOMElement from which this - * object should be constructed. - */ - public function __construct($element = null) - { - $this->registerAllNamespaces(Zend_Gdata_Photos::$namespaces); - parent::__construct($element); - - $category = new Zend_Gdata_App_Extension_Category( - 'http://schemas.google.com/photos/2007#user', - 'http://schemas.google.com/g/2005#kind'); - $this->setCategory(array($category)); - } - - /** - * Retrieves a DOMElement which corresponds to this element and all - * child properties. This is used to build an entry back into a DOM - * and eventually XML text for application storage/persistence. - * - * @param DOMDocument $doc The DOMDocument used to construct DOMElements - * @return DOMElement The DOMElement representing this element and all - * child properties. - */ - public function getDOM($doc = null, $majorVersion = 1, $minorVersion = null) - { - $element = parent::getDOM($doc, $majorVersion, $minorVersion); - if ($this->_gphotoNickname !== null) { - $element->appendChild($this->_gphotoNickname->getDOM($element->ownerDocument)); - } - if ($this->_gphotoThumbnail !== null) { - $element->appendChild($this->_gphotoThumbnail->getDOM($element->ownerDocument)); - } - if ($this->_gphotoUser !== null) { - $element->appendChild($this->_gphotoUser->getDOM($element->ownerDocument)); - } - if ($this->_gphotoQuotaCurrent !== null) { - $element->appendChild($this->_gphotoQuotaCurrent->getDOM($element->ownerDocument)); - } - if ($this->_gphotoQuotaLimit !== null) { - $element->appendChild($this->_gphotoQuotaLimit->getDOM($element->ownerDocument)); - } - if ($this->_gphotoMaxPhotosPerAlbum !== null) { - $element->appendChild($this->_gphotoMaxPhotosPerAlbum->getDOM($element->ownerDocument)); - } - return $element; - } - - /** - * Creates individual Entry objects of the appropriate type and - * stores them as members of this entry based upon DOM data. - * - * @param DOMNode $child The DOMNode to process - */ - protected function takeChildFromDOM($child) - { - $absoluteNodeName = $child->namespaceURI . ':' . $child->localName; - - switch ($absoluteNodeName) { - case $this->lookupNamespace('gphoto') . ':' . 'nickname'; - $nickname = new Zend_Gdata_Photos_Extension_Nickname(); - $nickname->transferFromDOM($child); - $this->_gphotoNickname = $nickname; - break; - case $this->lookupNamespace('gphoto') . ':' . 'thumbnail'; - $thumbnail = new Zend_Gdata_Photos_Extension_Thumbnail(); - $thumbnail->transferFromDOM($child); - $this->_gphotoThumbnail = $thumbnail; - break; - case $this->lookupNamespace('gphoto') . ':' . 'user'; - $user = new Zend_Gdata_Photos_Extension_User(); - $user->transferFromDOM($child); - $this->_gphotoUser = $user; - break; - case $this->lookupNamespace('gphoto') . ':' . 'quotacurrent'; - $quotaCurrent = new Zend_Gdata_Photos_Extension_QuotaCurrent(); - $quotaCurrent->transferFromDOM($child); - $this->_gphotoQuotaCurrent = $quotaCurrent; - break; - case $this->lookupNamespace('gphoto') . ':' . 'quotalimit'; - $quotaLimit = new Zend_Gdata_Photos_Extension_QuotaLimit(); - $quotaLimit->transferFromDOM($child); - $this->_gphotoQuotaLimit = $quotaLimit; - break; - case $this->lookupNamespace('gphoto') . ':' . 'maxPhotosPerAlbum'; - $maxPhotosPerAlbum = new Zend_Gdata_Photos_Extension_MaxPhotosPerAlbum(); - $maxPhotosPerAlbum->transferFromDOM($child); - $this->_gphotoMaxPhotosPerAlbum = $maxPhotosPerAlbum; - break; - default: - parent::takeChildFromDOM($child); - break; - } - } - - /** - * Get the value for this element's gphoto:nickname attribute. - * - * @see setGphotoNickname - * @return string The requested attribute. - */ - public function getGphotoNickname() - { - return $this->_gphotoNickname; - } - - /** - * Set the value for this element's gphoto:nickname attribute. - * - * @param string $value The desired value for this attribute. - * @return Zend_Gdata_Photos_Extension_Nickname The element being modified. - */ - public function setGphotoNickname($value) - { - $this->_gphotoNickname = $value; - return $this; - } - - /** - * Get the value for this element's gphoto:thumbnail attribute. - * - * @see setGphotoThumbnail - * @return string The requested attribute. - */ - public function getGphotoThumbnail() - { - return $this->_gphotoThumbnail; - } - - /** - * Set the value for this element's gphoto:thumbnail attribute. - * - * @param string $value The desired value for this attribute. - * @return Zend_Gdata_Photos_Extension_Thumbnail The element being modified. - */ - public function setGphotoThumbnail($value) - { - $this->_gphotoThumbnail = $value; - return $this; - } - - /** - * Get the value for this element's gphoto:quotacurrent attribute. - * - * @see setGphotoQuotaCurrent - * @return string The requested attribute. - */ - public function getGphotoQuotaCurrent() - { - return $this->_gphotoQuotaCurrent; - } - - /** - * Set the value for this element's gphoto:quotacurrent attribute. - * - * @param string $value The desired value for this attribute. - * @return Zend_Gdata_Photos_Extension_QuotaCurrent The element being modified. - */ - public function setGphotoQuotaCurrent($value) - { - $this->_gphotoQuotaCurrent = $value; - return $this; - } - - /** - * Get the value for this element's gphoto:quotalimit attribute. - * - * @see setGphotoQuotaLimit - * @return string The requested attribute. - */ - public function getGphotoQuotaLimit() - { - return $this->_gphotoQuotaLimit; - } - - /** - * Set the value for this element's gphoto:quotalimit attribute. - * - * @param string $value The desired value for this attribute. - * @return Zend_Gdata_Photos_Extension_QuotaLimit The element being modified. - */ - public function setGphotoQuotaLimit($value) - { - $this->_gphotoQuotaLimit = $value; - return $this; - } - - /** - * Get the value for this element's gphoto:maxPhotosPerAlbum attribute. - * - * @see setGphotoMaxPhotosPerAlbum - * @return string The requested attribute. - */ - public function getGphotoMaxPhotosPerAlbum() - { - return $this->_gphotoMaxPhotosPerAlbum; - } - - /** - * Set the value for this element's gphoto:maxPhotosPerAlbum attribute. - * - * @param string $value The desired value for this attribute. - * @return Zend_Gdata_Photos_Extension_MaxPhotosPerAlbum The element being modified. - */ - public function setGphotoMaxPhotosPerAlbum($value) - { - $this->_gphotoMaxPhotosPerAlbum = $value; - return $this; - } - - /** - * Get the value for this element's gphoto:user attribute. - * - * @see setGphotoUser - * @return string The requested attribute. - */ - public function getGphotoUser() - { - return $this->_gphotoUser; - } - - /** - * Set the value for this element's gphoto:user attribute. - * - * @param string $value The desired value for this attribute. - * @return Zend_Gdata_Photos_Extension_User The element being modified. - */ - public function setGphotoUser($value) - { - $this->_gphotoUser = $value; - return $this; - } - -} diff --git a/library/Zend/Gdata/Photos/UserFeed.php b/library/Zend/Gdata/Photos/UserFeed.php deleted file mode 100755 index 9b8366e7b0..0000000000 --- a/library/Zend/Gdata/Photos/UserFeed.php +++ /dev/null @@ -1,247 +0,0 @@ - 'Zend_Gdata_Photos_AlbumEntry', - 'http://schemas.google.com/photos/2007#photo' => 'Zend_Gdata_Photos_PhotoEntry', - 'http://schemas.google.com/photos/2007#comment' => 'Zend_Gdata_Photos_CommentEntry', - 'http://schemas.google.com/photos/2007#tag' => 'Zend_Gdata_Photos_TagEntry' - ); - - public function __construct($element = null) - { - $this->registerAllNamespaces(Zend_Gdata_Photos::$namespaces); - parent::__construct($element); - } - - /** - * Creates individual Entry objects of the appropriate type and - * stores them in the $_entry array based upon DOM data. - * - * @param DOMNode $child The DOMNode to process - */ - protected function takeChildFromDOM($child) - { - $absoluteNodeName = $child->namespaceURI . ':' . $child->localName; - switch ($absoluteNodeName) { - case $this->lookupNamespace('gphoto') . ':' . 'user'; - $user = new Zend_Gdata_Photos_Extension_User(); - $user->transferFromDOM($child); - $this->_gphotoUser = $user; - break; - case $this->lookupNamespace('gphoto') . ':' . 'nickname'; - $nickname = new Zend_Gdata_Photos_Extension_Nickname(); - $nickname->transferFromDOM($child); - $this->_gphotoNickname = $nickname; - break; - case $this->lookupNamespace('gphoto') . ':' . 'thumbnail'; - $thumbnail = new Zend_Gdata_Photos_Extension_Thumbnail(); - $thumbnail->transferFromDOM($child); - $this->_gphotoThumbnail = $thumbnail; - break; - case $this->lookupNamespace('atom') . ':' . 'entry': - $entryClassName = $this->_entryClassName; - $tmpEntry = new Zend_Gdata_App_Entry($child); - $categories = $tmpEntry->getCategory(); - foreach ($categories as $category) { - if ($category->scheme == Zend_Gdata_Photos::KIND_PATH && - $this->_entryKindClassMapping[$category->term] != "") { - $entryClassName = $this->_entryKindClassMapping[$category->term]; - break; - } else { - #require_once 'Zend/Gdata/App/Exception.php'; - throw new Zend_Gdata_App_Exception('Entry is missing kind declaration.'); - } - } - - $newEntry = new $entryClassName($child); - $newEntry->setHttpClient($this->getHttpClient()); - $this->_entry[] = $newEntry; - break; - default: - parent::takeChildFromDOM($child); - break; - } - } - - public function getDOM($doc = null, $majorVersion = 1, $minorVersion = null) - { - $element = parent::getDOM($doc, $majorVersion, $minorVersion); - if ($this->_gphotoUser != null) { - $element->appendChild($this->_gphotoUser->getDOM($element->ownerDocument)); - } - if ($this->_gphotoNickname != null) { - $element->appendChild($this->_gphotoNickname->getDOM($element->ownerDocument)); - } - if ($this->_gphotoThumbnail != null) { - $element->appendChild($this->_gphotoThumbnail->getDOM($element->ownerDocument)); - } - - return $element; - } - - /** - * Get the value for this element's gphoto:user attribute. - * - * @see setGphotoUser - * @return string The requested attribute. - */ - public function getGphotoUser() - { - return $this->_gphotoUser; - } - - /** - * Set the value for this element's gphoto:user attribute. - * - * @param string $value The desired value for this attribute. - * @return Zend_Gdata_Photos_Extension_User The element being modified. - */ - public function setGphotoUser($value) - { - $this->_gphotoUser = $value; - return $this; - } - - /** - * Get the value for this element's gphoto:nickname attribute. - * - * @see setGphotoNickname - * @return string The requested attribute. - */ - public function getGphotoNickname() - { - return $this->_gphotoNickname; - } - - /** - * Set the value for this element's gphoto:nickname attribute. - * - * @param string $value The desired value for this attribute. - * @return Zend_Gdata_Photos_Extension_Nickname The element being modified. - */ - public function setGphotoNickname($value) - { - $this->_gphotoNickname = $value; - return $this; - } - - /** - * Get the value for this element's gphoto:thumbnail attribute. - * - * @see setGphotoThumbnail - * @return string The requested attribute. - */ - public function getGphotoThumbnail() - { - return $this->_gphotoThumbnail; - } - - /** - * Set the value for this element's gphoto:thumbnail attribute. - * - * @param string $value The desired value for this attribute. - * @return Zend_Gdata_Photos_Extension_Thumbnail The element being modified. - */ - public function setGphotoThumbnail($value) - { - $this->_gphotoThumbnail = $value; - return $this; - } - -} diff --git a/library/Zend/Gdata/Photos/UserQuery.php b/library/Zend/Gdata/Photos/UserQuery.php deleted file mode 100755 index cce939c4c7..0000000000 --- a/library/Zend/Gdata/Photos/UserQuery.php +++ /dev/null @@ -1,355 +0,0 @@ -_projection = $value; - return $this; - } - - /** - * Gets the format of data in returned in Atom feeds. - * - * @see setProjection - * @return string projection - */ - public function getProjection() - { - return $this->_projection; - } - - /** - * Set's the type of data returned in queries. Can be either - * 'feed' or 'entry'. Normally, 'feed' will be desired. Default is 'feed'. - * - * @param string $value - * @return Zend_Gdata_Photos_UserQuery Provides a fluent interface - */ - public function setType($value) - { - $this->_type = $value; - return $this; - } - - /** - * Gets the type of data in returned in queries. - * - * @see setType - * @return string type - */ - public function getType() - { - return $this->_type; - } - - /** - * Set the user to query for. When set, this user's feed will be - * returned. If not set or null, the default user's feed will be returned - * instead. - * - * @param string $value The user to retrieve, or null for the default - * user. - */ - public function setUser($value) - { - if ($value !== null) { - $this->_user = $value; - } else { - $this->_user = Zend_Gdata_Photos::DEFAULT_USER; - } - } - - /** - * Get the user which is to be returned. - * - * @see setUser - * @return string The visibility to retrieve. - */ - public function getUser() - { - return $this->_user; - } - - /** - * Set the visibility filter for entries returned. Only entries which - * match this value will be returned. If null or unset, the default - * value will be used instead. - * - * Valid values are 'all' (default), 'public', and 'private'. - * - * @param string $value The visibility to filter by, or null to use the - * default value. - */ - public function setAccess($value) - { - if ($value !== null) { - $this->_params['access'] = $value; - } else { - unset($this->_params['access']); - } - } - - /** - * Get the visibility filter for entries returned. - * - * @see setAccess - * @return string The visibility to filter by, or null for the default - * user. - */ - public function getAccess() - { - return $this->_params['access']; - } - - /** - * Set the tag for entries that are returned. Only entries which - * match this value will be returned. If null or unset, this filter will - * not be applied. - * - * See http://code.google.com/apis/picasaweb/reference.html#Parameters - * for a list of valid values. - * - * @param string $value The tag to filter by, or null if no - * filter is to be applied. - */ - public function setTag($value) - { - if ($value !== null) { - $this->_params['tag'] = $value; - } else { - unset($this->_params['tag']); - } - } - - /** - * Get the tag filter for entries returned. - * - * @see setTag - * @return string The tag to filter by, or null if no filter - * is to be applied. - */ - public function getTag() - { - return $this->_params['tag']; - } - - /** - * Set the kind of entries that are returned. Only entries which - * match this value will be returned. If null or unset, this filter will - * not be applied. - * - * See http://code.google.com/apis/picasaweb/reference.html#Parameters - * for a list of valid values. - * - * @param string $value The kind to filter by, or null if no - * filter is to be applied. - */ - public function setKind($value) - { - if ($value !== null) { - $this->_params['kind'] = $value; - } else { - unset($this->_params['kind']); - } - } - - /** - * Get the kind of entries to be returned. - * - * @see setKind - * @return string The kind to filter by, or null if no filter - * is to be applied. - */ - public function getKind() - { - return $this->_params['kind']; - } - - /** - * Set the maximum image size for entries returned. Only entries which - * match this value will be returned. If null or unset, this filter will - * not be applied. - * - * See http://code.google.com/apis/picasaweb/reference.html#Parameters - * for a list of valid values. - * - * @param string $value The image size to filter by, or null if no - * filter is to be applied. - */ - public function setImgMax($value) - { - if ($value !== null) { - $this->_params['imgmax'] = $value; - } else { - unset($this->_params['imgmax']); - } - } - - /** - * Get the maximum image size filter for entries returned. - * - * @see setImgMax - * @return string The image size size to filter by, or null if no filter - * is to be applied. - */ - public function getImgMax() - { - return $this->_params['imgmax']; - } - - /** - * Set the thumbnail size filter for entries returned. Only entries which - * match this value will be returned. If null or unset, this filter will - * not be applied. - * - * See http://code.google.com/apis/picasaweb/reference.html#Parameters - * for a list of valid values. - * - * @param string $value The thumbnail size to filter by, or null if no - * filter is to be applied. - */ - public function setThumbsize($value) - { - if ($value !== null) { - $this->_params['thumbsize'] = $value; - } else { - unset($this->_params['thumbsize']); - } - } - - /** - * Get the thumbnail size filter for entries returned. - * - * @see setThumbsize - * @return string The thumbnail size to filter by, or null if no filter - * is to be applied. - */ - public function getThumbsize() - { - return $this->_params['thumbsize']; - } - - /** - * Returns the URL generated for this query, based on it's current - * parameters. - * - * @return string A URL generated based on the state of this query. - * @throws Zend_Gdata_App_InvalidArgumentException - */ - public function getQueryUrl($incomingUri = null) - { - $uri = Zend_Gdata_Photos::PICASA_BASE_URI; - - if ($this->getType() !== null) { - $uri .= '/' . $this->getType(); - } else { - #require_once 'Zend/Gdata/App/InvalidArgumentException.php'; - throw new Zend_Gdata_App_InvalidArgumentException( - 'Type must be feed or entry, not null'); - } - - if ($this->getProjection() !== null) { - $uri .= '/' . $this->getProjection(); - } else { - #require_once 'Zend/Gdata/App/InvalidArgumentException.php'; - throw new Zend_Gdata_App_InvalidArgumentException( - 'Projection must not be null'); - } - - if ($this->getUser() !== null) { - $uri .= '/user/' . $this->getUser(); - } else { - // Should never occur due to setter behavior - #require_once 'Zend/Gdata/App/InvalidArgumentException.php'; - throw new Zend_Gdata_App_InvalidArgumentException( - 'User must not be null'); - } - - $uri .= $incomingUri; - $uri .= $this->getQueryString(); - return $uri; - } - -} diff --git a/library/Zend/Gdata/Query.php b/library/Zend/Gdata/Query.php deleted file mode 100644 index b6005189d2..0000000000 --- a/library/Zend/Gdata/Query.php +++ /dev/null @@ -1,418 +0,0 @@ -_url = $url; - } - - /** - * @return string querystring - */ - public function getQueryString() - { - $queryArray = array(); - foreach ($this->_params as $name => $value) { - if (substr($name, 0, 1) == '_') { - continue; - } - $queryArray[] = urlencode($name) . '=' . urlencode($value); - } - if (count($queryArray) > 0) { - return '?' . implode('&', $queryArray); - } else { - return ''; - } - } - - /** - * - */ - public function resetParameters() - { - $this->_params = array(); - } - - /** - * @return string url - */ - public function getQueryUrl() - { - if ($this->_url == null) { - $url = $this->_defaultFeedUri; - } else { - $url = $this->_url; - } - if ($this->getCategory() !== null) { - $url .= '/-/' . $this->getCategory(); - } - $url .= $this->getQueryString(); - return $url; - } - - /** - * @param string $name - * @param string $value - * @return Zend_Gdata_Query Provides a fluent interface - */ - public function setParam($name, $value) - { - $this->_params[$name] = $value; - return $this; - } - - /** - * @param string $name - */ - public function getParam($name) - { - return $this->_params[$name]; - } - - /** - * @param string $value - * @return Zend_Gdata_Query Provides a fluent interface - */ - public function setAlt($value) - { - if ($value != null) { - $this->_params['alt'] = $value; - } else { - unset($this->_params['alt']); - } - return $this; - } - - /** - * @param int $value - * @return Zend_Gdata_Query Provides a fluent interface - */ - public function setMaxResults($value) - { - if ($value != null) { - $this->_params['max-results'] = $value; - } else { - unset($this->_params['max-results']); - } - return $this; - } - - /** - * @param string $value - * @return Zend_Gdata_Query Provides a fluent interface - */ - public function setQuery($value) - { - if ($value != null) { - $this->_params['q'] = $value; - } else { - unset($this->_params['q']); - } - return $this; - } - - /** - * @param int $value - * @return Zend_Gdata_Query Provides a fluent interface - */ - public function setStartIndex($value) - { - if ($value != null) { - $this->_params['start-index'] = $value; - } else { - unset($this->_params['start-index']); - } - return $this; - } - - /** - * @param string $value - * @return Zend_Gdata_Query Provides a fluent interface - */ - public function setUpdatedMax($value) - { - if ($value != null) { - $this->_params['updated-max'] = Zend_Gdata_App_Util::formatTimestamp($value); - } else { - unset($this->_params['updated-max']); - } - return $this; - } - - /** - * @param string $value - * @return Zend_Gdata_Query Provides a fluent interface - */ - public function setUpdatedMin($value) - { - if ($value != null) { - $this->_params['updated-min'] = Zend_Gdata_App_Util::formatTimestamp($value); - } else { - unset($this->_params['updated-min']); - } - return $this; - } - - /** - * @param string $value - * @return Zend_Gdata_Query Provides a fluent interface - */ - public function setPublishedMax($value) - { - if ($value !== null) { - $this->_params['published-max'] = Zend_Gdata_App_Util::formatTimestamp($value); - } else { - unset($this->_params['published-max']); - } - return $this; - } - - /** - * @param string $value - * @return Zend_Gdata_Query Provides a fluent interface - */ - public function setPublishedMin($value) - { - if ($value != null) { - $this->_params['published-min'] = Zend_Gdata_App_Util::formatTimestamp($value); - } else { - unset($this->_params['published-min']); - } - return $this; - } - - /** - * @param string $value - * @return Zend_Gdata_Query Provides a fluent interface - */ - public function setAuthor($value) - { - if ($value != null) { - $this->_params['author'] = $value; - } else { - unset($this->_params['author']); - } - return $this; - } - - /** - * @return string rss or atom - */ - public function getAlt() - { - if (array_key_exists('alt', $this->_params)) { - return $this->_params['alt']; - } else { - return null; - } - } - - /** - * @return int maxResults - */ - public function getMaxResults() - { - if (array_key_exists('max-results', $this->_params)) { - return intval($this->_params['max-results']); - } else { - return null; - } - } - - /** - * @return string query - */ - public function getQuery() - { - if (array_key_exists('q', $this->_params)) { - return $this->_params['q']; - } else { - return null; - } - } - - /** - * @return int startIndex - */ - public function getStartIndex() - { - if (array_key_exists('start-index', $this->_params)) { - return intval($this->_params['start-index']); - } else { - return null; - } - } - - /** - * @return string updatedMax - */ - public function getUpdatedMax() - { - if (array_key_exists('updated-max', $this->_params)) { - return $this->_params['updated-max']; - } else { - return null; - } - } - - /** - * @return string updatedMin - */ - public function getUpdatedMin() - { - if (array_key_exists('updated-min', $this->_params)) { - return $this->_params['updated-min']; - } else { - return null; - } - } - - /** - * @return string publishedMax - */ - public function getPublishedMax() - { - if (array_key_exists('published-max', $this->_params)) { - return $this->_params['published-max']; - } else { - return null; - } - } - - /** - * @return string publishedMin - */ - public function getPublishedMin() - { - if (array_key_exists('published-min', $this->_params)) { - return $this->_params['published-min']; - } else { - return null; - } - } - - /** - * @return string author - */ - public function getAuthor() - { - if (array_key_exists('author', $this->_params)) { - return $this->_params['author']; - } else { - return null; - } - } - - /** - * @param string $value - * @return Zend_Gdata_Query Provides a fluent interface - */ - public function setCategory($value) - { - $this->_category = $value; - return $this; - } - - /* - * @return string id - */ - public function getCategory() - { - return $this->_category; - } - - - public function __get($name) - { - $method = 'get'.ucfirst($name); - if (method_exists($this, $method)) { - return call_user_func(array(&$this, $method)); - } else { - #require_once 'Zend/Gdata/App/Exception.php'; - throw new Zend_Gdata_App_Exception('Property ' . $name . ' does not exist'); - } - } - - public function __set($name, $val) - { - $method = 'set'.ucfirst($name); - if (method_exists($this, $method)) { - return call_user_func(array(&$this, $method), $val); - } else { - #require_once 'Zend/Gdata/App/Exception.php'; - throw new Zend_Gdata_App_Exception('Property ' . $name . ' does not exist'); - } - } - -} diff --git a/library/Zend/Gdata/Spreadsheets.php b/library/Zend/Gdata/Spreadsheets.php deleted file mode 100644 index c1b674597f..0000000000 --- a/library/Zend/Gdata/Spreadsheets.php +++ /dev/null @@ -1,445 +0,0 @@ -registerPackage('Zend_Gdata_Spreadsheets'); - $this->registerPackage('Zend_Gdata_Spreadsheets_Extension'); - parent::__construct($client, $applicationId); - $this->_httpClient->setParameterPost('service', self::AUTH_SERVICE_NAME); - $this->_server = 'spreadsheets.google.com'; - } - - /** - * Gets a spreadsheet feed. - * - * @param mixed $location A DocumentQuery or a string URI specifying the feed location. - * @return Zend_Gdata_Spreadsheets_SpreadsheetFeed - */ - public function getSpreadsheetFeed($location = null) - { - if ($location == null) { - $uri = self::SPREADSHEETS_FEED_URI; - } else if ($location instanceof Zend_Gdata_Spreadsheets_DocumentQuery) { - if ($location->getDocumentType() == null) { - $location->setDocumentType('spreadsheets'); - } - $uri = $location->getQueryUrl(); - } else { - $uri = $location; - } - - return parent::getFeed($uri, 'Zend_Gdata_Spreadsheets_SpreadsheetFeed'); - } - - /** - * Gets a spreadsheet entry. - * - * @param string $location A DocumentQuery or a URI specifying the entry location. - * @return SpreadsheetEntry - */ - public function getSpreadsheetEntry($location) - { - if ($location instanceof Zend_Gdata_Spreadsheets_DocumentQuery) { - if ($location->getDocumentType() == null) { - $location->setDocumentType('spreadsheets'); - } - $uri = $location->getQueryUrl(); - } else { - $uri = $location; - } - - return parent::getEntry($uri, 'Zend_Gdata_Spreadsheets_SpreadsheetEntry'); - } - - /** - * Gets a worksheet feed. - * - * @param mixed $location A DocumentQuery, SpreadsheetEntry, or a string URI - * @return Zend_Gdata_Spreadsheets_WorksheetFeed The feed of worksheets - */ - public function getWorksheetFeed($location) - { - if ($location instanceof Zend_Gdata_Spreadsheets_DocumentQuery) { - if ($location->getDocumentType() == null) { - $location->setDocumentType('worksheets'); - } - $uri = $location->getQueryUrl(); - } else if ($location instanceof Zend_Gdata_Spreadsheets_SpreadsheetEntry) { - $uri = $location->getLink(self::WORKSHEETS_FEED_LINK_URI)->href; - } else { - $uri = $location; - } - - return parent::getFeed($uri, 'Zend_Gdata_Spreadsheets_WorksheetFeed'); - } - - /** - * Gets a worksheet entry. - * - * @param string $location A DocumentQuery or a URI specifying the entry location. - * @return WorksheetEntry - */ - public function GetWorksheetEntry($location) - { - if ($location instanceof Zend_Gdata_Spreadsheets_DocumentQuery) { - if ($location->getDocumentType() == null) { - $location->setDocumentType('worksheets'); - } - $uri = $location->getQueryUrl(); - } else { - $uri = $location; - } - - return parent::getEntry($uri, 'Zend_Gdata_Spreadsheets_WorksheetEntry'); - } - - /** - * Gets a cell feed. - * - * @param string $location A CellQuery, WorksheetEntry or a URI specifying the feed location. - * @return CellFeed - */ - public function getCellFeed($location) - { - if ($location instanceof Zend_Gdata_Spreadsheets_CellQuery) { - $uri = $location->getQueryUrl(); - } else if ($location instanceof Zend_Gdata_Spreadsheets_WorksheetEntry) { - $uri = $location->getLink(self::CELL_FEED_LINK_URI)->href; - } else { - $uri = $location; - } - return parent::getFeed($uri, 'Zend_Gdata_Spreadsheets_CellFeed'); - } - - /** - * Gets a cell entry. - * - * @param string $location A CellQuery or a URI specifying the entry location. - * @return CellEntry - */ - public function getCellEntry($location) - { - if ($location instanceof Zend_Gdata_Spreadsheets_CellQuery) { - $uri = $location->getQueryUrl(); - } else { - $uri = $location; - } - - return parent::getEntry($uri, 'Zend_Gdata_Spreadsheets_CellEntry'); - } - - /** - * Gets a list feed. - * - * @param mixed $location A ListQuery, WorksheetEntry or string URI specifying the feed location. - * @return ListFeed - */ - public function getListFeed($location) - { - if ($location instanceof Zend_Gdata_Spreadsheets_ListQuery) { - $uri = $location->getQueryUrl(); - } else if ($location instanceof Zend_Gdata_Spreadsheets_WorksheetEntry) { - $uri = $location->getLink(self::LIST_FEED_LINK_URI)->href; - } else { - $uri = $location; - } - - return parent::getFeed($uri, 'Zend_Gdata_Spreadsheets_ListFeed'); - } - - /** - * Gets a list entry. - * - * @param string $location A ListQuery or a URI specifying the entry location. - * @return ListEntry - */ - public function getListEntry($location) - { - if ($location instanceof Zend_Gdata_Spreadsheets_ListQuery) { - $uri = $location->getQueryUrl(); - } else { - $uri = $location; - } - - return parent::getEntry($uri, 'Zend_Gdata_Spreadsheets_ListEntry'); - } - - /** - * Updates an existing cell. - * - * @param int $row The row containing the cell to update - * @param int $col The column containing the cell to update - * @param int $inputValue The new value for the cell - * @param string $key The key for the spreadsheet to be updated - * @param string $wkshtId (optional) The worksheet to be updated - * @return CellEntry The updated cell entry. - */ - public function updateCell($row, $col, $inputValue, $key, $wkshtId = 'default') - { - $cell = 'R'.$row.'C'.$col; - - $query = new Zend_Gdata_Spreadsheets_CellQuery(); - $query->setSpreadsheetKey($key); - $query->setWorksheetId($wkshtId); - $query->setCellId($cell); - - $entry = $this->getCellEntry($query); - $entry->setCell(new Zend_Gdata_Spreadsheets_Extension_Cell(null, $row, $col, $inputValue)); - $response = $entry->save(); - return $response; - } - - /** - * Inserts a new row with provided data. - * - * @param array $rowData An array of column header to row data - * @param string $key The key of the spreadsheet to modify - * @param string $wkshtId (optional) The worksheet to modify - * @return ListEntry The inserted row - */ - public function insertRow($rowData, $key, $wkshtId = 'default') - { - $newEntry = new Zend_Gdata_Spreadsheets_ListEntry(); - $newCustomArr = array(); - foreach ($rowData as $k => $v) { - $newCustom = new Zend_Gdata_Spreadsheets_Extension_Custom(); - $newCustom->setText($v)->setColumnName($k); - $newEntry->addCustom($newCustom); - } - - $query = new Zend_Gdata_Spreadsheets_ListQuery(); - $query->setSpreadsheetKey($key); - $query->setWorksheetId($wkshtId); - - $feed = $this->getListFeed($query); - $editLink = $feed->getLink('http://schemas.google.com/g/2005#post'); - - return $this->insertEntry($newEntry->saveXML(), $editLink->href, 'Zend_Gdata_Spreadsheets_ListEntry'); - } - - /** - * Updates an existing row with provided data. - * - * @param ListEntry $entry The row entry to update - * @param array $newRowData An array of column header to row data - */ - public function updateRow($entry, $newRowData) - { - $newCustomArr = array(); - foreach ($newRowData as $k => $v) { - $newCustom = new Zend_Gdata_Spreadsheets_Extension_Custom(); - $newCustom->setText($v)->setColumnName($k); - $newCustomArr[] = $newCustom; - } - $entry->setCustom($newCustomArr); - - return $entry->save(); - } - - /** - * Deletes an existing row . - * - * @param ListEntry $entry The row to delete - */ - public function deleteRow($entry) - { - $entry->delete(); - } - - /** - * Returns the content of all rows as an associative array - * - * @param mixed $location A ListQuery or string URI specifying the feed location. - * @return array An array of rows. Each element of the array is an associative array of data - */ - public function getSpreadsheetListFeedContents($location) - { - $listFeed = $this->getListFeed($location); - $listFeed = $this->retrieveAllEntriesForFeed($listFeed); - $spreadsheetContents = array(); - foreach ($listFeed as $listEntry) { - $rowContents = array(); - $customArray = $listEntry->getCustom(); - foreach ($customArray as $custom) { - $rowContents[$custom->getColumnName()] = $custom->getText(); - } - $spreadsheetContents[] = $rowContents; - } - return $spreadsheetContents; - } - - /** - * Returns the content of all cells as an associative array, indexed - * off the cell location (ie 'A1', 'D4', etc). Each element of - * the array is an associative array with a 'value' and a 'function'. - * Only non-empty cells are returned by default. 'range' is the - * value of the 'range' query parameter specified at: - * http://code.google.com/apis/spreadsheets/reference.html#cells_Parameters - * - * @param mixed $location A CellQuery, WorksheetEntry or a URL (w/o query string) specifying the feed location. - * @param string $range The range of cells to retrieve - * @param boolean $empty Whether to retrieve empty cells - * @return array An associative array of cells - */ - public function getSpreadsheetCellFeedContents($location, $range = null, $empty = false) - { - $cellQuery = null; - if ($location instanceof Zend_Gdata_Spreadsheets_CellQuery) { - $cellQuery = $location; - } else if ($location instanceof Zend_Gdata_Spreadsheets_WorksheetEntry) { - $url = $location->getLink(self::CELL_FEED_LINK_URI)->href; - $cellQuery = new Zend_Gdata_Spreadsheets_CellQuery($url); - } else { - $url = $location; - $cellQuery = new Zend_Gdata_Spreadsheets_CellQuery($url); - } - - if ($range != null) { - $cellQuery->setRange($range); - } - $cellQuery->setReturnEmpty($empty); - - $cellFeed = $this->getCellFeed($cellQuery); - $cellFeed = $this->retrieveAllEntriesForFeed($cellFeed); - $spreadsheetContents = array(); - foreach ($cellFeed as $cellEntry) { - $cellContents = array(); - $cell = $cellEntry->getCell(); - $cellContents['formula'] = $cell->getInputValue(); - $cellContents['value'] = $cell->getText(); - $spreadsheetContents[$cellEntry->getTitle()->getText()] = $cellContents; - } - return $spreadsheetContents; - } - - /** - * Alias for getSpreadsheetFeed - * - * @param mixed $location A DocumentQuery or a string URI specifying the feed location. - * @return Zend_Gdata_Spreadsheets_SpreadsheetFeed - */ - public function getSpreadsheets($location = null) - { - return $this->getSpreadsheetFeed($location = null); - } - -} diff --git a/library/Zend/Gdata/Spreadsheets/CellEntry.php b/library/Zend/Gdata/Spreadsheets/CellEntry.php deleted file mode 100644 index 9fde0eefae..0000000000 --- a/library/Zend/Gdata/Spreadsheets/CellEntry.php +++ /dev/null @@ -1,104 +0,0 @@ -registerAllNamespaces(Zend_Gdata_Spreadsheets::$namespaces); - parent::__construct($element); - } - - public function getDOM($doc = null, $majorVersion = 1, $minorVersion = null) - { - $element = parent::getDOM($doc, $majorVersion, $minorVersion); - if ($this->_cell != null) { - $element->appendChild($this->_cell->getDOM($element->ownerDocument)); - } - return $element; - } - - protected function takeChildFromDOM($child) - { - $absoluteNodeName = $child->namespaceURI . ':' . $child->localName; - switch ($absoluteNodeName) { - case $this->lookupNamespace('gs') . ':' . 'cell'; - $cell = new Zend_Gdata_Spreadsheets_Extension_Cell(); - $cell->transferFromDOM($child); - $this->_cell = $cell; - break; - default: - parent::takeChildFromDOM($child); - break; - } - } - - /** - * Gets the Cell element of this Cell Entry. - * @return Zend_Gdata_Spreadsheets_Extension_Cell - */ - public function getCell() - { - return $this->_cell; - } - - /** - * Sets the Cell element of this Cell Entry. - * @param Zend_Gdata_Spreadsheets_Extension_Cell $cell - * @return Zend_Gdata_Spreadsheets_CellEntry - */ - public function setCell($cell) - { - $this->_cell = $cell; - return $this; - } - -} diff --git a/library/Zend/Gdata/Spreadsheets/CellFeed.php b/library/Zend/Gdata/Spreadsheets/CellFeed.php deleted file mode 100644 index a936efcb6a..0000000000 --- a/library/Zend/Gdata/Spreadsheets/CellFeed.php +++ /dev/null @@ -1,158 +0,0 @@ -registerAllNamespaces(Zend_Gdata_Spreadsheets::$namespaces); - parent::__construct($element); - } - - public function getDOM($doc = null, $majorVersion = 1, $minorVersion = null) - { - $element = parent::getDOM($doc, $majorVersion, $minorVersion); - if ($this->rowCount != null) { - $element->appendChild($this->_rowCount->getDOM($element->ownerDocument)); - } - if ($this->colCount != null) { - $element->appendChild($this->_colCount->getDOM($element->ownerDocument)); - } - return $element; - } - - protected function takeChildFromDOM($child) - { - $absoluteNodeName = $child->namespaceURI . ':' . $child->localName; - switch ($absoluteNodeName) { - case $this->lookupNamespace('gs') . ':' . 'rowCount'; - $rowCount = new Zend_Gdata_Spreadsheets_Extension_RowCount(); - $rowCount->transferFromDOM($child); - $this->_rowCount = $rowCount; - break; - case $this->lookupNamespace('gs') . ':' . 'colCount'; - $colCount = new Zend_Gdata_Spreadsheets_Extension_ColCount(); - $colCount->transferFromDOM($child); - $this->_colCount = $colCount; - break; - default: - parent::takeChildFromDOM($child); - break; - } - } - - /** - * Gets the row count for this feed. - * @return string The row count for the feed. - */ - public function getRowCount() - { - return $this->_rowCount; - } - - /** - * Gets the column count for this feed. - * @return string The column count for the feed. - */ - public function getColumnCount() - { - return $this->_colCount; - } - - /** - * Sets the row count for this feed. - * @param string $rowCount The new row count for the feed. - */ - public function setRowCount($rowCount) - { - $this->_rowCount = $rowCount; - return $this; - } - - /** - * Sets the column count for this feed. - * @param string $colCount The new column count for the feed. - */ - public function setColumnCount($colCount) - { - $this->_colCount = $colCount; - return $this; - } - -} diff --git a/library/Zend/Gdata/Spreadsheets/CellQuery.php b/library/Zend/Gdata/Spreadsheets/CellQuery.php deleted file mode 100644 index 16bc92e179..0000000000 --- a/library/Zend/Gdata/Spreadsheets/CellQuery.php +++ /dev/null @@ -1,417 +0,0 @@ -_spreadsheetKey = $value; - return $this; - } - - /** - * Gets the spreadsheet key for this query. - * - * @return string spreadsheet key - */ - public function getSpreadsheetKey() - { - return $this->_spreadsheetKey; - } - - /** - * Sets the worksheet id for this query. - * - * @param string $value - * @return Zend_Gdata_Spreadsheets_CellQuery Provides a fluent interface - */ - public function setWorksheetId($value) - { - $this->_worksheetId = $value; - return $this; - } - - /** - * Gets the worksheet id for this query. - * - * @return string worksheet id - */ - public function getWorksheetId() - { - return $this->_worksheetId; - } - - /** - * Sets the cell id for this query. - * - * @param string $value - * @return Zend_Gdata_Spreadsheets_CellQuery Provides a fluent interface - */ - public function setCellId($value) - { - $this->_cellId = $value; - return $this; - } - - /** - * Gets the cell id for this query. - * - * @return string cell id - */ - public function getCellId() - { - return $this->_cellId; - } - - /** - * Sets the projection for this query. - * - * @param string $value - * @return Zend_Gdata_Spreadsheets_CellQuery Provides a fluent interface - */ - public function setProjection($value) - { - $this->_projection = $value; - return $this; - } - - /** - * Sets the visibility for this query. - * - * @return Zend_Gdata_Spreadsheets_CellQuery Provides a fluent interface - */ - public function setVisibility($value) - { - $this->_visibility = $value; - return $this; - } - - /** - * Gets the projection for this query. - * - * @return string projection - */ - public function getProjection() - { - return $this->_projection; - } - - /** - * Gets the visibility for this query. - * - * @return string visibility - */ - public function getVisibility() - { - return $this->_visibility; - } - - /** - * Sets the min-row attribute for this query. - * - * @param string $value - * @return Zend_Gdata_Spreadsheets_CellQuery Provides a fluent interface - */ - public function setMinRow($value) - { - if ($value != null) { - $this->_params['min-row'] = $value; - } else { - unset($this->_params['min-row']); - } - return $this; - } - - /** - * Gets the min-row attribute for this query. - * - * @return string min-row - */ - public function getMinRow() - { - if (array_key_exists('min-row', $this->_params)) { - return $this->_params['min-row']; - } else { - return null; - } - } - - /** - * Sets the max-row attribute for this query. - * - * @param string $value - * @return Zend_Gdata_Spreadsheets_CellQuery Provides a fluent interface - */ - public function setMaxRow($value) - { - if ($value != null) { - $this->_params['max-row'] = $value; - } else { - unset($this->_params['max-row']); - } - return $this; - } - - /** - * Gets the max-row attribute for this query. - * - * @return string max-row - */ - public function getMaxRow() - { - if (array_key_exists('max-row', $this->_params)) { - return $this->_params['max-row']; - } else { - return null; - } - } - - /** - * Sets the min-col attribute for this query. - * - * @param string $value - * @return Zend_Gdata_Spreadsheets_CellQuery Provides a fluent interface - */ - public function setMinCol($value) - { - if ($value != null) { - $this->_params['min-col'] = $value; - } else { - unset($this->_params['min-col']); - } - return $this; - } - - /** - * Gets the min-col attribute for this query. - * - * @return string min-col - */ - public function getMinCol() - { - if (array_key_exists('min-col', $this->_params)) { - return $this->_params['min-col']; - } else { - return null; - } - } - - /** - * Sets the max-col attribute for this query. - * - * @param string $value - * @return Zend_Gdata_Spreadsheets_CellQuery Provides a fluent interface - */ - public function setMaxCol($value) - { - if ($value != null) { - $this->_params['max-col'] = $value; - } else { - unset($this->_params['max-col']); - } - return $this; - } - - /** - * Gets the max-col attribute for this query. - * - * @return string max-col - */ - public function getMaxCol() - { - if (array_key_exists('max-col', $this->_params)) { - return $this->_params['max-col']; - } else { - return null; - } - } - - /** - * Sets the range attribute for this query. - * - * @param string $value - * @return Zend_Gdata_Spreadsheets_CellQuery Provides a fluent interface - */ - public function setRange($value) - { - if ($value != null) { - $this->_params['range'] = $value; - } else { - unset($this->_params['range']); - } - return $this; - } - - /** - * Gets the range attribute for this query. - * - * @return string range - */ - public function getRange() - { - if (array_key_exists('range', $this->_params)) { - return $this->_params['range']; - } else { - return null; - } - } - - /** - * Sets the return-empty attribute for this query. - * - * @param mixed $value String or bool value for whether to return empty cells - * @return Zend_Gdata_Spreadsheets_CellQuery Provides a fluent interface - */ - public function setReturnEmpty($value) - { - if (is_bool($value)) { - $this->_params['return-empty'] = ($value?'true':'false'); - } else if ($value != null) { - $this->_params['return-empty'] = $value; - } else { - unset($this->_params['return-empty']); - } - return $this; - } - - /** - * Gets the return-empty attribute for this query. - * - * @return string return-empty - */ - public function getReturnEmpty() - { - if (array_key_exists('return-empty', $this->_params)) { - return $this->_params['return-empty']; - } else { - return null; - } - } - - /** - * Gets the full query URL for this query. - * - * @return string url - */ - public function getQueryUrl() - { - if ($this->_url == null) { - $uri = $this->_defaultFeedUri; - - if ($this->_spreadsheetKey != null) { - $uri .= '/'.$this->_spreadsheetKey; - } else { - #require_once 'Zend/Gdata/App/Exception.php'; - throw new Zend_Gdata_App_Exception('A spreadsheet key must be provided for cell queries.'); - } - - if ($this->_worksheetId != null) { - $uri .= '/'.$this->_worksheetId; - } else { - #require_once 'Zend/Gdata/App/Exception.php'; - throw new Zend_Gdata_App_Exception('A worksheet id must be provided for cell queries.'); - } - - if ($this->_visibility != null) { - $uri .= '/'.$this->_visibility; - } else { - #require_once 'Zend/Gdata/App/Exception.php'; - throw new Zend_Gdata_App_Exception('A visibility must be provided for cell queries.'); - } - - if ($this->_projection != null) { - $uri .= '/'.$this->_projection; - } else { - #require_once 'Zend/Gdata/App/Exception.php'; - throw new Zend_Gdata_App_Exception('A projection must be provided for cell queries.'); - } - - if ($this->_cellId != null) { - $uri .= '/'.$this->_cellId; - } - } else { - $uri = $this->_url; - } - - $uri .= $this->getQueryString(); - return $uri; - } - - /** - * Gets the attribute query string for this query. - * - * @return string query string - */ - public function getQueryString() - { - return parent::getQueryString(); - } - -} diff --git a/library/Zend/Gdata/Spreadsheets/DocumentQuery.php b/library/Zend/Gdata/Spreadsheets/DocumentQuery.php deleted file mode 100644 index b6145c7eb0..0000000000 --- a/library/Zend/Gdata/Spreadsheets/DocumentQuery.php +++ /dev/null @@ -1,288 +0,0 @@ -_spreadsheetKey = $value; - return $this; - } - - /** - * Gets the spreadsheet key for this query. - * @return string spreadsheet key - */ - public function getSpreadsheetKey() - { - return $this->_spreadsheetKey; - } - - /** - * Sets the worksheet id for this query. - * @param string $value - * @return Zend_Gdata_Spreadsheets_CellQuery Provides a fluent interface - */ - public function setWorksheetId($value) - { - $this->_worksheetId = $value; - return $this; - } - - /** - * Gets the worksheet id for this query. - * @return string worksheet id - */ - public function getWorksheetId() - { - return $this->_worksheetId; - } - - /** - * Sets the document type for this query. - * @param string $value spreadsheets or worksheets - * @return Zend_Gdata_Spreadsheets_DocumentQuery Provides a fluent interface - */ - public function setDocumentType($value) - { - $this->_documentType = $value; - return $this; - } - - /** - * Gets the document type for this query. - * @return string document type - */ - public function getDocumentType() - { - return $this->_documentType; - } - - /** - * Sets the projection for this query. - * @param string $value - * @return Zend_Gdata_Spreadsheets_DocumentQuery Provides a fluent interface - */ - public function setProjection($value) - { - $this->_projection = $value; - return $this; - } - - /** - * Sets the visibility for this query. - * @return Zend_Gdata_Spreadsheets_DocumentQuery Provides a fluent interface - */ - public function setVisibility($value) - { - $this->_visibility = $value; - return $this; - } - - /** - * Gets the projection for this query. - * @return string projection - */ - public function getProjection() - { - return $this->_projection; - } - - /** - * Gets the visibility for this query. - * @return string visibility - */ - public function getVisibility() - { - return $this->_visibility; - } - - /** - * Sets the title attribute for this query. - * @param string $value - * @return Zend_Gdata_Spreadsheets_DocumentQuery Provides a fluent interface - */ - public function setTitle($value) - { - if ($value != null) { - $this->_params['title'] = $value; - } else { - unset($this->_params['title']); - } - return $this; - } - - /** - * Sets the title-exact attribute for this query. - * @param string $value - * @return Zend_Gdata_Spreadsheets_DocumentQuery Provides a fluent interface - */ - public function setTitleExact($value) - { - if ($value != null) { - $this->_params['title-exact'] = $value; - } else { - unset($this->_params['title-exact']); - } - return $this; - } - - /** - * Gets the title attribute for this query. - * @return string title - */ - public function getTitle() - { - if (array_key_exists('title', $this->_params)) { - return $this->_params['title']; - } else { - return null; - } - } - - /** - * Gets the title-exact attribute for this query. - * @return string title-exact - */ - public function getTitleExact() - { - if (array_key_exists('title-exact', $this->_params)) { - return $this->_params['title-exact']; - } else { - return null; - } - } - - private function appendVisibilityProjection() - { - $uri = ''; - - if ($this->_visibility != null) { - $uri .= '/'.$this->_visibility; - } else { - #require_once 'Zend/Gdata/App/Exception.php'; - throw new Zend_Gdata_App_Exception('A visibility must be provided for document queries.'); - } - - if ($this->_projection != null) { - $uri .= '/'.$this->_projection; - } else { - #require_once 'Zend/Gdata/App/Exception.php'; - throw new Zend_Gdata_App_Exception('A projection must be provided for document queries.'); - } - - return $uri; - } - - - /** - * Gets the full query URL for this query. - * @return string url - */ - public function getQueryUrl() - { - $uri = $this->_defaultFeedUri; - - if ($this->_documentType != null) { - $uri .= '/'.$this->_documentType; - } else { - #require_once 'Zend/Gdata/App/Exception.php'; - throw new Zend_Gdata_App_Exception('A document type must be provided for document queries.'); - } - - if ($this->_documentType == 'spreadsheets') { - $uri .= $this->appendVisibilityProjection(); - if ($this->_spreadsheetKey != null) { - $uri .= '/'.$this->_spreadsheetKey; - } - } else if ($this->_documentType == 'worksheets') { - if ($this->_spreadsheetKey != null) { - $uri .= '/'.$this->_spreadsheetKey; - } else { - #require_once 'Zend/Gdata/App/Exception.php'; - throw new Zend_Gdata_App_Exception('A spreadsheet key must be provided for worksheet document queries.'); - } - $uri .= $this->appendVisibilityProjection(); - if ($this->_worksheetId != null) { - $uri .= '/'.$this->_worksheetId; - } - } - - $uri .= $this->getQueryString(); - return $uri; - } - - /** - * Gets the attribute query string for this query. - * @return string query string - */ - public function getQueryString() - { - return parent::getQueryString(); - } - -} diff --git a/library/Zend/Gdata/Spreadsheets/Extension/Cell.php b/library/Zend/Gdata/Spreadsheets/Extension/Cell.php deleted file mode 100644 index aa62011390..0000000000 --- a/library/Zend/Gdata/Spreadsheets/Extension/Cell.php +++ /dev/null @@ -1,201 +0,0 @@ -registerAllNamespaces(Zend_Gdata_Spreadsheets::$namespaces); - parent::__construct(); - $this->_text = $text; - $this->_row = $row; - $this->_col = $col; - $this->_inputValue = $inputValue; - $this->_numericValue = $numericValue; - } - - public function getDOM($doc = null, $majorVersion = 1, $minorVersion = null) - { - $element = parent::getDOM($doc, $majorVersion, $minorVersion); - $element->setAttribute('row', $this->_row); - $element->setAttribute('col', $this->_col); - if ($this->_inputValue) $element->setAttribute('inputValue', $this->_inputValue); - if ($this->_numericValue) $element->setAttribute('numericValue', $this->_numericValue); - return $element; - } - - protected function takeAttributeFromDOM($attribute) - { - switch ($attribute->localName) { - case 'row': - $this->_row = $attribute->nodeValue; - break; - case 'col': - $this->_col = $attribute->nodeValue; - break; - case 'inputValue': - $this->_inputValue = $attribute->nodeValue; - break; - case 'numericValue': - $this->_numericValue = $attribute->nodeValue; - break; - default: - parent::takeAttributeFromDOM($attribute); - } - } - - /** - * Gets the row attribute of the Cell element. - * @return string Row of the Cell. - */ - public function getRow() - { - return $this->_row; - } - - /** - * Gets the column attribute of the Cell element. - * @return string Column of the Cell. - */ - public function getColumn() - { - return $this->_col; - } - - /** - * Gets the input value attribute of the Cell element. - * @return string Input value of the Cell. - */ - public function getInputValue() - { - return $this->_inputValue; - } - - /** - * Gets the numeric value attribute of the Cell element. - * @return string Numeric value of the Cell. - */ - public function getNumericValue() - { - return $this->_numericValue; - } - - /** - * Sets the row attribute of the Cell element. - * @param string $row New row of the Cell. - */ - public function setRow($row) - { - $this->_row = $row; - return $this; - } - - /** - * Sets the column attribute of the Cell element. - * @param string $col New column of the Cell. - */ - public function setColumn($col) - { - $this->_col = $col; - return $this; - } - - /** - * Sets the input value attribute of the Cell element. - * @param string $inputValue New input value of the Cell. - */ - public function setInputValue($inputValue) - { - $this->_inputValue = $inputValue; - return $this; - } - - /** - * Sets the numeric value attribute of the Cell element. - * @param string $numericValue New numeric value of the Cell. - */ - public function setNumericValue($numericValue) - { - $this->_numericValue = $numericValue; - } - -} diff --git a/library/Zend/Gdata/Spreadsheets/Extension/ColCount.php b/library/Zend/Gdata/Spreadsheets/Extension/ColCount.php deleted file mode 100644 index 3b4cf09f37..0000000000 --- a/library/Zend/Gdata/Spreadsheets/Extension/ColCount.php +++ /dev/null @@ -1,59 +0,0 @@ -registerAllNamespaces(Zend_Gdata_Spreadsheets::$namespaces); - parent::__construct(); - $this->_text = $text; - } -} diff --git a/library/Zend/Gdata/Spreadsheets/Extension/Custom.php b/library/Zend/Gdata/Spreadsheets/Extension/Custom.php deleted file mode 100644 index 9acd1e4005..0000000000 --- a/library/Zend/Gdata/Spreadsheets/Extension/Custom.php +++ /dev/null @@ -1,100 +0,0 @@ -registerAllNamespaces(Zend_Gdata_Spreadsheets::$namespaces); - parent::__construct(); - $this->_text = $value; - $this->_rootElement = $column; - } - - public function getDOM($doc = null, $majorVersion = 1, $minorVersion = null) - { - $element = parent::getDOM($doc, $majorVersion, $minorVersion); - return $element; - } - - /** - * Transfers each child and attribute into member variables. - * This is called when XML is received over the wire and the data - * model needs to be built to represent this XML. - * - * @param DOMNode $node The DOMNode that represents this object's data - */ - public function transferFromDOM($node) - { - parent::transferFromDOM($node); - $this->_rootElement = $node->localName; - } - - /** - * Sets the column/tag name of the element. - * @param string $column The new column name. - */ - public function setColumnName($column) - { - $this->_rootElement = $column; - return $this; - } - - /** - * Gets the column name of the element - * @return string The column name. - */ - public function getColumnName() - { - return $this->_rootElement; - } - -} diff --git a/library/Zend/Gdata/Spreadsheets/Extension/RowCount.php b/library/Zend/Gdata/Spreadsheets/Extension/RowCount.php deleted file mode 100644 index 75c5a92b6d..0000000000 --- a/library/Zend/Gdata/Spreadsheets/Extension/RowCount.php +++ /dev/null @@ -1,60 +0,0 @@ -registerAllNamespaces(Zend_Gdata_Spreadsheets::$namespaces); - parent::__construct(); - $this->_text = $text; - } - -} diff --git a/library/Zend/Gdata/Spreadsheets/ListEntry.php b/library/Zend/Gdata/Spreadsheets/ListEntry.php deleted file mode 100644 index 623314279f..0000000000 --- a/library/Zend/Gdata/Spreadsheets/ListEntry.php +++ /dev/null @@ -1,208 +0,0 @@ -registerAllNamespaces(Zend_Gdata_Spreadsheets::$namespaces); - parent::__construct($element); - } - - public function getDOM($doc = null, $majorVersion = 1, $minorVersion = null) - { - $element = parent::getDOM($doc, $majorVersion, $minorVersion); - if (!empty($this->_custom)) { - foreach ($this->_custom as $custom) { - $element->appendChild($custom->getDOM($element->ownerDocument)); - } - } - return $element; - } - - protected function takeChildFromDOM($child) - { - switch ($child->namespaceURI) { - case $this->lookupNamespace('gsx'); - $custom = new Zend_Gdata_Spreadsheets_Extension_Custom($child->localName); - $custom->transferFromDOM($child); - $this->addCustom($custom); - break; - default: - parent::takeChildFromDOM($child); - break; - } - } - - /** - * Gets the row elements contained by this list entry. - * @return array The custom row elements in this list entry - */ - public function getCustom() - { - return $this->_custom; - } - - /** - * Gets a single row element contained by this list entry using its name. - * @param string $name The name of a custom element to return. If null - * or not defined, an array containing all custom elements - * indexed by name will be returned. - * @return mixed If a name is specified, the - * Zend_Gdata_Spreadsheets_Extension_Custom element requested, - * is returned or null if not found. Otherwise, an array of all - * Zend_Gdata_Spreadsheets_Extension_Custom elements is returned - * indexed by name. - */ - public function getCustomByName($name = null) - { - if ($name === null) { - return $this->_customByName; - } else { - if (array_key_exists($name, $this->customByName)) { - return $this->_customByName[$name]; - } else { - return null; - } - } - } - - /** - * Sets the row elements contained by this list entry. If any - * custom row elements were previously stored, they will be overwritten. - * @param array $custom The custom row elements to be contained in this - * list entry. - * @return Zend_Gdata_Spreadsheets_ListEntry Provides a fluent interface. - */ - public function setCustom($custom) - { - $this->_custom = array(); - foreach ($custom as $c) { - $this->addCustom($c); - } - return $this; - } - - /** - * Add an individual custom row element to this list entry. - * @param Zend_Gdata_Spreadsheets_Extension_Custom $custom The custom - * element to be added. - * @return Zend_Gdata_Spreadsheets_ListEntry Provides a fluent interface. - */ - public function addCustom($custom) - { - $this->_custom[] = $custom; - $this->_customByName[$custom->getColumnName()] = $custom; - return $this; - } - - /** - * Remove an individual row element from this list entry by index. This - * will cause the array to be re-indexed. - * @param int $index The index of the custom element to be deleted. - * @return Zend_Gdata_Spreadsheets_ListEntry Provides a fluent interface. - * @throws Zend_Gdata_App_InvalidArgumentException - */ - public function removeCustom($index) - { - if (array_key_exists($index, $this->_custom)) { - $element = $this->_custom[$index]; - // Remove element - unset($this->_custom[$index]); - // Re-index the array - $this->_custom = array_values($this->_custom); - // Be sure to delete form both arrays! - $key = array_search($element, $this->_customByName); - unset($this->_customByName[$key]); - } else { - #require_once 'Zend/Gdata/App/InvalidArgumentException.php'; - throw new Zend_Gdata_App_InvalidArgumentException( - 'Element does not exist.'); - } - return $this; - } - - /** - * Remove an individual row element from this list entry by name. - * @param string $name The name of the custom element to be deleted. - * @return Zend_Gdata_Spreadsheets_ListEntry Provides a fluent interface. - * @throws Zend_Gdata_App_InvalidArgumentException - */ - public function removeCustomByName($name) - { - if (array_key_exists($name, $this->_customByName)) { - $element = $this->_customByName[$name]; - // Remove element - unset($this->_customByName[$name]); - // Be sure to delete from both arrays! - $key = array_search($element, $this->_custom); - unset($this->_custom[$key]); - } else { - #require_once 'Zend/Gdata/App/InvalidArgumentException.php'; - throw new Zend_Gdata_App_InvalidArgumentException( - 'Element does not exist.'); - } - return $this; - } - -} diff --git a/library/Zend/Gdata/Spreadsheets/ListFeed.php b/library/Zend/Gdata/Spreadsheets/ListFeed.php deleted file mode 100644 index 38c4ba50ca..0000000000 --- a/library/Zend/Gdata/Spreadsheets/ListFeed.php +++ /dev/null @@ -1,64 +0,0 @@ -registerAllNamespaces(Zend_Gdata_Spreadsheets::$namespaces); - parent::__construct($element); - } - -} diff --git a/library/Zend/Gdata/Spreadsheets/ListQuery.php b/library/Zend/Gdata/Spreadsheets/ListQuery.php deleted file mode 100644 index 6f068c2512..0000000000 --- a/library/Zend/Gdata/Spreadsheets/ListQuery.php +++ /dev/null @@ -1,305 +0,0 @@ -_spreadsheetKey = $value; - return $this; - } - - /** - * Gets the spreadsheet key for the query. - * @return string spreadsheet key - */ - public function getSpreadsheetKey() - { - return $this->_spreadsheetKey; - } - - /** - * Sets the worksheet id for the query. - * @param string $value - * @return Zend_Gdata_Spreadsheets_CellQuery Provides a fluent interface - */ - public function setWorksheetId($value) - { - $this->_worksheetId = $value; - return $this; - } - - /** - * Gets the worksheet id for the query. - * @return string worksheet id - */ - public function getWorksheetId() - { - return $this->_worksheetId; - } - - /** - * Sets the row id for the query. - * @param string $value row id - * @return Zend_Gdata_Spreadsheets_CellQuery Provides a fluent interface - */ - public function setRowId($value) - { - $this->_rowId = $value; - return $this; - } - - /** - * Gets the row id for the query. - * @return string row id - */ - public function getRowId() - { - return $this->_rowId; - } - - /** - * Sets the projection for the query. - * @param string $value Projection - * @return Zend_Gdata_Spreadsheets_ListQuery Provides a fluent interface - */ - public function setProjection($value) - { - $this->_projection = $value; - return $this; - } - - /** - * Sets the visibility for this query. - * @param string $value visibility - * @return Zend_Gdata_Spreadsheets_ListQuery Provides a fluent interface - */ - public function setVisibility($value) - { - $this->_visibility = $value; - return $this; - } - - /** - * Gets the projection for this query. - * @return string projection - */ - public function getProjection() - { - return $this->_projection; - } - - /** - * Gets the visibility for this query. - * @return string visibility - */ - public function getVisibility() - { - return $this->_visibility; - } - - /** - * Sets the spreadsheet key for this query. - * @param string $value - * @return Zend_Gdata_Spreadsheets_DocumentQuery Provides a fluent interface - */ - public function setSpreadsheetQuery($value) - { - if ($value != null) { - $this->_params['sq'] = $value; - } else { - unset($this->_params['sq']); - } - return $this; - } - - /** - * Gets the spreadsheet key for this query. - * @return string spreadsheet query - */ - public function getSpreadsheetQuery() - { - if (array_key_exists('sq', $this->_params)) { - return $this->_params['sq']; - } else { - return null; - } - } - - /** - * Sets the orderby attribute for this query. - * @param string $value - * @return Zend_Gdata_Spreadsheets_DocumentQuery Provides a fluent interface - */ - public function setOrderBy($value) - { - if ($value != null) { - $this->_params['orderby'] = $value; - } else { - unset($this->_params['orderby']); - } - return $this; - } - - /** - * Gets the orderby attribute for this query. - * @return string orderby - */ - public function getOrderBy() - { - if (array_key_exists('orderby', $this->_params)) { - return $this->_params['orderby']; - } else { - return null; - } - } - - /** - * Sets the reverse attribute for this query. - * @param string $value - * @return Zend_Gdata_Spreadsheets_DocumentQuery Provides a fluent interface - */ - public function setReverse($value) - { - if ($value != null) { - $this->_params['reverse'] = $value; - } else { - unset($this->_params['reverse']); - } - return $this; - } - - /** - * Gets the reverse attribute for this query. - * @return string reverse - */ - public function getReverse() - { - - - if (array_key_exists('reverse', $this->_params)) { - return $this->_params['reverse']; - } else { - return null; - } - } - - /** - * Gets the full query URL for this query. - * @return string url - */ - public function getQueryUrl() - { - - $uri = $this->_defaultFeedUri; - - if ($this->_spreadsheetKey != null) { - $uri .= '/'.$this->_spreadsheetKey; - } else { - #require_once 'Zend/Gdata/App/Exception.php'; - throw new Zend_Gdata_App_Exception('A spreadsheet key must be provided for list queries.'); - } - - if ($this->_worksheetId != null) { - $uri .= '/'.$this->_worksheetId; - } else { - #require_once 'Zend/Gdata/App/Exception.php'; - throw new Zend_Gdata_App_Exception('A worksheet id must be provided for list queries.'); - } - - if ($this->_visibility != null) { - $uri .= '/'.$this->_visibility; - } else { - #require_once 'Zend/Gdata/App/Exception.php'; - throw new Zend_Gdata_App_Exception('A visibility must be provided for list queries.'); - } - - if ($this->_projection != null) { - $uri .= '/'.$this->_projection; - } else { - #require_once 'Zend/Gdata/App/Exception.php'; - throw new Zend_Gdata_App_Exception('A projection must be provided for list queries.'); - } - - if ($this->_rowId != null) { - $uri .= '/'.$this->_rowId; - } - - $uri .= $this->getQueryString(); - return $uri; - } - - /** - * Gets the attribute query string for this query. - * @return string query string - */ - public function getQueryString() - { - return parent::getQueryString(); - } - -} diff --git a/library/Zend/Gdata/Spreadsheets/SpreadsheetEntry.php b/library/Zend/Gdata/Spreadsheets/SpreadsheetEntry.php deleted file mode 100644 index 7e8e48ab1a..0000000000 --- a/library/Zend/Gdata/Spreadsheets/SpreadsheetEntry.php +++ /dev/null @@ -1,64 +0,0 @@ -registerAllNamespaces(Zend_Gdata_Spreadsheets::$namespaces); - parent::__construct($element); - } - - /** - * Returns the worksheets in this spreadsheet - * - * @return Zend_Gdata_Spreadsheets_WorksheetFeed The worksheets - */ - public function getWorksheets() - { - $service = new Zend_Gdata_Spreadsheets($this->getHttpClient()); - return $service->getWorksheetFeed($this); - } - -} diff --git a/library/Zend/Gdata/Spreadsheets/SpreadsheetFeed.php b/library/Zend/Gdata/Spreadsheets/SpreadsheetFeed.php deleted file mode 100644 index f2b1865374..0000000000 --- a/library/Zend/Gdata/Spreadsheets/SpreadsheetFeed.php +++ /dev/null @@ -1,64 +0,0 @@ -registerAllNamespaces(Zend_Gdata_Spreadsheets::$namespaces); - parent::__construct($element); - } - -} diff --git a/library/Zend/Gdata/Spreadsheets/WorksheetEntry.php b/library/Zend/Gdata/Spreadsheets/WorksheetEntry.php deleted file mode 100644 index 19e570a427..0000000000 --- a/library/Zend/Gdata/Spreadsheets/WorksheetEntry.php +++ /dev/null @@ -1,187 +0,0 @@ -registerAllNamespaces(Zend_Gdata_Spreadsheets::$namespaces); - parent::__construct($element); - } - - /** - * Retrieves a DOMElement which corresponds to this element and all - * child properties. This is used to build an entry back into a DOM - * and eventually XML text for sending to the server upon updates, or - * for application storage/persistence. - * - * @param DOMDocument $doc The DOMDocument used to construct DOMElements - * @return DOMElement The DOMElement representing this element and all - * child properties. - */ - public function getDOM($doc = null, $majorVersion = 1, $minorVersion = null) - { - $element = parent::getDOM($doc, $majorVersion, $minorVersion); - if ($this->_rowCount != null) { - $element->appendChild($this->_rowCount->getDOM($element->ownerDocument)); - } - if ($this->_colCount != null) { - $element->appendChild($this->_colCount->getDOM($element->ownerDocument)); - } - return $element; - } - - /** - * Creates individual Entry objects of the appropriate type and - * stores them in the $_entry array based upon DOM data. - * - * @param DOMNode $child The DOMNode to process - */ - protected function takeChildFromDOM($child) - { - $absoluteNodeName = $child->namespaceURI . ':' . $child->localName; - switch ($absoluteNodeName) { - case $this->lookupNamespace('gs') . ':' . 'rowCount'; - $rowCount = new Zend_Gdata_Spreadsheets_Extension_RowCount(); - $rowCount->transferFromDOM($child); - $this->_rowCount = $rowCount; - break; - case $this->lookupNamespace('gs') . ':' . 'colCount'; - $colCount = new Zend_Gdata_Spreadsheets_Extension_ColCount(); - $colCount->transferFromDOM($child); - $this->_colCount = $colCount; - break; - default: - parent::takeChildFromDOM($child); - break; - } - } - - - /** - * Gets the row count for this entry. - * - * @return string The row count for the entry. - */ - public function getRowCount() - { - return $this->_rowCount; - } - - /** - * Gets the column count for this entry. - * - * @return string The column count for the entry. - */ - public function getColumnCount() - { - return $this->_colCount; - } - - /** - * Sets the row count for this entry. - * - * @param string $rowCount The new row count for the entry. - */ - public function setRowCount($rowCount) - { - $this->_rowCount = $rowCount; - return $this; - } - - /** - * Sets the column count for this entry. - * - * @param string $colCount The new column count for the entry. - */ - public function setColumnCount($colCount) - { - $this->_colCount = $colCount; - return $this; - } - - /** - * Returns the content of all rows as an associative array - * - * @return array An array of rows. Each element of the array is an associative array of data - */ - public function getContentsAsRows() - { - $service = new Zend_Gdata_Spreadsheets($this->getHttpClient()); - return $service->getSpreadsheetListFeedContents($this); - } - - /** - * Returns the content of all cells as an associative array, indexed - * off the cell location (ie 'A1', 'D4', etc). Each element of - * the array is an associative array with a 'value' and a 'function'. - * Only non-empty cells are returned by default. 'range' is the - * value of the 'range' query parameter specified at: - * http://code.google.com/apis/spreadsheets/reference.html#cells_Parameters - * - * @param string $range The range of cells to retrieve - * @param boolean $empty Whether to retrieve empty cells - * @return array An associative array of cells - */ - public function getContentsAsCells($range = null, $empty = false) - { - $service = new Zend_Gdata_Spreadsheets($this->getHttpClient()); - return $service->getSpreadsheetCellFeedContents($this, $range, $empty); - } - -} diff --git a/library/Zend/Gdata/Spreadsheets/WorksheetFeed.php b/library/Zend/Gdata/Spreadsheets/WorksheetFeed.php deleted file mode 100644 index cc9d75dda0..0000000000 --- a/library/Zend/Gdata/Spreadsheets/WorksheetFeed.php +++ /dev/null @@ -1,64 +0,0 @@ -registerAllNamespaces(Zend_Gdata_Spreadsheets::$namespaces); - parent::__construct($element); - } - - /** - * The classname for individual feed elements. - * - * @var string - */ - protected $_entryClassName = 'Zend_Gdata_Spreadsheets_WorksheetEntry'; - - /** - * The classname for the feed. - * - * @var string - */ - protected $_feedClassName = 'Zend_Gdata_Spreadsheets_WorksheetFeed'; - -} diff --git a/library/Zend/Ldap.php b/library/Zend/Ldap.php deleted file mode 100644 index d1ecd770ab..0000000000 --- a/library/Zend/Ldap.php +++ /dev/null @@ -1,1598 +0,0 @@ -setOptions($options); - } - - /** - * Destructor. - * - * @return void - */ - public function __destruct() - { - $this->disconnect(); - } - - /** - * @return resource The raw LDAP extension resource. - */ - public function getResource() - { - if (!is_resource($this->_resource) || $this->_boundUser === false) { - $this->bind(); - } - return $this->_resource; - } - - /** - * Return the LDAP error number of the last LDAP command - * - * @return int - */ - public function getLastErrorCode() - { - $ret = @ldap_get_option($this->_resource, LDAP_OPT_ERROR_NUMBER, $err); - if ($ret === true) { - if ($err <= -1 && $err >= -17) { - /** - * @see Zend_Ldap_Exception - */ - #require_once 'Zend/Ldap/Exception.php'; - /* For some reason draft-ietf-ldapext-ldap-c-api-xx.txt error - * codes in OpenLDAP are negative values from -1 to -17. - */ - $err = Zend_Ldap_Exception::LDAP_SERVER_DOWN + (-$err - 1); - } - return $err; - } - return 0; - } - - /** - * Return the LDAP error message of the last LDAP command - * - * @param int $errorCode - * @param array $errorMessages - * @return string - */ - public function getLastError(&$errorCode = null, array &$errorMessages = null) - { - $errorCode = $this->getLastErrorCode(); - $errorMessages = array(); - - /* The various error retrieval functions can return - * different things so we just try to collect what we - * can and eliminate dupes. - */ - $estr1 = @ldap_error($this->_resource); - if ($errorCode !== 0 && $estr1 === 'Success') { - $estr1 = @ldap_err2str($errorCode); - } - if (!empty($estr1)) { - $errorMessages[] = $estr1; - } - - @ldap_get_option($this->_resource, LDAP_OPT_ERROR_STRING, $estr2); - if (!empty($estr2) && !in_array($estr2, $errorMessages)) { - $errorMessages[] = $estr2; - } - - $message = ''; - if ($errorCode > 0) { - $message = '0x' . dechex($errorCode) . ' '; - } else { - $message = ''; - } - if (count($errorMessages) > 0) { - $message .= '(' . implode('; ', $errorMessages) . ')'; - } else { - $message .= '(no error message from LDAP)'; - } - return $message; - } - - /** - * Get the currently bound user - * - * FALSE if no user is bound to the LDAP resource - * NULL if there has been an anonymous bind - * username of the currently bound user - * - * @return false|null|string - */ - public function getBoundUser() - { - return $this->_boundUser; - } - - /** - * Sets the options used in connecting, binding, etc. - * - * Valid option keys: - * host - * port - * useSsl - * username - * password - * bindRequiresDn - * baseDn - * accountCanonicalForm - * accountDomainName - * accountDomainNameShort - * accountFilterFormat - * allowEmptyPassword - * useStartTls - * optRefferals - * tryUsernameSplit - * - * @param array|Zend_Config $options Options used in connecting, binding, etc. - * @return Zend_Ldap Provides a fluent interface - * @throws Zend_Ldap_Exception - */ - public function setOptions($options) - { - if ($options instanceof Zend_Config) { - $options = $options->toArray(); - } - - $permittedOptions = array( - 'host' => null, - 'port' => 0, - 'useSsl' => false, - 'username' => null, - 'password' => null, - 'bindRequiresDn' => false, - 'baseDn' => null, - 'accountCanonicalForm' => null, - 'accountDomainName' => null, - 'accountDomainNameShort' => null, - 'accountFilterFormat' => null, - 'allowEmptyPassword' => false, - 'useStartTls' => false, - 'optReferrals' => false, - 'tryUsernameSplit' => true, - ); - - foreach ($permittedOptions as $key => $val) { - if (array_key_exists($key, $options)) { - $val = $options[$key]; - unset($options[$key]); - /* Enforce typing. This eliminates issues like Zend_Config_Ini - * returning '1' as a string (ZF-3163). - */ - switch ($key) { - case 'port': - case 'accountCanonicalForm': - $permittedOptions[$key] = (int)$val; - break; - case 'useSsl': - case 'bindRequiresDn': - case 'allowEmptyPassword': - case 'useStartTls': - case 'optReferrals': - case 'tryUsernameSplit': - $permittedOptions[$key] = ($val === true || - $val === '1' || strcasecmp($val, 'true') == 0); - break; - default: - $permittedOptions[$key] = trim($val); - break; - } - } - } - if (count($options) > 0) { - $key = key($options); - /** - * @see Zend_Ldap_Exception - */ - #require_once 'Zend/Ldap/Exception.php'; - throw new Zend_Ldap_Exception(null, "Unknown Zend_Ldap option: $key"); - } - $this->_options = $permittedOptions; - return $this; - } - - /** - * @return array The current options. - */ - public function getOptions() - { - return $this->_options; - } - - /** - * @return string The hostname of the LDAP server being used to authenticate accounts - */ - protected function _getHost() - { - return $this->_options['host']; - } - - /** - * @return int The port of the LDAP server or 0 to indicate that no port value is set - */ - protected function _getPort() - { - return $this->_options['port']; - } - - /** - * @return boolean The default SSL / TLS encrypted transport control - */ - protected function _getUseSsl() - { - return $this->_options['useSsl']; - } - - /** - * @return string The default acctname for binding - */ - protected function _getUsername() - { - return $this->_options['username']; - } - - /** - * @return string The default password for binding - */ - protected function _getPassword() - { - return $this->_options['password']; - } - - /** - * @return boolean Bind requires DN - */ - protected function _getBindRequiresDn() - { - return $this->_options['bindRequiresDn']; - } - - /** - * Gets the base DN under which objects of interest are located - * - * @return string - */ - public function getBaseDn() - { - return $this->_options['baseDn']; - } - - /** - * @return integer Either ACCTNAME_FORM_BACKSLASH, ACCTNAME_FORM_PRINCIPAL or - * ACCTNAME_FORM_USERNAME indicating the form usernames should be canonicalized to. - */ - protected function _getAccountCanonicalForm() - { - /* Account names should always be qualified with a domain. In some scenarios - * using non-qualified account names can lead to security vulnerabilities. If - * no account canonical form is specified, we guess based in what domain - * names have been supplied. - */ - - $accountCanonicalForm = $this->_options['accountCanonicalForm']; - if (!$accountCanonicalForm) { - $accountDomainName = $this->_getAccountDomainName(); - $accountDomainNameShort = $this->_getAccountDomainNameShort(); - if ($accountDomainNameShort) { - $accountCanonicalForm = Zend_Ldap::ACCTNAME_FORM_BACKSLASH; - } else if ($accountDomainName) { - $accountCanonicalForm = Zend_Ldap::ACCTNAME_FORM_PRINCIPAL; - } else { - $accountCanonicalForm = Zend_Ldap::ACCTNAME_FORM_USERNAME; - } - } - - return $accountCanonicalForm; - } - - /** - * @return string The account domain name - */ - protected function _getAccountDomainName() - { - return $this->_options['accountDomainName']; - } - - /** - * @return string The short account domain name - */ - protected function _getAccountDomainNameShort() - { - return $this->_options['accountDomainNameShort']; - } - - /** - * @return string A format string for building an LDAP search filter to match - * an account - */ - protected function _getAccountFilterFormat() - { - return $this->_options['accountFilterFormat']; - } - - /** - * @return boolean Allow empty passwords - */ - protected function _getAllowEmptyPassword() - { - return $this->_options['allowEmptyPassword']; - } - - /** - * @return boolean The default SSL / TLS encrypted transport control - */ - protected function _getUseStartTls() - { - return $this->_options['useStartTls']; - } - - /** - * @return boolean Opt. Referrals - */ - protected function _getOptReferrals() - { - return $this->_options['optReferrals']; - } - - /** - * @return boolean Try splitting the username into username and domain - */ - protected function _getTryUsernameSplit() - { - return $this->_options['tryUsernameSplit']; - } - - /** - * @return string The LDAP search filter for matching directory accounts - */ - protected function _getAccountFilter($acctname) - { - /** - * @see Zend_Ldap_Filter_Abstract - */ - #require_once 'Zend/Ldap/Filter/Abstract.php'; - $this->_splitName($acctname, $dname, $aname); - $accountFilterFormat = $this->_getAccountFilterFormat(); - $aname = Zend_Ldap_Filter_Abstract::escapeValue($aname); - if ($accountFilterFormat) { - return sprintf($accountFilterFormat, $aname); - } - if (!$this->_getBindRequiresDn()) { - // is there a better way to detect this? - return sprintf("(&(objectClass=user)(sAMAccountName=%s))", $aname); - } - return sprintf("(&(objectClass=posixAccount)(uid=%s))", $aname); - } - - /** - * @param string $name The name to split - * @param string $dname The resulting domain name (this is an out parameter) - * @param string $aname The resulting account name (this is an out parameter) - * @return void - */ - protected function _splitName($name, &$dname, &$aname) - { - $dname = null; - $aname = $name; - - if (!$this->_getTryUsernameSplit()) { - return; - } - - $pos = strpos($name, '@'); - if ($pos) { - $dname = substr($name, $pos + 1); - $aname = substr($name, 0, $pos); - } else { - $pos = strpos($name, '\\'); - if ($pos) { - $dname = substr($name, 0, $pos); - $aname = substr($name, $pos + 1); - } - } - } - - /** - * @param string $acctname The name of the account - * @return string The DN of the specified account - * @throws Zend_Ldap_Exception - */ - protected function _getAccountDn($acctname) - { - /** - * @see Zend_Ldap_Dn - */ - #require_once 'Zend/Ldap/Dn.php'; - if (Zend_Ldap_Dn::checkDn($acctname)) return $acctname; - $acctname = $this->getCanonicalAccountName($acctname, Zend_Ldap::ACCTNAME_FORM_USERNAME); - $acct = $this->_getAccount($acctname, array('dn')); - return $acct['dn']; - } - - /** - * @param string $dname The domain name to check - * @return boolean - */ - protected function _isPossibleAuthority($dname) - { - if ($dname === null) { - return true; - } - $accountDomainName = $this->_getAccountDomainName(); - $accountDomainNameShort = $this->_getAccountDomainNameShort(); - if ($accountDomainName === null && $accountDomainNameShort === null) { - return true; - } - if (strcasecmp($dname, $accountDomainName) == 0) { - return true; - } - if (strcasecmp($dname, $accountDomainNameShort) == 0) { - return true; - } - return false; - } - - /** - * @param string $acctname The name to canonicalize - * @param int $type The desired form of canonicalization - * @return string The canonicalized name in the desired form - * @throws Zend_Ldap_Exception - */ - public function getCanonicalAccountName($acctname, $form = 0) - { - $this->_splitName($acctname, $dname, $uname); - - if (!$this->_isPossibleAuthority($dname)) { - /** - * @see Zend_Ldap_Exception - */ - #require_once 'Zend/Ldap/Exception.php'; - throw new Zend_Ldap_Exception(null, - "Binding domain is not an authority for user: $acctname", - Zend_Ldap_Exception::LDAP_X_DOMAIN_MISMATCH); - } - - if (!$uname) { - /** - * @see Zend_Ldap_Exception - */ - #require_once 'Zend/Ldap/Exception.php'; - throw new Zend_Ldap_Exception(null, "Invalid account name syntax: $acctname"); - } - - if (function_exists('mb_strtolower')) { - $uname = mb_strtolower($uname, 'UTF-8'); - } else { - $uname = strtolower($uname); - } - - if ($form === 0) { - $form = $this->_getAccountCanonicalForm(); - } - - switch ($form) { - case Zend_Ldap::ACCTNAME_FORM_DN: - return $this->_getAccountDn($acctname); - case Zend_Ldap::ACCTNAME_FORM_USERNAME: - return $uname; - case Zend_Ldap::ACCTNAME_FORM_BACKSLASH: - $accountDomainNameShort = $this->_getAccountDomainNameShort(); - if (!$accountDomainNameShort) { - /** - * @see Zend_Ldap_Exception - */ - #require_once 'Zend/Ldap/Exception.php'; - throw new Zend_Ldap_Exception(null, 'Option required: accountDomainNameShort'); - } - return "$accountDomainNameShort\\$uname"; - case Zend_Ldap::ACCTNAME_FORM_PRINCIPAL: - $accountDomainName = $this->_getAccountDomainName(); - if (!$accountDomainName) { - /** - * @see Zend_Ldap_Exception - */ - #require_once 'Zend/Ldap/Exception.php'; - throw new Zend_Ldap_Exception(null, 'Option required: accountDomainName'); - } - return "$uname@$accountDomainName"; - default: - /** - * @see Zend_Ldap_Exception - */ - #require_once 'Zend/Ldap/Exception.php'; - throw new Zend_Ldap_Exception(null, "Unknown canonical name form: $form"); - } - } - - /** - * @param array $attrs An array of names of desired attributes - * @return array An array of the attributes representing the account - * @throws Zend_Ldap_Exception - */ - protected function _getAccount($acctname, array $attrs = null) - { - $baseDn = $this->getBaseDn(); - if (!$baseDn) { - /** - * @see Zend_Ldap_Exception - */ - #require_once 'Zend/Ldap/Exception.php'; - throw new Zend_Ldap_Exception(null, 'Base DN not set'); - } - - $accountFilter = $this->_getAccountFilter($acctname); - if (!$accountFilter) { - /** - * @see Zend_Ldap_Exception - */ - #require_once 'Zend/Ldap/Exception.php'; - throw new Zend_Ldap_Exception(null, 'Invalid account filter'); - } - - if (!is_resource($this->getResource())) { - $this->bind(); - } - - $accounts = $this->search($accountFilter, $baseDn, self::SEARCH_SCOPE_SUB, $attrs); - $count = $accounts->count(); - if ($count === 1) { - $acct = $accounts->getFirst(); - $accounts->close(); - return $acct; - } else if ($count === 0) { - /** - * @see Zend_Ldap_Exception - */ - #require_once 'Zend/Ldap/Exception.php'; - $code = Zend_Ldap_Exception::LDAP_NO_SUCH_OBJECT; - $str = "No object found for: $accountFilter"; - } else { - /** - * @see Zend_Ldap_Exception - */ - #require_once 'Zend/Ldap/Exception.php'; - $code = Zend_Ldap_Exception::LDAP_OPERATIONS_ERROR; - $str = "Unexpected result count ($count) for: $accountFilter"; - } - $accounts->close(); - /** - * @see Zend_Ldap_Exception - */ - #require_once 'Zend/Ldap/Exception.php'; - throw new Zend_Ldap_Exception($this, $str, $code); - } - - /** - * @return Zend_Ldap Provides a fluent interface - */ - public function disconnect() - { - if (is_resource($this->_resource)) { - @ldap_unbind($this->_resource); - } - $this->_resource = null; - $this->_boundUser = false; - return $this; - } - - /** - * To connect using SSL it seems the client tries to verify the server - * certificate by default. One way to disable this behavior is to set - * 'TLS_REQCERT never' in OpenLDAP's ldap.conf and restarting Apache. Or, - * if you really care about the server's cert you can put a cert on the - * web server. - * - * @param string $host The hostname of the LDAP server to connect to - * @param int $port The port number of the LDAP server to connect to - * @param boolean $useSsl Use SSL - * @param boolean $useStartTls Use STARTTLS - * @return Zend_Ldap Provides a fluent interface - * @throws Zend_Ldap_Exception - */ - public function connect($host = null, $port = null, $useSsl = null, $useStartTls = null) - { - if ($host === null) { - $host = $this->_getHost(); - } - if ($port === null) { - $port = $this->_getPort(); - } else { - $port = (int)$port; - } - if ($useSsl === null) { - $useSsl = $this->_getUseSsl(); - } else { - $useSsl = (bool)$useSsl; - } - if ($useStartTls === null) { - $useStartTls = $this->_getUseStartTls(); - } else { - $useStartTls = (bool)$useStartTls; - } - - if (!$host) { - /** - * @see Zend_Ldap_Exception - */ - #require_once 'Zend/Ldap/Exception.php'; - throw new Zend_Ldap_Exception(null, 'A host parameter is required'); - } - - $useUri = false; - /* Because ldap_connect doesn't really try to connect, any connect error - * will actually occur during the ldap_bind call. Therefore, we save the - * connect string here for reporting it in error handling in bind(). - */ - $hosts = array(); - if (preg_match_all('~ldap(?:i|s)?://~', $host, $hosts, PREG_SET_ORDER) > 0) { - $this->_connectString = $host; - $useUri = true; - $useSsl = false; - } else { - if ($useSsl) { - $this->_connectString = 'ldaps://' . $host; - $useUri = true; - } else { - $this->_connectString = 'ldap://' . $host; - } - if ($port) { - $this->_connectString .= ':' . $port; - } - } - - $this->disconnect(); - - /* Only OpenLDAP 2.2 + supports URLs so if SSL is not requested, just - * use the old form. - */ - $resource = ($useUri) ? @ldap_connect($this->_connectString) : @ldap_connect($host, $port); - - if (is_resource($resource) === true) { - $this->_resource = $resource; - $this->_boundUser = false; - - $optReferrals = ($this->_getOptReferrals()) ? 1 : 0; - if (@ldap_set_option($resource, LDAP_OPT_PROTOCOL_VERSION, 3) && - @ldap_set_option($resource, LDAP_OPT_REFERRALS, $optReferrals)) { - if ($useSsl || !$useStartTls || @ldap_start_tls($resource)) { - return $this; - } - } - - /** - * @see Zend_Ldap_Exception - */ - #require_once 'Zend/Ldap/Exception.php'; - $zle = new Zend_Ldap_Exception($this, "$host:$port"); - $this->disconnect(); - throw $zle; - } - /** - * @see Zend_Ldap_Exception - */ - #require_once 'Zend/Ldap/Exception.php'; - throw new Zend_Ldap_Exception(null, "Failed to connect to LDAP server: $host:$port"); - } - - /** - * @param string $username The username for authenticating the bind - * @param string $password The password for authenticating the bind - * @return Zend_Ldap Provides a fluent interface - * @throws Zend_Ldap_Exception - */ - public function bind($username = null, $password = null) - { - $moreCreds = true; - - // Security check: remove null bytes in password - // @see https://net.educause.edu/ir/library/pdf/csd4875.pdf - $password = str_replace("\0", '', $password); - - if ($username === null) { - $username = $this->_getUsername(); - $password = $this->_getPassword(); - $moreCreds = false; - } - - if (empty($username)) { - /* Perform anonymous bind - */ - $username = null; - $password = null; - } else { - /* Check to make sure the username is in DN form. - */ - /** - * @see Zend_Ldap_Dn - */ - #require_once 'Zend/Ldap/Dn.php'; - if (!Zend_Ldap_Dn::checkDn($username)) { - if ($this->_getBindRequiresDn()) { - /* moreCreds stops an infinite loop if _getUsername does not - * return a DN and the bind requires it - */ - if ($moreCreds) { - try { - $username = $this->_getAccountDn($username); - } catch (Zend_Ldap_Exception $zle) { - switch ($zle->getCode()) { - case Zend_Ldap_Exception::LDAP_NO_SUCH_OBJECT: - case Zend_Ldap_Exception::LDAP_X_DOMAIN_MISMATCH: - case Zend_Ldap_Exception::LDAP_X_EXTENSION_NOT_LOADED: - throw $zle; - } - throw new Zend_Ldap_Exception(null, - 'Failed to retrieve DN for account: ' . $username . - ' [' . $zle->getMessage() . ']', - Zend_Ldap_Exception::LDAP_OPERATIONS_ERROR); - } - } else { - /** - * @see Zend_Ldap_Exception - */ - #require_once 'Zend/Ldap/Exception.php'; - throw new Zend_Ldap_Exception(null, 'Binding requires username in DN form'); - } - } else { - $username = $this->getCanonicalAccountName($username, - $this->_getAccountCanonicalForm()); - } - } - } - - if (!is_resource($this->_resource)) { - $this->connect(); - } - - if ($username !== null && $password === '' && $this->_getAllowEmptyPassword() !== true) { - /** - * @see Zend_Ldap_Exception - */ - #require_once 'Zend/Ldap/Exception.php'; - $zle = new Zend_Ldap_Exception(null, - 'Empty password not allowed - see allowEmptyPassword option.'); - } else { - if (@ldap_bind($this->_resource, $username, $password)) { - $this->_boundUser = $username; - return $this; - } - - $message = ($username === null) ? $this->_connectString : $username; - /** - * @see Zend_Ldap_Exception - */ - #require_once 'Zend/Ldap/Exception.php'; - switch ($this->getLastErrorCode()) { - case Zend_Ldap_Exception::LDAP_SERVER_DOWN: - /* If the error is related to establishing a connection rather than binding, - * the connect string is more informative than the username. - */ - $message = $this->_connectString; - } - - $zle = new Zend_Ldap_Exception($this, $message); - } - $this->disconnect(); - throw $zle; - } - - /** - * A global LDAP search routine for finding information. - * - * Options can be either passed as single parameters according to the - * method signature or as an array with one or more of the following keys - * - filter - * - baseDn - * - scope - * - attributes - * - sort - * - collectionClass - * - sizelimit - * - timelimit - * - * @param string|Zend_Ldap_Filter_Abstract|array $filter - * @param string|Zend_Ldap_Dn|null $basedn - * @param integer $scope - * @param array $attributes - * @param string|null $sort - * @param string|null $collectionClass - * @param integer $sizelimit - * @param integer $timelimit - * @return Zend_Ldap_Collection - * @throws Zend_Ldap_Exception - */ - public function search($filter, $basedn = null, $scope = self::SEARCH_SCOPE_SUB, array $attributes = array(), - $sort = null, $collectionClass = null, $sizelimit = 0, $timelimit = 0) - { - if (is_array($filter)) { - $options = array_change_key_case($filter, CASE_LOWER); - foreach ($options as $key => $value) { - switch ($key) { - case 'filter': - case 'basedn': - case 'scope': - case 'sort': - $$key = $value; - break; - case 'attributes': - if (is_array($value)) { - $attributes = $value; - } - break; - case 'collectionclass': - $collectionClass = $value; - break; - case 'sizelimit': - case 'timelimit': - $$key = (int)$value; - } - } - } - - if ($basedn === null) { - $basedn = $this->getBaseDn(); - } - else if ($basedn instanceof Zend_Ldap_Dn) { - $basedn = $basedn->toString(); - } - - if ($filter instanceof Zend_Ldap_Filter_Abstract) { - $filter = $filter->toString(); - } - - switch ($scope) { - case self::SEARCH_SCOPE_ONE: - $search = @ldap_list($this->getResource(), $basedn, $filter, $attributes, 0, $sizelimit, $timelimit); - break; - case self::SEARCH_SCOPE_BASE: - $search = @ldap_read($this->getResource(), $basedn, $filter, $attributes, 0, $sizelimit, $timelimit); - break; - case self::SEARCH_SCOPE_SUB: - default: - $search = @ldap_search($this->getResource(), $basedn, $filter, $attributes, 0, $sizelimit, $timelimit); - break; - } - - if($search === false) { - /** - * @see Zend_Ldap_Exception - */ - #require_once 'Zend/Ldap/Exception.php'; - throw new Zend_Ldap_Exception($this, 'searching: ' . $filter); - } - if ($sort !== null && is_string($sort)) { - $isSorted = @ldap_sort($this->getResource(), $search, $sort); - if($isSorted === false) { - /** - * @see Zend_Ldap_Exception - */ - #require_once 'Zend/Ldap/Exception.php'; - throw new Zend_Ldap_Exception($this, 'sorting: ' . $sort); - } - } - - /** - * Zend_Ldap_Collection_Iterator_Default - */ - #require_once 'Zend/Ldap/Collection/Iterator/Default.php'; - $iterator = new Zend_Ldap_Collection_Iterator_Default($this, $search); - return $this->_createCollection($iterator, $collectionClass); - } - - /** - * Extension point for collection creation - * - * @param Zend_Ldap_Collection_Iterator_Default $iterator - * @param string|null $collectionClass - * @return Zend_Ldap_Collection - * @throws Zend_Ldap_Exception - */ - protected function _createCollection(Zend_Ldap_Collection_Iterator_Default $iterator, $collectionClass) - { - if ($collectionClass === null) { - /** - * Zend_Ldap_Collection - */ - #require_once 'Zend/Ldap/Collection.php'; - return new Zend_Ldap_Collection($iterator); - } else { - $collectionClass = (string)$collectionClass; - if (!class_exists($collectionClass)) { - /** - * @see Zend_Ldap_Exception - */ - #require_once 'Zend/Ldap/Exception.php'; - throw new Zend_Ldap_Exception(null, - "Class '$collectionClass' can not be found"); - } - if (!is_subclass_of($collectionClass, 'Zend_Ldap_Collection')) { - /** - * @see Zend_Ldap_Exception - */ - #require_once 'Zend/Ldap/Exception.php'; - throw new Zend_Ldap_Exception(null, - "Class '$collectionClass' must subclass 'Zend_Ldap_Collection'"); - } - return new $collectionClass($iterator); - } - } - - /** - * Count items found by given filter. - * - * @param string|Zend_Ldap_Filter_Abstract $filter - * @param string|Zend_Ldap_Dn|null $basedn - * @param integer $scope - * @return integer - * @throws Zend_Ldap_Exception - */ - public function count($filter, $basedn = null, $scope = self::SEARCH_SCOPE_SUB) - { - try { - $result = $this->search($filter, $basedn, $scope, array('dn'), null); - } catch (Zend_Ldap_Exception $e) { - if ($e->getCode() === Zend_Ldap_Exception::LDAP_NO_SUCH_OBJECT) return 0; - else throw $e; - } - return $result->count(); - } - - /** - * Count children for a given DN. - * - * @param string|Zend_Ldap_Dn $dn - * @return integer - * @throws Zend_Ldap_Exception - */ - public function countChildren($dn) - { - return $this->count('(objectClass=*)', $dn, self::SEARCH_SCOPE_ONE); - } - - /** - * Check if a given DN exists. - * - * @param string|Zend_Ldap_Dn $dn - * @return boolean - * @throws Zend_Ldap_Exception - */ - public function exists($dn) - { - return ($this->count('(objectClass=*)', $dn, self::SEARCH_SCOPE_BASE) == 1); - } - - /** - * Search LDAP registry for entries matching filter and optional attributes - * - * Options can be either passed as single parameters according to the - * method signature or as an array with one or more of the following keys - * - filter - * - baseDn - * - scope - * - attributes - * - sort - * - reverseSort - * - sizelimit - * - timelimit - * - * @param string|Zend_Ldap_Filter_Abstract|array $filter - * @param string|Zend_Ldap_Dn|null $basedn - * @param integer $scope - * @param array $attributes - * @param string|null $sort - * @param boolean $reverseSort - * @param integer $sizelimit - * @param integer $timelimit - * @return array - * @throws Zend_Ldap_Exception - */ - public function searchEntries($filter, $basedn = null, $scope = self::SEARCH_SCOPE_SUB, - array $attributes = array(), $sort = null, $reverseSort = false, $sizelimit = 0, $timelimit = 0) - { - if (is_array($filter)) { - $filter = array_change_key_case($filter, CASE_LOWER); - if (isset($filter['collectionclass'])) { - unset($filter['collectionclass']); - } - if (isset($filter['reversesort'])) { - $reverseSort = $filter['reversesort']; - unset($filter['reversesort']); - } - } - $result = $this->search($filter, $basedn, $scope, $attributes, $sort, null, $sizelimit, $timelimit); - $items = $result->toArray(); - if ((bool)$reverseSort === true) { - $items = array_reverse($items, false); - } - return $items; - } - - /** - * Get LDAP entry by DN - * - * @param string|Zend_Ldap_Dn $dn - * @param array $attributes - * @param boolean $throwOnNotFound - * @return array - * @throws Zend_Ldap_Exception - */ - public function getEntry($dn, array $attributes = array(), $throwOnNotFound = false) - { - try { - $result = $this->search("(objectClass=*)", $dn, self::SEARCH_SCOPE_BASE, - $attributes, null); - return $result->getFirst(); - } catch (Zend_Ldap_Exception $e){ - if ($throwOnNotFound !== false) throw $e; - } - return null; - } - - /** - * Prepares an ldap data entry array for insert/update operation - * - * @param array $entry - * @return void - * @throws InvalidArgumentException - */ - public static function prepareLdapEntryArray(array &$entry) - { - if (array_key_exists('dn', $entry)) unset($entry['dn']); - foreach ($entry as $key => $value) { - if (is_array($value)) { - foreach ($value as $i => $v) { - if ($v === null) unset($value[$i]); - else if (!is_scalar($v)) { - throw new InvalidArgumentException('Only scalar values allowed in LDAP data'); - } else { - $v = (string)$v; - if (strlen($v) == 0) { - unset($value[$i]); - } else { - $value[$i] = $v; - } - } - } - $entry[$key] = array_values($value); - } else { - if ($value === null) $entry[$key] = array(); - else if (!is_scalar($value)) { - throw new InvalidArgumentException('Only scalar values allowed in LDAP data'); - } else { - $value = (string)$value; - if (strlen($value) == 0) { - $entry[$key] = array(); - } else { - $entry[$key] = array($value); - } - } - } - } - $entry = array_change_key_case($entry, CASE_LOWER); - } - - /** - * Add new information to the LDAP repository - * - * @param string|Zend_Ldap_Dn $dn - * @param array $entry - * @return Zend_Ldap Provides a fluent interface - * @throws Zend_Ldap_Exception - */ - public function add($dn, array $entry) - { - if (!($dn instanceof Zend_Ldap_Dn)) { - $dn = Zend_Ldap_Dn::factory($dn, null); - } - self::prepareLdapEntryArray($entry); - foreach ($entry as $key => $value) { - if (is_array($value) && count($value) === 0) { - unset($entry[$key]); - } - } - - $rdnParts = $dn->getRdn(Zend_Ldap_Dn::ATTR_CASEFOLD_LOWER); - foreach ($rdnParts as $key => $value) { - $value = Zend_Ldap_Dn::unescapeValue($value); - if (!array_key_exists($key, $entry)) { - $entry[$key] = array($value); - } else if (!in_array($value, $entry[$key])) { - $entry[$key] = array_merge(array($value), $entry[$key]); - } - } - $adAttributes = array('distinguishedname', 'instancetype', 'name', 'objectcategory', - 'objectguid', 'usnchanged', 'usncreated', 'whenchanged', 'whencreated'); - foreach ($adAttributes as $attr) { - if (array_key_exists($attr, $entry)) { - unset($entry[$attr]); - } - } - - $isAdded = @ldap_add($this->getResource(), $dn->toString(), $entry); - if($isAdded === false) { - /** - * @see Zend_Ldap_Exception - */ - #require_once 'Zend/Ldap/Exception.php'; - throw new Zend_Ldap_Exception($this, 'adding: ' . $dn->toString()); - } - return $this; - } - - /** - * Update LDAP registry - * - * @param string|Zend_Ldap_Dn $dn - * @param array $entry - * @return Zend_Ldap Provides a fluent interface - * @throws Zend_Ldap_Exception - */ - public function update($dn, array $entry) - { - if (!($dn instanceof Zend_Ldap_Dn)) { - $dn = Zend_Ldap_Dn::factory($dn, null); - } - self::prepareLdapEntryArray($entry); - - $rdnParts = $dn->getRdn(Zend_Ldap_Dn::ATTR_CASEFOLD_LOWER); - foreach ($rdnParts as $key => $value) { - $value = Zend_Ldap_Dn::unescapeValue($value); - if (array_key_exists($key, $entry) && !in_array($value, $entry[$key])) { - $entry[$key] = array_merge(array($value), $entry[$key]); - } - } - - $adAttributes = array('distinguishedname', 'instancetype', 'name', 'objectcategory', - 'objectguid', 'usnchanged', 'usncreated', 'whenchanged', 'whencreated'); - foreach ($adAttributes as $attr) { - if (array_key_exists($attr, $entry)) { - unset($entry[$attr]); - } - } - - if (count($entry) > 0) { - $isModified = @ldap_modify($this->getResource(), $dn->toString(), $entry); - if($isModified === false) { - /** - * @see Zend_Ldap_Exception - */ - #require_once 'Zend/Ldap/Exception.php'; - throw new Zend_Ldap_Exception($this, 'updating: ' . $dn->toString()); - } - } - return $this; - } - - /** - * Save entry to LDAP registry. - * - * Internally decides if entry will be updated to added by calling - * {@link exists()}. - * - * @param string|Zend_Ldap_Dn $dn - * @param array $entry - * @return Zend_Ldap Provides a fluent interface - * @throws Zend_Ldap_Exception - */ - public function save($dn, array $entry) - { - if ($dn instanceof Zend_Ldap_Dn) { - $dn = $dn->toString(); - } - if ($this->exists($dn)) $this->update($dn, $entry); - else $this->add($dn, $entry); - return $this; - } - - /** - * Delete an LDAP entry - * - * @param string|Zend_Ldap_Dn $dn - * @param boolean $recursively - * @return Zend_Ldap Provides a fluent interface - * @throws Zend_Ldap_Exception - */ - public function delete($dn, $recursively = false) - { - if ($dn instanceof Zend_Ldap_Dn) { - $dn = $dn->toString(); - } - if ($recursively === true) { - if ($this->countChildren($dn)>0) { - $children = $this->_getChildrenDns($dn); - foreach ($children as $c) { - $this->delete($c, true); - } - } - } - $isDeleted = @ldap_delete($this->getResource(), $dn); - if($isDeleted === false) { - /** - * @see Zend_Ldap_Exception - */ - #require_once 'Zend/Ldap/Exception.php'; - throw new Zend_Ldap_Exception($this, 'deleting: ' . $dn); - } - return $this; - } - - /** - * Retrieve the immediate children DNs of the given $parentDn - * - * This method is used in recursive methods like {@see delete()} - * or {@see copy()} - * - * @param string|Zend_Ldap_Dn $parentDn - * @return array of DNs - */ - protected function _getChildrenDns($parentDn) - { - if ($parentDn instanceof Zend_Ldap_Dn) { - $parentDn = $parentDn->toString(); - } - $children = array(); - $search = @ldap_list($this->getResource(), $parentDn, '(objectClass=*)', array('dn')); - for ($entry = @ldap_first_entry($this->getResource(), $search); - $entry !== false; - $entry = @ldap_next_entry($this->getResource(), $entry)) { - $childDn = @ldap_get_dn($this->getResource(), $entry); - if ($childDn === false) { - /** - * @see Zend_Ldap_Exception - */ - #require_once 'Zend/Ldap/Exception.php'; - throw new Zend_Ldap_Exception($this, 'getting dn'); - } - $children[] = $childDn; - } - @ldap_free_result($search); - return $children; - } - - /** - * Moves a LDAP entry from one DN to another subtree. - * - * @param string|Zend_Ldap_Dn $from - * @param string|Zend_Ldap_Dn $to - * @param boolean $recursively - * @param boolean $alwaysEmulate - * @return Zend_Ldap Provides a fluent interface - * @throws Zend_Ldap_Exception - */ - public function moveToSubtree($from, $to, $recursively = false, $alwaysEmulate = false) - { - if ($from instanceof Zend_Ldap_Dn) { - $orgDnParts = $from->toArray(); - } else { - $orgDnParts = Zend_Ldap_Dn::explodeDn($from); - } - - if ($to instanceof Zend_Ldap_Dn) { - $newParentDnParts = $to->toArray(); - } else { - $newParentDnParts = Zend_Ldap_Dn::explodeDn($to); - } - - $newDnParts = array_merge(array(array_shift($orgDnParts)), $newParentDnParts); - $newDn = Zend_Ldap_Dn::fromArray($newDnParts); - return $this->rename($from, $newDn, $recursively, $alwaysEmulate); - } - - /** - * Moves a LDAP entry from one DN to another DN. - * - * This is an alias for {@link rename()} - * - * @param string|Zend_Ldap_Dn $from - * @param string|Zend_Ldap_Dn $to - * @param boolean $recursively - * @param boolean $alwaysEmulate - * @return Zend_Ldap Provides a fluent interface - * @throws Zend_Ldap_Exception - */ - public function move($from, $to, $recursively = false, $alwaysEmulate = false) - { - return $this->rename($from, $to, $recursively, $alwaysEmulate); - } - - /** - * Renames a LDAP entry from one DN to another DN. - * - * This method implicitely moves the entry to another location within the tree. - * - * @param string|Zend_Ldap_Dn $from - * @param string|Zend_Ldap_Dn $to - * @param boolean $recursively - * @param boolean $alwaysEmulate - * @return Zend_Ldap Provides a fluent interface - * @throws Zend_Ldap_Exception - */ - public function rename($from, $to, $recursively = false, $alwaysEmulate = false) - { - $emulate = (bool)$alwaysEmulate; - if (!function_exists('ldap_rename')) $emulate = true; - else if ($recursively) $emulate = true; - - if ($emulate === false) { - if ($from instanceof Zend_Ldap_Dn) { - $from = $from->toString(); - } - - if ($to instanceof Zend_Ldap_Dn) { - $newDnParts = $to->toArray(); - } else { - $newDnParts = Zend_Ldap_Dn::explodeDn($to); - } - - $newRdn = Zend_Ldap_Dn::implodeRdn(array_shift($newDnParts)); - $newParent = Zend_Ldap_Dn::implodeDn($newDnParts); - $isOK = @ldap_rename($this->getResource(), $from, $newRdn, $newParent, true); - if($isOK === false) { - /** - * @see Zend_Ldap_Exception - */ - #require_once 'Zend/Ldap/Exception.php'; - throw new Zend_Ldap_Exception($this, 'renaming ' . $from . ' to ' . $to); - } - else if (!$this->exists($to)) $emulate = true; - } - if ($emulate) { - $this->copy($from, $to, $recursively); - $this->delete($from, $recursively); - } - return $this; - } - - /** - * Copies a LDAP entry from one DN to another subtree. - * - * @param string|Zend_Ldap_Dn $from - * @param string|Zend_Ldap_Dn $to - * @param boolean $recursively - * @return Zend_Ldap Provides a fluent interface - * @throws Zend_Ldap_Exception - */ - public function copyToSubtree($from, $to, $recursively = false) - { - if ($from instanceof Zend_Ldap_Dn) { - $orgDnParts = $from->toArray(); - } else { - $orgDnParts = Zend_Ldap_Dn::explodeDn($from); - } - - if ($to instanceof Zend_Ldap_Dn) { - $newParentDnParts = $to->toArray(); - } else { - $newParentDnParts = Zend_Ldap_Dn::explodeDn($to); - } - - $newDnParts = array_merge(array(array_shift($orgDnParts)), $newParentDnParts); - $newDn = Zend_Ldap_Dn::fromArray($newDnParts); - return $this->copy($from, $newDn, $recursively); - } - - /** - * Copies a LDAP entry from one DN to another DN. - * - * @param string|Zend_Ldap_Dn $from - * @param string|Zend_Ldap_Dn $to - * @param boolean $recursively - * @return Zend_Ldap Provides a fluent interface - * @throws Zend_Ldap_Exception - */ - public function copy($from, $to, $recursively = false) - { - $entry = $this->getEntry($from, array(), true); - - if ($to instanceof Zend_Ldap_Dn) { - $toDnParts = $to->toArray(); - } else { - $toDnParts = Zend_Ldap_Dn::explodeDn($to); - } - $this->add($to, $entry); - - if ($recursively === true && $this->countChildren($from)>0) { - $children = $this->_getChildrenDns($from); - foreach ($children as $c) { - $cDnParts = Zend_Ldap_Dn::explodeDn($c); - $newChildParts = array_merge(array(array_shift($cDnParts)), $toDnParts); - $newChild = Zend_Ldap_Dn::implodeDn($newChildParts); - $this->copy($c, $newChild, true); - } - } - return $this; - } - - /** - * Returns the specified DN as a Zend_Ldap_Node - * - * @param string|Zend_Ldap_Dn $dn - * @return Zend_Ldap_Node|null - * @throws Zend_Ldap_Exception - */ - public function getNode($dn) - { - /** - * Zend_Ldap_Node - */ - #require_once 'Zend/Ldap/Node.php'; - return Zend_Ldap_Node::fromLdap($dn, $this); - } - - /** - * Returns the base node as a Zend_Ldap_Node - * - * @return Zend_Ldap_Node - * @throws Zend_Ldap_Exception - */ - public function getBaseNode() - { - return $this->getNode($this->getBaseDn(), $this); - } - - /** - * Returns the RootDSE - * - * @return Zend_Ldap_Node_RootDse - * @throws Zend_Ldap_Exception - */ - public function getRootDse() - { - if ($this->_rootDse === null) { - /** - * @see Zend_Ldap_Node_Schema - */ - #require_once 'Zend/Ldap/Node/RootDse.php'; - $this->_rootDse = Zend_Ldap_Node_RootDse::create($this); - } - return $this->_rootDse; - } - - /** - * Returns the schema - * - * @return Zend_Ldap_Node_Schema - * @throws Zend_Ldap_Exception - */ - public function getSchema() - { - if ($this->_schema === null) { - /** - * @see Zend_Ldap_Node_Schema - */ - #require_once 'Zend/Ldap/Node/Schema.php'; - $this->_schema = Zend_Ldap_Node_Schema::create($this); - } - return $this->_schema; - } -} diff --git a/library/Zend/Ldap/Attribute.php b/library/Zend/Ldap/Attribute.php deleted file mode 100644 index e8c8961c94..0000000000 --- a/library/Zend/Ldap/Attribute.php +++ /dev/null @@ -1,420 +0,0 @@ -= 0 && $indexformat('U'); - } else if (is_string($value)) { - try { - return Zend_Ldap_Converter::fromLdapDateTime($value, false)->format('U'); - } catch (InvalidArgumentException $e) { - return null; - } - } else return null; - } -} diff --git a/library/Zend/Ldap/Collection.php b/library/Zend/Ldap/Collection.php deleted file mode 100644 index f23c4cebc4..0000000000 --- a/library/Zend/Ldap/Collection.php +++ /dev/null @@ -1,239 +0,0 @@ -_iterator = $iterator; - } - - public function __destruct() - { - $this->close(); - } - - /** - * Closes the current result set - * - * @return boolean - */ - public function close() - { - return $this->_iterator->close(); - } - - /** - * Get all entries as an array - * - * @return array - */ - public function toArray() - { - $data = array(); - foreach ($this as $item) { - $data[] = $item; - } - return $data; - } - - /** - * Get first entry - * - * @return array - */ - public function getFirst() - { - if ($this->count() > 0) { - $this->rewind(); - return $this->current(); - } else { - return null; - } - } - - /** - * Returns the underlying iterator - * - * @return Zend_Ldap_Collection_Iterator_Default - */ - public function getInnerIterator() - { - return $this->_iterator; - } - - /** - * Returns the number of items in current result - * Implements Countable - * - * @return int - */ - public function count() - { - return $this->_iterator->count(); - } - - /** - * Return the current result item - * Implements Iterator - * - * @return array|null - * @throws Zend_Ldap_Exception - */ - public function current() - { - if ($this->count() > 0) { - if ($this->_current < 0) { - $this->rewind(); - } - if (!array_key_exists($this->_current, $this->_cache)) { - $current = $this->_iterator->current(); - if ($current === null) { - return null; - } - $this->_cache[$this->_current] = $this->_createEntry($current); - } - return $this->_cache[$this->_current]; - } else { - return null; - } - } - - /** - * Creates the data structure for the given entry data - * - * @param array $data - * @return array - */ - protected function _createEntry(array $data) - { - return $data; - } - - /** - * Return the current result item DN - * - * @return string|null - */ - public function dn() - { - if ($this->count() > 0) { - if ($this->_current < 0) { - $this->rewind(); - } - return $this->_iterator->key(); - } else { - return null; - } - } - - /** - * Return the current result item key - * Implements Iterator - * - * @return int|null - */ - public function key() - { - if ($this->count() > 0) { - if ($this->_current < 0) { - $this->rewind(); - } - return $this->_current; - } else { - return null; - } - } - - /** - * Move forward to next result item - * Implements Iterator - * - * @throws Zend_Ldap_Exception - */ - public function next() - { - $this->_iterator->next(); - $this->_current++; - } - - /** - * Rewind the Iterator to the first result item - * Implements Iterator - * - * @throws Zend_Ldap_Exception - */ - public function rewind() - { - $this->_iterator->rewind(); - $this->_current = 0; - } - - /** - * Check if there is a current result item - * after calls to rewind() or next() - * Implements Iterator - * - * @return boolean - */ - public function valid() - { - if (isset($this->_cache[$this->_current])) { - return true; - } else { - return $this->_iterator->valid(); - } - } -} diff --git a/library/Zend/Ldap/Collection/Iterator/Default.php b/library/Zend/Ldap/Collection/Iterator/Default.php deleted file mode 100644 index e9b1b08422..0000000000 --- a/library/Zend/Ldap/Collection/Iterator/Default.php +++ /dev/null @@ -1,312 +0,0 @@ -_ldap = $ldap; - $this->_resultId = $resultId; - $this->_itemCount = @ldap_count_entries($ldap->getResource(), $resultId); - if ($this->_itemCount === false) { - /** - * @see Zend_Ldap_Exception - */ - #require_once 'Zend/Ldap/Exception.php'; - throw new Zend_Ldap_Exception($this->_ldap, 'counting entries'); - } - } - - public function __destruct() - { - $this->close(); - } - - /** - * Closes the current result set - * - * @return bool - */ - public function close() - { - $isClosed = false; - if (is_resource($this->_resultId)) { - $isClosed = @ldap_free_result($this->_resultId); - $this->_resultId = null; - $this->_current = null; - } - return $isClosed; - } - - /** - * Gets the current LDAP connection. - * - * @return Zend_Ldap - */ - public function getLdap() - { - return $this->_ldap; - } - - /** - * Sets the attribute name treatment. - * - * Can either be one of the following constants - * - Zend_Ldap_Collection_Iterator_Default::ATTRIBUTE_TO_LOWER - * - Zend_Ldap_Collection_Iterator_Default::ATTRIBUTE_TO_UPPER - * - Zend_Ldap_Collection_Iterator_Default::ATTRIBUTE_NATIVE - * or a valid callback accepting the attribute's name as it's only - * argument and returning the new attribute's name. - * - * @param integer|callback $attributeNameTreatment - * @return Zend_Ldap_Collection_Iterator_Default Provides a fluent interface - */ - public function setAttributeNameTreatment($attributeNameTreatment) - { - if (is_callable($attributeNameTreatment)) { - if (is_string($attributeNameTreatment) && !function_exists($attributeNameTreatment)) { - $this->_attributeNameTreatment = self::ATTRIBUTE_TO_LOWER; - } else if (is_array($attributeNameTreatment) && - !method_exists($attributeNameTreatment[0], $attributeNameTreatment[1])) { - $this->_attributeNameTreatment = self::ATTRIBUTE_TO_LOWER; - } else { - $this->_attributeNameTreatment = $attributeNameTreatment; - } - } else { - $attributeNameTreatment = (int)$attributeNameTreatment; - switch ($attributeNameTreatment) { - case self::ATTRIBUTE_TO_LOWER: - case self::ATTRIBUTE_TO_UPPER: - case self::ATTRIBUTE_NATIVE: - $this->_attributeNameTreatment = $attributeNameTreatment; - break; - default: - $this->_attributeNameTreatment = self::ATTRIBUTE_TO_LOWER; - break; - } - } - return $this; - } - - /** - * Returns the currently set attribute name treatment - * - * @return integer|callback - */ - public function getAttributeNameTreatment() - { - return $this->_attributeNameTreatment; - } - - /** - * Returns the number of items in current result - * Implements Countable - * - * @return int - */ - public function count() - { - return $this->_itemCount; - } - - /** - * Return the current result item - * Implements Iterator - * - * @return array|null - * @throws Zend_Ldap_Exception - */ - public function current() - { - if (!is_resource($this->_current)) { - $this->rewind(); - } - if (!is_resource($this->_current)) { - return null; - } - - $entry = array('dn' => $this->key()); - $ber_identifier = null; - $name = @ldap_first_attribute($this->_ldap->getResource(), $this->_current, - $ber_identifier); - while ($name) { - $data = @ldap_get_values_len($this->_ldap->getResource(), $this->_current, $name); - unset($data['count']); - - switch($this->_attributeNameTreatment) { - case self::ATTRIBUTE_TO_LOWER: - $attrName = strtolower($name); - break; - case self::ATTRIBUTE_TO_UPPER: - $attrName = strtoupper($name); - break; - case self::ATTRIBUTE_NATIVE: - $attrName = $name; - break; - default: - $attrName = call_user_func($this->_attributeNameTreatment, $name); - break; - } - $entry[$attrName] = $data; - $name = @ldap_next_attribute($this->_ldap->getResource(), $this->_current, - $ber_identifier); - } - ksort($entry, SORT_LOCALE_STRING); - return $entry; - } - - /** - * Return the result item key - * Implements Iterator - * - * @return string|null - */ - public function key() - { - if (!is_resource($this->_current)) { - $this->rewind(); - } - if (is_resource($this->_current)) { - $currentDn = @ldap_get_dn($this->_ldap->getResource(), $this->_current); - if ($currentDn === false) { - /** @see Zend_Ldap_Exception */ - #require_once 'Zend/Ldap/Exception.php'; - throw new Zend_Ldap_Exception($this->_ldap, 'getting dn'); - } - return $currentDn; - } else { - return null; - } - } - - /** - * Move forward to next result item - * Implements Iterator - * - * @throws Zend_Ldap_Exception - */ - public function next() - { - if (is_resource($this->_current) && $this->_itemCount > 0) { - $this->_current = @ldap_next_entry($this->_ldap->getResource(), $this->_current); - /** @see Zend_Ldap_Exception */ - #require_once 'Zend/Ldap/Exception.php'; - if ($this->_current === false) { - $msg = $this->_ldap->getLastError($code); - if ($code === Zend_Ldap_Exception::LDAP_SIZELIMIT_EXCEEDED) { - // we have reached the size limit enforced by the server - return; - } else if ($code > Zend_Ldap_Exception::LDAP_SUCCESS) { - throw new Zend_Ldap_Exception($this->_ldap, 'getting next entry (' . $msg . ')'); - } - } - } else { - $this->_current = false; - } - } - - /** - * Rewind the Iterator to the first result item - * Implements Iterator - * - * @throws Zend_Ldap_Exception - */ - public function rewind() - { - if (is_resource($this->_resultId)) { - $this->_current = @ldap_first_entry($this->_ldap->getResource(), $this->_resultId); - /** @see Zend_Ldap_Exception */ - #require_once 'Zend/Ldap/Exception.php'; - if ($this->_current === false && - $this->_ldap->getLastErrorCode() > Zend_Ldap_Exception::LDAP_SUCCESS) { - throw new Zend_Ldap_Exception($this->_ldap, 'getting first entry'); - } - } - } - - /** - * Check if there is a current result item - * after calls to rewind() or next() - * Implements Iterator - * - * @return boolean - */ - public function valid() - { - return (is_resource($this->_current)); - } - -} diff --git a/library/Zend/Ldap/Converter.php b/library/Zend/Ldap/Converter.php deleted file mode 100644 index e8677e1f16..0000000000 --- a/library/Zend/Ldap/Converter.php +++ /dev/null @@ -1,410 +0,0 @@ - - * @link http://pear.php.net/package/Net_LDAP2 - * @author Benedikt Hallinger - * - * @param string $string String to convert - * @return string - */ - public static function ascToHex32($string) - { - for ($i = 0; $i, - * heavily based on work from DavidSmith@byu.net - * @link http://pear.php.net/package/Net_LDAP2 - * @author Benedikt Hallinger , heavily based on work from DavidSmith@byu.net - * - * @param string $string String to convert - * @return string - */ - public static function hex32ToAsc($string) - { - // Using a callback, since PHP 5.5 has deprecated the /e modifier in preg_replace. - $string = preg_replace_callback("/\\\([0-9A-Fa-f]{2})/", array('Zend_Ldap_Converter', '_charHex32ToAsc'), $string); - return $string; - } - - /** - * Convert a single slash-prefixed character from Hex32 to ASCII. - * Used as a callback in @see hex32ToAsc() - * @param array $matches - * - * @return string - */ - private static function _charHex32ToAsc(array $matches) - { - return chr(hexdec($matches[0])); - } - - /** - * Convert any value to an LDAP-compatible value. - * - * By setting the $type-parameter the conversion of a certain - * type can be forced - * - * @todo write more tests - * - * @param mixed $value The value to convert - * @param int $ytpe The conversion type to use - * @return string - * @throws Zend_Ldap_Converter_Exception - */ - public static function toLdap($value, $type = self::STANDARD) - { - try { - switch ($type) { - case self::BOOLEAN: - return self::toldapBoolean($value); - break; - case self::GENERALIZED_TIME: - return self::toLdapDatetime($value); - break; - default: - if (is_string($value)) { - return $value; - } else if (is_int($value) || is_float($value)) { - return (string)$value; - } else if (is_bool($value)) { - return self::toldapBoolean($value); - } else if (is_object($value)) { - if ($value instanceof DateTime) { - return self::toLdapDatetime($value); - } else if ($value instanceof Zend_Date) { - return self::toLdapDatetime($value); - } else { - return self::toLdapSerialize($value); - } - } else if (is_array($value)) { - return self::toLdapSerialize($value); - } else if (is_resource($value) && get_resource_type($value) === 'stream') { - return stream_get_contents($value); - } else { - return null; - } - break; - } - } catch (Exception $e) { - throw new Zend_Ldap_Converter_Exception($e->getMessage(), $e->getCode(), $e); - } - } - - /** - * Converts a date-entity to an LDAP-compatible date-string - * - * The date-entity $date can be either a timestamp, a - * DateTime Object, a string that is parseable by strtotime() or a Zend_Date - * Object. - * - * @param integer|string|DateTimt|Zend_Date $date The date-entity - * @param boolean $asUtc Whether to return the LDAP-compatible date-string - * as UTC or as local value - * @return string - * @throws InvalidArgumentException - */ - public static function toLdapDateTime($date, $asUtc = true) - { - if (!($date instanceof DateTime)) { - if (is_int($date)) { - $date = new DateTime('@' . $date); - $date->setTimezone(new DateTimeZone(date_default_timezone_get())); - } else if (is_string($date)) { - $date = new DateTime($date); - } else if ($date instanceof Zend_Date) { - $date = new DateTime($date->get(Zend_Date::ISO_8601)); - } else { - throw new InvalidArgumentException('Parameter $date is not of the expected type'); - } - } - $timezone = $date->format('O'); - if (true === $asUtc) { - $date->setTimezone(new DateTimeZone('UTC')); - $timezone = 'Z'; - } - if ( '+0000' === $timezone ) { - $timezone = 'Z'; - } - return $date->format('YmdHis') . $timezone; - } - - /** - * Convert a boolean value to an LDAP-compatible string - * - * This converts a boolean value of TRUE, an integer-value of 1 and a - * case-insensitive string 'true' to an LDAP-compatible 'TRUE'. All other - * other values are converted to an LDAP-compatible 'FALSE'. - * - * @param boolean|integer|string $value The boolean value to encode - * @return string - */ - public static function toLdapBoolean($value) - { - $return = 'FALSE'; - if (!is_scalar($value)) { - return $return; - } - if (true === $value || 'true' === strtolower($value) || 1 === $value) { - $return = 'TRUE'; - } - return $return; - } - - /** - * Serialize any value for storage in LDAP - * - * @param mixed $value The value to serialize - * @return string - */ - public static function toLdapSerialize($value) - { - return serialize($value); - } - - /** - * Convert an LDAP-compatible value to a corresponding PHP-value. - * - * By setting the $type-parameter the conversion of a certain - * type can be forced - * . - * @param string $value The value to convert - * @param int $ytpe The conversion type to use - * @param boolean $dateTimeAsUtc Return DateTime values in UTC timezone - * @return mixed - * @throws Zend_Ldap_Converter_Exception - */ - public static function fromLdap($value, $type = self::STANDARD, $dateTimeAsUtc = true) - { - switch ($type) { - case self::BOOLEAN: - return self::fromldapBoolean($value); - break; - case self::GENERALIZED_TIME: - return self::fromLdapDateTime($value); - break; - default: - if (is_numeric($value)) { - // prevent numeric values to be treated as date/time - return $value; - } else if ('TRUE' === $value || 'FALSE' === $value) { - return self::fromLdapBoolean($value); - } - if (preg_match('/^\d{4}[\d\+\-Z\.]*$/', $value)) { - return self::fromLdapDateTime($value, $dateTimeAsUtc); - } - try { - return self::fromLdapUnserialize($value); - } catch (UnexpectedValueException $e) { } - break; - } - return $value; - } - - /** - * Convert an LDAP-Generalized-Time-entry into a DateTime-Object - * - * CAVEAT: The DateTime-Object returned will alwasy be set to UTC-Timezone. - * - * @param string $date The generalized-Time - * @param boolean $asUtc Return the DateTime with UTC timezone - * @return DateTime - * @throws InvalidArgumentException if a non-parseable-format is given - */ - public static function fromLdapDateTime($date, $asUtc = true) - { - $datepart = array (); - if (!preg_match('/^(\d{4})/', $date, $datepart) ) { - throw new InvalidArgumentException('Invalid date format found'); - } - - if ($datepart[1] < 4) { - throw new InvalidArgumentException('Invalid date format found (too short)'); - } - - $time = array ( - // The year is mandatory! - 'year' => $datepart[1], - 'month' => 1, - 'day' => 1, - 'hour' => 0, - 'minute' => 0, - 'second' => 0, - 'offdir' => '+', - 'offsethours' => 0, - 'offsetminutes' => 0 - ); - - $length = strlen($date); - - // Check for month. - if ($length >= 6) { - $month = substr($date, 4, 2); - if ($month < 1 || $month > 12) { - throw new InvalidArgumentException('Invalid date format found (invalid month)'); - } - $time['month'] = $month; - } - - // Check for day - if ($length >= 8) { - $day = substr($date, 6, 2); - if ($day < 1 || $day > 31) { - throw new InvalidArgumentException('Invalid date format found (invalid day)'); - } - $time['day'] = $day; - } - - // Check for Hour - if ($length >= 10) { - $hour = substr($date, 8, 2); - if ($hour < 0 || $hour > 23) { - throw new InvalidArgumentException('Invalid date format found (invalid hour)'); - } - $time['hour'] = $hour; - } - - // Check for minute - if ($length >= 12) { - $minute = substr($date, 10, 2); - if ($minute < 0 || $minute > 59) { - throw new InvalidArgumentException('Invalid date format found (invalid minute)'); - } - $time['minute'] = $minute; - } - - // Check for seconds - if ($length >= 14) { - $second = substr($date, 12, 2); - if ($second < 0 || $second > 59) { - throw new InvalidArgumentException('Invalid date format found (invalid second)'); - } - $time['second'] = $second; - } - - // Set Offset - $offsetRegEx = '/([Z\-\+])(\d{2}\'?){0,1}(\d{2}\'?){0,1}$/'; - $off = array (); - if (preg_match($offsetRegEx, $date, $off)) { - $offset = $off[1]; - if ($offset == '+' || $offset == '-') { - $time['offdir'] = $offset; - // we have an offset, so lets calculate it. - if (isset($off[2])) { - $offsetHours = substr($off[2], 0, 2); - if ($offsetHours < 0 || $offsetHours > 12) { - throw new InvalidArgumentException('Invalid date format found (invalid offset hour)'); - } - $time['offsethours'] = $offsetHours; - } - if (isset($off[3])) { - $offsetMinutes = substr($off[3], 0, 2); - if ($offsetMinutes < 0 || $offsetMinutes > 59) { - throw new InvalidArgumentException('Invalid date format found (invalid offset minute)'); - } - $time['offsetminutes'] = $offsetMinutes; - } - } - } - - // Raw-Data is present, so lets create a DateTime-Object from it. - $offset = $time['offdir'] - . str_pad($time['offsethours'],2,'0',STR_PAD_LEFT) - . str_pad($time['offsetminutes'],2,'0',STR_PAD_LEFT); - $timestring = $time['year'] . '-' - . str_pad($time['month'], 2, '0', STR_PAD_LEFT) . '-' - . str_pad($time['day'], 2, '0', STR_PAD_LEFT) . ' ' - . str_pad($time['hour'], 2, '0', STR_PAD_LEFT) . ':' - . str_pad($time['minute'], 2, '0', STR_PAD_LEFT) . ':' - . str_pad($time['second'], 2, '0', STR_PAD_LEFT) - . $time['offdir'] - . str_pad($time['offsethours'], 2, '0', STR_PAD_LEFT) - . str_pad($time['offsetminutes'], 2, '0', STR_PAD_LEFT); - $date = new DateTime($timestring); - if ($asUtc) { - $date->setTimezone(new DateTimeZone('UTC')); - } - return $date; - } - - /** - * Convert an LDAP-compatible boolean value into a PHP-compatible one - * - * @param string $value The value to convert - * @return boolean - * @throws InvalidArgumentException - */ - public static function fromLdapBoolean($value) - { - if ( 'TRUE' === $value ) { - return true; - } else if ( 'FALSE' === $value ) { - return false; - } else { - throw new InvalidArgumentException('The given value is not a boolean value'); - } - } - - /** - * Unserialize a serialized value to return the corresponding object - * - * @param string $value The value to convert - * @return mixed - * @throws UnexpectedValueException - */ - public static function fromLdapUnserialize($value) - { - $v = @unserialize($value); - if (false===$v && $value != 'b:0;') { - throw new UnexpectedValueException('The given value could not be unserialized'); - } - return $v; - } -} diff --git a/library/Zend/Ldap/Converter/Exception.php b/library/Zend/Ldap/Converter/Exception.php deleted file mode 100644 index 57ce69df3d..0000000000 --- a/library/Zend/Ldap/Converter/Exception.php +++ /dev/null @@ -1,35 +0,0 @@ -_dn = $dn; - $this->setCaseFold($caseFold); - } - - /** - * Gets the RDN of the current DN - * - * @param string $caseFold - * @return array - * @throws Zend_Ldap_Exception if DN has no RDN (empty array) - */ - public function getRdn($caseFold = null) - { - $caseFold = self::_sanitizeCaseFold($caseFold, $this->_caseFold); - return self::_caseFoldRdn($this->get(0, 1, $caseFold), null); - } - - /** - * Gets the RDN of the current DN as a string - * - * @param string $caseFold - * @return string - * @throws Zend_Ldap_Exception if DN has no RDN (empty array) - */ - public function getRdnString($caseFold = null) - { - $caseFold = self::_sanitizeCaseFold($caseFold, $this->_caseFold); - return self::implodeRdn($this->getRdn(), $caseFold); - } - - /** - * Get the parent DN $levelUp levels up the tree - * - * @param int $levelUp - * @return Zend_Ldap_Dn - */ - public function getParentDn($levelUp = 1) - { - $levelUp = (int)$levelUp; - if ($levelUp < 1 || $levelUp >= count($this->_dn)) { - /** - * Zend_Ldap_Exception - */ - #require_once 'Zend/Ldap/Exception.php'; - throw new Zend_Ldap_Exception(null, 'Cannot retrieve parent DN with given $levelUp'); - } - $newDn = array_slice($this->_dn, $levelUp); - return new self($newDn, $this->_caseFold); - } - - /** - * Get a DN part - * - * @param int $index - * @param int $length - * @param string $caseFold - * @return array - * @throws Zend_Ldap_Exception if index is illegal - */ - public function get($index, $length = 1, $caseFold = null) - { - $caseFold = self::_sanitizeCaseFold($caseFold, $this->_caseFold); - $this->_assertIndex($index); - $length = (int)$length; - if ($length <= 0) { - $length = 1; - } - if ($length === 1) { - return self::_caseFoldRdn($this->_dn[$index], $caseFold); - } - else { - return self::_caseFoldDn(array_slice($this->_dn, $index, $length, false), $caseFold); - } - } - - /** - * Set a DN part - * - * @param int $index - * @param array $value - * @return Zend_Ldap_Dn Provides a fluent interface - * @throws Zend_Ldap_Exception if index is illegal - */ - public function set($index, array $value) - { - $this->_assertIndex($index); - self::_assertRdn($value); - $this->_dn[$index] = $value; - return $this; - } - - /** - * Remove a DN part - * - * @param int $index - * @param int $length - * @return Zend_Ldap_Dn Provides a fluent interface - * @throws Zend_Ldap_Exception if index is illegal - */ - public function remove($index, $length = 1) - { - $this->_assertIndex($index); - $length = (int)$length; - if ($length <= 0) { - $length = 1; - } - array_splice($this->_dn, $index, $length, null); - return $this; - } - - /** - * Append a DN part - * - * @param array $value - * @return Zend_Ldap_Dn Provides a fluent interface - */ - public function append(array $value) - { - self::_assertRdn($value); - $this->_dn[] = $value; - return $this; - } - - /** - * Prepend a DN part - * - * @param array $value - * @return Zend_Ldap_Dn Provides a fluent interface - */ - public function prepend(array $value) - { - self::_assertRdn($value); - array_unshift($this->_dn, $value); - return $this; - } - - /** - * Insert a DN part - * - * @param int $index - * @param array $value - * @return Zend_Ldap_Dn Provides a fluent interface - * @throws Zend_Ldap_Exception if index is illegal - */ - public function insert($index, array $value) - { - $this->_assertIndex($index); - self::_assertRdn($value); - $first = array_slice($this->_dn, 0, $index + 1); - $second = array_slice($this->_dn, $index + 1); - $this->_dn = array_merge($first, array($value), $second); - return $this; - } - - /** - * Assert index is correct and usable - * - * @param mixed $index - * @return boolean - * @throws Zend_Ldap_Exception - */ - protected function _assertIndex($index) - { - if (!is_int($index)) { - /** - * Zend_Ldap_Exception - */ - #require_once 'Zend/Ldap/Exception.php'; - throw new Zend_Ldap_Exception(null, 'Parameter $index must be an integer'); - } - if ($index < 0 || $index >= count($this->_dn)) { - /** - * Zend_Ldap_Exception - */ - #require_once 'Zend/Ldap/Exception.php'; - throw new Zend_Ldap_Exception(null, 'Parameter $index out of bounds'); - } - return true; - } - - /** - * Assert if value is in a correct RDN format - * - * @param array $value - * @return boolean - * @throws Zend_Ldap_Exception - */ - protected static function _assertRdn(array $value) - { - if (count($value)<1) { - /** - * Zend_Ldap_Exception - */ - #require_once 'Zend/Ldap/Exception.php'; - throw new Zend_Ldap_Exception(null, 'RDN Array is malformed: it must have at least one item'); - } - - foreach (array_keys($value) as $key) { - if (!is_string($key)) { - /** - * Zend_Ldap_Exception - */ - #require_once 'Zend/Ldap/Exception.php'; - throw new Zend_Ldap_Exception(null, 'RDN Array is malformed: it must use string keys'); - } - } - } - - /** - * Sets the case fold - * - * @param string|null $caseFold - */ - public function setCaseFold($caseFold) - { - $this->_caseFold = self::_sanitizeCaseFold($caseFold, self::$_defaultCaseFold); - } - - /** - * Return DN as a string - * - * @param string $caseFold - * @return string - * @throws Zend_Ldap_Exception - */ - public function toString($caseFold = null) - { - $caseFold = self::_sanitizeCaseFold($caseFold, $this->_caseFold); - return self::implodeDn($this->_dn, $caseFold); - } - - /** - * Return DN as an array - * - * @param string $caseFold - * @return array - */ - public function toArray($caseFold = null) - { - $caseFold = self::_sanitizeCaseFold($caseFold, $this->_caseFold); - - if ($caseFold === self::ATTR_CASEFOLD_NONE) { - return $this->_dn; - } else { - return self::_caseFoldDn($this->_dn, $caseFold); - } - } - - /** - * Do a case folding on a RDN - * - * @param array $part - * @param string $caseFold - * @return array - */ - protected static function _caseFoldRdn(array $part, $caseFold) - { - switch ($caseFold) { - case self::ATTR_CASEFOLD_UPPER: - return array_change_key_case($part, CASE_UPPER); - case self::ATTR_CASEFOLD_LOWER: - return array_change_key_case($part, CASE_LOWER); - case self::ATTR_CASEFOLD_NONE: - default: - return $part; - } - } - - /** - * Do a case folding on a DN ort part of it - * - * @param array $dn - * @param string $caseFold - * @return array - */ - protected static function _caseFoldDn(array $dn, $caseFold) - { - $return = array(); - foreach ($dn as $part) { - $return[] = self::_caseFoldRdn($part, $caseFold); - } - return $return; - } - - /** - * Cast to string representation {@see toString()} - * - * @return string - */ - public function __toString() - { - return $this->toString(); - } - - /** - * Required by the ArrayAccess implementation - * - * @param int $offset - * @return boolean - */ - public function offsetExists($offset) - { - $offset = (int)$offset; - if ($offset < 0 || $offset >= count($this->_dn)) { - return false; - } else { - return true; - } - } - - /** - * Proxy to {@see get()} - * Required by the ArrayAccess implementation - * - * @param int $offset - * @return array - */ - public function offsetGet($offset) - { - return $this->get($offset, 1, null); - } - - /** - * Proxy to {@see set()} - * Required by the ArrayAccess implementation - * - * @param int $offset - * @param array $value - */ - public function offsetSet($offset, $value) - { - $this->set($offset, $value); - } - - /** - * Proxy to {@see remove()} - * Required by the ArrayAccess implementation - * - * @param int $offset - */ - public function offsetUnset($offset) - { - $this->remove($offset, 1); - } - - /** - * Sets the default case fold - * - * @param string $caseFold - */ - public static function setDefaultCaseFold($caseFold) - { - self::$_defaultCaseFold = self::_sanitizeCaseFold($caseFold, self::ATTR_CASEFOLD_NONE); - } - - /** - * Sanitizes the case fold - * - * @param string $caseFold - * @return string - */ - protected static function _sanitizeCaseFold($caseFold, $default) - { - switch ($caseFold) { - case self::ATTR_CASEFOLD_NONE: - case self::ATTR_CASEFOLD_UPPER: - case self::ATTR_CASEFOLD_LOWER: - return $caseFold; - break; - default: - return $default; - break; - } - } - - /** - * Escapes a DN value according to RFC 2253 - * - * Escapes the given VALUES according to RFC 2253 so that they can be safely used in LDAP DNs. - * The characters ",", "+", """, "\", "<", ">", ";", "#", " = " with a special meaning in RFC 2252 - * are preceeded by ba backslash. Control characters with an ASCII code < 32 are represented as \hexpair. - * Finally all leading and trailing spaces are converted to sequences of \20. - * @see Net_LDAP2_Util::escape_dn_value() from Benedikt Hallinger - * @link http://pear.php.net/package/Net_LDAP2 - * @author Benedikt Hallinger - * - * @param string|array $values An array containing the DN values that should be escaped - * @return array The array $values, but escaped - */ - public static function escapeValue($values = array()) - { - /** - * @see Zend_Ldap_Converter - */ - #require_once 'Zend/Ldap/Converter.php'; - - if (!is_array($values)) $values = array($values); - foreach ($values as $key => $val) { - // Escaping of filter meta characters - $val = str_replace(array('\\', ',', '+', '"', '<', '>', ';', '#', '=', ), - array('\\\\', '\,', '\+', '\"', '\<', '\>', '\;', '\#', '\='), $val); - $val = Zend_Ldap_Converter::ascToHex32($val); - - // Convert all leading and trailing spaces to sequences of \20. - if (preg_match('/^(\s*)(.+?)(\s*)$/', $val, $matches)) { - $val = $matches[2]; - for ($i = 0; $i - * @link http://pear.php.net/package/Net_LDAP2 - * @author Benedikt Hallinger - * - * @param string|array $values Array of DN Values - * @return array Same as $values, but unescaped - */ - public static function unescapeValue($values = array()) - { - /** - * @see Zend_Ldap_Converter - */ - #require_once 'Zend/Ldap/Converter.php'; - - if (!is_array($values)) $values = array($values); - foreach ($values as $key => $val) { - // strip slashes from special chars - $val = str_replace(array('\\\\', '\,', '\+', '\"', '\<', '\>', '\;', '\#', '\='), - array('\\', ',', '+', '"', '<', '>', ';', '#', '=', ), $val); - $values[$key] = Zend_Ldap_Converter::hex32ToAsc($val); - } - return (count($values) == 1) ? $values[0] : $values; - } - - /** - * Creates an array containing all parts of the given DN. - * - * Array will be of type - * array( - * array("cn" => "name1", "uid" => "user"), - * array("cn" => "name2"), - * array("dc" => "example"), - * array("dc" => "org") - * ) - * for a DN of cn=name1+uid=user,cn=name2,dc=example,dc=org. - * - * @param string $dn - * @param array $keys An optional array to receive DN keys (e.g. CN, OU, DC, ...) - * @param array $vals An optional array to receive DN values - * @param string $caseFold - * @return array - * @throws Zend_Ldap_Exception - */ - public static function explodeDn($dn, array &$keys = null, array &$vals = null, - $caseFold = self::ATTR_CASEFOLD_NONE) - { - $k = array(); - $v = array(); - if (!self::checkDn($dn, $k, $v, $caseFold)) { - /** - * Zend_Ldap_Exception - */ - #require_once 'Zend/Ldap/Exception.php'; - throw new Zend_Ldap_Exception(null, 'DN is malformed'); - } - $ret = array(); - for ($i = 0; $i < count($k); $i++) { - if (is_array($k[$i]) && is_array($v[$i]) && (count($k[$i]) === count($v[$i]))) { - $multi = array(); - for ($j = 0; $j < count($k[$i]); $j++) { - $key=$k[$i][$j]; - $val=$v[$i][$j]; - $multi[$key] = $val; - } - $ret[] = $multi; - } else if (is_string($k[$i]) && is_string($v[$i])) { - $ret[] = array($k[$i] => $v[$i]); - } - } - if ($keys !== null) $keys = $k; - if ($vals !== null) $vals = $v; - return $ret; - } - - /** - * @param string $dn The DN to parse - * @param array $keys An optional array to receive DN keys (e.g. CN, OU, DC, ...) - * @param array $vals An optional array to receive DN values - * @param string $caseFold - * @return boolean True if the DN was successfully parsed or false if the string is not a valid DN. - */ - public static function checkDn($dn, array &$keys = null, array &$vals = null, - $caseFold = self::ATTR_CASEFOLD_NONE) - { - /* This is a classic state machine parser. Each iteration of the - * loop processes one character. State 1 collects the key. When equals ( = ) - * is encountered the state changes to 2 where the value is collected - * until a comma (,) or semicolon (;) is encountered after which we switch back - * to state 1. If a backslash (\) is encountered, state 3 is used to collect the - * following character without engaging the logic of other states. - */ - $key = null; - $value = null; - $slen = strlen($dn); - $state = 1; - $ko = $vo = 0; - $multi = false; - $ka = array(); - $va = array(); - for ($di = 0; $di <= $slen; $di++) { - $ch = ($di == $slen) ? 0 : $dn[$di]; - switch ($state) { - case 1: // collect key - if ($ch === '=') { - $key = trim(substr($dn, $ko, $di - $ko)); - if ($caseFold == self::ATTR_CASEFOLD_LOWER) $key = strtolower($key); - else if ($caseFold == self::ATTR_CASEFOLD_UPPER) $key = strtoupper($key); - if (is_array($multi)) { - $keyId = strtolower($key); - if (in_array($keyId, $multi)) { - return false; - } - $ka[count($ka)-1][] = $key; - $multi[] = $keyId; - } else { - $ka[] = $key; - } - $state = 2; - $vo = $di + 1; - } else if ($ch === ',' || $ch === ';' || $ch === '+') { - return false; - } - break; - case 2: // collect value - if ($ch === '\\') { - $state = 3; - } else if ($ch === ',' || $ch === ';' || $ch === 0 || $ch === '+') { - $value = self::unescapeValue(trim(substr($dn, $vo, $di - $vo))); - if (is_array($multi)) { - $va[count($va)-1][] = $value; - } else { - $va[] = $value; - } - $state = 1; - $ko = $di + 1; - if ($ch === '+' && $multi === false) { - $lastKey = array_pop($ka); - $lastVal = array_pop($va); - $ka[] = array($lastKey); - $va[] = array($lastVal); - $multi = array(strtolower($lastKey)); - } else if ($ch === ','|| $ch === ';' || $ch === 0) { - $multi = false; - } - } else if ($ch === '=') { - return false; - } - break; - case 3: // escaped - $state = 2; - break; - } - } - - if ($keys !== null) { - $keys = $ka; - } - if ($vals !== null) { - $vals = $va; - } - - return ($state === 1 && $ko > 0); - } - - /** - * Returns a DN part in the form $attribute = $value - * - * This method supports the creation of multi-valued RDNs - * $part must contain an even number of elemets. - * - * @param array $attribute - * @param string $caseFold - * @return string - * @throws Zend_Ldap_Exception - */ - public static function implodeRdn(array $part, $caseFold = null) - { - self::_assertRdn($part); - $part = self::_caseFoldRdn($part, $caseFold); - $rdnParts = array(); - foreach ($part as $key => $value) { - $value = self::escapeValue($value); - $keyId = strtolower($key); - $rdnParts[$keyId] = implode('=', array($key, $value)); - } - ksort($rdnParts, SORT_STRING); - return implode('+', $rdnParts); - } - - /** - * Implodes an array in the form delivered by {@link explodeDn()} - * to a DN string. - * - * $dnArray must be of type - * array( - * array("cn" => "name1", "uid" => "user"), - * array("cn" => "name2"), - * array("dc" => "example"), - * array("dc" => "org") - * ) - * - * @param array $dnArray - * @param string $caseFold - * @param string $separator - * @return string - * @throws Zend_Ldap_Exception - */ - public static function implodeDn(array $dnArray, $caseFold = null, $separator = ',') - { - $parts = array(); - foreach ($dnArray as $p) { - $parts[] = self::implodeRdn($p, $caseFold); - } - return implode($separator, $parts); - } - - /** - * Checks if given $childDn is beneath $parentDn subtree. - * - * @param string|Zend_Ldap_Dn $childDn - * @param string|Zend_Ldap_Dn $parentDn - * @return boolean - */ - public static function isChildOf($childDn, $parentDn) - { - try { - $keys = array(); - $vals = array(); - if ($childDn instanceof Zend_Ldap_Dn) { - $cdn = $childDn->toArray(Zend_Ldap_Dn::ATTR_CASEFOLD_LOWER); - } else { - $cdn = self::explodeDn($childDn, $keys, $vals, Zend_Ldap_Dn::ATTR_CASEFOLD_LOWER); - } - if ($parentDn instanceof Zend_Ldap_Dn) { - $pdn = $parentDn->toArray(Zend_Ldap_Dn::ATTR_CASEFOLD_LOWER); - } else { - $pdn = self::explodeDn($parentDn, $keys, $vals, Zend_Ldap_Dn::ATTR_CASEFOLD_LOWER); - } - } - catch (Zend_Ldap_Exception $e) { - return false; - } - - $startIndex = count($cdn)-count($pdn); - if ($startIndex<0) return false; - for ($i = 0; $igetLastError($code, $errorMessages) . ': '; - if ($code === 0) { - $message = ''; - $code = $oldCode; - } - } - if (empty($message)) { - if ($code > 0) { - $message = '0x' . dechex($code) . ': '; - } - } - - if (!empty($str)) { - $message .= $str; - } else { - $message .= 'no exception message'; - } - - parent::__construct($message, $code); - } - - - /** - * @deprecated not necessary any more - will be removed - * @param Zend_Ldap $ldap A Zend_Ldap object - * @return int The current error code for the resource - */ - public static function getLdapCode(Zend_Ldap $ldap = null) - { - if ($ldap !== null) { - return $ldap->getLastErrorCode(); - } - return 0; - } - - /** - * @deprecated will be removed - * @return int The current error code for this exception - */ - public function getErrorCode() - { - return $this->getCode(); - } -} diff --git a/library/Zend/Ldap/Filter.php b/library/Zend/Ldap/Filter.php deleted file mode 100644 index e22bb3e8a8..0000000000 --- a/library/Zend/Ldap/Filter.php +++ /dev/null @@ -1,265 +0,0 @@ -'; - const TYPE_GREATEROREQUAL = '>='; - const TYPE_LESS = '<'; - const TYPE_LESSOREQUAL = '<='; - const TYPE_APPROX = '~='; - - /** - * Creates an 'equals' filter. - * (attr=value) - * - * @param string $attr - * @param string $value - * @return Zend_Ldap_Filter - */ - public static function equals($attr, $value) - { - return new self($attr, $value, self::TYPE_EQUALS, null, null); - } - - /** - * Creates a 'begins with' filter. - * (attr=value*) - * - * @param string $attr - * @param string $value - * @return Zend_Ldap_Filter - */ - public static function begins($attr, $value) - { - return new self($attr, $value, self::TYPE_EQUALS, null, '*'); - } - - /** - * Creates an 'ends with' filter. - * (attr=*value) - * - * @param string $attr - * @param string $value - * @return Zend_Ldap_Filter - */ - public static function ends($attr, $value) - { - return new self($attr, $value, self::TYPE_EQUALS, '*', null); - } - - /** - * Creates a 'contains' filter. - * (attr=*value*) - * - * @param string $attr - * @param string $value - * @return Zend_Ldap_Filter - */ - public static function contains($attr, $value) - { - return new self($attr, $value, self::TYPE_EQUALS, '*', '*'); - } - - /** - * Creates a 'greater' filter. - * (attr>value) - * - * @param string $attr - * @param string $value - * @return Zend_Ldap_Filter - */ - public static function greater($attr, $value) - { - return new self($attr, $value, self::TYPE_GREATER, null, null); - } - - /** - * Creates a 'greater or equal' filter. - * (attr>=value) - * - * @param string $attr - * @param string $value - * @return Zend_Ldap_Filter - */ - public static function greaterOrEqual($attr, $value) - { - return new self($attr, $value, self::TYPE_GREATEROREQUAL, null, null); - } - - /** - * Creates a 'less' filter. - * (attrtoString(); - } - - /** - * Negates the filter. - * - * @return Zend_Ldap_Filter_Abstract - */ - public function negate() - { - /** - * Zend_Ldap_Filter_Not - */ - #require_once 'Zend/Ldap/Filter/Not.php'; - return new Zend_Ldap_Filter_Not($this); - } - - /** - * Creates an 'and' filter. - * - * @param Zend_Ldap_Filter_Abstract $filter,... - * @return Zend_Ldap_Filter_And - */ - public function addAnd($filter) - { - /** - * Zend_Ldap_Filter_And - */ - #require_once 'Zend/Ldap/Filter/And.php'; - $fa = func_get_args(); - $args = array_merge(array($this), $fa); - return new Zend_Ldap_Filter_And($args); - } - - /** - * Creates an 'or' filter. - * - * @param Zend_Ldap_Filter_Abstract $filter,... - * @return Zend_Ldap_Filter_Or - */ - public function addOr($filter) - { - /** - * Zend_Ldap_Filter_Or - */ - #require_once 'Zend/Ldap/Filter/Or.php'; - $fa = func_get_args(); - $args = array_merge(array($this), $fa); - return new Zend_Ldap_Filter_Or($args); - } - - /** - * Escapes the given VALUES according to RFC 2254 so that they can be safely used in LDAP filters. - * - * Any control characters with an ACII code < 32 as well as the characters with special meaning in - * LDAP filters "*", "(", ")", and "\" (the backslash) are converted into the representation of a - * backslash followed by two hex digits representing the hexadecimal value of the character. - * @see Net_LDAP2_Util::escape_filter_value() from Benedikt Hallinger - * @link http://pear.php.net/package/Net_LDAP2 - * @author Benedikt Hallinger - * - * @param string|array $values Array of values to escape - * @return array Array $values, but escaped - */ - public static function escapeValue($values = array()) - { - /** - * @see Zend_Ldap_Converter - */ - #require_once 'Zend/Ldap/Converter.php'; - - if (!is_array($values)) $values = array($values); - foreach ($values as $key => $val) { - // Escaping of filter meta characters - $val = str_replace(array('\\', '*', '(', ')'), array('\5c', '\2a', '\28', '\29'), $val); - // ASCII < 32 escaping - $val = Zend_Ldap_Converter::ascToHex32($val); - if (null === $val) $val = '\0'; // apply escaped "null" if string is empty - $values[$key] = $val; - } - return (count($values) == 1) ? $values[0] : $values; - } - - /** - * Undoes the conversion done by {@link escapeValue()}. - * - * Converts any sequences of a backslash followed by two hex digits into the corresponding character. - * @see Net_LDAP2_Util::escape_filter_value() from Benedikt Hallinger - * @link http://pear.php.net/package/Net_LDAP2 - * @author Benedikt Hallinger - * - * @param string|array $values Array of values to escape - * @return array Array $values, but unescaped - */ - public static function unescapeValue($values = array()) - { - /** - * @see Zend_Ldap_Converter - */ - #require_once 'Zend/Ldap/Converter.php'; - - if (!is_array($values)) $values = array($values); - foreach ($values as $key => $value) { - // Translate hex code into ascii - $values[$key] = Zend_Ldap_Converter::hex32ToAsc($value); - } - return (count($values) == 1) ? $values[0] : $values; - } -} diff --git a/library/Zend/Ldap/Filter/And.php b/library/Zend/Ldap/Filter/And.php deleted file mode 100644 index 357eca272b..0000000000 --- a/library/Zend/Ldap/Filter/And.php +++ /dev/null @@ -1,48 +0,0 @@ - $s) { - if (is_string($s)) $subfilters[$key] = new Zend_Ldap_Filter_String($s); - else if (!($s instanceof Zend_Ldap_Filter_Abstract)) { - /** - * @see Zend_Ldap_Filter_Exception - */ - #require_once 'Zend/Ldap/Filter/Exception.php'; - throw new Zend_Ldap_Filter_Exception('Only strings or Zend_Ldap_Filter_Abstract allowed.'); - } - } - $this->_subfilters = $subfilters; - $this->_symbol = $symbol; - } - - /** - * Adds a filter to this grouping filter. - * - * @param Zend_Ldap_Filter_Abstract $filter - * @return Zend_Ldap_Filter_Logical - */ - public function addFilter(Zend_Ldap_Filter_Abstract $filter) - { - $new = clone $this; - $new->_subfilters[] = $filter; - return $new; - } - - /** - * Returns a string representation of the filter. - * - * @return string - */ - public function toString() - { - $return = '(' . $this->_symbol; - foreach ($this->_subfilters as $sub) $return .= $sub->toString(); - $return .= ')'; - return $return; - } -} diff --git a/library/Zend/Ldap/Filter/Mask.php b/library/Zend/Ldap/Filter/Mask.php deleted file mode 100644 index 8b5dc9b1a9..0000000000 --- a/library/Zend/Ldap/Filter/Mask.php +++ /dev/null @@ -1,66 +0,0 @@ -_filter; - } -} diff --git a/library/Zend/Ldap/Filter/Not.php b/library/Zend/Ldap/Filter/Not.php deleted file mode 100644 index a4b9bd5101..0000000000 --- a/library/Zend/Ldap/Filter/Not.php +++ /dev/null @@ -1,75 +0,0 @@ -_filter = $filter; - } - - /** - * Negates the filter. - * - * @return Zend_Ldap_Filter_Abstract - */ - public function negate() - { - return $this->_filter; - } - - /** - * Returns a string representation of the filter. - * - * @return string - */ - public function toString() - { - return '(!' . $this->_filter->toString() . ')'; - } -} diff --git a/library/Zend/Ldap/Filter/Or.php b/library/Zend/Ldap/Filter/Or.php deleted file mode 100644 index c1a4dcd277..0000000000 --- a/library/Zend/Ldap/Filter/Or.php +++ /dev/null @@ -1,48 +0,0 @@ -_filter = $filter; - } - - /** - * Returns a string representation of the filter. - * - * @return string - */ - public function toString() - { - return '(' . $this->_filter . ')'; - } -} diff --git a/library/Zend/Ldap/Ldif/Encoder.php b/library/Zend/Ldap/Ldif/Encoder.php deleted file mode 100644 index d8e04cb9f2..0000000000 --- a/library/Zend/Ldap/Ldif/Encoder.php +++ /dev/null @@ -1,304 +0,0 @@ - true, - 'version' => 1, - 'wrap' => 78 - ); - - /** - * @var boolean - */ - protected $_versionWritten = false; - - /** - * Constructor. - * - * @param array $options Additional options used during encoding - * @return void - */ - protected function __construct(array $options = array()) - { - $this->_options = array_merge($this->_options, $options); - } - - /** - * Decodes the string $string into an array of LDIF items - * - * @param string $string - * @return array - */ - public static function decode($string) - { - $encoder = new self(array()); - return $encoder->_decode($string); - } - - /** - * Decodes the string $string into an array of LDIF items - * - * @param string $string - * @return array - */ - protected function _decode($string) - { - $items = array(); - $item = array(); - $last = null; - foreach (explode("\n", $string) as $line) { - $line = rtrim($line, "\x09\x0A\x0D\x00\x0B"); - $matches = array(); - if (substr($line, 0, 1) === ' ' && $last !== null) { - $last[2] .= substr($line, 1); - } else if (substr($line, 0, 1) === '#') { - continue; - } else if (preg_match('/^([a-z0-9;-]+)(:[:<]?\s*)([^:<]*)$/i', $line, $matches)) { - $name = strtolower($matches[1]); - $type = trim($matches[2]); - $value = $matches[3]; - if ($last !== null) { - $this->_pushAttribute($last, $item); - } - if ($name === 'version') { - continue; - } else if (count($item) > 0 && $name === 'dn') { - $items[] = $item; - $item = array(); - $last = null; - } - $last = array($name, $type, $value); - } else if (trim($line) === '') { - continue; - } - } - if ($last !== null) { - $this->_pushAttribute($last, $item); - } - $items[] = $item; - return (count($items)>1) ? $items : $items[0]; - } - - /** - * Pushes a decoded attribute to the stack - * - * @param array $attribute - * @param array $entry - */ - protected function _pushAttribute(array $attribute, array &$entry) - { - $name = $attribute[0]; - $type = $attribute[1]; - $value = $attribute[2]; - if ($type === '::') { - $value = base64_decode($value); - } - if ($name === 'dn') { - $entry[$name] = $value; - } else if (isset($entry[$name]) && $value !== '') { - $entry[$name][] = $value; - } else { - $entry[$name] = ($value !== '') ? array($value) : array(); - } - } - - /** - * Encode $value into a LDIF representation - * - * @param mixed $value The value to be encoded - * @param array $options Additional options used during encoding - * @return string The encoded value - */ - public static function encode($value, array $options = array()) - { - $encoder = new self($options); - return $encoder->_encode($value); - } - - /** - * Recursive driver which determines the type of value to be encoded - * and then dispatches to the appropriate method. - * - * @param mixed $value The value to be encoded - * @return string Encoded value - */ - protected function _encode($value) - { - if (is_scalar($value)) { - return $this->_encodeString($value); - } else if (is_array($value)) { - return $this->_encodeAttributes($value); - } else if ($value instanceof Zend_Ldap_Node) { - return $value->toLdif($this->_options); - } - return null; - } - - /** - * Encodes $string according to RFC2849 - * - * @link http://www.faqs.org/rfcs/rfc2849.html - * - * @param string $string - * @param boolen $base64 - * @return string - */ - protected function _encodeString($string, &$base64 = null) - { - $string = (string)$string; - if (!is_numeric($string) && empty($string)) { - return ''; - } - - /* - * SAFE-INIT-CHAR = %x01-09 / %x0B-0C / %x0E-1F / - * %x21-39 / %x3B / %x3D-7F - * ; any value <= 127 except NUL, LF, CR, - * ; SPACE, colon (":", ASCII 58 decimal) - * ; and less-than ("<" , ASCII 60 decimal) - * - */ - $unsafe_init_char = array(0, 10, 13, 32, 58, 60); - /* - * SAFE-CHAR = %x01-09 / %x0B-0C / %x0E-7F - * ; any value <= 127 decimal except NUL, LF, - * ; and CR - */ - $unsafe_char = array(0, 10, 13); - - $base64 = false; - for ($i = 0; $i < strlen($string); $i++) { - $char = ord(substr($string, $i, 1)); - if ($char >= 127) { - $base64 = true; - break; - } else if ($i === 0 && in_array($char, $unsafe_init_char)) { - $base64 = true; - break; - } else if (in_array($char, $unsafe_char)) { - $base64 = true; - break; - } - } - // Test for ending space - if (substr($string, -1) == ' ') { - $base64 = true; - } - - if ($base64 === true) { - $string = base64_encode($string); - } - - return $string; - } - - /** - * Encodes an attribute with $name and $value according to RFC2849 - * - * @link http://www.faqs.org/rfcs/rfc2849.html - * - * @param string $name - * @param array|string $value - * @return string - */ - protected function _encodeAttribute($name, $value) - { - if (!is_array($value)) { - $value = array($value); - } - - $output = ''; - - if (count($value) < 1) { - return $name . ': '; - } - - foreach ($value as $v) { - $base64 = null; - $v = $this->_encodeString($v, $base64); - $attribute = $name . ':'; - if ($base64 === true) { - $attribute .= ': ' . $v; - } else { - $attribute .= ' ' . $v; - } - if (isset($this->_options['wrap']) && strlen($attribute) > $this->_options['wrap']) { - $attribute = trim(chunk_split($attribute, $this->_options['wrap'], PHP_EOL . ' ')); - } - $output .= $attribute . PHP_EOL; - } - return trim($output, PHP_EOL); - } - - /** - * Encodes a collection of attributes according to RFC2849 - * - * @link http://www.faqs.org/rfcs/rfc2849.html - * - * @param array $attributes - * @return string - */ - protected function _encodeAttributes(array $attributes) - { - $string = ''; - $attributes = array_change_key_case($attributes, CASE_LOWER); - if (!$this->_versionWritten && array_key_exists('dn', $attributes) && isset($this->_options['version']) - && array_key_exists('objectclass', $attributes)) { - $string .= sprintf('version: %d', $this->_options['version']) . PHP_EOL; - $this->_versionWritten = true; - } - - if (isset($this->_options['sort']) && $this->_options['sort'] === true) { - ksort($attributes, SORT_STRING); - if (array_key_exists('objectclass', $attributes)) { - $oc = $attributes['objectclass']; - unset($attributes['objectclass']); - $attributes = array_merge(array('objectclass' => $oc), $attributes); - } - if (array_key_exists('dn', $attributes)) { - $dn = $attributes['dn']; - unset($attributes['dn']); - $attributes = array_merge(array('dn' => $dn), $attributes); - } - } - foreach ($attributes as $key => $value) { - $string .= $this->_encodeAttribute($key, $value) . PHP_EOL; - } - return trim($string, PHP_EOL); - } -} diff --git a/library/Zend/Ldap/Node.php b/library/Zend/Ldap/Node.php deleted file mode 100644 index cb4e05a775..0000000000 --- a/library/Zend/Ldap/Node.php +++ /dev/null @@ -1,1185 +0,0 @@ -attachLdap($ldap); - else $this->detachLdap(); - } - - /** - * Serialization callback - * - * Only DN and attributes will be serialized. - * - * @return array - */ - public function __sleep() - { - return array('_dn', '_currentData', '_newDn', '_originalData', - '_new', '_delete', '_children'); - } - - /** - * Deserialization callback - * - * Enforces a detached node. - * - * @return null - */ - public function __wakeup() - { - $this->detachLdap(); - } - - /** - * Gets the current LDAP connection. - * - * @return Zend_Ldap - * @throws Zend_Ldap_Exception - */ - public function getLdap() - { - if ($this->_ldap === null) { - /** - * @see Zend_Ldap_Exception - */ - #require_once 'Zend/Ldap/Exception.php'; - throw new Zend_Ldap_Exception(null, 'No LDAP connection specified.', Zend_Ldap_Exception::LDAP_OTHER); - } - else return $this->_ldap; - } - - /** - * Attach node to an LDAP connection - * - * This is an offline method. - * - * @uses Zend_Ldap_Dn::isChildOf() - * @param Zend_Ldap $ldap - * @return Zend_Ldap_Node Provides a fluent interface - * @throws Zend_Ldap_Exception - */ - public function attachLdap(Zend_Ldap $ldap) - { - if (!Zend_Ldap_Dn::isChildOf($this->_getDn(), $ldap->getBaseDn())) { - /** - * @see Zend_Ldap_Exception - */ - #require_once 'Zend/Ldap/Exception.php'; - throw new Zend_Ldap_Exception(null, 'LDAP connection is not responsible for given node.', - Zend_Ldap_Exception::LDAP_OTHER); - } - - if ($ldap !== $this->_ldap) { - $this->_ldap = $ldap; - if (is_array($this->_children)) { - foreach ($this->_children as $child) { - /* @var Zend_Ldap_Node $child */ - $child->attachLdap($ldap); - } - } - } - return $this; - } - - /** - * Detach node from LDAP connection - * - * This is an offline method. - * - * @return Zend_Ldap_Node Provides a fluent interface - */ - public function detachLdap() - { - $this->_ldap = null; - if (is_array($this->_children)) { - foreach ($this->_children as $child) { - /* @var Zend_Ldap_Node $child */ - $child->detachLdap(); - } - } - return $this; - } - - /** - * Checks if the current node is attached to a LDAP server. - * - * This is an offline method. - * - * @return boolean - */ - public function isAttached() - { - return ($this->_ldap !== null); - } - - /** - * @param array $data - * @param boolean $fromDataSource - * @throws Zend_Ldap_Exception - */ - protected function _loadData(array $data, $fromDataSource) - { - parent::_loadData($data, $fromDataSource); - if ($fromDataSource === true) { - $this->_originalData = $data; - } else { - $this->_originalData = array(); - } - $this->_children = null; - $this->_markAsNew(($fromDataSource === true) ? false : true); - $this->_markAsToBeDeleted(false); - } - - /** - * Factory method to create a new detached Zend_Ldap_Node for a given DN. - * - * @param string|array|Zend_Ldap_Dn $dn - * @param array $objectClass - * @return Zend_Ldap_Node - * @throws Zend_Ldap_Exception - */ - public static function create($dn, array $objectClass = array()) - { - if (is_string($dn) || is_array($dn)) { - $dn = Zend_Ldap_Dn::factory($dn); - } else if ($dn instanceof Zend_Ldap_Dn) { - $dn = clone $dn; - } else { - /** - * @see Zend_Ldap_Exception - */ - #require_once 'Zend/Ldap/Exception.php'; - throw new Zend_Ldap_Exception(null, '$dn is of a wrong data type.'); - } - $new = new self($dn, array(), false, null); - $new->_ensureRdnAttributeValues(); - $new->setAttribute('objectClass', $objectClass); - return $new; - } - - /** - * Factory method to create an attached Zend_Ldap_Node for a given DN. - * - * @param string|array|Zend_Ldap_Dn $dn - * @param Zend_Ldap $ldap - * @return Zend_Ldap_Node|null - * @throws Zend_Ldap_Exception - */ - public static function fromLdap($dn, Zend_Ldap $ldap) - { - if (is_string($dn) || is_array($dn)) { - $dn = Zend_Ldap_Dn::factory($dn); - } else if ($dn instanceof Zend_Ldap_Dn) { - $dn = clone $dn; - } else { - /** - * @see Zend_Ldap_Exception - */ - #require_once 'Zend/Ldap/Exception.php'; - throw new Zend_Ldap_Exception(null, '$dn is of a wrong data type.'); - } - $data = $ldap->getEntry($dn, array('*', '+'), true); - if ($data === null) { - return null; - } - $entry = new self($dn, $data, true, $ldap); - return $entry; - } - - /** - * Factory method to create a detached Zend_Ldap_Node from array data. - * - * @param array $data - * @param boolean $fromDataSource - * @return Zend_Ldap_Node - * @throws Zend_Ldap_Exception - */ - public static function fromArray(array $data, $fromDataSource = false) - { - if (!array_key_exists('dn', $data)) { - /** - * @see Zend_Ldap_Exception - */ - #require_once 'Zend/Ldap/Exception.php'; - throw new Zend_Ldap_Exception(null, '\'dn\' key is missing in array.'); - } - if (is_string($data['dn']) || is_array($data['dn'])) { - $dn = Zend_Ldap_Dn::factory($data['dn']); - } else if ($data['dn'] instanceof Zend_Ldap_Dn) { - $dn = clone $data['dn']; - } else { - /** - * @see Zend_Ldap_Exception - */ - #require_once 'Zend/Ldap/Exception.php'; - throw new Zend_Ldap_Exception(null, '\'dn\' key is of a wrong data type.'); - } - $fromDataSource = ($fromDataSource === true) ? true : false; - $new = new self($dn, $data, $fromDataSource, null); - $new->_ensureRdnAttributeValues(); - return $new; - } - - /** - * Ensures that teh RDN attributes are correctly set. - * - * @param boolean $overwrite True to overwrite the RDN attributes - * @return void - */ - protected function _ensureRdnAttributeValues($overwrite = false) - { - foreach ($this->getRdnArray() as $key => $value) { - if (!array_key_exists($key, $this->_currentData) || $overwrite) { - Zend_Ldap_Attribute::setAttribute($this->_currentData, $key, $value, false); - } else if (!in_array($value, $this->_currentData[$key])) { - Zend_Ldap_Attribute::setAttribute($this->_currentData, $key, $value, true); - } - } - } - - /** - * Marks this node as new. - * - * Node will be added (instead of updated) on calling update() if $new is true. - * - * @param boolean $new - */ - protected function _markAsNew($new) - { - $this->_new = ($new === false) ? false : true; - } - - /** - * Tells if the node is consiedered as new (not present on the server) - * - * Please note, that this doesn't tell you if the node is present on the server. - * Use {@link exits()} to see if a node is already there. - * - * @return boolean - */ - public function isNew() - { - return $this->_new; - } - - /** - * Marks this node as to be deleted. - * - * Node will be deleted on calling update() if $delete is true. - * - * @param boolean $delete - */ - protected function _markAsToBeDeleted($delete) - { - $this->_delete = ($delete === true) ? true : false; - } - - - /** - * Is this node going to be deleted once update() is called? - * - * @return boolean - */ - public function willBeDeleted() - { - return $this->_delete; - } - - /** - * Marks this node as to be deleted - * - * Node will be deleted on calling update() if $delete is true. - * - * @return Zend_Ldap_Node Provides a fluent interface - */ - public function delete() - { - $this->_markAsToBeDeleted(true); - return $this; - } - - /** - * Is this node going to be moved once update() is called? - * - * @return boolean - */ - public function willBeMoved() - { - if ($this->isNew() || $this->willBeDeleted()) { - return false; - } else if ($this->_newDn !== null) { - return ($this->_dn != $this->_newDn); - } else { - return false; - } - } - - /** - * Sends all pending changes to the LDAP server - * - * @param Zend_Ldap $ldap - * @return Zend_Ldap_Node Provides a fluent interface - * @throws Zend_Ldap_Exception - */ - public function update(Zend_Ldap $ldap = null) - { - if ($ldap !== null) { - $this->attachLdap($ldap); - } - $ldap = $this->getLdap(); - if (!($ldap instanceof Zend_Ldap)) { - /** - * @see Zend_Ldap_Exception - */ - #require_once 'Zend/Ldap/Exception.php'; - throw new Zend_Ldap_Exception(null, 'No LDAP connection available'); - } - - if ($this->willBeDeleted()) { - if ($ldap->exists($this->_dn)) { - $this->_preDelete(); - $ldap->delete($this->_dn); - $this->_postDelete(); - } - return $this; - } - - if ($this->isNew()) { - $this->_preAdd(); - $data = $this->getData(); - $ldap->add($this->_getDn(), $data); - $this->_loadData($data, true); - $this->_postAdd(); - return $this; - } - - $changedData = $this->getChangedData(); - if ($this->willBeMoved()) { - $this->_preRename(); - $recursive = $this->hasChildren(); - $ldap->rename($this->_dn, $this->_newDn, $recursive, false); - foreach ($this->_newDn->getRdn() as $key => $value) { - if (array_key_exists($key, $changedData)) { - unset($changedData[$key]); - } - } - $this->_dn = $this->_newDn; - $this->_newDn = null; - $this->_postRename(); - } - if (count($changedData) > 0) { - $this->_preUpdate(); - $ldap->update($this->_getDn(), $changedData); - $this->_postUpdate(); - } - $this->_originalData = $this->_currentData; - return $this; - } - - /** - * Gets the DN of the current node as a Zend_Ldap_Dn. - * - * This is an offline method. - * - * @return Zend_Ldap_Dn - */ - protected function _getDn() - { - return ($this->_newDn === null) ? parent::_getDn() : $this->_newDn; - } - - /** - * Gets the current DN of the current node as a Zend_Ldap_Dn. - * The method returns a clone of the node's DN to prohibit modification. - * - * This is an offline method. - * - * @return Zend_Ldap_Dn - */ - public function getCurrentDn() - { - $dn = clone parent::_getDn(); - return $dn; - } - - /** - * Sets the new DN for this node - * - * This is an offline method. - * - * @param Zend_Ldap_Dn|string|array $newDn - * @throws Zend_Ldap_Exception - * @return Zend_Ldap_Node Provides a fluent interface - */ - public function setDn($newDn) - { - if ($newDn instanceof Zend_Ldap_Dn) { - $this->_newDn = clone $newDn; - } else { - $this->_newDn = Zend_Ldap_Dn::factory($newDn); - } - $this->_ensureRdnAttributeValues(true); - return $this; - } - - /** - * {@see setDn()} - * - * This is an offline method. - * - * @param Zend_Ldap_Dn|string|array $newDn - * @throws Zend_Ldap_Exception - * @return Zend_Ldap_Node Provides a fluent interface - */ - public function move($newDn) - { - return $this->setDn($newDn); - } - - /** - * {@see setDn()} - * - * This is an offline method. - * - * @param Zend_Ldap_Dn|string|array $newDn - * @throws Zend_Ldap_Exception - * @return Zend_Ldap_Node Provides a fluent interface - */ - public function rename($newDn) - { - return $this->setDn($newDn); - } - - /** - * Sets the objectClass. - * - * This is an offline method. - * - * @param array|string $value - * @return Zend_Ldap_Node Provides a fluent interface - * @throws Zend_Ldap_Exception - */ - public function setObjectClass($value) - { - $this->setAttribute('objectClass', $value); - return $this; - } - - /** - * Appends to the objectClass. - * - * This is an offline method. - * - * @param array|string $value - * @return Zend_Ldap_Node Provides a fluent interface - * @throws Zend_Ldap_Exception - */ - public function appendObjectClass($value) - { - $this->appendToAttribute('objectClass', $value); - return $this; - } - - /** - * Returns a LDIF representation of the current node - * - * @param array $options Additional options used during encoding - * @return string - */ - public function toLdif(array $options = array()) - { - $attributes = array_merge(array('dn' => $this->getDnString()), $this->getData(false)); - /** - * Zend_Ldap_Ldif_Encoder - */ - #require_once 'Zend/Ldap/Ldif/Encoder.php'; - return Zend_Ldap_Ldif_Encoder::encode($attributes, $options); - } - - /** - * Gets changed node data. - * - * The array contains all changed attributes. - * This format can be used in {@link Zend_Ldap::add()} and {@link Zend_Ldap::update()}. - * - * This is an offline method. - * - * @return array - */ - public function getChangedData() - { - $changed = array(); - foreach ($this->_currentData as $key => $value) { - if (!array_key_exists($key, $this->_originalData) && !empty($value)) { - $changed[$key] = $value; - } else if ($this->_originalData[$key] !== $this->_currentData[$key]) { - $changed[$key] = $value; - } - } - return $changed; - } - - /** - * Returns all changes made. - * - * This is an offline method. - * - * @return array - */ - public function getChanges() - { - $changes = array( - 'add' => array(), - 'delete' => array(), - 'replace' => array()); - foreach ($this->_currentData as $key => $value) { - if (!array_key_exists($key, $this->_originalData) && !empty($value)) { - $changes['add'][$key] = $value; - } else if (count($this->_originalData[$key]) === 0 && !empty($value)) { - $changes['add'][$key] = $value; - } else if ($this->_originalData[$key] !== $this->_currentData[$key]) { - if (empty($value)) { - $changes['delete'][$key] = $value; - } else { - $changes['replace'][$key] = $value; - } - } - } - return $changes; - } - - /** - * Sets a LDAP attribute. - * - * This is an offline method. - * - * @param string $name - * @param mixed $value - * @return Zend_Ldap_Node Provides a fluent interface - * @throws Zend_Ldap_Exception - */ - public function setAttribute($name, $value) - { - $this->_setAttribute($name, $value, false); - return $this; - } - - /** - * Appends to a LDAP attribute. - * - * This is an offline method. - * - * @param string $name - * @param mixed $value - * @return Zend_Ldap_Node Provides a fluent interface - * @throws Zend_Ldap_Exception - */ - public function appendToAttribute($name, $value) - { - $this->_setAttribute($name, $value, true); - return $this; - } - - /** - * Checks if the attribute can be set and sets it accordingly. - * - * @param string $name - * @param mixed $value - * @param boolean $append - * @throws Zend_Ldap_Exception - */ - protected function _setAttribute($name, $value, $append) - { - $this->_assertChangeableAttribute($name); - Zend_Ldap_Attribute::setAttribute($this->_currentData, $name, $value, $append); - } - - /** - * Sets a LDAP date/time attribute. - * - * This is an offline method. - * - * @param string $name - * @param integer|array $value - * @param boolean $utc - * @return Zend_Ldap_Node Provides a fluent interface - * @throws Zend_Ldap_Exception - */ - public function setDateTimeAttribute($name, $value, $utc = false) - { - $this->_setDateTimeAttribute($name, $value, $utc, false); - return $this; - } - - /** - * Appends to a LDAP date/time attribute. - * - * This is an offline method. - * - * @param string $name - * @param integer|array $value - * @param boolean $utc - * @return Zend_Ldap_Node Provides a fluent interface - * @throws Zend_Ldap_Exception - */ - public function appendToDateTimeAttribute($name, $value, $utc = false) - { - $this->_setDateTimeAttribute($name, $value, $utc, true); - return $this; - } - - /** - * Checks if the attribute can be set and sets it accordingly. - * - * @param string $name - * @param integer|array $value - * @param boolean $utc - * @param boolean $append - * @throws Zend_Ldap_Exception - */ - protected function _setDateTimeAttribute($name, $value, $utc, $append) - { - $this->_assertChangeableAttribute($name); - Zend_Ldap_Attribute::setDateTimeAttribute($this->_currentData, $name, $value, $utc, $append); - } - - /** - * Sets a LDAP password. - * - * @param string $password - * @param string $hashType - * @param string $attribName - * @return Zend_Ldap_Node Provides a fluent interface - * @throws Zend_Ldap_Exception - */ - public function setPasswordAttribute($password, $hashType = Zend_Ldap_Attribute::PASSWORD_HASH_MD5, - $attribName = 'userPassword') - { - $this->_assertChangeableAttribute($attribName); - Zend_Ldap_Attribute::setPassword($this->_currentData, $password, $hashType, $attribName); - return $this; - } - - /** - * Deletes a LDAP attribute. - * - * This method deletes the attribute. - * - * This is an offline method. - * - * @param string $name - * @return Zend_Ldap_Node Provides a fluent interface - * @throws Zend_Ldap_Exception - */ - public function deleteAttribute($name) - { - if ($this->existsAttribute($name, true)) { - $this->_setAttribute($name, null, false); - } - return $this; - } - - /** - * Removes duplicate values from a LDAP attribute - * - * @param string $attribName - * @return void - */ - public function removeDuplicatesFromAttribute($attribName) - { - Zend_Ldap_Attribute::removeDuplicatesFromAttribute($this->_currentData, $attribName); - } - - /** - * Remove given values from a LDAP attribute - * - * @param string $attribName - * @param mixed|array $value - * @return void - */ - public function removeFromAttribute($attribName, $value) - { - Zend_Ldap_Attribute::removeFromAttribute($this->_currentData, $attribName, $value); - } - - /** - * @param string $name - * @return boolean - * @throws Zend_Ldap_Exception - */ - protected function _assertChangeableAttribute($name) - { - $name = strtolower($name); - $rdn = $this->getRdnArray(Zend_Ldap_Dn::ATTR_CASEFOLD_LOWER); - if ($name == 'dn') { - /** - * @see Zend_Ldap_Exception - */ - #require_once 'Zend/Ldap/Exception.php'; - throw new Zend_Ldap_Exception(null, 'DN cannot be changed.'); - } - else if (array_key_exists($name, $rdn)) { - /** - * @see Zend_Ldap_Exception - */ - #require_once 'Zend/Ldap/Exception.php'; - throw new Zend_Ldap_Exception(null, 'Cannot change attribute because it\'s part of the RDN'); - } else if (in_array($name, self::$_systemAttributes)) { - /** - * @see Zend_Ldap_Exception - */ - #require_once 'Zend/Ldap/Exception.php'; - throw new Zend_Ldap_Exception(null, 'Cannot change attribute because it\'s read-only'); - } - else return true; - } - - /** - * Sets a LDAP attribute. - * - * This is an offline method. - * - * @param string $name - * @param mixed $value - * @return null - * @throws Zend_Ldap_Exception - */ - public function __set($name, $value) - { - $this->setAttribute($name, $value); - } - - /** - * Deletes a LDAP attribute. - * - * This method deletes the attribute. - * - * This is an offline method. - * - * @param string $name - * @return null - * @throws Zend_Ldap_Exception - */ - public function __unset($name) - { - $this->deleteAttribute($name); - } - - /** - * Sets a LDAP attribute. - * Implements ArrayAccess. - * - * This is an offline method. - * - * @param string $name - * @param mixed $value - * @return null - * @throws Zend_Ldap_Exception - */ - public function offsetSet($name, $value) - { - $this->setAttribute($name, $value); - } - - /** - * Deletes a LDAP attribute. - * Implements ArrayAccess. - * - * This method deletes the attribute. - * - * This is an offline method. - * - * @param string $name - * @return null - * @throws Zend_Ldap_Exception - */ - public function offsetUnset($name) - { - $this->deleteAttribute($name); - } - - /** - * Check if node exists on LDAP. - * - * This is an online method. - * - * @param Zend_Ldap $ldap - * @return boolean - * @throws Zend_Ldap_Exception - */ - public function exists(Zend_Ldap $ldap = null) - { - if ($ldap !== null) { - $this->attachLdap($ldap); - } - $ldap = $this->getLdap(); - return $ldap->exists($this->_getDn()); - } - - /** - * Reload node attributes from LDAP. - * - * This is an online method. - * - * @param Zend_Ldap $ldap - * @return Zend_Ldap_Node Provides a fluent interface - * @throws Zend_Ldap_Exception - */ - public function reload(Zend_Ldap $ldap = null) - { - if ($ldap !== null) { - $this->attachLdap($ldap); - } - $ldap = $this->getLdap(); - parent::reload($ldap); - return $this; - } - - /** - * Search current subtree with given options. - * - * This is an online method. - * - * @param string|Zend_Ldap_Filter_Abstract $filter - * @param integer $scope - * @param string $sort - * @return Zend_Ldap_Node_Collection - * @throws Zend_Ldap_Exception - */ - public function searchSubtree($filter, $scope = Zend_Ldap::SEARCH_SCOPE_SUB, $sort = null) - { - /** - * @see Zend_Ldap_Node_Collection - */ - #require_once 'Zend/Ldap/Node/Collection.php'; - return $this->getLdap()->search($filter, $this->_getDn(), $scope, array('*', '+'), $sort, - 'Zend_Ldap_Node_Collection'); - } - - /** - * Count items in current subtree found by given filter. - * - * This is an online method. - * - * @param string|Zend_Ldap_Filter_Abstract $filter - * @param integer $scope - * @return integer - * @throws Zend_Ldap_Exception - */ - public function countSubtree($filter, $scope = Zend_Ldap::SEARCH_SCOPE_SUB) - { - return $this->getLdap()->count($filter, $this->_getDn(), $scope); - } - - /** - * Count children of current node. - * - * This is an online method. - * - * @return integer - * @throws Zend_Ldap_Exception - */ - public function countChildren() - { - return $this->countSubtree('(objectClass=*)', Zend_Ldap::SEARCH_SCOPE_ONE); - } - - /** - * Gets children of current node. - * - * This is an online method. - * - * @param string|Zend_Ldap_Filter_Abstract $filter - * @param string $sort - * @return Zend_Ldap_Node_Collection - * @throws Zend_Ldap_Exception - */ - public function searchChildren($filter, $sort = null) - { - return $this->searchSubtree($filter, Zend_Ldap::SEARCH_SCOPE_ONE, $sort); - } - - /** - * Checks if current node has children. - * Returns whether the current element has children. - * - * Can be used offline but returns false if children have not been retrieved yet. - * - * @return boolean - * @throws Zend_Ldap_Exception - */ - public function hasChildren() - { - if (!is_array($this->_children)) { - if ($this->isAttached()) { - return ($this->countChildren() > 0); - } else { - return false; - } - } else { - return (count($this->_children) > 0); - } - } - - /** - * Returns the children for the current node. - * - * Can be used offline but returns an empty array if children have not been retrieved yet. - * - * @return Zend_Ldap_Node_ChildrenIterator - * @throws Zend_Ldap_Exception - */ - public function getChildren() - { - if (!is_array($this->_children)) { - $this->_children = array(); - if ($this->isAttached()) { - $children = $this->searchChildren('(objectClass=*)', null); - foreach ($children as $child) { - /* @var Zend_Ldap_Node $child */ - $this->_children[$child->getRdnString(Zend_Ldap_Dn::ATTR_CASEFOLD_LOWER)] = $child; - } - } - } - /** - * @see Zend_Ldap_Node_ChildrenIterator - */ - #require_once 'Zend/Ldap/Node/ChildrenIterator.php'; - return new Zend_Ldap_Node_ChildrenIterator($this->_children); - } - - /** - * Returns the parent of the current node. - * - * @param Zend_Ldap $ldap - * @return Zend_Ldap_Node - * @throws Zend_Ldap_Exception - */ - public function getParent(Zend_Ldap $ldap = null) - { - if ($ldap !== null) { - $this->attachLdap($ldap); - } - $ldap = $this->getLdap(); - $parentDn = $this->_getDn()->getParentDn(1); - return self::fromLdap($parentDn, $ldap); - } - - /** - * Return the current attribute. - * Implements Iterator - * - * @return array - */ - public function current() - { - return $this; - } - - /** - * Return the attribute name. - * Implements Iterator - * - * @return string - */ - public function key() - { - return $this->getRdnString(); - } - - /** - * Move forward to next attribute. - * Implements Iterator - */ - public function next() - { - $this->_iteratorRewind = false; - } - - /** - * Rewind the Iterator to the first attribute. - * Implements Iterator - */ - public function rewind() - { - $this->_iteratorRewind = true; - } - - /** - * Check if there is a current attribute - * after calls to rewind() or next(). - * Implements Iterator - * - * @return boolean - */ - public function valid() - { - return $this->_iteratorRewind; - } - - #################################################### - # Empty method bodies for overriding in subclasses # - #################################################### - - /** - * Allows pre-delete logic to be applied to node. - * Subclasses may override this method. - * - * @return void - */ - protected function _preDelete() { } - - /** - * Allows post-delete logic to be applied to node. - * Subclasses may override this method. - * - * @return void - */ - protected function _postDelete() { } - - /** - * Allows pre-add logic to be applied to node. - * Subclasses may override this method. - * - * @return void - */ - protected function _preAdd() { } - - /** - * Allows post-add logic to be applied to node. - * Subclasses may override this method. - * - * @return void - */ - protected function _postAdd() { } - - /** - * Allows pre-rename logic to be applied to node. - * Subclasses may override this method. - * - * @return void - */ - protected function _preRename() { } - - /** - * Allows post-rename logic to be applied to node. - * Subclasses may override this method. - * - * @return void - */ - protected function _postRename() { } - - /** - * Allows pre-update logic to be applied to node. - * Subclasses may override this method. - * - * @return void - */ - protected function _preUpdate() { } - - /** - * Allows post-update logic to be applied to node. - * Subclasses may override this method. - * - * @return void - */ - protected function _postUpdate() { } -} diff --git a/library/Zend/Ldap/Node/Abstract.php b/library/Zend/Ldap/Node/Abstract.php deleted file mode 100644 index 67d1e3d98b..0000000000 --- a/library/Zend/Ldap/Node/Abstract.php +++ /dev/null @@ -1,485 +0,0 @@ -_dn = $dn; - $this->_loadData($data, $fromDataSource); - } - - /** - * @param array $data - * @param boolean $fromDataSource - * @throws Zend_Ldap_Exception - */ - protected function _loadData(array $data, $fromDataSource) - { - if (array_key_exists('dn', $data)) { - unset($data['dn']); - } - ksort($data, SORT_STRING); - $this->_currentData = $data; - } - - /** - * Reload node attributes from LDAP. - * - * This is an online method. - * - * @param Zend_Ldap $ldap - * @return Zend_Ldap_Node_Abstract Provides a fluent interface - * @throws Zend_Ldap_Exception - */ - public function reload(Zend_Ldap $ldap = null) - { - if ($ldap !== null) { - $data = $ldap->getEntry($this->_getDn(), array('*', '+'), true); - $this->_loadData($data, true); - } - return $this; - } - - /** - * Gets the DN of the current node as a Zend_Ldap_Dn. - * - * This is an offline method. - * - * @return Zend_Ldap_Dn - */ - protected function _getDn() - { - return $this->_dn; - } - - /** - * Gets the DN of the current node as a Zend_Ldap_Dn. - * The method returns a clone of the node's DN to prohibit modification. - * - * This is an offline method. - * - * @return Zend_Ldap_Dn - */ - public function getDn() - { - $dn = clone $this->_getDn(); - return $dn; - } - - /** - * Gets the DN of the current node as a string. - * - * This is an offline method. - * - * @param string $caseFold - * @return string - */ - public function getDnString($caseFold = null) - { - return $this->_getDn()->toString($caseFold); - } - - /** - * Gets the DN of the current node as an array. - * - * This is an offline method. - * - * @param string $caseFold - * @return array - */ - public function getDnArray($caseFold = null) - { - return $this->_getDn()->toArray($caseFold); - } - - /** - * Gets the RDN of the current node as a string. - * - * This is an offline method. - * - * @param string $caseFold - * @return string - */ - public function getRdnString($caseFold = null) - { - return $this->_getDn()->getRdnString($caseFold); - } - - /** - * Gets the RDN of the current node as an array. - * - * This is an offline method. - * - * @param string $caseFold - * @return array - */ - public function getRdnArray($caseFold = null) - { - return $this->_getDn()->getRdn($caseFold); - } - - /** - * Gets the objectClass of the node - * - * @return array - */ - public function getObjectClass() - { - return $this->getAttribute('objectClass', null); - } - - /** - * Gets all attributes of node. - * - * The collection contains all attributes. - * - * This is an offline method. - * - * @param boolean $includeSystemAttributes - * @return array - */ - public function getAttributes($includeSystemAttributes = true) - { - $data = array(); - foreach ($this->getData($includeSystemAttributes) as $name => $value) { - $data[$name] = $this->getAttribute($name, null); - } - return $data; - } - - /** - * Returns the DN of the current node. {@see getDnString()} - * - * @return string - */ - public function toString() - { - return $this->getDnString(); - } - - /** - * Cast to string representation {@see toString()} - * - * @return string - */ - public function __toString() - { - return $this->toString(); - } - - /** - * Returns an array representation of the current node - * - * @param boolean $includeSystemAttributes - * @return array - */ - public function toArray($includeSystemAttributes = true) - { - $attributes = $this->getAttributes($includeSystemAttributes); - return array_merge(array('dn' => $this->getDnString()), $attributes); - } - - /** - * Returns a JSON representation of the current node - * - * @param boolean $includeSystemAttributes - * @return string - */ - public function toJson($includeSystemAttributes = true) - { - return json_encode($this->toArray($includeSystemAttributes)); - } - - /** - * Gets node attributes. - * - * The array contains all attributes in its internal format (no conversion). - * - * This is an offline method. - * - * @param boolean $includeSystemAttributes - * @return array - */ - public function getData($includeSystemAttributes = true) - { - if ($includeSystemAttributes === false) { - $data = array(); - foreach ($this->_currentData as $key => $value) { - if (!in_array($key, self::$_systemAttributes)) { - $data[$key] = $value; - } - } - return $data; - } else { - return $this->_currentData; - } - } - - /** - * Checks whether a given attribute exists. - * - * If $emptyExists is false empty attributes (containing only array()) are - * treated as non-existent returning false. - * If $emptyExists is true empty attributes are treated as existent returning - * true. In this case method returns false only if the attribute name is - * missing in the key-collection. - * - * @param string $name - * @param boolean $emptyExists - * @return boolean - */ - public function existsAttribute($name, $emptyExists = false) - { - $name = strtolower($name); - if (isset($this->_currentData[$name])) { - if ($emptyExists) return true; - return count($this->_currentData[$name])>0; - } - else return false; - } - - /** - * Checks if the given value(s) exist in the attribute - * - * @param string $attribName - * @param mixed|array $value - * @return boolean - */ - public function attributeHasValue($attribName, $value) - { - return Zend_Ldap_Attribute::attributeHasValue($this->_currentData, $attribName, $value); - } - - /** - * Gets a LDAP attribute. - * - * This is an offline method. - * - * @param string $name - * @param integer $index - * @return mixed - * @throws Zend_Ldap_Exception - */ - public function getAttribute($name, $index = null) - { - if ($name == 'dn') { - return $this->getDnString(); - } - else { - return Zend_Ldap_Attribute::getAttribute($this->_currentData, $name, $index); - } - } - - /** - * Gets a LDAP date/time attribute. - * - * This is an offline method. - * - * @param string $name - * @param integer $index - * @return array|integer - * @throws Zend_Ldap_Exception - */ - public function getDateTimeAttribute($name, $index = null) - { - return Zend_Ldap_Attribute::getDateTimeAttribute($this->_currentData, $name, $index); - } - - /** - * Sets a LDAP attribute. - * - * This is an offline method. - * - * @param string $name - * @param mixed $value - * @return null - * @throws BadMethodCallException - */ - public function __set($name, $value) - { - throw new BadMethodCallException(); - } - - /** - * Gets a LDAP attribute. - * - * This is an offline method. - * - * @param string $name - * @return array - * @throws Zend_Ldap_Exception - */ - public function __get($name) - { - return $this->getAttribute($name, null); - } - - /** - * Deletes a LDAP attribute. - * - * This method deletes the attribute. - * - * This is an offline method. - * - * @param string $name - * @return null - * @throws BadMethodCallException - */ - public function __unset($name) - { - throw new BadMethodCallException(); - } - - /** - * Checks whether a given attribute exists. - * - * Empty attributes will be treated as non-existent. - * - * @param string $name - * @return boolean - */ - public function __isset($name) - { - return $this->existsAttribute($name, false); - } - - /** - * Sets a LDAP attribute. - * Implements ArrayAccess. - * - * This is an offline method. - * - * @param string $name - * @param mixed $value - * @return null - * @throws BadMethodCallException - */ - public function offsetSet($name, $value) - { - throw new BadMethodCallException(); - } - - /** - * Gets a LDAP attribute. - * Implements ArrayAccess. - * - * This is an offline method. - * - * @param string $name - * @return array - * @throws Zend_Ldap_Exception - */ - public function offsetGet($name) - { - return $this->getAttribute($name, null); - } - - /** - * Deletes a LDAP attribute. - * Implements ArrayAccess. - * - * This method deletes the attribute. - * - * This is an offline method. - * - * @param string $name - * @return null - * @throws BadMethodCallException - */ - public function offsetUnset($name) - { - throw new BadMethodCallException(); - } - - /** - * Checks whether a given attribute exists. - * Implements ArrayAccess. - * - * Empty attributes will be treated as non-existent. - * - * @param string $name - * @return boolean - */ - public function offsetExists($name) - { - return $this->existsAttribute($name, false); - } - - /** - * Returns the number of attributes in node. - * Implements Countable - * - * @return int - */ - public function count() - { - return count($this->_currentData); - } -} diff --git a/library/Zend/Ldap/Node/ChildrenIterator.php b/library/Zend/Ldap/Node/ChildrenIterator.php deleted file mode 100644 index b52e5784a6..0000000000 --- a/library/Zend/Ldap/Node/ChildrenIterator.php +++ /dev/null @@ -1,209 +0,0 @@ -_data = $data; - } - - /** - * Returns the number of child nodes. - * Implements Countable - * - * @return int - */ - public function count() - { - return count($this->_data); - } - - /** - * Return the current child. - * Implements Iterator - * - * @return Zend_Ldap_Node - */ - public function current() - { - return current($this->_data); - } - - /** - * Return the child'd RDN. - * Implements Iterator - * - * @return string - */ - public function key() - { - return key($this->_data); - } - - /** - * Move forward to next child. - * Implements Iterator - */ - public function next() - { - next($this->_data); - } - - /** - * Rewind the Iterator to the first child. - * Implements Iterator - */ - public function rewind() - { - reset($this->_data); - } - - /** - * Check if there is a current child - * after calls to rewind() or next(). - * Implements Iterator - * - * @return boolean - */ - public function valid() - { - return (current($this->_data)!==false); - } - - /** - * Checks if current node has children. - * Returns whether the current element has children. - * - * @return boolean - */ - public function hasChildren() - { - if ($this->current() instanceof Zend_Ldap_Node) { - return $this->current()->hasChildren(); - } else { - return false; - } - } - - /** - * Returns the children for the current node. - * - * @return Zend_Ldap_Node_ChildrenIterator - */ - public function getChildren() - { - if ($this->current() instanceof Zend_Ldap_Node) { - return $this->current()->getChildren(); - } else { - return null; - } - } - - /** - * Returns a child with a given RDN. - * Implements ArrayAccess. - * - * @param string $rdn - * @return Zend_Ldap_node - */ - public function offsetGet($rdn) - { - if ($this->offsetExists($rdn)) { - return $this->_data[$rdn]; - } else { - return null; - } - } - - /** - * Checks whether a given rdn exists. - * Implements ArrayAccess. - * - * @param string $rdn - * @return boolean - */ - public function offsetExists($rdn) - { - return (array_key_exists($rdn, $this->_data)); - } - - /** - * Does nothing. - * Implements ArrayAccess. - * - * @param string $name - * @return null - */ - public function offsetUnset($name) { } - - /** - * Does nothing. - * Implements ArrayAccess. - * - * @param string $name - * @param mixed $value - * @return null - */ - public function offsetSet($name, $value) { } - - /** - * Get all children as an array - * - * @return array - */ - public function toArray() - { - $data = array(); - foreach ($this as $rdn => $node) { - $data[$rdn] = $node; - } - return $data; - } -} diff --git a/library/Zend/Ldap/Node/Collection.php b/library/Zend/Ldap/Node/Collection.php deleted file mode 100644 index 40fe57fa50..0000000000 --- a/library/Zend/Ldap/Node/Collection.php +++ /dev/null @@ -1,67 +0,0 @@ -attachLdap($this->_iterator->getLdap()); - return $node; - } - - /** - * Return the child key (DN). - * Implements Iterator and RecursiveIterator - * - * @return string - */ - public function key() - { - return $this->_iterator->key(); - } -} diff --git a/library/Zend/Ldap/Node/RootDse.php b/library/Zend/Ldap/Node/RootDse.php deleted file mode 100644 index 66a5caad17..0000000000 --- a/library/Zend/Ldap/Node/RootDse.php +++ /dev/null @@ -1,158 +0,0 @@ -getEntry($dn, array('*', '+'), true); - if (isset($data['domainfunctionality'])) { - /** - * @see Zend_Ldap_Node_RootDse_ActiveDirectory - */ - #require_once 'Zend/Ldap/Node/RootDse/ActiveDirectory.php'; - return new Zend_Ldap_Node_RootDse_ActiveDirectory($dn, $data); - } else if (isset($data['dsaname'])) { - /** - * @see Zend_Ldap_Node_RootDse_ActiveDirectory - */ - #require_once 'Zend/Ldap/Node/RootDse/eDirectory.php'; - return new Zend_Ldap_Node_RootDse_eDirectory($dn, $data); - } else if (isset($data['structuralobjectclass']) && - $data['structuralobjectclass'][0] === 'OpenLDAProotDSE') { - /** - * @see Zend_Ldap_Node_RootDse_OpenLdap - */ - #require_once 'Zend/Ldap/Node/RootDse/OpenLdap.php'; - return new Zend_Ldap_Node_RootDse_OpenLdap($dn, $data); - } else { - return new self($dn, $data); - } - } - - /** - * Constructor. - * - * Constructor is protected to enforce the use of factory methods. - * - * @param Zend_Ldap_Dn $dn - * @param array $data - */ - protected function __construct(Zend_Ldap_Dn $dn, array $data) - { - parent::__construct($dn, $data, true); - } - - /** - * Gets the namingContexts. - * - * @return array - */ - public function getNamingContexts() - { - return $this->getAttribute('namingContexts', null); - } - - /** - * Gets the subschemaSubentry. - * - * @return string|null - */ - public function getSubschemaSubentry() - { - return $this->getAttribute('subschemaSubentry', 0); - } - - /** - * Determines if the version is supported - * - * @param string|int|array $versions version(s) to check - * @return boolean - */ - public function supportsVersion($versions) - { - return $this->attributeHasValue('supportedLDAPVersion', $versions); - } - - /** - * Determines if the sasl mechanism is supported - * - * @param string|array $mechlist SASL mechanisms to check - * @return boolean - */ - public function supportsSaslMechanism($mechlist) - { - return $this->attributeHasValue('supportedSASLMechanisms', $mechlist); - } - - /** - * Gets the server type - * - * @return int - */ - public function getServerType() - { - return self::SERVER_TYPE_GENERIC; - } - - /** - * Returns the schema DN - * - * @return Zend_Ldap_Dn - */ - public function getSchemaDn() - { - $schemaDn = $this->getSubschemaSubentry(); - /** - * @see Zend_Ldap_Dn - */ - #require_once 'Zend/Ldap/Dn.php'; - return Zend_Ldap_Dn::fromString($schemaDn); - } -} diff --git a/library/Zend/Ldap/Node/RootDse/ActiveDirectory.php b/library/Zend/Ldap/Node/RootDse/ActiveDirectory.php deleted file mode 100644 index 5ed8c71802..0000000000 --- a/library/Zend/Ldap/Node/RootDse/ActiveDirectory.php +++ /dev/null @@ -1,247 +0,0 @@ -getAttribute('configurationNamingContext', 0); - } - - /** - * Gets the currentTime. - * - * @return string|null - */ - public function getCurrentTime() - { - return $this->getAttribute('currentTime', 0); - } - - /** - * Gets the defaultNamingContext. - * - * @return string|null - */ - public function getDefaultNamingContext() - { - return $this->getAttribute('defaultNamingContext', 0); - } - - /** - * Gets the dnsHostName. - * - * @return string|null - */ - public function getDnsHostName() - { - return $this->getAttribute('dnsHostName', 0); - } - - /** - * Gets the domainControllerFunctionality. - * - * @return string|null - */ - public function getDomainControllerFunctionality() - { - return $this->getAttribute('domainControllerFunctionality', 0); - } - - /** - * Gets the domainFunctionality. - * - * @return string|null - */ - public function getDomainFunctionality() - { - return $this->getAttribute('domainFunctionality', 0); - } - - /** - * Gets the dsServiceName. - * - * @return string|null - */ - public function getDsServiceName() - { - return $this->getAttribute('dsServiceName', 0); - } - - /** - * Gets the forestFunctionality. - * - * @return string|null - */ - public function getForestFunctionality() - { - return $this->getAttribute('forestFunctionality', 0); - } - - /** - * Gets the highestCommittedUSN. - * - * @return string|null - */ - public function getHighestCommittedUSN() - { - return $this->getAttribute('highestCommittedUSN', 0); - } - - /** - * Gets the isGlobalCatalogReady. - * - * @return string|null - */ - public function getIsGlobalCatalogReady() - { - return $this->getAttribute('isGlobalCatalogReady', 0); - } - - /** - * Gets the isSynchronized. - * - * @return string|null - */ - public function getIsSynchronized() - { - return $this->getAttribute('isSynchronized', 0); - } - - /** - * Gets the ldapServiceName. - * - * @return string|null - */ - public function getLdapServiceName() - { - return $this->getAttribute('ldapServiceName', 0); - } - - /** - * Gets the rootDomainNamingContext. - * - * @return string|null - */ - public function getRootDomainNamingContext() - { - return $this->getAttribute('rootDomainNamingContext', 0); - } - - /** - * Gets the schemaNamingContext. - * - * @return string|null - */ - public function getSchemaNamingContext() - { - return $this->getAttribute('schemaNamingContext', 0); - } - - /** - * Gets the serverName. - * - * @return string|null - */ - public function getServerName() - { - return $this->getAttribute('serverName', 0); - } - - /** - * Determines if the capability is supported - * - * @param string|string|array $oids capability(s) to check - * @return boolean - */ - public function supportsCapability($oids) - { - return $this->attributeHasValue('supportedCapabilities', $oids); - } - - /** - * Determines if the control is supported - * - * @param string|array $oids control oid(s) to check - * @return boolean - */ - public function supportsControl($oids) - { - return $this->attributeHasValue('supportedControl', $oids); - } - - /** - * Determines if the version is supported - * - * @param string|array $policies policy(s) to check - * @return boolean - */ - public function supportsPolicy($policies) - { - return $this->attributeHasValue('supportedLDAPPolicies', $policies); - } - - /** - * Gets the server type - * - * @return int - */ - public function getServerType() - { - return self::SERVER_TYPE_ACTIVEDIRECTORY; - } - - /** - * Returns the schema DN - * - * @return Zend_Ldap_Dn - */ - public function getSchemaDn() - { - $schemaDn = $this->getSchemaNamingContext(); - /** - * @see Zend_Ldap_Dn - */ - #require_once 'Zend/Ldap/Dn.php'; - return Zend_Ldap_Dn::fromString($schemaDn); - } -} diff --git a/library/Zend/Ldap/Node/RootDse/OpenLdap.php b/library/Zend/Ldap/Node/RootDse/OpenLdap.php deleted file mode 100644 index 8ab6c45b91..0000000000 --- a/library/Zend/Ldap/Node/RootDse/OpenLdap.php +++ /dev/null @@ -1,102 +0,0 @@ -getAttribute('configContext', 0); - } - - /** - * Gets the monitorContext. - * - * @return string|null - */ - public function getMonitorContext() - { - return $this->getAttribute('monitorContext', 0); - } - - /** - * Determines if the control is supported - * - * @param string|array $oids control oid(s) to check - * @return boolean - */ - public function supportsControl($oids) - { - return $this->attributeHasValue('supportedControl', $oids); - } - - /** - * Determines if the extension is supported - * - * @param string|array $oids oid(s) to check - * @return boolean - */ - public function supportsExtension($oids) - { - return $this->attributeHasValue('supportedExtension', $oids); - } - - /** - * Determines if the feature is supported - * - * @param string|array $oids feature oid(s) to check - * @return boolean - */ - public function supportsFeature($oids) - { - return $this->attributeHasValue('supportedFeatures', $oids); - } - - /** - * Gets the server type - * - * @return int - */ - public function getServerType() - { - return self::SERVER_TYPE_OPENLDAP; - } -} diff --git a/library/Zend/Ldap/Node/RootDse/eDirectory.php b/library/Zend/Ldap/Node/RootDse/eDirectory.php deleted file mode 100644 index e93a9ff87a..0000000000 --- a/library/Zend/Ldap/Node/RootDse/eDirectory.php +++ /dev/null @@ -1,160 +0,0 @@ -attributeHasValue('supportedExtension', $oids); - } - - /** - * Gets the vendorName. - * - * @return string|null - */ - public function getVendorName() - { - return $this->getAttribute('vendorName', 0); - } - - /** - * Gets the vendorVersion. - * - * @return string|null - */ - public function getVendorVersion() - { - return $this->getAttribute('vendorVersion', 0); - } - - /** - * Gets the dsaName. - * - * @return string|null - */ - public function getDsaName() - { - return $this->getAttribute('dsaName', 0); - } - - /** - * Gets the server statistics "errors". - * - * @return string|null - */ - public function getStatisticsErrors() - { - return $this->getAttribute('errors', 0); - } - - /** - * Gets the server statistics "securityErrors". - * - * @return string|null - */ - public function getStatisticsSecurityErrors() - { - return $this->getAttribute('securityErrors', 0); - } - - /** - * Gets the server statistics "chainings". - * - * @return string|null - */ - public function getStatisticsChainings() - { - return $this->getAttribute('chainings', 0); - } - - /** - * Gets the server statistics "referralsReturned". - * - * @return string|null - */ - public function getStatisticsReferralsReturned() - { - return $this->getAttribute('referralsReturned', 0); - } - - /** - * Gets the server statistics "extendedOps". - * - * @return string|null - */ - public function getStatisticsExtendedOps() - { - return $this->getAttribute('extendedOps', 0); - } - - /** - * Gets the server statistics "abandonOps". - * - * @return string|null - */ - public function getStatisticsAbandonOps() - { - return $this->getAttribute('abandonOps', 0); - } - - /** - * Gets the server statistics "wholeSubtreeSearchOps". - * - * @return string|null - */ - public function getStatisticsWholeSubtreeSearchOps() - { - return $this->getAttribute('wholeSubtreeSearchOps', 0); - } - - /** - * Gets the server type - * - * @return int - */ - public function getServerType() - { - return self::SERVER_TYPE_EDIRECTORY; - } -} diff --git a/library/Zend/Ldap/Node/Schema.php b/library/Zend/Ldap/Node/Schema.php deleted file mode 100644 index 4e08eea366..0000000000 --- a/library/Zend/Ldap/Node/Schema.php +++ /dev/null @@ -1,120 +0,0 @@ -getRootDse()->getSchemaDn(); - $data = $ldap->getEntry($dn, array('*', '+'), true); - switch ($ldap->getRootDse()->getServerType()) { - case Zend_Ldap_Node_RootDse::SERVER_TYPE_ACTIVEDIRECTORY: - /** - * @see Zend_Ldap_Node_Schema_ActiveDirectory - */ - #require_once 'Zend/Ldap/Node/Schema/ActiveDirectory.php'; - return new Zend_Ldap_Node_Schema_ActiveDirectory($dn, $data, $ldap); - case Zend_Ldap_Node_RootDse::SERVER_TYPE_OPENLDAP: - /** - * @see Zend_Ldap_Node_RootDse_ActiveDirectory - */ - #require_once 'Zend/Ldap/Node/Schema/OpenLdap.php'; - return new Zend_Ldap_Node_Schema_OpenLdap($dn, $data, $ldap); - case Zend_Ldap_Node_RootDse::SERVER_TYPE_EDIRECTORY: - default: - return new self($dn, $data, $ldap); - } - } - - /** - * Constructor. - * - * Constructor is protected to enforce the use of factory methods. - * - * @param Zend_Ldap_Dn $dn - * @param array $data - * @param Zend_Ldap $ldap - */ - protected function __construct(Zend_Ldap_Dn $dn, array $data, Zend_Ldap $ldap) - { - parent::__construct($dn, $data, true); - $this->_parseSchema($dn, $ldap); - } - - /** - * Parses the schema - * - * @param Zend_Ldap_Dn $dn - * @param Zend_Ldap $ldap - * @return Zend_Ldap_Node_Schema Provides a fluent interface - */ - protected function _parseSchema(Zend_Ldap_Dn $dn, Zend_Ldap $ldap) - { - return $this; - } - - /** - * Gets the attribute Types - * - * @return array - */ - public function getAttributeTypes() - { - return array(); - } - - /** - * Gets the object classes - * - * @return array - */ - public function getObjectClasses() - { - return array(); - } -} diff --git a/library/Zend/Ldap/Node/Schema/ActiveDirectory.php b/library/Zend/Ldap/Node/Schema/ActiveDirectory.php deleted file mode 100644 index 3e9ce07070..0000000000 --- a/library/Zend/Ldap/Node/Schema/ActiveDirectory.php +++ /dev/null @@ -1,103 +0,0 @@ -search('(objectClass=classSchema)', $dn, - Zend_Ldap::SEARCH_SCOPE_ONE) as $node) { - $val = new Zend_Ldap_Node_Schema_ObjectClass_ActiveDirectory($node); - $this->_objectClasses[$val->getName()] = $val; - } - foreach ($ldap->search('(objectClass=attributeSchema)', $dn, - Zend_Ldap::SEARCH_SCOPE_ONE) as $node) { - $val = new Zend_Ldap_Node_Schema_AttributeType_ActiveDirectory($node); - $this->_attributeTypes[$val->getName()] = $val; - } - return $this; - } - - /** - * Gets the attribute Types - * - * @return array - */ - public function getAttributeTypes() - { - return $this->_attributeTypes; - } - - /** - * Gets the object classes - * - * @return array - */ - public function getObjectClasses() - { - return $this->_objectClasses; - } -} diff --git a/library/Zend/Ldap/Node/Schema/AttributeType/ActiveDirectory.php b/library/Zend/Ldap/Node/Schema/AttributeType/ActiveDirectory.php deleted file mode 100644 index b04f6d7c1b..0000000000 --- a/library/Zend/Ldap/Node/Schema/AttributeType/ActiveDirectory.php +++ /dev/null @@ -1,104 +0,0 @@ -ldapdisplayname[0]; - } - - /** - * Gets the attribute OID - * - * @return string - */ - public function getOid() - { - - } - - /** - * Gets the attribute syntax - * - * @return string - */ - public function getSyntax() - { - - } - - /** - * Gets the attribute maximum length - * - * @return int|null - */ - public function getMaxLength() - { - - } - - /** - * Returns if the attribute is single-valued. - * - * @return boolean - */ - public function isSingleValued() - { - - } - - /** - * Gets the attribute description - * - * @return string - */ - public function getDescription() - { - - } -} diff --git a/library/Zend/Ldap/Node/Schema/AttributeType/Interface.php b/library/Zend/Ldap/Node/Schema/AttributeType/Interface.php deleted file mode 100644 index 59226635ed..0000000000 --- a/library/Zend/Ldap/Node/Schema/AttributeType/Interface.php +++ /dev/null @@ -1,75 +0,0 @@ -name; - } - - /** - * Gets the attribute OID - * - * @return string - */ - public function getOid() - { - return $this->oid; - } - - /** - * Gets the attribute syntax - * - * @return string - */ - public function getSyntax() - { - if ($this->syntax === null) { - $parent = $this->getParent(); - if ($parent === null) return null; - else return $parent->getSyntax(); - } else { - return $this->syntax; - } - } - - /** - * Gets the attribute maximum length - * - * @return int|null - */ - public function getMaxLength() - { - $maxLength = $this->{'max-length'}; - if ($maxLength === null) { - $parent = $this->getParent(); - if ($parent === null) return null; - else return $parent->getMaxLength(); - } else { - return (int)$maxLength; - } - } - - /** - * Returns if the attribute is single-valued. - * - * @return boolean - */ - public function isSingleValued() - { - return $this->{'single-value'}; - } - - /** - * Gets the attribute description - * - * @return string - */ - public function getDescription() - { - return $this->desc; - } - - /** - * Returns the parent attribute type in the inhertitance tree if one exists - * - * @return Zend_Ldap_Node_Schema_AttributeType_OpenLdap|null - */ - public function getParent() - { - if (count($this->_parents) === 1) { - return $this->_parents[0]; - } - } -} diff --git a/library/Zend/Ldap/Node/Schema/Item.php b/library/Zend/Ldap/Node/Schema/Item.php deleted file mode 100644 index 4404f1dcbd..0000000000 --- a/library/Zend/Ldap/Node/Schema/Item.php +++ /dev/null @@ -1,163 +0,0 @@ -setData($data); - } - - /** - * Sets the data - * - * @param array $data - * @return Zend_Ldap_Node_Schema_Item Provides a fluent interface - */ - public function setData(array $data) - { - $this->_data = $data; - return $this; - } - - /** - * Gets the data - * - * @return array - */ - public function getData() - { - return $this->_data; - } - - /** - * Gets a specific attribute from this item - * - * @param string $name - * @return mixed - */ - public function __get($name) - { - if (array_key_exists($name, $this->_data)) { - return $this->_data[$name]; - } else { - return null; - } - } - - /** - * Checks whether a specific attribute exists. - * - * @param string $name - * @return boolean - */ - public function __isset($name) - { - return (array_key_exists($name, $this->_data)); - } - - /** - * Always throws BadMethodCallException - * Implements ArrayAccess. - * - * This method is needed for a full implementation of ArrayAccess - * - * @param string $name - * @param mixed $value - * @return null - * @throws BadMethodCallException - */ - public function offsetSet($name, $value) - { - throw new BadMethodCallException(); - } - - /** - * Gets a specific attribute from this item - * - * @param string $name - * @return mixed - */ - public function offsetGet($name) - { - return $this->__get($name); - } - - /** - * Always throws BadMethodCallException - * Implements ArrayAccess. - * - * This method is needed for a full implementation of ArrayAccess - * - * @param string $name - * @return null - * @throws BadMethodCallException - */ - public function offsetUnset($name) - { - throw new BadMethodCallException(); - } - - /** - * Checks whether a specific attribute exists. - * - * @param string $name - * @return boolean - */ - public function offsetExists($name) - { - return $this->__isset($name); - } - - /** - * Returns the number of attributes. - * Implements Countable - * - * @return int - */ - public function count() - { - return count($this->_data); - } -} diff --git a/library/Zend/Ldap/Node/Schema/ObjectClass/ActiveDirectory.php b/library/Zend/Ldap/Node/Schema/ObjectClass/ActiveDirectory.php deleted file mode 100644 index 541b6bd332..0000000000 --- a/library/Zend/Ldap/Node/Schema/ObjectClass/ActiveDirectory.php +++ /dev/null @@ -1,115 +0,0 @@ -ldapdisplayname[0]; - } - - /** - * Gets the objectClass OID - * - * @return string - */ - public function getOid() - { - - } - - /** - * Gets the attributes that this objectClass must contain - * - * @return array - */ - public function getMustContain() - { - - } - - /** - * Gets the attributes that this objectClass may contain - * - * @return array - */ - public function getMayContain() - { - - } - - /** - * Gets the objectClass description - * - * @return string - */ - public function getDescription() - { - - } - - /** - * Gets the objectClass type - * - * @return integer - */ - public function getType() - { - - } - - /** - * Returns the parent objectClasses of this class. - * This includes structural, abstract and auxiliary objectClasses - * - * @return array - */ - public function getParentClasses() - { - - } -} diff --git a/library/Zend/Ldap/Node/Schema/ObjectClass/Interface.php b/library/Zend/Ldap/Node/Schema/ObjectClass/Interface.php deleted file mode 100644 index f735190260..0000000000 --- a/library/Zend/Ldap/Node/Schema/ObjectClass/Interface.php +++ /dev/null @@ -1,83 +0,0 @@ -name; - } - - /** - * Gets the objectClass OID - * - * @return string - */ - public function getOid() - { - return $this->oid; - } - - /** - * Gets the attributes that this objectClass must contain - * - * @return array - */ - public function getMustContain() - { - if ($this->_inheritedMust === null) { - $this->_resolveInheritance(); - } - return $this->_inheritedMust; - } - - /** - * Gets the attributes that this objectClass may contain - * - * @return array - */ - public function getMayContain() - { - if ($this->_inheritedMay === null) { - $this->_resolveInheritance(); - } - return $this->_inheritedMay; - } - - /** - * Resolves the inheritance tree - * - * @return void - */ - protected function _resolveInheritance() - { - $must = $this->must; - $may = $this->may; - foreach ($this->getParents() as $p) { - $must = array_merge($must, $p->getMustContain()); - $may = array_merge($may, $p->getMayContain()); - } - $must = array_unique($must); - $may = array_unique($may); - $may = array_diff($may, $must); - sort($must, SORT_STRING); - sort($may, SORT_STRING); - $this->_inheritedMust = $must; - $this->_inheritedMay = $may; - } - - /** - * Gets the objectClass description - * - * @return string - */ - public function getDescription() - { - return $this->desc; - } - - /** - * Gets the objectClass type - * - * @return integer - */ - public function getType() - { - if ($this->structural) { - return Zend_Ldap_Node_Schema::OBJECTCLASS_TYPE_STRUCTURAL; - } else if ($this->abstract) { - return Zend_Ldap_Node_Schema::OBJECTCLASS_TYPE_ABSTRACT; - } else if ($this->auxiliary) { - return Zend_Ldap_Node_Schema::OBJECTCLASS_TYPE_AUXILIARY; - } else { - return Zend_Ldap_Node_Schema::OBJECTCLASS_TYPE_UNKNOWN; - } - } - - /** - * Returns the parent objectClasses of this class. - * This includes structural, abstract and auxiliary objectClasses - * - * @return array - */ - public function getParentClasses() - { - return $this->sup; - } - - /** - * Returns the parent object classes in the inhertitance tree if one exists - * - * @return array of Zend_Ldap_Node_Schema_ObjectClass_OpenLdap - */ - public function getParents() - { - return $this->_parents; - } -} diff --git a/library/Zend/Ldap/Node/Schema/OpenLdap.php b/library/Zend/Ldap/Node/Schema/OpenLdap.php deleted file mode 100644 index d3cdaa5188..0000000000 --- a/library/Zend/Ldap/Node/Schema/OpenLdap.php +++ /dev/null @@ -1,502 +0,0 @@ -_loadAttributeTypes(); - $this->_loadLdapSyntaxes(); - $this->_loadMatchingRules(); - $this->_loadMatchingRuleUse(); - $this->_loadObjectClasses(); - return $this; - } - - /** - * Gets the attribute Types - * - * @return array - */ - public function getAttributeTypes() - { - return $this->_attributeTypes; - } - - /** - * Gets the object classes - * - * @return array - */ - public function getObjectClasses() - { - return $this->_objectClasses; - } - - /** - * Gets the LDAP syntaxes - * - * @return array - */ - public function getLdapSyntaxes() - { - return $this->_ldapSyntaxes; - } - - /** - * Gets the matching rules - * - * @return array - */ - public function getMatchingRules() - { - return $this->_matchingRules; - } - - /** - * Gets the matching rule use - * - * @return array - */ - public function getMatchingRuleUse() - { - return $this->_matchingRuleUse; - } - - /** - * Loads the attribute Types - * - * @return void - */ - protected function _loadAttributeTypes() - { - $this->_attributeTypes = array(); - foreach ($this->getAttribute('attributeTypes') as $value) { - $val = $this->_parseAttributeType($value); - $val = new Zend_Ldap_Node_Schema_AttributeType_OpenLdap($val); - $this->_attributeTypes[$val->getName()] = $val; - - } - foreach ($this->_attributeTypes as $val) { - if (count($val->sup) > 0) { - $this->_resolveInheritance($val, $this->_attributeTypes); - } - foreach ($val->aliases as $alias) { - $this->_attributeTypes[$alias] = $val; - } - } - ksort($this->_attributeTypes, SORT_STRING); - } - - /** - * Parses an attributeType value - * - * @param string $value - * @return array - */ - protected function _parseAttributeType($value) - { - $attributeType = array( - 'oid' => null, - 'name' => null, - 'desc' => null, - 'obsolete' => false, - 'sup' => null, - 'equality' => null, - 'ordering' => null, - 'substr' => null, - 'syntax' => null, - 'max-length' => null, - 'single-value' => false, - 'collective' => false, - 'no-user-modification' => false, - 'usage' => 'userApplications', - '_string' => $value, - '_parents' => array()); - - $tokens = $this->_tokenizeString($value); - $attributeType['oid'] = array_shift($tokens); // first token is the oid - $this->_parseLdapSchemaSyntax($attributeType, $tokens); - - if (array_key_exists('syntax', $attributeType)) { - // get max length from syntax - if (preg_match('/^(.+){(\d+)}$/', $attributeType['syntax'], $matches)) { - $attributeType['syntax'] = $matches[1]; - $attributeType['max-length'] = $matches[2]; - } - } - - $this->_ensureNameAttribute($attributeType); - - return $attributeType; - } - - /** - * Loads the object classes - * - * @return void - */ - protected function _loadObjectClasses() - { - $this->_objectClasses = array(); - foreach ($this->getAttribute('objectClasses') as $value) { - $val = $this->_parseObjectClass($value); - $val = new Zend_Ldap_Node_Schema_ObjectClass_OpenLdap($val); - $this->_objectClasses[$val->getName()] = $val; - } - foreach ($this->_objectClasses as $val) { - if (count($val->sup) > 0) { - $this->_resolveInheritance($val, $this->_objectClasses); - } - foreach ($val->aliases as $alias) { - $this->_objectClasses[$alias] = $val; - } - } - ksort($this->_objectClasses, SORT_STRING); - } - - /** - * Parses an objectClasses value - * - * @param string $value - * @return array - */ - protected function _parseObjectClass($value) - { - $objectClass = array( - 'oid' => null, - 'name' => null, - 'desc' => null, - 'obsolete' => false, - 'sup' => array(), - 'abstract' => false, - 'structural' => false, - 'auxiliary' => false, - 'must' => array(), - 'may' => array(), - '_string' => $value, - '_parents' => array()); - - $tokens = $this->_tokenizeString($value); - $objectClass['oid'] = array_shift($tokens); // first token is the oid - $this->_parseLdapSchemaSyntax($objectClass, $tokens); - - $this->_ensureNameAttribute($objectClass); - - return $objectClass; - } - - /** - * Resolves inheritance in objectClasses and attributes - * - * @param Zend_Ldap_Node_Schema_Item $node - * @param array $repository - */ - protected function _resolveInheritance(Zend_Ldap_Node_Schema_Item $node, array $repository) - { - $data = $node->getData(); - $parents = $data['sup']; - if ($parents === null || !is_array($parents) || count($parents) < 1) return; - foreach ($parents as $parent) { - if (!array_key_exists($parent, $repository)) continue; - if (!array_key_exists('_parents', $data) || !is_array($data['_parents'])) { - $data['_parents'] = array(); - } - $data['_parents'][] = $repository[$parent]; - } - $node->setData($data); - } - - /** - * Loads the LDAP syntaxes - * - * @return void - */ - protected function _loadLdapSyntaxes() - { - $this->_ldapSyntaxes = array(); - foreach ($this->getAttribute('ldapSyntaxes') as $value) { - $val = $this->_parseLdapSyntax($value); - $this->_ldapSyntaxes[$val['oid']] = $val; - } - ksort($this->_ldapSyntaxes, SORT_STRING); - } - - /** - * Parses an ldapSyntaxes value - * - * @param string $value - * @return array - */ - protected function _parseLdapSyntax($value) - { - $ldapSyntax = array( - 'oid' => null, - 'desc' => null, - '_string' => $value); - - $tokens = $this->_tokenizeString($value); - $ldapSyntax['oid'] = array_shift($tokens); // first token is the oid - $this->_parseLdapSchemaSyntax($ldapSyntax, $tokens); - - return $ldapSyntax; - } - - /** - * Loads the matching rules - * - * @return void - */ - protected function _loadMatchingRules() - { - $this->_matchingRules = array(); - foreach ($this->getAttribute('matchingRules') as $value) { - $val = $this->_parseMatchingRule($value); - $this->_matchingRules[$val['name']] = $val; - } - ksort($this->_matchingRules, SORT_STRING); - } - - /** - * Parses an matchingRules value - * - * @param string $value - * @return array - */ - protected function _parseMatchingRule($value) - { - $matchingRule = array( - 'oid' => null, - 'name' => null, - 'desc' => null, - 'obsolete' => false, - 'syntax' => null, - '_string' => $value); - - $tokens = $this->_tokenizeString($value); - $matchingRule['oid'] = array_shift($tokens); // first token is the oid - $this->_parseLdapSchemaSyntax($matchingRule, $tokens); - - $this->_ensureNameAttribute($matchingRule); - - return $matchingRule; - } - - /** - * Loads the matching rule use - * - * @return void - */ - protected function _loadMatchingRuleUse() - { - $this->_matchingRuleUse = array(); - foreach ($this->getAttribute('matchingRuleUse') as $value) { - $val = $this->_parseMatchingRuleUse($value); - $this->_matchingRuleUse[$val['name']] = $val; - } - ksort($this->_matchingRuleUse, SORT_STRING); - } - - /** - * Parses an matchingRuleUse value - * - * @param string $value - * @return array - */ - protected function _parseMatchingRuleUse($value) - { - $matchingRuleUse = array( - 'oid' => null, - 'name' => null, - 'desc' => null, - 'obsolete' => false, - 'applies' => array(), - '_string' => $value); - - $tokens = $this->_tokenizeString($value); - $matchingRuleUse['oid'] = array_shift($tokens); // first token is the oid - $this->_parseLdapSchemaSyntax($matchingRuleUse, $tokens); - - $this->_ensureNameAttribute($matchingRuleUse); - - return $matchingRuleUse; - } - - /** - * Ensures that a name element is present and that it is single-values. - * - * @param array $data - */ - protected function _ensureNameAttribute(array &$data) - { - if (!array_key_exists('name', $data) || empty($data['name'])) { - // force a name - $data['name'] = $data['oid']; - } - if (is_array($data['name'])) { - // make one name the default and put the other ones into aliases - $aliases = $data['name']; - $data['name'] = array_shift($aliases); - $data['aliases'] = $aliases; - } else { - $data['aliases'] = array(); - } - } - - /** - * Parse the given tokens into a data structure - * - * @param array $data - * @param array $tokens - * @return void - */ - protected function _parseLdapSchemaSyntax(array &$data, array $tokens) - { - // tokens that have no value associated - $noValue = array('single-value', - 'obsolete', - 'collective', - 'no-user-modification', - 'abstract', - 'structural', - 'auxiliary'); - // tokens that can have multiple values - $multiValue = array('must', 'may', 'sup'); - - while (count($tokens) > 0) { - $token = strtolower(array_shift($tokens)); - if (in_array($token, $noValue)) { - $data[$token] = true; // single value token - } else { - $data[$token] = array_shift($tokens); - // this one follows a string or a list if it is multivalued - if ($data[$token] == '(') { - // this creates the list of values and cycles through the tokens - // until the end of the list is reached ')' - $data[$token] = array(); - while ($tmp = array_shift($tokens)) { - if ($tmp == ')') break; - if ($tmp != '$') { - $data[$token][] = Zend_Ldap_Attribute::convertFromLdapValue($tmp); - } - } - } else { - $data[$token] = Zend_Ldap_Attribute::convertFromLdapValue($data[$token]); - } - // create a array if the value should be multivalued but was not - if (in_array($token, $multiValue) && !is_array($data[$token])) { - $data[$token] = array($data[$token]); - } - } - } - } - - /** - * Tokenizes the given value into an array - * - * @param string $value - * @return array tokens - */ - protected function _tokenizeString($value) - { - $tokens = array(); - $matches = array(); - // this one is taken from PEAR::Net_LDAP2 - $pattern = "/\s* (?:([()]) | ([^'\s()]+) | '((?:[^']+|'[^\s)])*)') \s*/x"; - preg_match_all($pattern, $value, $matches); - $cMatches = count($matches[0]); - $cPattern = count($matches); - for ($i = 0; $i < $cMatches; $i++) { // number of tokens (full pattern match) - for ($j = 1; $j < $cPattern; $j++) { // each subpattern - $tok = trim($matches[$j][$i]); - if (!empty($tok)) { // pattern match in this subpattern - $tokens[$i] = $tok; // this is the token - } - } - } - if ($tokens[0] == '(') array_shift($tokens); - if ($tokens[count($tokens) - 1] == ')') array_pop($tokens); - return $tokens; - } -} diff --git a/library/Zend/Log/Formatter/Firebug.php b/library/Zend/Log/Formatter/Firebug.php deleted file mode 100644 index 2b41a1d74b..0000000000 --- a/library/Zend/Log/Formatter/Firebug.php +++ /dev/null @@ -1,61 +0,0 @@ - Zend_Wildfire_Plugin_FirePhp::ERROR, - Zend_Log::ALERT => Zend_Wildfire_Plugin_FirePhp::ERROR, - Zend_Log::CRIT => Zend_Wildfire_Plugin_FirePhp::ERROR, - Zend_Log::ERR => Zend_Wildfire_Plugin_FirePhp::ERROR, - Zend_Log::WARN => Zend_Wildfire_Plugin_FirePhp::WARN, - Zend_Log::NOTICE => Zend_Wildfire_Plugin_FirePhp::INFO, - Zend_Log::INFO => Zend_Wildfire_Plugin_FirePhp::INFO, - Zend_Log::DEBUG => Zend_Wildfire_Plugin_FirePhp::LOG); - - /** - * The default logging style for un-mapped priorities - * - * @var string - */ - protected $_defaultPriorityStyle = Zend_Wildfire_Plugin_FirePhp::LOG; - - /** - * Flag indicating whether the log writer is enabled - * - * @var boolean - */ - protected $_enabled = true; - - /** - * Class constructor - * - * @return void - */ - public function __construct() - { - if (php_sapi_name() == 'cli') { - $this->setEnabled(false); - } - - $this->_formatter = new Zend_Log_Formatter_Firebug(); - } - - /** - * Create a new instance of Zend_Log_Writer_Firebug - * - * @param array|Zend_Config $config - * @return Zend_Log_Writer_Firebug - */ - static public function factory($config) - { - return new self(); - } - - /** - * Enable or disable the log writer. - * - * @param boolean $enabled Set to TRUE to enable the log writer - * @return boolean The previous value. - */ - public function setEnabled($enabled) - { - $previous = $this->_enabled; - $this->_enabled = $enabled; - return $previous; - } - - /** - * Determine if the log writer is enabled. - * - * @return boolean Returns TRUE if the log writer is enabled. - */ - public function getEnabled() - { - return $this->_enabled; - } - - /** - * Set the default display style for user-defined priorities - * - * @param string $style The default log display style - * @return string Returns previous default log display style - */ - public function setDefaultPriorityStyle($style) - { - $previous = $this->_defaultPriorityStyle; - $this->_defaultPriorityStyle = $style; - return $previous; - } - - /** - * Get the default display style for user-defined priorities - * - * @return string Returns the default log display style - */ - public function getDefaultPriorityStyle() - { - return $this->_defaultPriorityStyle; - } - - /** - * Set a display style for a logging priority - * - * @param int $priority The logging priority - * @param string $style The logging display style - * @return string|boolean The previous logging display style if defined or TRUE otherwise - */ - public function setPriorityStyle($priority, $style) - { - $previous = true; - if (array_key_exists($priority,$this->_priorityStyles)) { - $previous = $this->_priorityStyles[$priority]; - } - $this->_priorityStyles[$priority] = $style; - return $previous; - } - - /** - * Get a display style for a logging priority - * - * @param int $priority The logging priority - * @return string|boolean The logging display style if defined or FALSE otherwise - */ - public function getPriorityStyle($priority) - { - if (array_key_exists($priority,$this->_priorityStyles)) { - return $this->_priorityStyles[$priority]; - } - return false; - } - - /** - * Log a message to the Firebug Console. - * - * @param array $event The event data - * @return void - */ - protected function _write($event) - { - if (!$this->getEnabled()) { - return; - } - - if (array_key_exists($event['priority'],$this->_priorityStyles)) { - $type = $this->_priorityStyles[$event['priority']]; - } else { - $type = $this->_defaultPriorityStyle; - } - - $message = $this->_formatter->format($event); - - $label = isset($event['firebugLabel'])?$event['firebugLabel']:null; - - Zend_Wildfire_Plugin_FirePhp::getInstance()->send($message, - $label, - $type, - array('traceOffset'=>4, - 'fixZendLogOffsetIfApplicable'=>true)); - } -} diff --git a/library/Zend/Log/Writer/Mail.php b/library/Zend/Log/Writer/Mail.php deleted file mode 100644 index 09ac40de47..0000000000 --- a/library/Zend/Log/Writer/Mail.php +++ /dev/null @@ -1,430 +0,0 @@ - 'setFrom', - 'to' => 'addTo', - 'cc' => 'addCc', - 'bcc' => 'addBcc', - ); - - /** - * Class constructor. - * - * Constructs the mail writer; requires a Zend_Mail instance, and takes an - * optional Zend_Layout instance. If Zend_Layout is being used, - * $this->_layout->events will be set for use in the layout template. - * - * @param Zend_Mail $mail Mail instance - * @param Zend_Layout $layout Layout instance; optional - * @return void - */ - public function __construct(Zend_Mail $mail, Zend_Layout $layout = null) - { - $this->_mail = $mail; - if (null !== $layout) { - $this->setLayout($layout); - } - $this->_formatter = new Zend_Log_Formatter_Simple(); - } - - /** - * Create a new instance of Zend_Log_Writer_Mail - * - * @param array|Zend_Config $config - * @return Zend_Log_Writer_Mail - */ - static public function factory($config) - { - $config = self::_parseConfig($config); - $mail = self::_constructMailFromConfig($config); - $writer = new self($mail); - - if (isset($config['layout']) || isset($config['layoutOptions'])) { - $writer->setLayout($config); - } - if (isset($config['layoutFormatter'])) { - $layoutFormatter = new $config['layoutFormatter']; - $writer->setLayoutFormatter($layoutFormatter); - } - if (isset($config['subjectPrependText'])) { - $writer->setSubjectPrependText($config['subjectPrependText']); - } - - return $writer; - } - - /** - * Set the layout - * - * @param Zend_Layout|array $layout - * @return Zend_Log_Writer_Mail - * @throws Zend_Log_Exception - */ - public function setLayout($layout) - { - if (is_array($layout)) { - $layout = $this->_constructLayoutFromConfig($layout); - } - - if (!$layout instanceof Zend_Layout) { - #require_once 'Zend/Log/Exception.php'; - throw new Zend_Log_Exception('Mail must be an instance of Zend_Layout or an array'); - } - $this->_layout = $layout; - - return $this; - } - - /** - * Construct a Zend_Mail instance based on a configuration array - * - * @param array $config - * @return Zend_Mail - * @throws Zend_Log_Exception - */ - protected static function _constructMailFromConfig(array $config) - { - $mailClass = 'Zend_Mail'; - if (isset($config['mail'])) { - $mailClass = $config['mail']; - } - - if (!array_key_exists('charset', $config)) { - $config['charset'] = null; - } - $mail = new $mailClass($config['charset']); - if (!$mail instanceof Zend_Mail) { - throw new Zend_Log_Exception($mail . 'must extend Zend_Mail'); - } - - if (isset($config['subject'])) { - $mail->setSubject($config['subject']); - } - - $headerAddresses = array_intersect_key($config, self::$_methodMapHeaders); - if (count($headerAddresses)) { - foreach ($headerAddresses as $header => $address) { - $method = self::$_methodMapHeaders[$header]; - if (is_array($address) && isset($address['name']) - && !is_numeric($address['name']) - ) { - $params = array( - $address['email'], - $address['name'] - ); - } else if (is_array($address) && isset($address['email'])) { - $params = array($address['email']); - } else { - $params = array($address); - } - call_user_func_array(array($mail, $method), $params); - } - } - - return $mail; - } - - /** - * Construct a Zend_Layout instance based on a configuration array - * - * @param array $config - * @return Zend_Layout - * @throws Zend_Log_Exception - */ - protected function _constructLayoutFromConfig(array $config) - { - $config = array_merge(array( - 'layout' => 'Zend_Layout', - 'layoutOptions' => null - ), $config); - - $layoutClass = $config['layout']; - $layout = new $layoutClass($config['layoutOptions']); - if (!$layout instanceof Zend_Layout) { - throw new Zend_Log_Exception($layout . 'must extend Zend_Layout'); - } - - return $layout; - } - - /** - * Places event line into array of lines to be used as message body. - * - * Handles the formatting of both plaintext entries, as well as those - * rendered with Zend_Layout. - * - * @param array $event Event data - * @return void - */ - protected function _write($event) - { - // Track the number of entries per priority level. - if (!isset($this->_numEntriesPerPriority[$event['priorityName']])) { - $this->_numEntriesPerPriority[$event['priorityName']] = 1; - } else { - $this->_numEntriesPerPriority[$event['priorityName']]++; - } - - $formattedEvent = $this->_formatter->format($event); - - // All plaintext events are to use the standard formatter. - $this->_eventsToMail[] = $formattedEvent; - - // If we have a Zend_Layout instance, use a specific formatter for the - // layout if one exists. Otherwise, just use the event with its - // default format. - if ($this->_layout) { - if ($this->_layoutFormatter) { - $this->_layoutEventsToMail[] = - $this->_layoutFormatter->format($event); - } else { - $this->_layoutEventsToMail[] = $formattedEvent; - } - } - } - - /** - * Gets instance of Zend_Log_Formatter_Instance used for formatting a - * message using Zend_Layout, if applicable. - * - * @return Zend_Log_Formatter_Interface|null The formatter, or null. - */ - public function getLayoutFormatter() - { - return $this->_layoutFormatter; - } - - /** - * Sets a specific formatter for use with Zend_Layout events. - * - * Allows use of a second formatter on lines that will be rendered with - * Zend_Layout. In the event that Zend_Layout is not being used, this - * formatter cannot be set, so an exception will be thrown. - * - * @param Zend_Log_Formatter_Interface $formatter - * @return Zend_Log_Writer_Mail - * @throws Zend_Log_Exception - */ - public function setLayoutFormatter(Zend_Log_Formatter_Interface $formatter) - { - if (!$this->_layout) { - throw new Zend_Log_Exception( - 'cannot set formatter for layout; ' . - 'a Zend_Layout instance is not in use'); - } - - $this->_layoutFormatter = $formatter; - return $this; - } - - /** - * Allows caller to have the mail subject dynamically set to contain the - * entry counts per-priority level. - * - * Sets the text for use in the subject, with entry counts per-priority - * level appended to the end. Since a Zend_Mail subject can only be set - * once, this method cannot be used if the Zend_Mail object already has a - * subject set. - * - * @param string $subject Subject prepend text. - * @return Zend_Log_Writer_Mail - * @throws Zend_Log_Exception - */ - public function setSubjectPrependText($subject) - { - if ($this->_mail->getSubject()) { - throw new Zend_Log_Exception( - 'subject already set on mail; ' . - 'cannot set subject prepend text'); - } - - $this->_subjectPrependText = (string) $subject; - return $this; - } - - /** - * Sends mail to recipient(s) if log entries are present. Note that both - * plaintext and HTML portions of email are handled here. - * - * @return void - */ - public function shutdown() - { - // If there are events to mail, use them as message body. Otherwise, - // there is no mail to be sent. - if (empty($this->_eventsToMail)) { - return; - } - - if ($this->_subjectPrependText !== null) { - // Tack on the summary of entries per-priority to the subject - // line and set it on the Zend_Mail object. - $numEntries = $this->_getFormattedNumEntriesPerPriority(); - $this->_mail->setSubject( - "{$this->_subjectPrependText} ({$numEntries})"); - } - - - // Always provide events to mail as plaintext. - $this->_mail->setBodyText(implode('', $this->_eventsToMail)); - - // If a Zend_Layout instance is being used, set its "events" - // value to the lines formatted for use with the layout. - if ($this->_layout) { - // Set the required "messages" value for the layout. Here we - // are assuming that the layout is for use with HTML. - $this->_layout->events = - implode('', $this->_layoutEventsToMail); - - // If an exception occurs during rendering, convert it to a notice - // so we can avoid an exception thrown without a stack frame. - try { - $this->_mail->setBodyHtml($this->_layout->render()); - } catch (Exception $e) { - trigger_error( - "exception occurred when rendering layout; " . - "unable to set html body for message; " . - "message = {$e->getMessage()}; " . - "code = {$e->getCode()}; " . - "exception class = " . get_class($e), - E_USER_NOTICE); - } - } - - // Finally, send the mail. If an exception occurs, convert it into a - // warning-level message so we can avoid an exception thrown without a - // stack frame. - try { - $this->_mail->send(); - } catch (Exception $e) { - trigger_error( - "unable to send log entries via email; " . - "message = {$e->getMessage()}; " . - "code = {$e->getCode()}; " . - "exception class = " . get_class($e), - E_USER_WARNING); - } - } - - /** - * Gets a string of number of entries per-priority level that occurred, or - * an emptry string if none occurred. - * - * @return string - */ - protected function _getFormattedNumEntriesPerPriority() - { - $strings = array(); - - foreach ($this->_numEntriesPerPriority as $priority => $numEntries) { - $strings[] = "{$priority}={$numEntries}"; - } - - return implode(', ', $strings); - } -} diff --git a/library/Zend/Markup.php b/library/Zend/Markup.php deleted file mode 100644 index bb99be4b4a..0000000000 --- a/library/Zend/Markup.php +++ /dev/null @@ -1,134 +0,0 @@ - 'Zend/Markup/Parser/', - )); - } - - return self::$_parserLoader; - } - - /** - * Get the renderer loader - * - * @return Zend_Loader_PluginLoader - */ - public static function getRendererLoader() - { - if (!(self::$_rendererLoader instanceof Zend_Loader_PluginLoader)) { - self::$_rendererLoader = new Zend_Loader_PluginLoader(array( - 'Zend_Markup_Renderer' => 'Zend/Markup/Renderer/', - )); - } - - return self::$_rendererLoader; - } - - /** - * Add a parser path - * - * @param string $prefix - * @param string $path - * @return Zend_Loader_PluginLoader - */ - public static function addParserPath($prefix, $path) - { - return self::getParserLoader()->addPrefixPath($prefix, $path); - } - - /** - * Add a renderer path - * - * @param string $prefix - * @param string $path - * @return Zend_Loader_PluginLoader - */ - public static function addRendererPath($prefix, $path) - { - return self::getRendererLoader()->addPrefixPath($prefix, $path); - } - - /** - * Factory pattern - * - * @param string $parser - * @param string $renderer - * @param array $options - * @return Zend_Markup_Renderer_RendererAbstract - */ - public static function factory($parser, $renderer = 'Html', array $options = array()) - { - $parserClass = self::getParserLoader()->load($parser); - $rendererClass = self::getRendererLoader()->load($renderer); - - $parser = new $parserClass(); - $options['parser'] = $parser; - $renderer = new $rendererClass($options); - - return $renderer; - } -} diff --git a/library/Zend/Markup/Exception.php b/library/Zend/Markup/Exception.php deleted file mode 100644 index 7609e51b89..0000000000 --- a/library/Zend/Markup/Exception.php +++ /dev/null @@ -1,38 +0,0 @@ - array( - 'type' => self::TYPE_DEFAULT, - 'stoppers' => array(), - ), - '*' => array( - 'type' => self::TYPE_DEFAULT, - 'stoppers' => array(self::NEWLINE, '[/*]', '[/]'), - ), - 'hr' => array( - 'type' => self::TYPE_SINGLE, - 'stoppers' => array(), - ), - 'code' => array( - 'type' => self::TYPE_DEFAULT, - 'stoppers' => array('[/code]', '[/]'), - 'parse_inside' => false - ) - ); - - /** - * Token array - * - * @var array - */ - protected $_tokens = array(); - - /** - * State - * - * @var int - */ - protected $_state = self::STATE_SCAN; - - - /** - * Prepare the parsing of a bbcode string, the real parsing is done in {@link _parse()} - * - * @param string $value - * @return Zend_Markup_TokenList - */ - public function parse($value) - { - if (!is_string($value)) { - /** - * @see Zend_Markup_Parser_Exception - */ - #require_once 'Zend/Markup/Parser/Exception.php'; - throw new Zend_Markup_Parser_Exception('Value to parse should be a string.'); - } - - if (empty($value)) { - /** - * @see Zend_Markup_Parser_Exception - */ - #require_once 'Zend/Markup/Parser/Exception.php'; - throw new Zend_Markup_Parser_Exception('Value to parse cannot be left empty.'); - } - - $this->_value = str_replace(array("\r\n", "\r", "\n"), self::NEWLINE, $value); - - // variable initialization for tokenizer - $this->_valueLen = strlen($this->_value); - $this->_pointer = 0; - $this->_buffer = ''; - $this->_temp = array(); - $this->_state = self::STATE_SCAN; - $this->_tokens = array(); - - $this->_tokenize(); - - // variable initialization for treebuilder - $this->_searchedStoppers = array(); - $this->_tree = new Zend_Markup_TokenList(); - $this->_current = new Zend_Markup_Token( - '', - Zend_Markup_Token::TYPE_NONE, - 'Zend_Markup_Root' - ); - - $this->_tree->addChild($this->_current); - - $this->_createTree(); - - return $this->_tree; - } - - /** - * Tokenize - * - * @param string $input - * - * @return void - */ - protected function _tokenize() - { - $attribute = ''; - - while ($this->_pointer < $this->_valueLen) { - switch ($this->_state) { - case self::STATE_SCAN: - $matches = array(); - $regex = '#\G(?[^\[]*)(?\[(?[' . self::NAME_CHARSET . ']+)?)?#'; - preg_match($regex, $this->_value, $matches, null, $this->_pointer); - - $this->_pointer += strlen($matches[0]); - - if (!empty($matches['text'])) { - $this->_buffer .= $matches['text']; - } - - if (!isset($matches['open'])) { - // great, no tag, we are ending the string - break; - } - if (!isset($matches['name'])) { - $this->_buffer .= $matches['open']; - break; - } - - $this->_temp = array( - 'tag' => '[' . $matches['name'], - 'name' => $matches['name'], - 'attributes' => array() - ); - - if ($this->_pointer >= $this->_valueLen) { - // damn, no tag - $this->_buffer .= $this->_temp['tag']; - break 2; - } - - if ($this->_value[$this->_pointer] == '=') { - $this->_pointer++; - - $this->_temp['tag'] .= '='; - $this->_state = self::STATE_PARSEVALUE; - $attribute = $this->_temp['name']; - } else { - $this->_state = self::STATE_SCANATTRS; - } - break; - case self::STATE_SCANATTRS: - $matches = array(); - $regex = '#\G((?\s*\])|\s+(?[' . self::NAME_CHARSET . ']+)(?=?))#'; - if (!preg_match($regex, $this->_value, $matches, null, $this->_pointer)) { - break 2; - } - - $this->_pointer += strlen($matches[0]); - - if (!empty($matches['end'])) { - if (!empty($this->_buffer)) { - $this->_tokens[] = array( - 'tag' => $this->_buffer, - 'type' => Zend_Markup_Token::TYPE_NONE - ); - $this->_buffer = ''; - } - $this->_temp['tag'] .= $matches['end']; - $this->_temp['type'] = Zend_Markup_Token::TYPE_TAG; - - $this->_tokens[] = $this->_temp; - $this->_temp = array(); - - $this->_state = self::STATE_SCAN; - } else { - // attribute name - $attribute = $matches['attribute']; - - $this->_temp['tag'] .= $matches[0]; - - $this->_temp['attributes'][$attribute] = ''; - - if (empty($matches['eq'])) { - $this->_state = self::STATE_SCANATTRS; - } else { - $this->_state = self::STATE_PARSEVALUE; - } - } - break; - case self::STATE_PARSEVALUE: - $matches = array(); - $regex = '#\G((?"|\')(?.*?)\\2|(?[^\]\s]+))#'; - if (!preg_match($regex, $this->_value, $matches, null, $this->_pointer)) { - $this->_state = self::STATE_SCANATTRS; - break; - } - - $this->_pointer += strlen($matches[0]); - - if (!empty($matches['quote'])) { - $this->_temp['attributes'][$attribute] = $matches['valuequote']; - } else { - $this->_temp['attributes'][$attribute] = $matches['value']; - } - $this->_temp['tag'] .= $matches[0]; - - $this->_state = self::STATE_SCANATTRS; - break; - } - } - - if (!empty($this->_buffer)) { - $this->_tokens[] = array( - 'tag' => $this->_buffer, - 'type' => Zend_Markup_Token::TYPE_NONE - ); - } - } - - /** - * Parse the token array into a tree - * - * @param array $tokens - * - * @return void - */ - public function _createTree() - { - foreach ($this->_tokens as $token) { - // first we want to know if this tag is a stopper, or at least a searched one - if ($this->_isStopper($token['tag'])) { - // find the stopper - $oldItems = array(); - - while (!in_array($token['tag'], $this->_tags[$this->_current->getName()]['stoppers'])) { - $oldItems[] = clone $this->_current; - $this->_current = $this->_current->getParent(); - } - - // we found the stopper, so stop the tag - $this->_current->setStopper($token['tag']); - $this->_removeFromSearchedStoppers($this->_current); - $this->_current = $this->_current->getParent(); - - // add the old items again if there are any - if (!empty($oldItems)) { - foreach (array_reverse($oldItems) as $item) { - /* @var $token Zend_Markup_Token */ - $this->_current->addChild($item); - $item->setParent($this->_current); - $this->_current = $item; - } - } - } else { - if ($token['type'] == Zend_Markup_Token::TYPE_TAG) { - if ($token['tag'] == self::NEWLINE) { - // this is a newline tag, add it as a token - $this->_current->addChild(new Zend_Markup_Token( - "\n", - Zend_Markup_Token::TYPE_NONE, - '', - array(), - $this->_current - )); - } elseif (isset($token['name']) && ($token['name'][0] == '/')) { - // this is a stopper, add it as a empty token - $this->_current->addChild(new Zend_Markup_Token( - $token['tag'], - Zend_Markup_Token::TYPE_NONE, - '', - array(), - $this->_current - )); - } elseif (isset($this->_tags[$this->_current->getName()]['parse_inside']) - && !$this->_tags[$this->_current->getName()]['parse_inside'] - ) { - $this->_current->addChild(new Zend_Markup_Token( - $token['tag'], - Zend_Markup_Token::TYPE_NONE, - '', - array(), - $this->_current - )); - } else { - // add the tag - $child = new Zend_Markup_Token( - $token['tag'], - $token['type'], - $token['name'], - $token['attributes'], - $this->_current - ); - $this->_current->addChild($child); - - // add stoppers for this tag, if its has stoppers - if ($this->_getType($token['name']) == self::TYPE_DEFAULT) { - $this->_current = $child; - - $this->_addToSearchedStoppers($this->_current); - } - } - } else { - // no tag, just add it as a simple token - $this->_current->addChild(new Zend_Markup_Token( - $token['tag'], - Zend_Markup_Token::TYPE_NONE, - '', - array(), - $this->_current - )); - } - } - } - } - - /** - * Check if there is a tag declaration, and if it isnt there, add it - * - * @param string $name - * - * @return void - */ - protected function _checkTagDeclaration($name) - { - if (!isset($this->_tags[$name])) { - $this->_tags[$name] = array( - 'type' => self::TYPE_DEFAULT, - 'stoppers' => array( - '[/' . $name . ']', - '[/]' - ) - ); - } - } - /** - * Check the tag's type - * - * @param string $name - * @return string - */ - protected function _getType($name) - { - $this->_checkTagDeclaration($name); - - return $this->_tags[$name]['type']; - } - - /** - * Check if the tag is a stopper - * - * @param string $tag - * @return bool - */ - protected function _isStopper($tag) - { - $this->_checkTagDeclaration($this->_current->getName()); - - if (!empty($this->_searchedStoppers[$tag])) { - return true; - } - - return false; - } - - /** - * Add to searched stoppers - * - * @param Zend_Markup_Token $token - * @return void - */ - protected function _addToSearchedStoppers(Zend_Markup_Token $token) - { - $this->_checkTagDeclaration($token->getName()); - - foreach ($this->_tags[$token->getName()]['stoppers'] as $stopper) { - if (!isset($this->_searchedStoppers[$stopper])) { - $this->_searchedStoppers[$stopper] = 0; - } - ++$this->_searchedStoppers[$stopper]; - } - } - - /** - * Remove from searched stoppers - * - * @param Zend_Markup_Token $token - * @return void - */ - protected function _removeFromSearchedStoppers(Zend_Markup_Token $token) - { - $this->_checkTagDeclaration($token->getName()); - - foreach ($this->_tags[$token->getName()]['stoppers'] as $stopper) { - --$this->_searchedStoppers[$stopper]; - } - } - -} diff --git a/library/Zend/Markup/Parser/Exception.php b/library/Zend/Markup/Parser/Exception.php deleted file mode 100644 index a71062e9f8..0000000000 --- a/library/Zend/Markup/Parser/Exception.php +++ /dev/null @@ -1,40 +0,0 @@ - - * array( - * array( - * 'tag' => '[tag="a" attr=val]', - * 'type' => Zend_Markup::TYPE_TAG, - * 'name' => 'tag', - * 'stoppers' => array('[/]', '[/tag]'), - * 'attributes' => array( - * 'tag' => 'a', - * 'attr' => 'val' - * ) - * ), - * array( - * 'tag' => 'value', - * 'type' => Zend_Markup::TYPE_NONE - * ), - * array( - * 'tag' => '[/tag]', - * 'type' => Zend_Markup::TYPE_STOPPER, - * 'name' => 'tag', - * 'stoppers' => array(), - * 'attributes' => array() - * ) - * ) - * - * - * @param string $value - * @return array - */ - public function parse($value); -} diff --git a/library/Zend/Markup/Renderer/Exception.php b/library/Zend/Markup/Renderer/Exception.php deleted file mode 100644 index 4c5c527e11..0000000000 --- a/library/Zend/Markup/Renderer/Exception.php +++ /dev/null @@ -1,40 +0,0 @@ - array('block', 'inline', 'block-empty', 'inline-empty', 'list'), - 'inline' => array('inline', 'inline-empty'), - 'list' => array('list-item'), - 'list-item' => array('inline', 'inline-empty', 'list'), - 'block-empty' => array(), - 'inline-empty' => array(), - ); - - /** - * The current group - * - * @var string - */ - protected $_group = 'block'; - - /** - * Default attributes - * - * @var array - */ - protected static $_defaultAttributes = array( - 'id' => '', - 'class' => '', - 'style' => '', - 'lang' => '', - 'title' => '' - ); - - - /** - * Constructor - * - * @param array|Zend_Config $options - * - * @return void - */ - public function __construct($options = array()) - { - if ($options instanceof Zend_Config) { - $options = $options->toArray(); - } - - $this->_pluginLoader = new Zend_Loader_PluginLoader(array( - 'Zend_Markup_Renderer_Html' => 'Zend/Markup/Renderer/Html/' - )); - - if (!isset($options['useDefaultMarkups']) && isset($options['useDefaultTags'])) { - $options['useDefaultMarkups'] = $options['useDefaultTags']; - } - if (isset($options['useDefaultMarkups']) && ($options['useDefaultMarkups'] !== false)) { - $this->_defineDefaultMarkups(); - } elseif (!isset($options['useDefaultMarkups'])) { - $this->_defineDefaultMarkups(); - } - - parent::__construct($options); - } - - /** - * Define the default markups - * - * @return void - */ - protected function _defineDefaultMarkups() - { - $this->_markups = array( - 'b' => array( - 'type' => 10, // self::TYPE_REPLACE | self::TAG_NORMAL - 'tag' => 'strong', - 'group' => 'inline', - 'filter' => true, - ), - 'u' => array( - 'type' => 10, - 'tag' => 'span', - 'attributes' => array( - 'style' => 'text-decoration: underline;', - ), - 'group' => 'inline', - 'filter' => true, - ), - 'i' => array( - 'type' => 10, - 'tag' => 'em', - 'group' => 'inline', - 'filter' => true, - ), - 'cite' => array( - 'type' => 10, - 'tag' => 'cite', - 'group' => 'inline', - 'filter' => true, - ), - 'del' => array( - 'type' => 10, - 'tag' => 'del', - 'group' => 'inline', - 'filter' => true, - ), - 'ins' => array( - 'type' => 10, - 'tag' => 'ins', - 'group' => 'inline', - 'filter' => true, - ), - 'sub' => array( - 'type' => 10, - 'tag' => 'sub', - 'group' => 'inline', - 'filter' => true, - ), - 'sup' => array( - 'type' => 10, - 'tag' => 'sup', - 'group' => 'inline', - 'filter' => true, - ), - 'span' => array( - 'type' => 10, - 'tag' => 'span', - 'group' => 'inline', - 'filter' => true, - ), - 'acronym' => array( - 'type' => 10, - 'tag' => 'acronym', - 'group' => 'inline', - 'filter' => true, - ), - // headings - 'h1' => array( - 'type' => 10, - 'tag' => 'h1', - 'group' => 'inline', - 'filter' => true, - ), - 'h2' => array( - 'type' => 10, - 'tag' => 'h2', - 'group' => 'inline', - 'filter' => true, - ), - 'h3' => array( - 'type' => 10, - 'tag' => 'h3', - 'group' => 'inline', - 'filter' => true, - ), - 'h4' => array( - 'type' => 10, - 'tag' => 'h4', - 'group' => 'inline', - 'filter' => true, - ), - 'h5' => array( - 'type' => 10, - 'tag' => 'h5', - 'group' => 'inline', - 'filter' => true, - ), - 'h6' => array( - 'type' => 10, - 'tag' => 'h6', - 'group' => 'inline', - 'filter' => true, - ), - // callback tags - 'url' => array( - 'type' => 6, // self::TYPE_CALLBACK | self::TAG_NORMAL - 'callback' => null, - 'group' => 'inline', - 'filter' => true, - ), - 'img' => array( - 'type' => 6, - 'callback' => null, - 'group' => 'inline-empty', - 'filter' => true, - ), - 'code' => array( - 'type' => 6, - 'callback' => null, - 'group' => 'block-empty', - 'filter' => false, - ), - 'p' => array( - 'type' => 10, - 'tag' => 'p', - 'group' => 'block', - 'filter' => true, - ), - 'ignore' => array( - 'type' => 10, - 'start' => '', - 'end' => '', - 'group' => 'block-empty', - 'filter' => true, - ), - 'quote' => array( - 'type' => 10, - 'tag' => 'blockquote', - 'group' => 'block', - 'filter' => true, - ), - 'list' => array( - 'type' => 6, - 'callback' => null, - 'group' => 'list', - 'filter' => new Zend_Filter_PregReplace('/.*/is', ''), - ), - '*' => array( - 'type' => 10, - 'tag' => 'li', - 'group' => 'list-item', - 'filter' => true, - ), - 'hr' => array( - 'type' => 9, // self::TYPE_REPLACE | self::TAG_SINGLE - 'tag' => 'hr', - 'group' => 'block', - 'empty' => true, - ), - // aliases - 'bold' => array( - 'type' => 16, - 'name' => 'b', - ), - 'strong' => array( - 'type' => 16, - 'name' => 'b', - ), - 'italic' => array( - 'type' => 16, - 'name' => 'i', - ), - 'em' => array( - 'type' => 16, - 'name' => 'i', - ), - 'emphasized' => array( - 'type' => 16, - 'name' => 'i', - ), - 'underline' => array( - 'type' => 16, - 'name' => 'u', - ), - 'citation' => array( - 'type' => 16, - 'name' => 'cite', - ), - 'deleted' => array( - 'type' => 16, - 'name' => 'del', - ), - 'insert' => array( - 'type' => 16, - 'name' => 'ins', - ), - 'strike' => array( - 'type' => 16, - 'name' => 's', - ), - 's' => array( - 'type' => 16, - 'name' => 'del', - ), - 'subscript' => array( - 'type' => 16, - 'name' => 'sub', - ), - 'superscript' => array( - 'type' => 16, - 'name' => 'sup', - ), - 'a' => array( - 'type' => 16, - 'name' => 'url', - ), - 'image' => array( - 'type' => 16, - 'name' => 'img', - ), - 'li' => array( - 'type' => 16, - 'name' => '*', - ), - 'color' => array( - 'type' => 16, - 'name' => 'span', - ), - ); - } - - /** - * Add the default filters - * - * @return void - */ - public function addDefaultFilters() - { - $this->_defaultFilter = new Zend_Filter(); - - $this->_defaultFilter->addFilter(new Zend_Filter_HtmlEntities(array('encoding' => self::getEncoding()))); - $this->_defaultFilter->addFilter(new Zend_Filter_Callback('nl2br')); - } - - /** - * Execute a replace token - * - * @param Zend_Markup_Token $token - * @param array $markup - * @return string - */ - protected function _executeReplace(Zend_Markup_Token $token, $markup) - { - if (isset($markup['tag'])) { - if (!isset($markup['attributes'])) { - $markup['attributes'] = array(); - } - $attrs = self::renderAttributes($token, $markup['attributes']); - return "<{$markup['tag']}{$attrs}>{$this->_render($token)}"; - } - - return parent::_executeReplace($token, $markup); - } - - /** - * Execute a single replace token - * - * @param Zend_Markup_Token $token - * @param array $markup - * @return string - */ - protected function _executeSingleReplace(Zend_Markup_Token $token, $markup) - { - if (isset($markup['tag'])) { - if (!isset($markup['attributes'])) { - $markup['attributes'] = array(); - } - $attrs = self::renderAttributes($token, $markup['attributes']); - return "<{$markup['tag']}{$attrs} />"; - } - return parent::_executeSingleReplace($token, $markup); - } - - /** - * Render some attributes - * - * @param Zend_Markup_Token $token - * @param array $attributes - * @return string - */ - public static function renderAttributes(Zend_Markup_Token $token, array $attributes = array()) - { - $attributes = array_merge(self::$_defaultAttributes, $attributes); - - $return = ''; - - $tokenAttributes = $token->getAttributes(); - - // correct style attribute - if (isset($tokenAttributes['style'])) { - $tokenAttributes['style'] = trim($tokenAttributes['style']); - - if ($tokenAttributes['style'][strlen($tokenAttributes['style']) - 1] != ';') { - $tokenAttributes['style'] .= ';'; - } - } else { - $tokenAttributes['style'] = ''; - } - - // special treathment for 'align' and 'color' attribute - if (isset($tokenAttributes['align'])) { - $tokenAttributes['style'] .= 'text-align: ' . $tokenAttributes['align'] . ';'; - unset($tokenAttributes['align']); - } - if (isset($tokenAttributes['color']) && self::checkColor($tokenAttributes['color'])) { - $tokenAttributes['style'] .= 'color: ' . $tokenAttributes['color'] . ';'; - unset($tokenAttributes['color']); - } - - /* - * loop through all the available attributes, and check if there is - * a value defined by the token - * if there is no value defined by the token, use the default value or - * don't set the attribute - */ - foreach ($attributes as $attribute => $value) { - if (isset($tokenAttributes[$attribute]) && !empty($tokenAttributes[$attribute])) { - $return .= ' ' . $attribute . '="' . htmlentities($tokenAttributes[$attribute], - ENT_QUOTES, - self::getEncoding()) . '"'; - } elseif (!empty($value)) { - $return .= ' ' . $attribute . '="' . htmlentities($value, ENT_QUOTES, self::getEncoding()) . '"'; - } - } - - return $return; - } - - /** - * Check if a color is a valid HTML color - * - * @param string $color - * - * @return bool - */ - public static function checkColor($color) - { - /* - * aqua, black, blue, fuchsia, gray, green, lime, maroon, navy, olive, - * purple, red, silver, teal, white, and yellow. - */ - $colors = array( - 'aqua', 'black', 'blue', 'fuchsia', 'gray', 'green', 'lime', - 'maroon', 'navy', 'olive', 'purple', 'red', 'silver', 'teal', - 'white', 'yellow' - ); - - if (in_array($color, $colors)) { - return true; - } - - if (preg_match('/\#[0-9a-f]{6}/i', $color)) { - return true; - } - - return false; - } - - /** - * Check if the URI is valid - * - * @param string $uri - * - * @return bool - */ - public static function isValidUri($uri) - { - if (!preg_match('/^([a-z][a-z+\-.]*):/i', $uri, $matches)) { - return false; - } - - $scheme = strtolower($matches[1]); - - switch ($scheme) { - case 'javascript': - // JavaScript scheme is not allowed for security reason - return false; - - case 'http': - case 'https': - case 'ftp': - $components = @parse_url($uri); - - if ($components === false) { - return false; - } - - if (!isset($components['host'])) { - return false; - } - - return true; - - default: - return true; - } - } -} diff --git a/library/Zend/Markup/Renderer/Html/Code.php b/library/Zend/Markup/Renderer/Html/Code.php deleted file mode 100644 index 38b6631ae7..0000000000 --- a/library/Zend/Markup/Renderer/Html/Code.php +++ /dev/null @@ -1,53 +0,0 @@ -_renderer = $renderer; - } - - /** - * Get the HTML renderer instance - * - * @return Zend_Markup_Renderer_Html - */ - public function getRenderer() - { - return $this->_renderer; - } -} diff --git a/library/Zend/Markup/Renderer/Html/Img.php b/library/Zend/Markup/Renderer/Html/Img.php deleted file mode 100644 index 7febc2f98a..0000000000 --- a/library/Zend/Markup/Renderer/Html/Img.php +++ /dev/null @@ -1,84 +0,0 @@ -hasAttribute('alt')) { - $alt = $token->getAttribute('alt'); - } else { - // try to get the alternative from the URL - $alt = rtrim($text, '/'); - $alt = strrchr($alt, '/'); - if (false !== strpos($alt, '.')) { - $alt = substr($alt, 1, strpos($alt, '.') - 1); - } - } - - // run the URI and alt through htmlentities - $uri = htmlentities($uri, ENT_QUOTES, Zend_Markup_Renderer_Html::getEncoding()); - $alt = htmlentities($alt, ENT_QUOTES, Zend_Markup_Renderer_Html::getEncoding()); - - - return "\"{$alt}\"""; - } - -} diff --git a/library/Zend/Markup/Renderer/Html/List.php b/library/Zend/Markup/Renderer/Html/List.php deleted file mode 100644 index 2175fd84e0..0000000000 --- a/library/Zend/Markup/Renderer/Html/List.php +++ /dev/null @@ -1,103 +0,0 @@ -hasAttribute('list')) { - // because '01' == '1' - if ($token->getAttribute('list') === '01') { - $type = 'decimal-leading-zero'; - } else { - switch ($token->getAttribute('list')) { - case '1': - $type = 'decimal'; - break; - case 'i': - $type = 'lower-roman'; - break; - case 'I': - $type = 'upper-roman'; - break; - case 'a': - $type = 'lower-alpha'; - break; - case 'A': - $type = 'upper-alpha'; - break; - - // the following type is unsupported by IE (including IE8) - case 'alpha': - $type = 'lower-greek'; - break; - - // the CSS names itself - case 'armenian': // unsupported by IE (including IE8) - case 'decimal': - case 'decimal-leading-zero': // unsupported by IE (including IE8) - case 'georgian': // unsupported by IE (including IE8) - case 'lower-alpha': - case 'lower-greek': // unsupported by IE (including IE8) - case 'lower-latin': // unsupported by IE (including IE8) - case 'lower-roman': - case 'upper-alpha': - case 'upper-latin': // unsupported by IE (including IE8) - case 'upper-roman': - $type = $token->getAttribute('list'); - break; - } - } - } - - if (null !== $type) { - return "
    {$text}
"; - } else { - return "
    {$text}
"; - } - } - -} diff --git a/library/Zend/Markup/Renderer/Html/Url.php b/library/Zend/Markup/Renderer/Html/Url.php deleted file mode 100644 index 0eb276d680..0000000000 --- a/library/Zend/Markup/Renderer/Html/Url.php +++ /dev/null @@ -1,77 +0,0 @@ -hasAttribute('url')) { - $uri = $token->getAttribute('url'); - } else { - $uri = $text; - } - - if (!preg_match('/^([a-z][a-z+\-.]*):/i', $uri)) { - $uri = 'http://' . $uri; - } - - // check if the URL is valid - if (!Zend_Markup_Renderer_Html::isValidUri($uri)) { - return $text; - } - - $attributes = Zend_Markup_Renderer_Html::renderAttributes($token); - - // run the URI through htmlentities - $uri = htmlentities($uri, ENT_QUOTES, Zend_Markup_Renderer_Html::getEncoding()); - - return "{$text}"; - } - -} diff --git a/library/Zend/Markup/Renderer/RendererAbstract.php b/library/Zend/Markup/Renderer/RendererAbstract.php deleted file mode 100644 index 3ec5db5077..0000000000 --- a/library/Zend/Markup/Renderer/RendererAbstract.php +++ /dev/null @@ -1,702 +0,0 @@ -toArray(); - } - - if (isset($options['encoding'])) { - $this->setEncoding($options['encoding']); - } - if (isset($options['parser'])) { - $this->setParser($options['parser']); - } - if (!isset($options['useDefaultFilters']) || ($options['useDefaultFilters'] === true)) { - $this->addDefaultFilters(); - } - if (isset($options['defaultFilter'])) { - $this->addDefaultFilter($options['defaultFilter']); - } - } - - /** - * Set the parser - * - * @param Zend_Markup_Parser_ParserInterface $parser - * @return Zend_Markup_Renderer_RendererAbstract - */ - public function setParser(Zend_Markup_Parser_ParserInterface $parser) - { - $this->_parser = $parser; - return $this; - } - - /** - * Get the parser - * - * @return Zend_Markup_Parser_ParserInterface - */ - public function getParser() - { - return $this->_parser; - } - - /** - * Get the plugin loader - * - * @return Zend_Loader_PluginLoader - */ - public function getPluginLoader() - { - return $this->_pluginLoader; - } - - /** - * Set the renderer's encoding - * - * @param string $encoding - * - * @return void - */ - public static function setEncoding($encoding) - { - self::$_encoding = $encoding; - } - - /** - * Get the renderer's encoding - * - * @return string - */ - public static function getEncoding() - { - return self::$_encoding; - } - - /** - * Add a new markup - * - * @param string $name - * @param string $type - * @param array $options - * - * @return Zend_Markup_Renderer_RendererAbstract - */ - public function addMarkup($name, $type, array $options) - { - if (!isset($options['group']) && ($type ^ self::TYPE_ALIAS)) { - #require_once 'Zend/Markup/Renderer/Exception.php'; - throw new Zend_Markup_Renderer_Exception("There is no render group defined."); - } - - // add the filter - if (isset($options['filter'])) { - if ($options['filter'] instanceof Zend_Filter_Interface) { - $filter = $options['filter']; - } elseif ($options['filter'] === true) { - $filter = $this->getDefaultFilter(); - } else { - $filter = false; - } - } else { - $filter = $this->getDefaultFilter(); - } - - // check the type - if ($type & self::TYPE_CALLBACK) { - // add a callback tag - if (isset($options['callback'])) { - if (!($options['callback'] instanceof Zend_Markup_Renderer_TokenConverterInterface)) { - #require_once 'Zend/Markup/Renderer/Exception.php'; - throw new Zend_Markup_Renderer_Exception("Not a valid tag callback."); - } - if (method_exists($options['callback'], 'setRenderer')) { - $options['callback']->setRenderer($this); - } - } else { - $options['callback'] = null; - } - - $options['type'] = $type; - $options['filter'] = $filter; - - $this->_markups[$name] = $options; - } elseif ($type & self::TYPE_ALIAS) { - // add an alias - if (empty($options['name'])) { - #require_once 'Zend/Markup/Renderer/Exception.php'; - throw new Zend_Markup_Renderer_Exception( - 'No alias was provided but tag was defined as such'); - } - - $this->_markups[$name] = array( - 'type' => self::TYPE_ALIAS, - 'name' => $options['name'] - ); - } else { - if ($type && array_key_exists('empty', $options) && $options['empty']) { - // add a single replace markup - $options['type'] = $type; - $options['filter'] = $filter; - - $this->_markups[$name] = $options; - } else { - // add a replace markup - $options['type'] = $type; - $options['filter'] = $filter; - - $this->_markups[$name] = $options; - } - } - return $this; - } - - /** - * Remove a markup - * - * @param string $name - * - * @return void - */ - public function removeMarkup($name) - { - unset($this->_markups[$name]); - } - - /** - * Remove the default tags - * - * @return void - */ - public function clearMarkups() - { - $this->_markups = array(); - } - - /** - * Render function - * - * @param Zend_Markup_TokenList|string $tokenList - * @return string - */ - public function render($value) - { - if ($value instanceof Zend_Markup_TokenList) { - $tokenList = $value; - } else { - $tokenList = $this->getParser()->parse($value); - } - - $root = $tokenList->current(); - - $this->_filter = $this->getDefaultFilter(); - - return $this->_render($root); - } - - /** - * Render a single token - * - * @param Zend_Markup_Token $token - * @return string - */ - protected function _render(Zend_Markup_Token $token) - { - $return = ''; - - $this->_token = $token; - - // if this tag has children, execute them - if ($token->hasChildren()) { - foreach ($token->getChildren() as $child) { - $return .= $this->_execute($child); - } - } - - return $return; - } - - /** - * Get the group of a token - * - * @param Zend_Markup_Token $token - * @return string|bool - */ - protected function _getGroup(Zend_Markup_Token $token) - { - if (!isset($this->_markups[$token->getName()])) { - return false; - } - - $tag = $this->_markups[$token->getName()]; - - // alias processing - while ($tag['type'] & self::TYPE_ALIAS) { - $tag = $this->_markups[$tag['name']]; - } - - return isset($tag['group']) ? $tag['group'] : false; - } - - /** - * Execute the token - * - * @param Zend_Markup_Token $token - * @return string - */ - protected function _execute(Zend_Markup_Token $token) - { - // first return the normal text tags - if ($token->getType() == Zend_Markup_Token::TYPE_NONE) { - return $this->_filter($token->getTag()); - } - - // if the token doesn't have a notation, return the plain text - if (!isset($this->_markups[$token->getName()])) { - $oldToken = $this->_token; - $return = $this->_filter($token->getTag()) . $this->_render($token) . $token->getStopper(); - $this->_token = $oldToken; - return $return; - } - - $name = $this->_getMarkupName($token); - $markup = (!$name) ? false : $this->_markups[$name]; - $empty = (is_array($markup) && array_key_exists('empty', $markup) && $markup['empty']); - - // check if the tag has content - if (!$empty && !$token->hasChildren()) { - return ''; - } - - // check for the context - if (is_array($markup) && !in_array($markup['group'], $this->_groups[$this->_group])) { - $oldToken = $this->_token; - $return = $this->_filter($token->getTag()) . $this->_render($token) . $token->getStopper(); - $this->_token = $oldToken; - return $return; - } - - // check for the filter - if (!isset($markup['filter']) - || (!($markup['filter'] instanceof Zend_Filter_Interface) && ($markup['filter'] !== false))) { - $this->_markups[$name]['filter'] = $this->getDefaultFilter(); - } - - // save old values to reset them after the work is done - $oldFilter = $this->_filter; - $oldGroup = $this->_group; - - $return = ''; - - // set the filter and the group - $this->_filter = $this->getFilter($name); - - if ($group = $this->_getGroup($token)) { - $this->_group = $group; - } - - // callback - if (is_array($markup) && ($markup['type'] & self::TYPE_CALLBACK)) { - // load the callback if the tag doesn't exist - if (!($markup['callback'] instanceof Zend_Markup_Renderer_TokenConverterInterface)) { - $class = $this->getPluginLoader()->load($name); - - $markup['callback'] = new $class; - - if (!($markup['callback'] instanceof Zend_Markup_Renderer_TokenConverterInterface)) { - #require_once 'Zend/Markup/Renderer/Exception.php'; - throw new Zend_Markup_Renderer_Exception("Callback for tag '$name' found, but it isn't valid."); - } - - if (method_exists($markup['callback'], 'setRenderer')) { - $markup['callback']->setRenderer($this); - } - } - if ($markup['type'] && !$empty) { - $return = $markup['callback']->convert($token, $this->_render($token)); - } else { - $return = $markup['callback']->convert($token, null); - } - } else { - // replace - if ($markup['type'] && !$empty) { - $return = $this->_executeReplace($token, $markup); - } else { - $return = $this->_executeSingleReplace($token, $markup); - } - } - - // reset to the old values - $this->_filter = $oldFilter; - $this->_group = $oldGroup; - - return $return; - } - - /** - * Filter method - * - * @param string $value - * - * @return string - */ - protected function _filter($value) - { - if ($this->_filter instanceof Zend_Filter_Interface) { - return $this->_filter->filter($value); - } - return $value; - } - - /** - * Get the markup name - * - * @param Zend_Markup_Token - * - * @return string - */ - protected function _getMarkupName(Zend_Markup_Token $token) - { - $name = $token->getName(); - if (empty($name)) { - return false; - } - - return $this->_resolveMarkupName($name); - } - - /** - * Resolve aliases for a markup name - * - * @param string $name - * - * @return string - */ - protected function _resolveMarkupName($name) - { - while (($type = $this->_getMarkupType($name)) - && ($type & self::TYPE_ALIAS) - ) { - $name = $this->_markups[$name]['name']; - } - - return $name; - } - - /** - * Retrieve markup type - * - * @param string $name - * @return false|int - */ - protected function _getMarkupType($name) - { - if (!isset($this->_markups[$name])) { - return false; - } - if (!isset($this->_markups[$name]['type'])) { - return false; - } - return $this->_markups[$name]['type']; - } - - /** - * Execute a replace token - * - * @param Zend_Markup_Token $token - * @param array $tag - * @return string - */ - protected function _executeReplace(Zend_Markup_Token $token, $tag) - { - return $tag['start'] . $this->_render($token) . $tag['end']; - } - - /** - * Execute a single replace token - * - * @param Zend_Markup_Token $token - * @param array $tag - * @return string - */ - protected function _executeSingleReplace(Zend_Markup_Token $token, $tag) - { - return $tag['replace']; - } - - /** - * Get the default filter - * - * @return void - */ - public function getDefaultFilter() - { - if (null === $this->_defaultFilter) { - $this->addDefaultFilters(); - } - - return $this->_defaultFilter; - } - - /** - * Add a default filter - * - * @param string $filter - * - * @return void - */ - public function addDefaultFilter(Zend_Filter_Interface $filter, $placement = Zend_Filter::CHAIN_APPEND) - { - if (!($this->_defaultFilter instanceof Zend_Filter)) { - $defaultFilter = new Zend_Filter(); - $defaultFilter->addFilter($filter); - $this->_defaultFilter = $defaultFilter; - } - - $this->_defaultFilter->addFilter($filter, $placement); - } - - /** - * Set the default filter - * - * @param Zend_Filter_Interface $filter - * - * @return void - */ - public function setDefaultFilter(Zend_Filter_Interface $filter) - { - $this->_defaultFilter = $filter; - } - - /** - * Get the filter for an existing markup - * - * @param string $markup - * - * @return Zend_Filter_Interface - */ - public function getFilter($markup) - { - $markup = $this->_resolveMarkupName($markup); - - if (!isset($this->_markups[$markup]['filter']) - || !($this->_markups[$markup]['filter'] instanceof Zend_Filter_Interface) - ) { - if (isset($this->_markups[$markup]['filter']) && $this->_markups[$markup]['filter']) { - $this->_markups[$markup]['filter'] = $this->getDefaultFilter(); - } else { - return false; - } - } - - return $this->_markups[$markup]['filter']; - } - - /** - * Add a filter for an existing markup - * - * @param Zend_Filter_Interface $filter - * @param string $markup - * @param string $placement - * - * @return Zend_Markup_Renderer_RendererAbstract - */ - public function addFilter(Zend_Filter_Interface $filter, $markup, $placement = Zend_Filter::CHAIN_APPEND) - { - $markup = $this->_resolveMarkupName($markup); - - $oldFilter = $this->getFilter($markup); - - // if this filter is the default filter, clone it first - if ($oldFilter === $this->getDefaultFilter()) { - $oldFilter = clone $oldFilter; - } - - if (!($oldFilter instanceof Zend_Filter)) { - $this->_markups[$markup]['filter'] = new Zend_Filter(); - - if ($oldFilter instanceof Zend_Filter_Interface) { - $this->_markups[$markup]['filter']->addFilter($oldFilter); - } - } else { - $this->_markups[$markup]['filter'] = $oldFilter; - } - - $this->_markups[$markup]['filter']->addFilter($filter, $placement); - - return $this; - } - - /** - * Set the filter for an existing - * - * @param Zend_Filter_Interface $filter - * @param string $markup - * - * @return Zend_Markup_Renderer_RendererAbstract - */ - public function setFilter(Zend_Filter_Interface $filter, $markup) - { - $markup = $this->_resolveMarkupName($markup); - - $this->_markups[$markup]['filter'] = $filter; - - return $this; - } - - /** - * Add a render group - * - * @param string $name - * @param array $allowedInside - * @param array $allowsInside - * - * @return void - */ - public function addGroup($name, array $allowedInside = array(), array $allowsInside = array()) - { - $this->_groups[$name] = $allowsInside; - - foreach ($allowedInside as $group) { - $this->_groups[$group][] = $name; - } - } - - /** - * Get group definitions - * - * @return array - */ - public function getGroups() - { - return $this->_groups; - } - - /** - * Set the default filters - * - * @return void - */ - abstract public function addDefaultFilters(); - -} diff --git a/library/Zend/Markup/Renderer/TokenConverterInterface.php b/library/Zend/Markup/Renderer/TokenConverterInterface.php deleted file mode 100644 index 253c0c8a36..0000000000 --- a/library/Zend/Markup/Renderer/TokenConverterInterface.php +++ /dev/null @@ -1,44 +0,0 @@ -_tag = $tag; - $this->_type = $type; - $this->_name = $name; - $this->_attributes = $attributes; - $this->_parent = $parent; - } - - // accessors - - /** - * Set the stopper - * - * @param string $stopper - * @return Zend_Markup_Token - */ - public function setStopper($stopper) - { - $this->_stopper = $stopper; - - return $this; - } - - /** - * Get the stopper - * - * @return string - */ - public function getStopper() - { - return $this->_stopper; - } - - /** - * Get the token's name - * - * @return string - */ - public function getName() - { - return $this->_name; - } - - /** - * Get the token's type - * - * @return string - */ - public function getType() - { - return $this->_type; - } - - /** - * Get the complete tag - * - * @return string - */ - public function getTag() - { - return $this->_tag; - } - - /** - * Get an attribute - * - * @param string $name - * - * @return string - */ - public function getAttribute($name) - { - return isset($this->_attributes[$name]) ? $this->_attributes[$name] : null; - } - - /** - * Check if the token has an attribute - * - * @param string $name - * - * @return bool - */ - public function hasAttribute($name) - { - return isset($this->_attributes[$name]); - } - - /** - * Get all the attributes - * - * @return array - */ - public function getAttributes() - { - return $this->_attributes; - } - - /** - * Add an attribute - * - * @return Zend_Markup_Token - */ - public function addAttribute($name, $value) - { - $this->_attributes[$name] = $value; - - return $this; - } - - /** - * Check if an attribute is empty - * - * @param string $name - * - * @return bool - */ - public function attributeIsEmpty($name) - { - return empty($this->_attributes[$name]); - } - - // functions for child/parent tokens - - /** - * Add a child token - * - * @return void - */ - public function addChild(Zend_Markup_Token $child) - { - $this->getChildren()->addChild($child); - } - - /** - * Set the children token list - * - * @param Zend_Markup_TokenList $children - * @return Zend_Markup_Token - */ - public function setChildren(Zend_Markup_TokenList $children) - { - $this->_children = $children; - return $this; - } - - /** - * Get the children for this token - * - * @return Zend_Markup_TokenList - */ - public function getChildren() - { - if (null === $this->_children) { - $this->setChildren(new Zend_Markup_TokenList()); - } - return $this->_children; - } - - /** - * Does this token have any children - * - * @return bool - */ - public function hasChildren() - { - return !empty($this->_children); - } - - /** - * Get the parent token (if any) - * - * @return Zend_Markup_Token - */ - public function getParent() - { - return $this->_parent; - } - - /** - * Set a parent token - * - * @param Zend_Markup_Token $parent - * @return Zend_Markup_Token - */ - public function setParent(Zend_Markup_Token $parent) - { - $this->_parent = $parent; - return $this; - } - - /** - * Magic clone function - * - * @return void - */ - public function __clone() - { - $this->_parent = null; - $this->_children = null; - $this->_tag = ''; - } -} diff --git a/library/Zend/Markup/TokenList.php b/library/Zend/Markup/TokenList.php deleted file mode 100644 index b7762ee5eb..0000000000 --- a/library/Zend/Markup/TokenList.php +++ /dev/null @@ -1,124 +0,0 @@ -_tokens); - } - - /** - * Get the children of the current token - * - * @return Zend_Markup_TokenList - */ - public function getChildren() - { - return current($this->_tokens)->getChildren(); - } - - /** - * Add a new child token - * - * @param Zend_Markup_Token $child - * - * @return void - */ - public function addChild(Zend_Markup_Token $child) - { - $this->_tokens[] = $child; - } - - /** - * Check if the current token has children - * - * @return bool - */ - public function hasChildren() - { - return current($this->_tokens)->hasChildren(); - } - - /** - * Get the key of the current token - * - * @return int - */ - public function key() - { - return key($this->_tokens); - } - - /** - * Go to the next token - * - * @return Zend_Markup_Token - */ - public function next() - { - return next($this->_tokens); - } - - /** - * Rewind the iterator - * - * @return void - */ - public function rewind() - { - reset($this->_tokens); - } - - /** - * Check if the element is valid - * - * @return void - */ - public function valid() - { - return $this->current() !== false; - } -} diff --git a/library/Zend/Mobile/Exception.php b/library/Zend/Mobile/Exception.php deleted file mode 100644 index b9a1228f80..0000000000 --- a/library/Zend/Mobile/Exception.php +++ /dev/null @@ -1,33 +0,0 @@ -_isConnected = true; - return $this; - } - - /** - * Send a Push Message - * - * @param Zend_Mobile_Push_Message_Abstract $message - * @return boolean - * @throws DomainException - */ - public function send(Zend_Mobile_Push_Message_Abstract $message) - { - if (!$this->_isConnected) { - $this->connect(); - } - return true; - } - - /** - * Close the Connection to the Push Server - * - * @return void - */ - public function close() - { - $this->_isConnected = false; - } - - /** - * Is Connected - * - * @return boolean - */ - public function isConnected() - { - return $this->_isConnected; - } - - /** - * Set Options - * - * @param array $options - * @return Zend_Mobile_Push_Abstract - * @throws Zend_Mobile_Push_Exception - */ - public function setOptions(array $options) - { - foreach ($options as $k => $v) { - $method = 'set' . ucwords($k); - if (!method_exists($this, $method)) { - throw new Zend_Mobile_Push_Exception('The method "' . $method . "' does not exist."); - } - $this->$method($v); - } - return $this; - } -} diff --git a/library/Zend/Mobile/Push/Apns.php b/library/Zend/Mobile/Push/Apns.php deleted file mode 100644 index 8f62fae0cb..0000000000 --- a/library/Zend/Mobile/Push/Apns.php +++ /dev/null @@ -1,399 +0,0 @@ -_certificate; - } - - /** - * Set Certificate - * - * @param string $cert - * @return Zend_Mobile_Push_Apns - * @throws Zend_Mobile_Push_Exception - */ - public function setCertificate($cert) - { - if (!is_string($cert)) { - throw new Zend_Mobile_Push_Exception('$cert must be a string'); - } - if (!file_exists($cert)) { - throw new Zend_Mobile_Push_Exception('$cert must be a valid path to the certificate'); - } - $this->_certificate = $cert; - return $this; - } - - /** - * Get Certificate Passphrase - * - * @return string - */ - public function getCertificatePassphrase() - { - return $this->_certificatePassphrase; - } - - /** - * Set Certificate Passphrase - * - * @param string $passphrase - * @return Zend_Mobile_Push_Apns - * @throws Zend_Mobile_Push_Exception - */ - public function setCertificatePassphrase($passphrase) - { - if (!is_string($passphrase)) { - throw new Zend_Mobile_Push_Exception('$passphrase must be a string'); - } - $this->_certificatePassphrase = $passphrase; - return $this; - } - - /** - * Connect to Socket - * - * @param string $uri - * @return bool - * @throws Zend_Mobile_Push_Exception_ServerUnavailable - */ - protected function _connect($uri) - { - $ssl = array( - 'local_cert' => $this->_certificate, - ); - if ($this->_certificatePassphrase) { - $ssl['passphrase'] = $this->_certificatePassphrase; - } - - $this->_socket = stream_socket_client($uri, - $errno, - $errstr, - ini_get('default_socket_timeout'), - STREAM_CLIENT_CONNECT, - stream_context_create(array( - 'ssl' => $ssl, - )) - ); - - if (!is_resource($this->_socket)) { - #require_once 'Zend/Mobile/Push/Exception/ServerUnavailable.php'; - throw new Zend_Mobile_Push_Exception_ServerUnavailable(sprintf('Unable to connect: %s: %d (%s)', - $uri, - $errno, - $errstr - )); - } - - stream_set_blocking($this->_socket, 0); - stream_set_write_buffer($this->_socket, 0); - return true; - } - - /** - * Read from the Socket Server - * - * @param int $length - * @return string - */ - protected function _read($length) { - $data = false; - if (!feof($this->_socket)) { - $data = fread($this->_socket, $length); - } - return $data; - } - - /** - * Write to the Socket Server - * - * @param string $payload - * @return int - */ - protected function _write($payload) { - return @fwrite($this->_socket, $payload); - } - - /** - * Connect to the Push Server - * - * @param int|string $env - * @throws Zend_Mobile_Push_Exception - * @throws Zend_Mobile_Push_Exception_ServerUnavailable - * @return Zend_Mobile_Push_Abstract - */ - public function connect($env = self::SERVER_PRODUCTION_URI) - { - if ($this->_isConnected) { - if ($this->_currentEnv == self::SERVER_PRODUCTION_URI) { - return $this; - } - $this->close(); - } - - if (!isset($this->_serverUriList[$env])) { - throw new Zend_Mobile_Push_Exception('$env is not a valid environment'); - } - - if (!$this->_certificate) { - throw new Zend_Mobile_Push_Exception('A certificate must be set prior to calling ::connect'); - } - - $this->_connect($this->_serverUriList[$env]); - - $this->_currentEnv = $env; - $this->_isConnected = true; - return $this; - } - - - - /** - * Feedback - * - * @return array array w/ key = token and value = time - * @throws Zend_Mobile_Push_Exception - * @throws Zend_Mobile_Push_Exception_ServerUnavailable - */ - public function feedback() - { - if (!$this->_isConnected || - !in_array($this->_currentEnv, - array(self::SERVER_FEEDBACK_SANDBOX_URI, self::SERVER_FEEDBACK_PRODUCTION_URI))) { - $this->connect(self::SERVER_FEEDBACK_PRODUCTION_URI); - } - - $tokens = array(); - while ($token = $this->_read(38)) { - if (strlen($token) < 38) { - continue; - } - $token = unpack('Ntime/ntokenLength/H*token', $token); - if (!isset($tokens[$token['token']]) || $tokens[$token['token']] < $token['time']) { - $tokens[$token['token']] = $token['time']; - } - } - return $tokens; - } - - /** - * Send Message - * - * @param Zend_Mobile_Push_Message_Abstract $message - * @throws Zend_Mobile_Push_Exception - * @throws Zend_Mobile_Push_Exception_InvalidPayload - * @throws Zend_Mobile_Push_Exception_InvalidToken - * @throws Zend_Mobile_Push_Exception_InvalidTopic - * @throws Zend_Mobile_Push_Exception_ServerUnavailable - * @return bool - */ - public function send(Zend_Mobile_Push_Message_Abstract $message) - { - if (!$message->validate()) { - throw new Zend_Mobile_Push_Exception('The message is not valid.'); - } - - if (!$this->_isConnected || !in_array($this->_currentEnv, array( - self::SERVER_SANDBOX_URI, - self::SERVER_PRODUCTION_URI))) { - $this->connect(self::SERVER_PRODUCTION_URI); - } - - $payload = array('aps' => array()); - - $alert = $message->getAlert(); - foreach ($alert as $k => $v) { - if ($v == null) { - unset($alert[$k]); - } - } - if (!empty($alert)) { - $payload['aps']['alert'] = $alert; - } - if (!is_null($message->getBadge())) { - $payload['aps']['badge'] = $message->getBadge(); - } - $sound = $message->getSound(); - if (!empty($sound)) { - $payload['aps']['sound'] = $sound; - } - - foreach($message->getCustomData() as $k => $v) { - $payload[$k] = $v; - } - - if (version_compare(PHP_VERSION, '5.4.0') >= 0) { - $payload = json_encode($payload, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES); - } else { - $payload = json_encode($payload); - } - - $expire = $message->getExpire(); - if ($expire > 0) { - $expire += time(); - } - $id = $message->getId(); - if (empty($id)) { - $id = time(); - } - - $payload = pack('CNNnH*', 1, $id, $expire, 32, $message->getToken()) - . pack('n', strlen($payload)) - . $payload; - $ret = $this->_write($payload); - if ($ret === false) { - #require_once 'Zend/Mobile/Push/Exception/ServerUnavailable.php'; - throw new Zend_Mobile_Push_Exception_ServerUnavailable('Unable to send message'); - } - // check for errors from apple - $err = $this->_read(1024); - if (strlen($err) > 0) { - $err = unpack('Ccmd/Cerrno/Nid', $err); - switch ($err['errno']) { - case 0: - return true; - break; - case 1: - throw new Zend_Mobile_Push_Exception('A processing error has occurred on the apple push notification server.'); - break; - case 2: - #require_once 'Zend/Mobile/Push/Exception/InvalidToken.php'; - throw new Zend_Mobile_Push_Exception_InvalidToken('Missing token; you must set a token for the message.'); - break; - case 3: - #require_once 'Zend/Mobile/Push/Exception/InvalidTopic.php'; - throw new Zend_Mobile_Push_Exception_InvalidTopic('Missing id; you must set an id for the message.'); - break; - case 4: - #require_once 'Zend/Mobile/Push/Exception/InvalidPayload.php'; - throw new Zend_Mobile_Push_Exception_InvalidPayload('Missing message; the message must always have some content.'); - break; - case 5: - #require_once 'Zend/Mobile/Push/Exception/InvalidToken.php'; - throw new Zend_Mobile_Push_Exception_InvalidToken('Bad token. This token is too big and is not a regular apns token.'); - break; - case 6: - #require_once 'Zend/Mobile/Push/Exception/InvalidTopic.php'; - throw new Zend_Mobile_Push_Exception_InvalidTopic('The message id is too big; reduce the size of the id.'); - break; - case 7: - #require_once 'Zend/Mobile/Push/Exception/InvalidPayload.php'; - throw new Zend_Mobile_Push_Exception_InvalidPayload('The message is too big; reduce the size of the message.'); - break; - case 8: - #require_once 'Zend/Mobile/Push/Exception/InvalidToken.php'; - throw new Zend_Mobile_Push_Exception_InvalidToken('Bad token. Remove this token from being sent to again.'); - break; - default: - throw new Zend_Mobile_Push_Exception(sprintf('An unknown error occurred: %d', $err['errno'])); - break; - } - } - return true; - } - - /** - * Close Connection - * - * @return void - */ - public function close() - { - if ($this->_isConnected && is_resource($this->_socket)) { - fclose($this->_socket); - } - $this->_isConnected = false; - } -} diff --git a/library/Zend/Mobile/Push/Exception.php b/library/Zend/Mobile/Push/Exception.php deleted file mode 100644 index 7e70189f1a..0000000000 --- a/library/Zend/Mobile/Push/Exception.php +++ /dev/null @@ -1,35 +0,0 @@ -_apiKey; - } - - /** - * Set API Key - * - * @param string $key - * @return Zend_Mobile_Push_Gcm - * @throws Zend_Mobile_Push_Exception - */ - public function setApiKey($key) - { - if (!is_string($key) || empty($key)) { - throw new Zend_Mobile_Push_Exception('The api key must be a string and not empty'); - } - $this->_apiKey = $key; - return $this; - } - - /** - * Get Http Client - * - * @return Zend_Http_Client - */ - public function getHttpClient() - { - if (!$this->_httpClient) { - $this->_httpClient = new Zend_Http_Client(); - $this->_httpClient->setConfig(array( - 'strictredirects' => true, - )); - } - return $this->_httpClient; - } - - /** - * Set Http Client - * - * @return Zend_Mobile_Push_Gcm - */ - public function setHttpClient(Zend_Http_Client $client) - { - $this->_httpClient = $client; - return $this; - } - - /** - * Send Message - * - * @param Zend_Mobile_Push_Message_Abstract $message - * @throws Zend_Http_Client_Exception - * @throws Zend_Mobile_Push_Exception - * @throws Zend_Mobile_Push_Exception_InvalidAuthToken - * @throws Zend_Mobile_Push_Exception_InvalidPayload - * @throws Zend_Mobile_Push_Exception_ServerUnavailable - * @return Zend_Mobile_Push_Response_Gcm - */ - public function send(Zend_Mobile_Push_Message_Abstract $message) - { - if (!$message->validate()) { - throw new Zend_Mobile_Push_Exception('The message is not valid.'); - } - - $this->connect(); - - $client = $this->getHttpClient(); - $client->setUri(self::SERVER_URI); - $client->setHeaders('Authorization', 'key=' . $this->getApiKey()); - - $response = $client->setRawData($message->toJson(), 'application/json') - ->request('POST'); - $this->close(); - - switch ($response->getStatus()) - { - case 500: - #require_once 'Zend/Mobile/Push/Exception/ServerUnavailable.php'; - throw new Zend_Mobile_Push_Exception_ServerUnavailable('The server encountered an internal error, try again'); - break; - case 503: - #require_once 'Zend/Mobile/Push/Exception/ServerUnavailable.php'; - throw new Zend_Mobile_Push_Exception_ServerUnavailable('The server was unavailable, check Retry-After header'); - break; - case 401: - #require_once 'Zend/Mobile/Push/Exception/InvalidAuthToken.php'; - throw new Zend_Mobile_Push_Exception_InvalidAuthToken('There was an error authenticating the sender account'); - break; - case 400: - #require_once 'Zend/Mobile/Push/Exception/InvalidPayload.php'; - throw new Zend_Mobile_Push_Exception_InvalidPayload('The request could not be parsed as JSON or contains invalid fields'); - break; - } - return new Zend_Mobile_Push_Response_Gcm($response->getBody(), $message); - } -} diff --git a/library/Zend/Mobile/Push/Interface.php b/library/Zend/Mobile/Push/Interface.php deleted file mode 100644 index d8315e85d0..0000000000 --- a/library/Zend/Mobile/Push/Interface.php +++ /dev/null @@ -1,64 +0,0 @@ -_token; - } - - /** - * Set Token - * - * @param string $token - * @throws Zend_Mobile_Push_Message_Exception - * @return Zend_Mobile_Push_Message_Abstract - */ - public function setToken($token) - { - if (!is_string($token)) { - throw new Zend_Mobile_Push_Message_Exception('$token must be a string'); - } - $this->_token = $token; - return $this; - } - - /** - * Get Message ID - * - * @return int|string|float|bool Scalar - */ - public function getId() - { - return $this->_id; - } - - /** - * Set Message ID - * - * @param int|string|float|bool $id Scalar - * @return Zend_Mobile_Push_Message_Abstract - * @throws Exception - */ - public function setId($id) - { - if (!is_scalar($id)) { - throw new Zend_Mobile_Push_Message_Exception('$id must be a scalar'); - } - $this->_id = $id; - return $this; - } - - /** - * Set Options - * - * @param array $options - * @return Zend_Mobile_Push_Message_Abstract - * @throws Zend_Mobile_Push_Message_Exception - */ - public function setOptions(array $options) - { - foreach ($options as $k => $v) { - $method = 'set' . ucwords($k); - if (!method_exists($this, $method)) { - throw new Zend_Mobile_Push_Message_Exception('The method "' . $method . "' does not exist."); - } - $this->$method($v); - } - return $this; - } - - - /** - * Validate Message format - * - * @return boolean - */ - public function validate() - { - return true; - } -} diff --git a/library/Zend/Mobile/Push/Message/Apns.php b/library/Zend/Mobile/Push/Message/Apns.php deleted file mode 100644 index d4d4637ed4..0000000000 --- a/library/Zend/Mobile/Push/Message/Apns.php +++ /dev/null @@ -1,285 +0,0 @@ -_alert; - } - - /** - * Set Alert - * - * @param string $text - * @param string|null $actionLocKey - * @param string|null $locKey - * @param array|null $locArgs - * @param string|null $launchImage - * @throws Zend_Mobile_Push_Message_Exception - * @return Zend_Mobile_Push_Message_Apns - */ - public function setAlert($text, $actionLocKey=null, $locKey=null, $locArgs=null, $launchImage=null) - { - if ($text !== null && !is_string($text)) { - throw new Zend_Mobile_Push_Message_Exception('$text must be a string'); - } - - if ($actionLocKey !== null && !is_string($actionLocKey)) { - throw new Zend_Mobile_Push_Message_Exception('$actionLocKey must be a string'); - } - - if ($locKey !== null && !is_string($locKey)) { - throw new Zend_Mobile_Push_Message_Exception('$locKey must be a string'); - } - - if ($locArgs !== null) { - if (!is_array($locArgs)) { - throw new Zend_Mobile_Push_Message_Exception('$locArgs must be an array of strings'); - } else { - foreach ($locArgs as $str) { - if (!is_string($str)) { - throw new Zend_Mobile_Push_Message_Exception('$locArgs contains an item that is not a string'); - } - } - } - } - - if (null !== $launchImage && !is_string($launchImage)) { - throw new Zend_Mobile_Push_Message_Exception('$launchImage must be a string'); - } - - $this->_alert = array( - 'body' => $text, - 'action-loc-key' => $actionLocKey, - 'loc-key' => $locKey, - 'loc-args' => $locArgs, - 'launch-image' => $launchImage, - ); - return $this; - } - - /** - * Get Badge - * - * @return int - */ - public function getBadge() - { - return $this->_badge; - } - - /** - * Set Badge - * - * @param int $badge - * @return Zend_Mobile_Push_Message_Apns - * @throws Zend_Mobile_Push_Message_Exception - */ - public function setBadge($badge) - { - if (!is_null($badge) && !is_numeric($badge)) { - throw new Zend_Mobile_Push_Message_Exception('$badge must be an integer'); - } - if (!is_null($badge) && $badge < 0) { - throw new Zend_Mobile_Push_Message_Exception('$badge must be greater or equal to 0'); - } - $this->_badge = $badge; - } - - /** - * Get Expire - * - * @return int - */ - public function getExpire() - { - return $this->_expire; - } - - /** - * Set Expire - * - * @param int $expire - * @return Zend_Mobile_Push_Message_Apns - * @throws Zend_Mobile_Push_Message_Exception - */ - public function setExpire($expire) - { - if (!is_numeric($expire)) { - throw new Zend_Mobile_Push_Message_Exception('$expire must be an integer'); - } - $this->_expire = (int) $expire; - return $this; - } - - /** - * Get Sound - * - * @return string - */ - public function getSound() - { - return $this->_sound; - } - - /** - * Set Sound - * - * @param string $sound - * @return Zend_Mobile_Push_Message_Apns - * @throws Zend_Mobile_Push_Message_Exception - */ - public function setSound($sound) - { - if (!is_string($sound)) { - throw new Zend_Mobile_Push_Message_Exception('$sound must be a string'); - } - $this->_sound = $sound; - return $this; - } - - /** - * Add Custom Data - * - * @param string $key - * @param mixed $value - * @return Zend_Mobile_Push_Message_Apns - * @throws Zend_Mobile_Push_Message_Exception - */ - public function addCustomData($key, $value) - { - if (!is_string($key)) { - throw new Zend_Mobile_Push_Message_Exception('$key is not a string'); - } - if ($key == 'aps') { - throw new Zend_Mobile_Push_Message_Exception('$key must not be aps as it is reserved by apple'); - } - $this->_custom[$key] = $value; - } - - /** - * Clear Custom Data - * - * @return throw new Zend_Mobile_Push_Message_Apns - */ - public function clearCustomData() - { - $this->_custom = array(); - return $this; - } - - /** - * Set Custom Data - * - * @param array $array - * @throws Zend_Mobile_Push_Message_Exception - * @return Zend_Mobile_Push_Message_Apns - */ - public function setCustomData($array) - { - $this->_custom = array(); - foreach ($array as $k => $v) { - $this->addCustomData($k, $v); - } - return $this; - } - - /** - * Get Custom Data - * - * @return array - */ - public function getCustomData() - { - return $this->_custom; - } - - /** - * Validate this is a proper Apns message - * - * @return boolean - */ - public function validate() - { - if (!is_string($this->_token) || strlen($this->_token) === 0) { - return false; - } - if (null != $this->_id && !is_numeric($this->_id)) { - return false; - } - return true; - } -} diff --git a/library/Zend/Mobile/Push/Message/Exception.php b/library/Zend/Mobile/Push/Message/Exception.php deleted file mode 100644 index a23eb6bc4d..0000000000 --- a/library/Zend/Mobile/Push/Message/Exception.php +++ /dev/null @@ -1,35 +0,0 @@ -_token)) { - $this->_token[] = $token; - } - return $this; - } - - /** - * Set Token - * - * @param string|array $token - * @return Zend_Mobile_Push_Message_Gcm - * @throws Zend_Mobile_Push_Message_Exception - */ - public function setToken($token) - { - $this->clearToken(); - if (is_string($token)) { - $this->addToken($token); - } else if (is_array($token)) { - foreach ($token as $t) { - $this->addToken($t); - } - } - return $this; - } - - /** - * Clear Tokens - * - * @return Zend_Mobile_Push_Message_Gcm - */ - public function clearToken() - { - $this->_token = array(); - return $this; - } - - - /** - * Add Data - * - * @param string $key - * @param string $value - * @return Zend_Mobile_Push_Message_Gcm - * @throws Zend_Mobile_Push_Message_Exception - */ - public function addData($key, $value) - { - if (!is_string($key)) { - throw new Zend_Mobile_Push_Message_Exception('$key is not a string'); - } - if (!is_scalar($value)) { - throw new Zend_Mobile_Push_Message_Exception('$value is not a string'); - } - $this->_data[$key] = $value; - return $this; - } - - /** - * Set Data - * - * @param array $data - * @return Zend_Mobile_Push_Message_Gcm - * @throws Zend_Mobile_Push_Message_Exception - */ - public function setData(array $data) - { - $this->clearData(); - foreach ($data as $k => $v) { - $this->addData($k, $v); - } - return $this; - } - - /** - * Clear Data - * - * @return Zend_Mobile_Push_Message_Gcm - */ - public function clearData() - { - $this->_data = array(); - return $this; - } - - /** - * Get Data - * - * @return array - */ - public function getData() - { - return $this->_data; - } - - /** - * Set Delay While Idle - * - * @param boolean $delay - * @return Zend_Mobile_Push_Message_Gcm - * @throws Zend_Mobile_Push_Message_Exception - */ - public function setDelayWhileIdle($delay) - { - if (!is_bool($delay)) { - throw new Zend_Mobile_Push_Message_Exception('$delay must be boolean'); - } - $this->_delay = $delay; - return $this; - } - - /** - * Get Delay While Idle - * - * @return boolean - */ - public function getDelayWhileIdle() - { - return $this->_delay; - } - - /** - * Set time to live. - * - * @param int $secs - * @throws Zend_Mobile_Push_Message_Exception - * @return Zend_Mobile_Push_Message_Gcm - */ - public function setTtl($secs) - { - if (!is_numeric($secs)) { - throw new Zend_Mobile_Push_Message_Exception('$secs must be numeric'); - } - $this->_ttl = (int) $secs; - return $this; - } - - /** - * Get time to live - * - * @return int - */ - public function getTtl() - { - return $this->_ttl; - } - - /** - * Validate this is a proper Gcm message - * Does not validate size. - * - * @return boolean - */ - public function validate() - { - if (!is_array($this->_token) || empty($this->_token)) { - return false; - } - if ($this->_ttl !== 2419200 && - (!is_scalar($this->_id) || - strlen($this->_id) === 0)) { - return false; - } - return true; - } - - /** - * To Json utility method - * Takes the data and properly assigns it to - * a json encoded array to match the Gcm format. - * - * @return string - */ - public function toJson() - { - $json = array(); - if ($this->_token) { - $json['registration_ids'] = $this->_token; - } - if ($this->_id) { - $json['collapse_key'] = (string) $this->_id; - } - if ($this->_data) { - $json['data'] = $this->_data; - } - if ($this->_delay) { - $json['delay_while_idle'] = $this->_delay; - } - if ($this->_ttl !== 2419200) { - $json['time_to_live'] = $this->_ttl; - } - if (version_compare(PHP_VERSION, '5.4.0') >= 0) { - return json_encode($json, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES); - } else { - return json_encode($json); - } - } -} diff --git a/library/Zend/Mobile/Push/Message/Interface.php b/library/Zend/Mobile/Push/Message/Interface.php deleted file mode 100644 index 27be3256a3..0000000000 --- a/library/Zend/Mobile/Push/Message/Interface.php +++ /dev/null @@ -1,79 +0,0 @@ -_token) || strlen($this->_token) === 0) { - return false; - } - return parent::validate(); - } -} diff --git a/library/Zend/Mobile/Push/Message/Mpns/Raw.php b/library/Zend/Mobile/Push/Message/Mpns/Raw.php deleted file mode 100644 index df38c5c17e..0000000000 --- a/library/Zend/Mobile/Push/Message/Mpns/Raw.php +++ /dev/null @@ -1,152 +0,0 @@ -_delay) { - return self::DELAY_IMMEDIATE; - } - return $this->_delay; - } - - /** - * Set Delay - * - * @param int $delay - * @return Zend_Mobile_Push_Message_Mpns_Raw - * @throws Zend_Mobile_Push_Message_Exception - */ - public function setDelay($delay) - { - if (!in_array($delay, array( - self::DELAY_IMMEDIATE, - self::DELAY_450S, - self::DELAY_900S - ))) { - throw new Zend_Mobile_Push_Message_Exception('$delay must be one of the DELAY_* constants'); - } - $this->_delay = $delay; - return $this; - } - - /** - * Set Message - * - * @param string $msg XML string - * @return Zend_Mobile_Push_Message_Mpns_Raw - * @throws Zend_Mobile_Push_Message_Exception - */ - public function setMessage($msg) - { - if (!is_string($msg)) { - throw new Zend_Mobile_Push_Message_Exception('$msg is not a string'); - } - if (!Zend_Xml_Security::scan($msg)) { - throw new Zend_Mobile_Push_Message_Exception('$msg is not valid xml'); - } - $this->_msg = $msg; - return $this; - } - - /** - * Get Message - * - * @return string - */ - public function getMessage() - { - return $this->_msg; - } - - /** - * Get Notification Type - * - * @return string - */ - public static function getNotificationType() - { - return 'raw'; - } - - /** - * Get XML Payload - * - * @return string - */ - public function getXmlPayload() - { - return $this->_msg; - } - - /** - * Validate proper mpns message - * - * @return boolean - */ - public function validate() - { - if (!isset($this->_token) || strlen($this->_token) === 0) { - return false; - } - if (empty($this->_msg)) { - return false; - } - return parent::validate(); - } -} diff --git a/library/Zend/Mobile/Push/Message/Mpns/Tile.php b/library/Zend/Mobile/Push/Message/Mpns/Tile.php deleted file mode 100644 index 0b35729291..0000000000 --- a/library/Zend/Mobile/Push/Message/Mpns/Tile.php +++ /dev/null @@ -1,365 +0,0 @@ -_backgroundImage; - } - - /** - * Set Background Image - * - * @param string $bgImg - * @return Zend_Mobile_Push_Message_Mpns_Tile - * @throws Zend_Mobile_Push_Message_Exception - */ - public function setBackgroundImage($bgImg) - { - if (!is_string($bgImg)) { - throw new Zend_Mobile_Push_Message_Exception('$bgImg must be a string'); - } - $this->_backgroundImage = $bgImg; - return $this; - } - - /** - * Get Count - * - * @return int - */ - public function getCount() - { - return $this->_count; - } - - /** - * Set Count - * - * @param int $count - * @return Zend_Mobile_Push_Message_Mpns_Tile - * @throws Zend_Mobile_Push_Message_Exception - */ - public function setCount($count) - { - if (!is_numeric($count)) { - throw new Zend_Mobile_Push_Message_Exception('$count is not numeric'); - } - $this->_count = (int) $count; - return $this; - } - - /** - * Get Title - * - * @return string - */ - public function getTitle() - { - return $this->_title; - } - - /** - * Set Title - * - * @param string $title - * @return Zend_Mobile_Push_Message_Mpns_Tile - * @throws Zend_Mobile_Push_Message_Exception - */ - public function setTitle($title) - { - if (!is_string($title)) { - throw new Zend_Mobile_Push_Message_Exception('$title must be a string'); - } - $this->_title = $title; - return $this; - } - - /** - * Get Back Background Image - * - * @return string - */ - public function getBackBackgroundImage() - { - return $this->_backBackgroundImage; - } - - /** - * Set Back Background Image - * - * @param string $bgImg - * @return Zend_Mobile_Push_Message_Mpns_Tile - * @throws Zend_Mobile_Push_Message_Exception - */ - public function setBackBackgroundImage($bgImg) - { - if (!is_string($bgImg)) { - throw new Zend_Mobile_Push_Message_Exception('$bgImg must be a string'); - } - $this->_backBackgroundImage = $bgImg; - return $this; - } - - /** - * Get Back Title - * - * @return string - */ - public function getBackTitle() - { - return $this->_backTitle; - } - - /** - * Set Back Title - * - * @param string $title - * @return Zend_Mobile_Push_Message_Mpns_Tile - * @throws Zend_Mobile_Push_Message_Exception - */ - public function setBackTitle($title) - { - if (!is_string($title)) { - throw new Zend_Mobile_Push_Message_Exception('$title must be a string'); - } - $this->_backTitle = $title; - return $this; - } - - /** - * Get Back Content - * - * @return string - */ - public function getBackContent() - { - return $this->_backContent; - } - - /** - * Set Back Content - * - * @param string $content - * @return Zend_Mobile_Push_Message_Mpns_Tile - * @throws Zend_Mobile_Push_Message_Exception - */ - public function setBackContent($content) - { - if (!is_string($content)) { - throw new Zend_Mobile_Push_Message_Exception('$content must be a string'); - } - $this->_backContent = $content; - } - - /** - * Get Tile Id - * - * @return string - */ - public function getTileId() - { - return $this->_tileId; - } - - /** - * Set Tile Id - * - * @param string $tileId - * @return Zend_Mobile_Push_Message_Mpns_Tile - * @throws Zend_Mobile_Push_Message_Exception - */ - public function setTileId($tileId) - { - if (!is_string($tileId)) { - throw new Zend_Mobile_Push_Message_Exception('$tileId is not a string'); - } - $this->_tileId = $tileId; - return $this; - } - - /** - * Get Delay - * - * @return int - */ - public function getDelay() - { - if (!$this->_delay) { - return self::DELAY_IMMEDIATE; - } - return $this->_delay; - } - - /** - * Set Delay - * - * @param int $delay - * @return Zend_Mobile_Push_Message_Mpns_Tile - * @throws Zend_Mobile_Push_Message_Exception - */ - public function setDelay($delay) - { - if (!in_array($delay, array( - self::DELAY_IMMEDIATE, - self::DELAY_450S, - self::DELAY_900S - ))) { - throw new Zend_Mobile_Push_Message_Exception('$delay must be one of the DELAY_* constants'); - } - $this->_delay = $delay; - return $this; - } - - /** - * Get Notification Type - * - * @return string - */ - public static function getNotificationType() - { - return 'token'; - } - - /** - * Get XML Payload - * - * @return string - */ - public function getXmlPayload() - { - $ret = '' - . '' - . '_tileId) ? ' Id="' . htmlspecialchars($this->_tileId) . '"' : '') . '>' - . '' . htmlspecialchars($this->_backgroundImage) . '' - . '' . (int) $this->_count . '' - . '' . htmlspecialchars($this->_title) . ''; - - if ($this->_backBackgroundImage) { - $ret .= '' . htmlspecialchars($this->_backBackgroundImage) . ''; - } - if ($this->_backTitle) { - $ret .= '' . htmlspecialchars($this->_backTitle) . ''; - } - if ($this->_backContent) { - $ret .= '' . htmlspecialchars($this->_backContent) . ''; - } - - $ret .= '' - . ''; - return $ret; - } - - /** - * Validate proper mpns message - * - * @return boolean - */ - public function validate() - { - if (!isset($this->_token) || strlen($this->_token) === 0) { - return false; - } - if (empty($this->_backgroundImage)) { - return false; - } - if (empty($this->_title)) { - return false; - } - return parent::validate(); - } -} diff --git a/library/Zend/Mobile/Push/Message/Mpns/Toast.php b/library/Zend/Mobile/Push/Message/Mpns/Toast.php deleted file mode 100644 index a6282ad142..0000000000 --- a/library/Zend/Mobile/Push/Message/Mpns/Toast.php +++ /dev/null @@ -1,225 +0,0 @@ -_title; - } - - /** - * Set Title - * - * @param string $title - * @return Zend_Mobile_Push_Message_Mpns_Toast - * @throws Zend_Mobile_Push_Message_Exception - */ - public function setTitle($title) - { - if (!is_string($title)) { - throw new Zend_Mobile_Push_Message_Exception('$title must be a string'); - } - $this->_title = $title; - return $this; - } - - /** - * Get Message - * - * @return string - */ - public function getMessage() - { - return $this->_msg; - } - - /** - * Set Message - * - * @param string $msg - * @return Zend_Mobile_Push_Message_Mpns_Toast - * @throws Zend_Mobile_Push_Message_Exception - */ - public function setMessage($msg) - { - if (!is_string($msg)) { - throw new Zend_Mobile_Push_Message_Exception('$msg must be a string'); - } - $this->_msg = $msg; - return $this; - } - - /** - * Get Params - * - * @return string - */ - public function getParams() - { - return $this->_params; - } - - /** - * Set Params - * - * @param string $params - * @return Zend_Mobile_Push_Message_Mpns_Toast - * @throws Zend_Mobile_Push_Message_Exception - */ - public function setParams($params) - { - if (!is_string($params)) { - throw new Zend_Mobile_Push_Message_Exception('$params must be a string'); - } - $this->_params = $params; - return $this; - } - - /** - * Get Delay - * - * @return int - */ - public function getDelay() - { - if (!$this->_delay) { - return self::DELAY_IMMEDIATE; - } - return $this->_delay; - } - - /** - * Set Delay - * - * @param int $delay - * @return Zend_Mobile_Push_Message_Mpns_Toast - * @throws Zend_Mobile_Push_Message_Exception - */ - public function setDelay($delay) - { - if (!in_array($delay, array( - self::DELAY_IMMEDIATE, - self::DELAY_450S, - self::DELAY_900S - ))) { - throw new Zend_Mobile_Push_Message_Exception('$delay must be one of the DELAY_* constants'); - } - $this->_delay = $delay; - return $this; - } - - /** - * Get Notification Type - * - * @return string - */ - public static function getNotificationType() - { - return 'toast'; - } - - /** - * Get XML Payload - * - * @return string - */ - public function getXmlPayload() - { - $ret = '' - . '' - . '' - . '' . htmlspecialchars($this->_title) . '' - . '' . htmlspecialchars($this->_msg) . ''; - if (!empty($this->_params)) { - $ret .= '' . htmlspecialchars($this->_params) . ''; - } - $ret .= '' - . ''; - return $ret; - } - - /** - * Validate proper mpns message - * - * @return boolean - */ - public function validate() - { - if (!isset($this->_token) || strlen($this->_token) === 0) { - return false; - } - if (empty($this->_title)) { - return false; - } - if (empty($this->_msg)) { - return false; - } - return parent::validate(); - } -} diff --git a/library/Zend/Mobile/Push/Mpns.php b/library/Zend/Mobile/Push/Mpns.php deleted file mode 100644 index dec0acd9cc..0000000000 --- a/library/Zend/Mobile/Push/Mpns.php +++ /dev/null @@ -1,158 +0,0 @@ -_httpClient) { - $this->_httpClient = new Zend_Http_Client(); - $this->_httpClient->setConfig(array( - 'strictredirects' => true, - )); - } - return $this->_httpClient; - } - - /** - * Set Http Client - * - * @return Zend_Mobile_Push_Mpns - */ - public function setHttpClient(Zend_Http_Client $client) - { - $this->_httpClient = $client; - return $this; - } - - /** - * Send Message - * - * @param Zend_Mobile_Push_Message_Abstract $message - * @throws Zend_Http_Client_Exception - * @throws Zend_Mobile_Push_Exception - * @throws Zend_Mobile_Push_Exception_DeviceQuotaExceeded - * @throws Zend_Mobile_Push_Exception_InvalidPayload - * @throws Zend_Mobile_Push_Exception_InvalidToken - * @throws Zend_Mobile_Push_Exception_QuotaExceeded - * @throws Zend_Mobile_Push_Exception_ServerUnavailable - * @return boolean - */ - public function send(Zend_Mobile_Push_Message_Abstract $message) - { - if (!$message->validate()) { - throw new Zend_Mobile_Push_Exception('The message is not valid.'); - } - - $this->connect(); - - $client = $this->getHttpClient(); - $client->setUri($message->getToken()); - $client->setHeaders(array( - 'Context-Type' => 'text/xml', - 'Accept' => 'application/*', - 'X-NotificationClass' => $message->getDelay() - )); - if ($message->getId()) { - $client->setHeaders('X-MessageID', $message->getId()); - } - if ($message->getNotificationType() != Zend_Mobile_Push_Message_Mpns::TYPE_RAW) { - $client->setHeaders('X-WindowsPhone-Target', $message->getNotificationType()); - } - $client->setRawData($message->getXmlPayload(), 'text/xml'); - $response = $client->request('POST'); - $this->close(); - - - switch ($response->getStatus()) - { - case 200: - // check headers for response? need to test how this actually works to correctly handle different states. - if ($response->getHeader('NotificationStatus') == 'QueueFull') { - #require_once 'Zend/Mobile/Push/Exception/DeviceQuotaExceeded.php'; - throw new Zend_Mobile_Push_Exception_DeviceQuotaExceeded('The devices push notification queue is full, use exponential backoff'); - } - break; - case 400: - #require_once 'Zend/Mobile/Push/Exception/InvalidPayload.php'; - throw new Zend_Mobile_Push_Exception_InvalidPayload('The message xml was invalid'); - break; - case 401: - #require_once 'Zend/Mobile/Push/Exception/InvalidToken.php'; - throw new Zend_Mobile_Push_Exception_InvalidToken('The device token is not valid or there is a mismatch between certificates'); - break; - case 404: - #require_once 'Zend/Mobile/Push/Exception/InvalidToken.php'; - throw new Zend_Mobile_Push_Exception_InvalidToken('The device subscription is invalid, stop sending notifications to this device'); - break; - case 405: - throw new Zend_Mobile_Push_Exception('Invalid method, only POST is allowed'); // will never be hit unless overwritten - break; - case 406: - #require_once 'Zend/Mobile/Push/Exception/QuotaExceeded.php'; - throw new Zend_Mobile_Push_Exception_QuotaExceeded('The unauthenticated web service has reached the per-day throttling limit'); - break; - case 412: - #require_once 'Zend/Mobile/Push/Exception/InvalidToken.php'; - throw new Zend_Mobile_Push_Exception_InvalidToken('The device is in an inactive state. You may retry once per hour'); - break; - case 503: - #require_once 'Zend/Mobile/Push/Exception/ServerUnavailable.php'; - throw new Zend_Mobile_Push_Exception_ServerUnavailable('The server was unavailable.'); - break; - default: - break; - } - return true; - } -} diff --git a/library/Zend/Mobile/Push/Response/Gcm.php b/library/Zend/Mobile/Push/Response/Gcm.php deleted file mode 100644 index 151733a734..0000000000 --- a/library/Zend/Mobile/Push/Response/Gcm.php +++ /dev/null @@ -1,243 +0,0 @@ -setResponse($response); - } - - if ($message) { - $this->setMessage($message); - } - - } - - /** - * Get Message - * - * @return Zend_Mobile_Push_Message_Gcm - */ - public function getMessage() - { - return $this->_message; - } - - /** - * Set Message - * - * @param Zend_Mobile_Push_Message_Gcm $message - * @return Zend_Mobile_Push_Response_Gcm - */ - public function setMessage(Zend_Mobile_Push_Message_Gcm $message) - { - $this->_message = $message; - return $this; - } - - /** - * Get Response - * - * @return array - */ - public function getResponse() - { - return $this->_response; - } - - /** - * Set Response - * - * @param array $response - * @throws Zend_Mobile_Push_Exception - * @return Zend_Mobile_Push_Response_Gcm - */ - public function setResponse(array $response) - { - if (!isset($response['results']) || - !isset($response['success']) || - !isset($response['failure']) || - !isset($response['canonical_ids']) || - !isset($response['multicast_id'])) { - throw new Zend_Mobile_Push_Exception('Response did not contain the proper fields'); - } - $this->_response = $response; - $this->_results = $response['results']; - $this->_successCnt = (int) $response['success']; - $this->_failureCnt = (int) $response['failure']; - $this->_canonicalCnt = (int) $response['canonical_ids']; - $this->_id = (int) $response['multicast_id']; - return $this; - } - - /** - * Get Success Count - * - * @return int - */ - public function getSuccessCount() - { - return $this->_successCnt; - } - - /** - * Get Failure Count - * - * @return int - */ - public function getFailureCount() - { - return $this->_failureCnt; - } - - /** - * Get Canonical Count - * - * @return int - */ - public function getCanonicalCount() - { - return $this->_canonicalCnt; - } - - /** - * Get Results - * - * @return array multi dimensional array of: - * NOTE: key is registration_id if the message is passed. - * 'registration_id' => array( - * 'message_id' => 'id', - * 'error' => 'error', - * 'registration_id' => 'id' - * ) - */ - public function getResults() - { - return $this->_correlate(); - } - - /** - * Get Singular Result - * - * @param int $flag one of the RESULT_* flags - * @return array singular array with keys being registration id - * value is the type of result - */ - public function getResult($flag) - { - $ret = array(); - foreach ($this->_correlate() as $k => $v) { - if (isset($v[$flag])) { - $ret[$k] = $v[$flag]; - } - } - return $ret; - } - - /** - * Correlate Message and Result - * - * @return array - */ - protected function _correlate() - { - $results = $this->_results; - if ($this->_message && $results) { - $tokens = $this->_message->getToken(); - while($token = array_shift($tokens)) { - $results[$token] = array_shift($results); - } - } - return $results; - } -} diff --git a/library/Zend/Mobile/Push/Test/ApnsProxy.php b/library/Zend/Mobile/Push/Test/ApnsProxy.php deleted file mode 100644 index cbef7f15f0..0000000000 --- a/library/Zend/Mobile/Push/Test/ApnsProxy.php +++ /dev/null @@ -1,102 +0,0 @@ -_readResponse = $str; - } - - /** - * Set the write response - * - * @param mixed $resp - * @return void - */ - public function setWriteResponse($resp) - { - $this->_writeResponse = $resp; - } - - /** - * Connect - * - * @return true - */ - protected function _connect($uri) { - return true; - } - - /** - * Return Response - * - * @param string $length - * @return string - */ - protected function _read($length) { - $ret = substr($this->_readResponse, 0, $length); - $this->_readResponse = null; - return $ret; - } - - /** - * Write and Return Length - * - * @param string $payload - * @return int - */ - protected function _write($payload) { - $ret = $this->_writeResponse; - $this->_writeResponse = null; - return (null === $ret) ? strlen($payload) : $ret; - } -} diff --git a/library/Zend/OpenId.php b/library/Zend/OpenId.php deleted file mode 100644 index 5e99854681..0000000000 --- a/library/Zend/OpenId.php +++ /dev/null @@ -1,757 +0,0 @@ - 1 ? $dir : '') - . '/' - . $url; - } - } - } - return $url; - } - - /** - * Converts variable/value pairs into URL encoded query string - * - * @param array $params variable/value pairs - * @return string URL encoded query string - */ - static public function paramsToQuery($params) - { - foreach($params as $key => $value) { - if (isset($query)) { - $query .= '&' . $key . '=' . urlencode($value); - } else { - $query = $key . '=' . urlencode($value); - } - } - return isset($query) ? $query : ''; - } - - /** - * Normalizes URL according to RFC 3986 to use it in comparison operations. - * The function gets URL argument by reference and modifies it. - * It returns true on success and false of failure. - * - * @param string &$id url to be normalized - * @return bool - */ - static public function normalizeUrl(&$id) - { - // RFC 3986, 6.2.2. Syntax-Based Normalization - - // RFC 3986, 6.2.2.2 Percent-Encoding Normalization - $i = 0; - $n = strlen($id); - $res = ''; - while ($i < $n) { - if ($id[$i] == '%') { - if ($i + 2 >= $n) { - return false; - } - ++$i; - if ($id[$i] >= '0' && $id[$i] <= '9') { - $c = ord($id[$i]) - ord('0'); - } else if ($id[$i] >= 'A' && $id[$i] <= 'F') { - $c = ord($id[$i]) - ord('A') + 10; - } else if ($id[$i] >= 'a' && $id[$i] <= 'f') { - $c = ord($id[$i]) - ord('a') + 10; - } else { - return false; - } - ++$i; - if ($id[$i] >= '0' && $id[$i] <= '9') { - $c = ($c << 4) | (ord($id[$i]) - ord('0')); - } else if ($id[$i] >= 'A' && $id[$i] <= 'F') { - $c = ($c << 4) | (ord($id[$i]) - ord('A') + 10); - } else if ($id[$i] >= 'a' && $id[$i] <= 'f') { - $c = ($c << 4) | (ord($id[$i]) - ord('a') + 10); - } else { - return false; - } - ++$i; - $ch = chr($c); - if (($ch >= 'A' && $ch <= 'Z') || - ($ch >= 'a' && $ch <= 'z') || - $ch == '-' || - $ch == '.' || - $ch == '_' || - $ch == '~') { - $res .= $ch; - } else { - $res .= '%'; - if (($c >> 4) < 10) { - $res .= chr(($c >> 4) + ord('0')); - } else { - $res .= chr(($c >> 4) - 10 + ord('A')); - } - $c = $c & 0xf; - if ($c < 10) { - $res .= chr($c + ord('0')); - } else { - $res .= chr($c - 10 + ord('A')); - } - } - } else { - $res .= $id[$i++]; - } - } - - if (!preg_match('|^([^:]+)://([^:@]*(?:[:][^@]*)?@)?([^/:@?#]*)(?:[:]([^/?#]*))?(/[^?#]*)?((?:[?](?:[^#]*))?)((?:#.*)?)$|', $res, $reg)) { - return false; - } - $scheme = $reg[1]; - $auth = $reg[2]; - $host = $reg[3]; - $port = $reg[4]; - $path = $reg[5]; - $query = $reg[6]; - $fragment = $reg[7]; /* strip it */ /* ZF-4358 Fragment retained under OpenID 2.0 */ - - if (empty($scheme) || empty($host)) { - return false; - } - - // RFC 3986, 6.2.2.1. Case Normalization - $scheme = strtolower($scheme); - $host = strtolower($host); - - // RFC 3986, 6.2.2.3. Path Segment Normalization - if (!empty($path)) { - $i = 0; - $n = strlen($path); - $res = ""; - while ($i < $n) { - if ($path[$i] == '/') { - ++$i; - while ($i < $n && $path[$i] == '/') { - ++$i; - } - if ($i < $n && $path[$i] == '.') { - ++$i; - if ($i < $n && $path[$i] == '.') { - ++$i; - if ($i == $n || $path[$i] == '/') { - if (($pos = strrpos($res, '/')) !== false) { - $res = substr($res, 0, $pos); - } - } else { - $res .= '/..'; - } - } else if ($i != $n && $path[$i] != '/') { - $res .= '/.'; - } - } else { - $res .= '/'; - } - } else { - $res .= $path[$i++]; - } - } - $path = $res; - } - - // RFC 3986,6.2.3. Scheme-Based Normalization - if ($scheme == 'http') { - if ($port == 80) { - $port = ''; - } - } else if ($scheme == 'https') { - if ($port == 443) { - $port = ''; - } - } - if (empty($path)) { - $path = '/'; - } - - $id = $scheme - . '://' - . $auth - . $host - . (empty($port) ? '' : (':' . $port)) - . $path - . $query - . $fragment; - return true; - } - - /** - * Normalizes OpenID identifier that can be URL or XRI name. - * Returns true on success and false of failure. - * - * Normalization is performed according to the following rules: - * 1. If the user's input starts with one of the "xri://", "xri://$ip*", - * or "xri://$dns*" prefixes, they MUST be stripped off, so that XRIs - * are used in the canonical form, and URI-authority XRIs are further - * considered URL identifiers. - * 2. If the first character of the resulting string is an XRI Global - * Context Symbol ("=", "@", "+", "$", "!"), then the input SHOULD be - * treated as an XRI. - * 3. Otherwise, the input SHOULD be treated as an http URL; if it does - * not include a "http" or "https" scheme, the Identifier MUST be - * prefixed with the string "http://". - * 4. URL identifiers MUST then be further normalized by both following - * redirects when retrieving their content and finally applying the - * rules in Section 6 of [RFC3986] to the final destination URL. - * @param string &$id identifier to be normalized - * @return bool - */ - static public function normalize(&$id) - { - $id = trim($id); - if (strlen($id) === 0) { - return true; - } - - // 7.2.1 - if (strpos($id, 'xri://$ip*') === 0) { - $id = substr($id, strlen('xri://$ip*')); - } else if (strpos($id, 'xri://$dns*') === 0) { - $id = substr($id, strlen('xri://$dns*')); - } else if (strpos($id, 'xri://') === 0) { - $id = substr($id, strlen('xri://')); - } - - // 7.2.2 - if ($id[0] == '=' || - $id[0] == '@' || - $id[0] == '+' || - $id[0] == '$' || - $id[0] == '!') { - return true; - } - - // 7.2.3 - if (strpos($id, "://") === false) { - $id = 'http://' . $id; - } - - // 7.2.4 - return self::normalizeURL($id); - } - - /** - * Performs a HTTP redirection to specified URL with additional data. - * It may generate redirected request using GET or POST HTTP method. - * The function never returns. - * - * @param string $url URL to redirect to - * @param array $params additional variable/value pairs to send - * @param Zend_Controller_Response_Abstract $response - * @param string $method redirection method ('GET' or 'POST') - */ - static public function redirect($url, $params = null, - Zend_Controller_Response_Abstract $response = null, $method = 'GET') - { - $url = Zend_OpenId::absoluteUrl($url); - $body = ""; - if (null === $response) { - #require_once "Zend/Controller/Response/Http.php"; - $response = new Zend_Controller_Response_Http(); - } - - if ($method == 'POST') { - $body = "\n"; - $body .= "
\n"; - if (is_array($params) && count($params) > 0) { - foreach($params as $key => $value) { - $body .= '\n"; - } - } - $body .= "\n"; - $body .= "
\n"; - } else if (is_array($params) && count($params) > 0) { - if (strpos($url, '?') === false) { - $url .= '?' . self::paramsToQuery($params); - } else { - $url .= '&' . self::paramsToQuery($params); - } - } - if (!empty($body)) { - $response->setBody($body); - } else if (!$response->canSendHeaders()) { - $response->setBody(""); - } else { - $response->setRedirect($url); - } - $response->sendResponse(); - if (self::$exitOnRedirect) { - exit(); - } - } - - /** - * Produces string of random byte of given length. - * - * @param integer $len length of requested string - * @return string RAW random binary string - */ - static public function randomBytes($len) - { - return (string) Zend_Crypt_Math::randBytes($len); - } - - /** - * Generates a hash value (message digest) according to given algorithm. - * It returns RAW binary string. - * - * This is a wrapper function that uses one of available internal function - * dependent on given PHP configuration. It may use various functions from - * ext/openssl, ext/hash, ext/mhash or ext/standard. - * - * @param string $func digest algorithm - * @param string $data data to sign - * @return string RAW digital signature - * @throws Zend_OpenId_Exception - */ - static public function digest($func, $data) - { - if (function_exists('openssl_digest')) { - return openssl_digest($data, $func, true); - } else if (function_exists('hash')) { - return hash($func, $data, true); - } else if ($func === 'sha1') { - return sha1($data, true); - } else if ($func === 'sha256') { - if (function_exists('mhash')) { - return mhash(MHASH_SHA256 , $data); - } - } - #require_once "Zend/OpenId/Exception.php"; - throw new Zend_OpenId_Exception( - 'Unsupported digest algorithm "' . $func . '".', - Zend_OpenId_Exception::UNSUPPORTED_DIGEST); - } - - /** - * Generates a keyed hash value using the HMAC method. It uses ext/hash - * if available or user-level PHP implementation, that is not significantly - * slower. - * - * @param string $macFunc name of selected hashing algorithm (sha1, sha256) - * @param string $data data to sign - * @param string $secret shared secret key used for generating the HMAC - * variant of the message digest - * @return string RAW HMAC value - */ - static public function hashHmac($macFunc, $data, $secret) - { -// #require_once "Zend/Crypt/Hmac.php"; -// return Zend_Crypt_Hmac::compute($secret, $macFunc, $data, Zend_Crypt_Hmac::BINARY); - if (function_exists('hash_hmac')) { - return hash_hmac($macFunc, $data, $secret, true); - } else { - if (Zend_OpenId::strlen($secret) > 64) { - $secret = self::digest($macFunc, $secret); - } - $secret = str_pad($secret, 64, chr(0x00)); - $ipad = str_repeat(chr(0x36), 64); - $opad = str_repeat(chr(0x5c), 64); - $hash1 = self::digest($macFunc, ($secret ^ $ipad) . $data); - return self::digest($macFunc, ($secret ^ $opad) . $hash1); - } - } - - /** - * Converts binary representation into ext/gmp or ext/bcmath big integer - * representation. - * - * @param string $bin binary representation of big number - * @return mixed - * @throws Zend_OpenId_Exception - */ - static protected function binToBigNum($bin) - { - if (extension_loaded('gmp')) { - return gmp_init(bin2hex($bin), 16); - } else if (extension_loaded('bcmath')) { - $bn = 0; - $len = Zend_OpenId::strlen($bin); - for ($i = 0; $i < $len; $i++) { - $bn = bcmul($bn, 256); - $bn = bcadd($bn, ord($bin[$i])); - } - return $bn; - } - #require_once "Zend/OpenId/Exception.php"; - throw new Zend_OpenId_Exception( - 'The system doesn\'t have proper big integer extension', - Zend_OpenId_Exception::UNSUPPORTED_LONG_MATH); - } - - /** - * Converts internal ext/gmp or ext/bcmath big integer representation into - * binary string. - * - * @param mixed $bn big number - * @return string - * @throws Zend_OpenId_Exception - */ - static protected function bigNumToBin($bn) - { - if (extension_loaded('gmp')) { - $s = gmp_strval($bn, 16); - if (strlen($s) % 2 != 0) { - $s = '0' . $s; - } else if ($s[0] > '7') { - $s = '00' . $s; - } - return pack("H*", $s); - } else if (extension_loaded('bcmath')) { - $cmp = bccomp($bn, 0); - if ($cmp == 0) { - return "\0"; - } else if ($cmp < 0) { - #require_once "Zend/OpenId/Exception.php"; - throw new Zend_OpenId_Exception( - 'Big integer arithmetic error', - Zend_OpenId_Exception::ERROR_LONG_MATH); - } - $bin = ""; - while (bccomp($bn, 0) > 0) { - $bin = chr(bcmod($bn, 256)) . $bin; - $bn = bcdiv($bn, 256); - } - if (ord($bin[0]) > 127) { - $bin = "\0" . $bin; - } - return $bin; - } - #require_once "Zend/OpenId/Exception.php"; - throw new Zend_OpenId_Exception( - 'The system doesn\'t have proper big integer extension', - Zend_OpenId_Exception::UNSUPPORTED_LONG_MATH); - } - - /** - * Performs the first step of a Diffie-Hellman key exchange by generating - * private and public DH values based on given prime number $p and - * generator $g. Both sides of key exchange MUST have the same prime number - * and generator. In this case they will able to create a random shared - * secret that is never send from one to the other. - * - * @param string $p prime number in binary representation - * @param string $g generator in binary representation - * @param string $priv_key private key in binary representation - * @return mixed - */ - static public function createDhKey($p, $g, $priv_key = null) - { - if (function_exists('openssl_dh_compute_key')) { - $dh_details = array( - 'p' => $p, - 'g' => $g - ); - if ($priv_key !== null) { - $dh_details['priv_key'] = $priv_key; - } - return openssl_pkey_new(array('dh'=>$dh_details)); - } else { - $bn_p = self::binToBigNum($p); - $bn_g = self::binToBigNum($g); - if ($priv_key === null) { - $priv_key = self::randomBytes(Zend_OpenId::strlen($p)); - } - $bn_priv_key = self::binToBigNum($priv_key); - if (extension_loaded('gmp')) { - $bn_pub_key = gmp_powm($bn_g, $bn_priv_key, $bn_p); - } else if (extension_loaded('bcmath')) { - $bn_pub_key = bcpowmod($bn_g, $bn_priv_key, $bn_p); - } - $pub_key = self::bigNumToBin($bn_pub_key); - - return array( - 'p' => $bn_p, - 'g' => $bn_g, - 'priv_key' => $bn_priv_key, - 'pub_key' => $bn_pub_key, - 'details' => array( - 'p' => $p, - 'g' => $g, - 'priv_key' => $priv_key, - 'pub_key' => $pub_key)); - } - } - - /** - * Returns an associative array with Diffie-Hellman key components in - * binary representation. The array includes original prime number 'p' and - * generator 'g', random private key 'priv_key' and corresponding public - * key 'pub_key'. - * - * @param mixed $dh Diffie-Hellman key - * @return array - */ - static public function getDhKeyDetails($dh) - { - if (function_exists('openssl_dh_compute_key')) { - $details = openssl_pkey_get_details($dh); - if (isset($details['dh'])) { - return $details['dh']; - } - } else { - return $dh['details']; - } - } - - /** - * Computes the shared secret from the private DH value $dh and the other - * party's public value in $pub_key - * - * @param string $pub_key other party's public value - * @param mixed $dh Diffie-Hellman key - * @return string - * @throws Zend_OpenId_Exception - */ - static public function computeDhSecret($pub_key, $dh) - { - if (function_exists('openssl_dh_compute_key')) { - $ret = openssl_dh_compute_key($pub_key, $dh); - if (ord($ret[0]) > 127) { - $ret = "\0" . $ret; - } - return $ret; - } else if (extension_loaded('gmp')) { - $bn_pub_key = self::binToBigNum($pub_key); - $bn_secret = gmp_powm($bn_pub_key, $dh['priv_key'], $dh['p']); - return self::bigNumToBin($bn_secret); - } else if (extension_loaded('bcmath')) { - $bn_pub_key = self::binToBigNum($pub_key); - $bn_secret = bcpowmod($bn_pub_key, $dh['priv_key'], $dh['p']); - return self::bigNumToBin($bn_secret); - } - #require_once "Zend/OpenId/Exception.php"; - throw new Zend_OpenId_Exception( - 'The system doesn\'t have proper big integer extension', - Zend_OpenId_Exception::UNSUPPORTED_LONG_MATH); - } - - /** - * Takes an arbitrary precision integer and returns its shortest big-endian - * two's complement representation. - * - * Arbitrary precision integers MUST be encoded as big-endian signed two's - * complement binary strings. Henceforth, "btwoc" is a function that takes - * an arbitrary precision integer and returns its shortest big-endian two's - * complement representation. All integers that are used with - * Diffie-Hellman Key Exchange are positive. This means that the left-most - * bit of the two's complement representation MUST be zero. If it is not, - * implementations MUST add a zero byte at the front of the string. - * - * @param string $str binary representation of arbitrary precision integer - * @return string big-endian signed representation - */ - static public function btwoc($str) - { - if (ord($str[0]) > 127) { - return "\0" . $str; - } - return $str; - } - - /** - * Returns lenght of binary string in bytes - * - * @param string $str - * @return int the string lenght - */ - static public function strlen($str) - { - if (extension_loaded('mbstring') && - (((int)ini_get('mbstring.func_overload')) & 2)) { - return mb_strlen($str, 'latin1'); - } else { - return strlen($str); - } - } - -} diff --git a/library/Zend/OpenId/Consumer.php b/library/Zend/OpenId/Consumer.php deleted file mode 100644 index 128bf34fda..0000000000 --- a/library/Zend/OpenId/Consumer.php +++ /dev/null @@ -1,999 +0,0 @@ -_storage = new Zend_OpenId_Consumer_Storage_File(); - } else { - $this->_storage = $storage; - } - $this->_dumbMode = $dumbMode; - } - - /** - * Performs check (with possible user interaction) of OpenID identity. - * - * This is the first step of OpenID authentication process. - * On success the function does not return (it does HTTP redirection to - * server and exits). On failure it returns false. - * - * @param string $id OpenID identity - * @param string $returnTo URL to redirect response from server to - * @param string $root HTTP URL to identify consumer on server - * @param mixed $extensions extension object or array of extensions objects - * @param Zend_Controller_Response_Abstract $response an optional response - * object to perform HTTP or HTML form redirection - * @return bool - */ - public function login($id, $returnTo = null, $root = null, $extensions = null, - Zend_Controller_Response_Abstract $response = null) - { - return $this->_checkId( - false, - $id, - $returnTo, - $root, - $extensions, - $response); - } - - /** - * Performs immediate check (without user interaction) of OpenID identity. - * - * This is the first step of OpenID authentication process. - * On success the function does not return (it does HTTP redirection to - * server and exits). On failure it returns false. - * - * @param string $id OpenID identity - * @param string $returnTo HTTP URL to redirect response from server to - * @param string $root HTTP URL to identify consumer on server - * @param mixed $extensions extension object or array of extensions objects - * @param Zend_Controller_Response_Abstract $response an optional response - * object to perform HTTP or HTML form redirection - * @return bool - */ - public function check($id, $returnTo=null, $root=null, $extensions = null, - Zend_Controller_Response_Abstract $response = null) - - { - return $this->_checkId( - true, - $id, - $returnTo, - $root, - $extensions, - $response); - } - - /** - * Verifies authentication response from OpenID server. - * - * This is the second step of OpenID authentication process. - * The function returns true on successful authentication and false on - * failure. - * - * @param array $params HTTP query data from OpenID server - * @param string &$identity this argument is set to end-user's claimed - * identifier or OpenID provider local identifier. - * @param mixed $extensions extension object or array of extensions objects - * @return bool - */ - public function verify($params, &$identity = "", $extensions = null) - { - $this->_setError(''); - - $version = 1.1; - if (isset($params['openid_ns']) && - $params['openid_ns'] == Zend_OpenId::NS_2_0) { - $version = 2.0; - } - - if (isset($params["openid_claimed_id"])) { - $identity = $params["openid_claimed_id"]; - } else if (isset($params["openid_identity"])){ - $identity = $params["openid_identity"]; - } else { - $identity = ""; - } - - if ($version < 2.0 && !isset($params["openid_claimed_id"])) { - if ($this->_session !== null) { - if ($this->_session->identity === $identity) { - $identity = $this->_session->claimed_id; - } - } else if (defined('SID')) { - if (isset($_SESSION["zend_openid"]["identity"]) && - isset($_SESSION["zend_openid"]["claimed_id"]) && - $_SESSION["zend_openid"]["identity"] === $identity) { - $identity = $_SESSION["zend_openid"]["claimed_id"]; - } - } else { - #require_once "Zend/Session/Namespace.php"; - $this->_session = new Zend_Session_Namespace("zend_openid"); - if ($this->_session->identity === $identity) { - $identity = $this->_session->claimed_id; - } - } - } - - if (empty($params['openid_mode'])) { - $this->_setError("Missing openid.mode"); - return false; - } - if (empty($params['openid_return_to'])) { - $this->_setError("Missing openid.return_to"); - return false; - } - if (empty($params['openid_signed'])) { - $this->_setError("Missing openid.signed"); - return false; - } - if (empty($params['openid_sig'])) { - $this->_setError("Missing openid.sig"); - return false; - } - if ($params['openid_mode'] != 'id_res') { - $this->_setError("Wrong openid.mode '".$params['openid_mode']."' != 'id_res'"); - return false; - } - if (empty($params['openid_assoc_handle'])) { - $this->_setError("Missing openid.assoc_handle"); - return false; - } - if ($params['openid_return_to'] != Zend_OpenId::selfUrl()) { - /* Ignore query part in openid.return_to */ - $pos = strpos($params['openid_return_to'], '?'); - if ($pos === false || - SUBSTR($params['openid_return_to'], 0 , $pos) != Zend_OpenId::selfUrl()) { - - $this->_setError("Wrong openid.return_to '". - $params['openid_return_to']."' != '" . Zend_OpenId::selfUrl() ."'"); - return false; - } - } - if ($version >= 2.0) { - if (empty($params['openid_response_nonce'])) { - $this->_setError("Missing openid.response_nonce"); - return false; - } - if (empty($params['openid_op_endpoint'])) { - $this->_setError("Missing openid.op_endpoint"); - return false; - /* OpenID 2.0 (11.3) Checking the Nonce */ - } else if (!$this->_storage->isUniqueNonce($params['openid_op_endpoint'], $params['openid_response_nonce'])) { - $this->_setError("Duplicate openid.response_nonce"); - return false; - } - } - - if (!empty($params['openid_invalidate_handle'])) { - if ($this->_storage->getAssociationByHandle( - $params['openid_invalidate_handle'], - $url, - $macFunc, - $secret, - $expires)) { - $this->_storage->delAssociation($url); - } - } - - if ($this->_storage->getAssociationByHandle( - $params['openid_assoc_handle'], - $url, - $macFunc, - $secret, - $expires)) { - // Security fix - check the association bewteen op_endpoint and assoc_handle - if (isset($params['openid_op_endpoint']) && $url !== $params['openid_op_endpoint']) { - $this->_setError("The op_endpoint URI is not the same of URI associated with the assoc_handle"); - return false; - } - $signed = explode(',', $params['openid_signed']); - // Check the parameters for the signature - // @see https://openid.net/specs/openid-authentication-2_0.html#positive_assertions - $toCheck = $this->_signParams; - if (isset($params['openid_claimed_id']) && isset($params['openid_identity'])) { - $toCheck = array_merge($toCheck, array('claimed_id', 'identity')); - } - foreach ($toCheck as $param) { - if (!in_array($param, $signed, true)) { - $this->_setError("The required parameter $param is missing in the signed"); - return false; - } - } - - $data = ''; - foreach ($signed as $key) { - $data .= $key . ':' . $params['openid_' . strtr($key,'.','_')] . "\n"; - } - if (base64_decode($params['openid_sig']) == - Zend_OpenId::hashHmac($macFunc, $data, $secret)) { - if (!Zend_OpenId_Extension::forAll($extensions, 'parseResponse', $params)) { - $this->_setError("Extension::parseResponse failure"); - return false; - } - /* OpenID 2.0 (11.2) Verifying Discovered Information */ - if (isset($params['openid_claimed_id'])) { - $id = $params['openid_claimed_id']; - if (!Zend_OpenId::normalize($id)) { - $this->_setError("Normalization failed"); - return false; - } else if (!$this->_discovery($id, $discovered_server, $discovered_version)) { - $this->_setError("Discovery failed: " . $this->getError()); - return false; - } else if ((!empty($params['openid_identity']) && - $params["openid_identity"] != $id) || - (!empty($params['openid_op_endpoint']) && - $params['openid_op_endpoint'] != $discovered_server) || - $discovered_version != $version) { - $this->_setError("Discovery information verification failed"); - return false; - } - } - return true; - } - $this->_storage->delAssociation($url); - $this->_setError("Signature check failed"); - return false; - } - else - { - /* Use dumb mode */ - if (isset($params['openid_claimed_id'])) { - $id = $params['openid_claimed_id']; - } else if (isset($params['openid_identity'])) { - $id = $params['openid_identity']; - } else { - $this->_setError("Missing openid.claimed_id and openid.identity"); - return false; - } - - if (!Zend_OpenId::normalize($id)) { - $this->_setError("Normalization failed"); - return false; - } else if (!$this->_discovery($id, $server, $discovered_version)) { - $this->_setError("Discovery failed: " . $this->getError()); - return false; - } - - /* OpenID 2.0 (11.2) Verifying Discovered Information */ - if ((isset($params['openid_identity']) && - $params["openid_identity"] != $id) || - (isset($params['openid_op_endpoint']) && - $params['openid_op_endpoint'] != $server) || - $discovered_version != $version) { - $this->_setError("Discovery information verification failed"); - return false; - } - - $params2 = array(); - foreach ($params as $key => $val) { - if (strpos($key, 'openid_ns_') === 0) { - $key = 'openid.ns.' . substr($key, strlen('openid_ns_')); - } else if (strpos($key, 'openid_sreg_') === 0) { - $key = 'openid.sreg.' . substr($key, strlen('openid_sreg_')); - } else if (strpos($key, 'openid_') === 0) { - $key = 'openid.' . substr($key, strlen('openid_')); - } - $params2[$key] = $val; - } - $params2['openid.mode'] = 'check_authentication'; - $ret = $this->_httpRequest($server, 'POST', $params2, $status); - if ($status != 200) { - $this->_setError("'Dumb' signature verification HTTP request failed"); - return false; - } - $r = array(); - if (is_string($ret)) { - foreach(explode("\n", $ret) as $line) { - $line = trim($line); - if (!empty($line)) { - $x = explode(':', $line, 2); - if (is_array($x) && count($x) == 2) { - list($key, $value) = $x; - $r[trim($key)] = trim($value); - } - } - } - } - $ret = $r; - if (!empty($ret['invalidate_handle'])) { - if ($this->_storage->getAssociationByHandle( - $ret['invalidate_handle'], - $url, - $macFunc, - $secret, - $expires)) { - $this->_storage->delAssociation($url); - } - } - if (isset($ret['is_valid']) && $ret['is_valid'] == 'true') { - if (!Zend_OpenId_Extension::forAll($extensions, 'parseResponse', $params)) { - $this->_setError("Extension::parseResponse failure"); - return false; - } - return true; - } - $this->_setError("'Dumb' signature verification failed"); - return false; - } - } - - /** - * Store assiciation in internal chace and external storage - * - * @param string $url OpenID server url - * @param string $handle association handle - * @param string $macFunc HMAC function (sha1 or sha256) - * @param string $secret shared secret - * @param integer $expires expiration UNIX time - * @return void - */ - protected function _addAssociation($url, $handle, $macFunc, $secret, $expires) - { - $this->_cache[$url] = array($handle, $macFunc, $secret, $expires); - return $this->_storage->addAssociation( - $url, - $handle, - $macFunc, - $secret, - $expires); - } - - /** - * Retrive assiciation information for given $url from internal cahce or - * external storage - * - * @param string $url OpenID server url - * @param string &$handle association handle - * @param string &$macFunc HMAC function (sha1 or sha256) - * @param string &$secret shared secret - * @param integer &$expires expiration UNIX time - * @return void - */ - protected function _getAssociation($url, &$handle, &$macFunc, &$secret, &$expires) - { - if (isset($this->_cache[$url])) { - $handle = $this->_cache[$url][0]; - $macFunc = $this->_cache[$url][1]; - $secret = $this->_cache[$url][2]; - $expires = $this->_cache[$url][3]; - return true; - } - if ($this->_storage->getAssociation( - $url, - $handle, - $macFunc, - $secret, - $expires)) { - $this->_cache[$url] = array($handle, $macFunc, $secret, $expires); - return true; - } - return false; - } - - /** - * Performs HTTP request to given $url using given HTTP $method. - * Send additinal query specified by variable/value array, - * On success returns HTTP response without headers, false on failure. - * - * @param string $url OpenID server url - * @param string $method HTTP request method 'GET' or 'POST' - * @param array $params additional qwery parameters to be passed with - * @param int &$staus HTTP status code - * request - * @return mixed - */ - protected function _httpRequest($url, $method = 'GET', array $params = array(), &$status = null) - { - $client = $this->_httpClient; - if ($client === null) { - $client = new Zend_Http_Client( - $url, - array( - 'maxredirects' => 4, - 'timeout' => 15, - 'useragent' => 'Zend_OpenId' - ) - ); - } else { - $client->setUri($url); - } - - $client->resetParameters(); - if ($method == 'POST') { - $client->setMethod(Zend_Http_Client::POST); - $client->setParameterPost($params); - } else { - $client->setMethod(Zend_Http_Client::GET); - $client->setParameterGet($params); - } - - try { - $response = $client->request(); - } catch (Exception $e) { - $this->_setError('HTTP Request failed: ' . $e->getMessage()); - return false; - } - $status = $response->getStatus(); - $body = $response->getBody(); - if ($status == 200 || ($status == 400 && !empty($body))) { - return $body; - }else{ - $this->_setError('Bad HTTP response'); - return false; - } - } - - /** - * Create (or reuse existing) association between OpenID consumer and - * OpenID server based on Diffie-Hellman key agreement. Returns true - * on success and false on failure. - * - * @param string $url OpenID server url - * @param float $version OpenID protocol version - * @param string $priv_key for testing only - * @return bool - */ - protected function _associate($url, $version, $priv_key=null) - { - - /* Check if we already have association in chace or storage */ - if ($this->_getAssociation( - $url, - $handle, - $macFunc, - $secret, - $expires)) { - return true; - } - - if ($this->_dumbMode) { - /* Use dumb mode */ - return true; - } - - $params = array(); - - if ($version >= 2.0) { - $params = array( - 'openid.ns' => Zend_OpenId::NS_2_0, - 'openid.mode' => 'associate', - 'openid.assoc_type' => 'HMAC-SHA256', - 'openid.session_type' => 'DH-SHA256', - ); - } else { - $params = array( - 'openid.mode' => 'associate', - 'openid.assoc_type' => 'HMAC-SHA1', - 'openid.session_type' => 'DH-SHA1', - ); - } - - $dh = Zend_OpenId::createDhKey(pack('H*', Zend_OpenId::DH_P), - pack('H*', Zend_OpenId::DH_G), - $priv_key); - $dh_details = Zend_OpenId::getDhKeyDetails($dh); - - $params['openid.dh_modulus'] = base64_encode( - Zend_OpenId::btwoc($dh_details['p'])); - $params['openid.dh_gen'] = base64_encode( - Zend_OpenId::btwoc($dh_details['g'])); - $params['openid.dh_consumer_public'] = base64_encode( - Zend_OpenId::btwoc($dh_details['pub_key'])); - - while(1) { - $ret = $this->_httpRequest($url, 'POST', $params, $status); - if ($ret === false) { - $this->_setError("HTTP request failed"); - return false; - } - - $r = array(); - $bad_response = false; - foreach(explode("\n", $ret) as $line) { - $line = trim($line); - if (!empty($line)) { - $x = explode(':', $line, 2); - if (is_array($x) && count($x) == 2) { - list($key, $value) = $x; - $r[trim($key)] = trim($value); - } else { - $bad_response = true; - } - } - } - if ($bad_response && strpos($ret, 'Unknown session type') !== false) { - $r['error_code'] = 'unsupported-type'; - } - $ret = $r; - - if (isset($ret['error_code']) && - $ret['error_code'] == 'unsupported-type') { - if ($params['openid.session_type'] == 'DH-SHA256') { - $params['openid.session_type'] = 'DH-SHA1'; - $params['openid.assoc_type'] = 'HMAC-SHA1'; - } else if ($params['openid.session_type'] == 'DH-SHA1') { - $params['openid.session_type'] = 'no-encryption'; - } else { - $this->_setError("The OpenID service responded with: " . $ret['error_code']); - return false; - } - } else { - break; - } - } - - if ($status != 200) { - $this->_setError("The server responded with status code: " . $status); - return false; - } - - if ($version >= 2.0 && - isset($ret['ns']) && - $ret['ns'] != Zend_OpenId::NS_2_0) { - $this->_setError("Wrong namespace definition in the server response"); - return false; - } - - if (!isset($ret['assoc_handle']) || - !isset($ret['expires_in']) || - !isset($ret['assoc_type']) || - $params['openid.assoc_type'] != $ret['assoc_type']) { - if ($params['openid.assoc_type'] != $ret['assoc_type']) { - $this->_setError("The returned assoc_type differed from the supplied openid.assoc_type"); - } else { - $this->_setError("Missing required data from provider (assoc_handle, expires_in, assoc_type are required)"); - } - return false; - } - - $handle = $ret['assoc_handle']; - $expiresIn = $ret['expires_in']; - - if ($ret['assoc_type'] == 'HMAC-SHA1') { - $macFunc = 'sha1'; - } else if ($ret['assoc_type'] == 'HMAC-SHA256' && - $version >= 2.0) { - $macFunc = 'sha256'; - } else { - $this->_setError("Unsupported assoc_type"); - return false; - } - - if ((empty($ret['session_type']) || - ($version >= 2.0 && $ret['session_type'] == 'no-encryption')) && - isset($ret['mac_key'])) { - $secret = base64_decode($ret['mac_key']); - } else if (isset($ret['session_type']) && - $ret['session_type'] == 'DH-SHA1' && - !empty($ret['dh_server_public']) && - !empty($ret['enc_mac_key'])) { - $dhFunc = 'sha1'; - } else if (isset($ret['session_type']) && - $ret['session_type'] == 'DH-SHA256' && - $version >= 2.0 && - !empty($ret['dh_server_public']) && - !empty($ret['enc_mac_key'])) { - $dhFunc = 'sha256'; - } else { - $this->_setError("Unsupported session_type"); - return false; - } - if (isset($dhFunc)) { - $serverPub = base64_decode($ret['dh_server_public']); - $dhSec = Zend_OpenId::computeDhSecret($serverPub, $dh); - if ($dhSec === false) { - $this->_setError("DH secret comutation failed"); - return false; - } - $sec = Zend_OpenId::digest($dhFunc, $dhSec); - if ($sec === false) { - $this->_setError("Could not create digest"); - return false; - } - $secret = $sec ^ base64_decode($ret['enc_mac_key']); - } - if ($macFunc == 'sha1') { - if (Zend_OpenId::strlen($secret) != 20) { - $this->_setError("The length of the sha1 secret must be 20"); - return false; - } - } else if ($macFunc == 'sha256') { - if (Zend_OpenId::strlen($secret) != 32) { - $this->_setError("The length of the sha256 secret must be 32"); - return false; - } - } - $this->_addAssociation( - $url, - $handle, - $macFunc, - $secret, - time() + $expiresIn); - return true; - } - - /** - * Performs discovery of identity and finds OpenID URL, OpenID server URL - * and OpenID protocol version. Returns true on succees and false on - * failure. - * - * @param string &$id OpenID identity URL - * @param string &$server OpenID server URL - * @param float &$version OpenID protocol version - * @return bool - * @todo OpenID 2.0 (7.3) XRI and Yadis discovery - */ - protected function _discovery(&$id, &$server, &$version) - { - $realId = $id; - if ($this->_storage->getDiscoveryInfo( - $id, - $realId, - $server, - $version, - $expire)) { - $id = $realId; - return true; - } - - $response = $this->_httpRequest($id, 'GET', array(), $status); - if ($status != 200 || !is_string($response)) { - return false; - } - - /* OpenID 2.0 (7.3) XRI and Yadis discovery */ - if (preg_match( - '/]*http-equiv=(["\'])[ \t]*(?:[^ \t"\']+[ \t]+)*?X-XRDS-Location[ \t]*[^"\']*\\1[^>]*content=(["\'])([^"\']+)\\2[^>]*\/?>/i', - $response, - $r)) { - $XRDS = $r[3]; - $version = 2.0; - $response = $this->_httpRequest($XRDS); - if (preg_match( - '/([^\t]*)<\/URI>/i', - $response, - $x)) { - $server = $x[1]; - // $realId - $realId = 'http://specs.openid.net/auth/2.0/identifier_select'; - } - else { - $this->_setError("Unable to get URI for XRDS discovery"); - } - } - - /* HTML-based discovery */ - else if (preg_match( - '/]*rel=(["\'])[ \t]*(?:[^ \t"\']+[ \t]+)*?openid2.provider[ \t]*[^"\']*\\1[^>]*href=(["\'])([^"\']+)\\2[^>]*\/?>/i', - $response, - $r)) { - $version = 2.0; - $server = $r[3]; - } else if (preg_match( - '/]*href=(["\'])([^"\']+)\\1[^>]*rel=(["\'])[ \t]*(?:[^ \t"\']+[ \t]+)*?openid2.provider[ \t]*[^"\']*\\3[^>]*\/?>/i', - $response, - $r)) { - $version = 2.0; - $server = $r[2]; - } else if (preg_match( - '/]*rel=(["\'])[ \t]*(?:[^ \t"\']+[ \t]+)*?openid.server[ \t]*[^"\']*\\1[^>]*href=(["\'])([^"\']+)\\2[^>]*\/?>/i', - $response, - $r)) { - $version = 1.1; - $server = $r[3]; - } else if (preg_match( - '/]*href=(["\'])([^"\']+)\\1[^>]*rel=(["\'])[ \t]*(?:[^ \t"\']+[ \t]+)*?openid.server[ \t]*[^"\']*\\3[^>]*\/?>/i', - $response, - $r)) { - $version = 1.1; - $server = $r[2]; - } else { - return false; - } - if ($version >= 2.0) { - if (preg_match( - '/]*rel=(["\'])[ \t]*(?:[^ \t"\']+[ \t]+)*?openid2.local_id[ \t]*[^"\']*\\1[^>]*href=(["\'])([^"\']+)\\2[^>]*\/?>/i', - $response, - $r)) { - $realId = $r[3]; - } else if (preg_match( - '/]*href=(["\'])([^"\']+)\\1[^>]*rel=(["\'])[ \t]*(?:[^ \t"\']+[ \t]+)*?openid2.local_id[ \t]*[^"\']*\\3[^>]*\/?>/i', - $response, - $r)) { - $realId = $r[2]; - } - } else { - if (preg_match( - '/]*rel=(["\'])[ \t]*(?:[^ \t"\']+[ \t]+)*?openid.delegate[ \t]*[^"\']*\\1[^>]*href=(["\'])([^"\']+)\\2[^>]*\/?>/i', - $response, - $r)) { - $realId = $r[3]; - } else if (preg_match( - '/]*href=(["\'])([^"\']+)\\1[^>]*rel=(["\'])[ \t]*(?:[^ \t"\']+[ \t]+)*?openid.delegate[ \t]*[^"\']*\\3[^>]*\/?>/i', - $response, - $r)) { - $realId = $r[2]; - } - } - - $expire = time() + 60 * 60; - $this->_storage->addDiscoveryInfo($id, $realId, $server, $version, $expire); - $id = $realId; - return true; - } - - /** - * Performs check of OpenID identity. - * - * This is the first step of OpenID authentication process. - * On success the function does not return (it does HTTP redirection to - * server and exits). On failure it returns false. - * - * @param bool $immediate enables or disables interaction with user - * @param string $id OpenID identity - * @param string $returnTo HTTP URL to redirect response from server to - * @param string $root HTTP URL to identify consumer on server - * @param mixed $extensions extension object or array of extensions objects - * @param Zend_Controller_Response_Abstract $response an optional response - * object to perform HTTP or HTML form redirection - * @return bool - */ - protected function _checkId($immediate, $id, $returnTo=null, $root=null, - $extensions=null, Zend_Controller_Response_Abstract $response = null) - { - $this->_setError(''); - - if (!Zend_OpenId::normalize($id)) { - $this->_setError("Normalisation failed"); - return false; - } - $claimedId = $id; - - if (!$this->_discovery($id, $server, $version)) { - $this->_setError("Discovery failed: " . $this->getError()); - return false; - } - if (!$this->_associate($server, $version)) { - $this->_setError("Association failed: " . $this->getError()); - return false; - } - if (!$this->_getAssociation( - $server, - $handle, - $macFunc, - $secret, - $expires)) { - /* Use dumb mode */ - unset($handle); - unset($macFunc); - unset($secret); - unset($expires); - } - - $params = array(); - if ($version >= 2.0) { - $params['openid.ns'] = Zend_OpenId::NS_2_0; - } - - $params['openid.mode'] = $immediate ? - 'checkid_immediate' : 'checkid_setup'; - - $params['openid.identity'] = $id; - - $params['openid.claimed_id'] = $claimedId; - - if ($version <= 2.0) { - if ($this->_session !== null) { - $this->_session->identity = $id; - $this->_session->claimed_id = $claimedId; - } else if (defined('SID')) { - $_SESSION["zend_openid"] = array( - "identity" => $id, - "claimed_id" => $claimedId); - } else { - #require_once "Zend/Session/Namespace.php"; - $this->_session = new Zend_Session_Namespace("zend_openid"); - $this->_session->identity = $id; - $this->_session->claimed_id = $claimedId; - } - } - - if (isset($handle)) { - $params['openid.assoc_handle'] = $handle; - } - - $params['openid.return_to'] = Zend_OpenId::absoluteUrl($returnTo); - - if (empty($root)) { - $root = Zend_OpenId::selfUrl(); - if ($root[strlen($root)-1] != '/') { - $root = dirname($root); - } - } - if ($version >= 2.0) { - $params['openid.realm'] = $root; - } else { - $params['openid.trust_root'] = $root; - } - - if (!Zend_OpenId_Extension::forAll($extensions, 'prepareRequest', $params)) { - $this->_setError("Extension::prepareRequest failure"); - return false; - } - - Zend_OpenId::redirect($server, $params, $response); - return true; - } - - /** - * Sets HTTP client object to make HTTP requests - * - * @param Zend_Http_Client $client HTTP client object to be used - */ - public function setHttpClient($client) { - $this->_httpClient = $client; - } - - /** - * Returns HTTP client object that will be used to make HTTP requests - * - * @return Zend_Http_Client - */ - public function getHttpClient() { - return $this->_httpClient; - } - - /** - * Sets session object to store climed_id - * - * @param Zend_Session_Namespace $session HTTP client object to be used - */ - public function setSession(Zend_Session_Namespace $session) { - $this->_session = $session; - } - - /** - * Returns session object that is used to store climed_id - * - * @return Zend_Session_Namespace - */ - public function getSession() { - return $this->_session; - } - - /** - * Saves error message - * - * @param string $message error message - */ - protected function _setError($message) - { - $this->_error = $message; - } - - /** - * Returns error message that explains failure of login, check or verify - * - * @return string - */ - public function getError() - { - return $this->_error; - } - -} diff --git a/library/Zend/OpenId/Consumer/Storage.php b/library/Zend/OpenId/Consumer/Storage.php deleted file mode 100644 index 89b0cd2877..0000000000 --- a/library/Zend/OpenId/Consumer/Storage.php +++ /dev/null @@ -1,132 +0,0 @@ -_dir = $dir; - if (!is_dir($this->_dir)) { - if (!@mkdir($this->_dir, 0700, 1)) { - /** - * @see Zend_OpenId_Exception - */ - #require_once 'Zend/OpenId/Exception.php'; - throw new Zend_OpenId_Exception( - 'Cannot access storage directory ' . $dir, - Zend_OpenId_Exception::ERROR_STORAGE); - } - } - if (($f = fopen($this->_dir.'/assoc.lock', 'w+')) === null) { - /** - * @see Zend_OpenId_Exception - */ - #require_once 'Zend/OpenId/Exception.php'; - throw new Zend_OpenId_Exception( - 'Cannot create a lock file in the directory ' . $dir, - Zend_OpenId_Exception::ERROR_STORAGE); - } - fclose($f); - if (($f = fopen($this->_dir.'/discovery.lock', 'w+')) === null) { - /** - * @see Zend_OpenId_Exception - */ - #require_once 'Zend/OpenId/Exception.php'; - throw new Zend_OpenId_Exception( - 'Cannot create a lock file in the directory ' . $dir, - Zend_OpenId_Exception::ERROR_STORAGE); - } - fclose($f); - if (($f = fopen($this->_dir.'/nonce.lock', 'w+')) === null) { - /** - * @see Zend_OpenId_Exception - */ - #require_once 'Zend/OpenId/Exception.php'; - throw new Zend_OpenId_Exception( - 'Cannot create a lock file in the directory ' . $dir, - Zend_OpenId_Exception::ERROR_STORAGE); - } - fclose($f); - } - - /** - * Stores information about association identified by $url/$handle - * - * @param string $url OpenID server URL - * @param string $handle assiciation handle - * @param string $macFunc HMAC function (sha1 or sha256) - * @param string $secret shared secret - * @param long $expires expiration UNIX time - * @return bool - */ - public function addAssociation($url, $handle, $macFunc, $secret, $expires) - { - $name1 = $this->_dir . '/assoc_url_' . md5($url); - $name2 = $this->_dir . '/assoc_handle_' . md5($handle); - $lock = @fopen($this->_dir . '/assoc.lock', 'w+'); - if ($lock === false) { - return false; - } - if (!flock($lock, LOCK_EX)) { - fclose($lock); - return false; - } - try { - $f = @fopen($name1, 'w+'); - if ($f === false) { - fclose($lock); - return false; - } - $data = serialize(array($url, $handle, $macFunc, $secret, $expires)); - fwrite($f, $data); - if (function_exists('symlink')) { - @unlink($name2); - if (symlink($name1, $name2)) { - fclose($f); - fclose($lock); - return true; - } - } - $f2 = @fopen($name2, 'w+'); - if ($f2) { - fwrite($f2, $data); - fclose($f2); - @unlink($name1); - $ret = true; - } else { - $ret = false; - } - fclose($f); - fclose($lock); - return $ret; - } catch (Exception $e) { - fclose($lock); - throw $e; - } - } - - /** - * Gets information about association identified by $url - * Returns true if given association found and not expired and false - * otherwise - * - * @param string $url OpenID server URL - * @param string &$handle assiciation handle - * @param string &$macFunc HMAC function (sha1 or sha256) - * @param string &$secret shared secret - * @param long &$expires expiration UNIX time - * @return bool - */ - public function getAssociation($url, &$handle, &$macFunc, &$secret, &$expires) - { - $name1 = $this->_dir . '/assoc_url_' . md5($url); - $lock = @fopen($this->_dir . '/assoc.lock', 'w+'); - if ($lock === false) { - return false; - } - if (!flock($lock, LOCK_EX)) { - fclose($lock); - return false; - } - try { - $f = @fopen($name1, 'r'); - if ($f === false) { - fclose($lock); - return false; - } - $ret = false; - $data = stream_get_contents($f); - if (!empty($data)) { - list($storedUrl, $handle, $macFunc, $secret, $expires) = unserialize($data); - if ($url === $storedUrl && $expires > time()) { - $ret = true; - } else { - $name2 = $this->_dir . '/assoc_handle_' . md5($handle); - fclose($f); - @unlink($name2); - @unlink($name1); - fclose($lock); - return false; - } - } - fclose($f); - fclose($lock); - return $ret; - } catch (Exception $e) { - fclose($lock); - throw $e; - } - } - - /** - * Gets information about association identified by $handle - * Returns true if given association found and not expired and false - * otherwise - * - * @param string $handle assiciation handle - * @param string &$url OpenID server URL - * @param string &$macFunc HMAC function (sha1 or sha256) - * @param string &$secret shared secret - * @param long &$expires expiration UNIX time - * @return bool - */ - public function getAssociationByHandle($handle, &$url, &$macFunc, &$secret, &$expires) - { - $name2 = $this->_dir . '/assoc_handle_' . md5($handle); - $lock = @fopen($this->_dir . '/assoc.lock', 'w+'); - if ($lock === false) { - return false; - } - if (!flock($lock, LOCK_EX)) { - fclose($lock); - return false; - } - try { - $f = @fopen($name2, 'r'); - if ($f === false) { - fclose($lock); - return false; - } - $ret = false; - $data = stream_get_contents($f); - if (!empty($data)) { - list($url, $storedHandle, $macFunc, $secret, $expires) = unserialize($data); - if ($handle === $storedHandle && $expires > time()) { - $ret = true; - } else { - fclose($f); - @unlink($name2); - $name1 = $this->_dir . '/assoc_url_' . md5($url); - @unlink($name1); - fclose($lock); - return false; - } - } - fclose($f); - fclose($lock); - return $ret; - } catch (Exception $e) { - fclose($lock); - throw $e; - } - } - - /** - * Deletes association identified by $url - * - * @param string $url OpenID server URL - * @return bool - */ - public function delAssociation($url) - { - $name1 = $this->_dir . '/assoc_url_' . md5($url); - $lock = @fopen($this->_dir . '/assoc.lock', 'w+'); - if ($lock === false) { - return false; - } - if (!flock($lock, LOCK_EX)) { - fclose($lock); - return false; - } - try { - $f = @fopen($name1, 'r'); - if ($f === false) { - fclose($lock); - return false; - } - $data = stream_get_contents($f); - if (!empty($data)) { - list($storedUrl, $handle, $macFunc, $secret, $expires) = unserialize($data); - if ($url === $storedUrl) { - $name2 = $this->_dir . '/assoc_handle_' . md5($handle); - fclose($f); - @unlink($name2); - @unlink($name1); - fclose($lock); - return true; - } - } - fclose($f); - fclose($lock); - return true; - } catch (Exception $e) { - fclose($lock); - throw $e; - } - } - - /** - * Stores information discovered from identity $id - * - * @param string $id identity - * @param string $realId discovered real identity URL - * @param string $server discovered OpenID server URL - * @param float $version discovered OpenID protocol version - * @param long $expires expiration UNIX time - * @return bool - */ - public function addDiscoveryInfo($id, $realId, $server, $version, $expires) - { - $name = $this->_dir . '/discovery_' . md5($id); - $lock = @fopen($this->_dir . '/discovery.lock', 'w+'); - if ($lock === false) { - return false; - } - if (!flock($lock, LOCK_EX)) { - fclose($lock); - return false; - } - try { - $f = @fopen($name, 'w+'); - if ($f === false) { - fclose($lock); - return false; - } - $data = serialize(array($id, $realId, $server, $version, $expires)); - fwrite($f, $data); - fclose($f); - fclose($lock); - return true; - } catch (Exception $e) { - fclose($lock); - throw $e; - } - } - - /** - * Gets information discovered from identity $id - * Returns true if such information exists and false otherwise - * - * @param string $id identity - * @param string &$realId discovered real identity URL - * @param string &$server discovered OpenID server URL - * @param float &$version discovered OpenID protocol version - * @param long &$expires expiration UNIX time - * @return bool - */ - public function getDiscoveryInfo($id, &$realId, &$server, &$version, &$expires) - { - $name = $this->_dir . '/discovery_' . md5($id); - $lock = @fopen($this->_dir . '/discovery.lock', 'w+'); - if ($lock === false) { - return false; - } - if (!flock($lock, LOCK_EX)) { - fclose($lock); - return false; - } - try { - $f = @fopen($name, 'r'); - if ($f === false) { - fclose($lock); - return false; - } - $ret = false; - $data = stream_get_contents($f); - if (!empty($data)) { - list($storedId, $realId, $server, $version, $expires) = unserialize($data); - if ($id === $storedId && $expires > time()) { - $ret = true; - } else { - fclose($f); - @unlink($name); - fclose($lock); - return false; - } - } - fclose($f); - fclose($lock); - return $ret; - } catch (Exception $e) { - fclose($lock); - throw $e; - } - } - - /** - * Removes cached information discovered from identity $id - * - * @param string $id identity - * @return bool - */ - public function delDiscoveryInfo($id) - { - $name = $this->_dir . '/discovery_' . md5($id); - $lock = @fopen($this->_dir . '/discovery.lock', 'w+'); - if ($lock === false) { - return false; - } - if (!flock($lock, LOCK_EX)) { - fclose($lock); - return false; - } - try { - @unlink($name); - fclose($lock); - return true; - } catch (Exception $e) { - fclose($lock); - throw $e; - } - } - - /** - * The function checks the uniqueness of openid.response_nonce - * - * @param string $provider openid.openid_op_endpoint field from authentication response - * @param string $nonce openid.response_nonce field from authentication response - * @return bool - */ - public function isUniqueNonce($provider, $nonce) - { - $name = $this->_dir . '/nonce_' . md5($provider.';'.$nonce); - $lock = @fopen($this->_dir . '/nonce.lock', 'w+'); - if ($lock === false) { - return false; - } - if (!flock($lock, LOCK_EX)) { - fclose($lock); - return false; - } - try { - $f = @fopen($name, 'x'); - if ($f === false) { - fclose($lock); - return false; - } - fwrite($f, $provider.';'.$nonce); - fclose($f); - fclose($lock); - return true; - } catch (Exception $e) { - fclose($lock); - throw $e; - } - } - - /** - * Removes data from the uniqueness database that is older then given date - * - * @param mixed $date date of expired data - */ - public function purgeNonces($date=null) - { - $lock = @fopen($this->_dir . '/nonce.lock', 'w+'); - if ($lock !== false) { - flock($lock, LOCK_EX); - } - try { - if (!is_int($date) && !is_string($date)) { - $nonceFiles = glob($this->_dir . '/nonce_*'); - foreach ((array) $nonceFiles as $name) { - @unlink($name); - } - unset($nonceFiles); - } else { - if (is_string($date)) { - $time = time($date); - } else { - $time = $date; - } - $nonceFiles = glob($this->_dir . '/nonce_*'); - foreach ((array) $nonceFiles as $name) { - if (filemtime($name) < $time) { - @unlink($name); - } - } - unset($nonceFiles); - } - if ($lock !== false) { - fclose($lock); - } - } catch (Exception $e) { - if ($lock !== false) { - fclose($lock); - } - throw $e; - } - } -} diff --git a/library/Zend/OpenId/Exception.php b/library/Zend/OpenId/Exception.php deleted file mode 100644 index a545502ce9..0000000000 --- a/library/Zend/OpenId/Exception.php +++ /dev/null @@ -1,58 +0,0 @@ -$func($params)) { - return false; - } - } else { - return false; - } - } - } else if (!is_object($extensions) || - !($extensions instanceof Zend_OpenId_Extension) || - !$extensions->$func($params)) { - return false; - } - } - return true; - } - - /** - * Method to add additional data to OpenId 'checkid_immediate' or - * 'checkid_setup' request. This method addes nothing but inherited class - * may add additional data into request. - * - * @param array &$params request's var/val pairs - * @return bool - */ - public function prepareRequest(&$params) - { - return true; - } - - /** - * Method to parse OpenId 'checkid_immediate' or 'checkid_setup' request - * and initialize object with passed data. This method parses nothing but - * inherited class may override this method to do somthing. - * - * @param array $params request's var/val pairs - * @return bool - */ - public function parseRequest($params) - { - return true; - } - - /** - * Method to add additional data to OpenId 'id_res' response. This method - * addes nothing but inherited class may add additional data into response. - * - * @param array &$params response's var/val pairs - * @return bool - */ - public function prepareResponse(&$params) - { - return true; - } - - /** - * Method to parse OpenId 'id_res' response and initialize object with - * passed data. This method parses nothing but inherited class may override - * this method to do somthing. - * - * @param array $params response's var/val pairs - * @return bool - */ - public function parseResponse($params) - { - return true; - } - - /** - * Method to prepare data to store it in trusted servers database. - * - * @param array &$data data to be stored in tusted servers database - * @return bool - */ - public function getTrustData(&$data) - { - return true; - } - - /** - * Method to check if data from trusted servers database is enough to - * sutisfy request. - * - * @param array $data data from tusted servers database - * @return bool - */ - public function checkTrustData($data) - { - return true; - } -} diff --git a/library/Zend/OpenId/Extension/Sreg.php b/library/Zend/OpenId/Extension/Sreg.php deleted file mode 100644 index 159e2f9d75..0000000000 --- a/library/Zend/OpenId/Extension/Sreg.php +++ /dev/null @@ -1,300 +0,0 @@ -_props = $props; - $this->_policy_url = $policy_url; - $this->_version = $version; - } - - /** - * Returns associative array of SREG variables - * - * @return array - */ - public function getProperties() { - if (is_array($this->_props)) { - return $this->_props; - } else { - return array(); - } - } - - /** - * Returns SREG policy URL - * - * @return string - */ - public function getPolicyUrl() { - return $this->_policy_url; - } - - /** - * Returns SREG protocol version - * - * @return float - */ - public function getVersion() { - return $this->_version; - } - - /** - * Returns array of allowed SREG variable names. - * - * @return array - */ - public static function getSregProperties() - { - return array( - "nickname", - "email", - "fullname", - "dob", - "gender", - "postcode", - "country", - "language", - "timezone" - ); - } - - /** - * Adds additional SREG data to OpenId 'checkid_immediate' or - * 'checkid_setup' request. - * - * @param array &$params request's var/val pairs - * @return bool - */ - public function prepareRequest(&$params) - { - if (is_array($this->_props) && count($this->_props) > 0) { - foreach ($this->_props as $prop => $req) { - if ($req) { - if (isset($required)) { - $required .= ','.$prop; - } else { - $required = $prop; - } - } else { - if (isset($optional)) { - $optional .= ','.$prop; - } else { - $optional = $prop; - } - } - } - if ($this->_version >= 1.1) { - $params['openid.ns.sreg'] = Zend_OpenId_Extension_Sreg::NAMESPACE_1_1; - } - if (!empty($required)) { - $params['openid.sreg.required'] = $required; - } - if (!empty($optional)) { - $params['openid.sreg.optional'] = $optional; - } - if (!empty($this->_policy_url)) { - $params['openid.sreg.policy_url'] = $this->_policy_url; - } - } - return true; - } - - /** - * Parses OpenId 'checkid_immediate' or 'checkid_setup' request, - * extracts SREG variables and sets ovject properties to corresponding - * values. - * - * @param array $params request's var/val pairs - * @return bool - */ - public function parseRequest($params) - { - if (isset($params['openid_ns_sreg']) && - $params['openid_ns_sreg'] === Zend_OpenId_Extension_Sreg::NAMESPACE_1_1) { - $this->_version= 1.1; - } else { - $this->_version= 1.0; - } - if (!empty($params['openid_sreg_policy_url'])) { - $this->_policy_url = $params['openid_sreg_policy_url']; - } else { - $this->_policy_url = null; - } - $props = array(); - if (!empty($params['openid_sreg_optional'])) { - foreach (explode(',', $params['openid_sreg_optional']) as $prop) { - $prop = trim($prop); - $props[$prop] = false; - } - } - if (!empty($params['openid_sreg_required'])) { - foreach (explode(',', $params['openid_sreg_required']) as $prop) { - $prop = trim($prop); - $props[$prop] = true; - } - } - $props2 = array(); - foreach (self::getSregProperties() as $prop) { - if (isset($props[$prop])) { - $props2[$prop] = $props[$prop]; - } - } - - $this->_props = (count($props2) > 0) ? $props2 : null; - return true; - } - - /** - * Adds additional SREG data to OpenId 'id_res' response. - * - * @param array &$params response's var/val pairs - * @return bool - */ - public function prepareResponse(&$params) - { - if (is_array($this->_props) && count($this->_props) > 0) { - if ($this->_version >= 1.1) { - $params['openid.ns.sreg'] = Zend_OpenId_Extension_Sreg::NAMESPACE_1_1; - } - foreach (self::getSregProperties() as $prop) { - if (!empty($this->_props[$prop])) { - $params['openid.sreg.' . $prop] = $this->_props[$prop]; - } - } - } - return true; - } - - /** - * Parses OpenId 'id_res' response and sets object's properties according - * to 'openid.sreg.*' variables in response - * - * @param array $params response's var/val pairs - * @return bool - */ - public function parseResponse($params) - { - if (isset($params['openid_ns_sreg']) && - $params['openid_ns_sreg'] === Zend_OpenId_Extension_Sreg::NAMESPACE_1_1) { - $this->_version= 1.1; - } else { - $this->_version= 1.0; - } - $props = array(); - foreach (self::getSregProperties() as $prop) { - if (!empty($params['openid_sreg_' . $prop])) { - $props[$prop] = $params['openid_sreg_' . $prop]; - } - } - if (isset($this->_props) && is_array($this->_props)) { - foreach (self::getSregProperties() as $prop) { - if (isset($this->_props[$prop]) && - $this->_props[$prop] && - !isset($props[$prop])) { - return false; - } - } - } - $this->_props = (count($props) > 0) ? $props : null; - return true; - } - - /** - * Addes SREG properties that are allowed to be send to consumer to - * the given $data argument. - * - * @param array &$data data to be stored in tusted servers database - * @return bool - */ - public function getTrustData(&$data) - { - $data[get_class()] = $this->getProperties(); - return true; - } - - /** - * Check if given $data contains necessury SREG properties to sutisfy - * OpenId request. On success sets SREG response properties from given - * $data and returns true, on failure returns false. - * - * @param array $data data from tusted servers database - * @return bool - */ - public function checkTrustData($data) - { - if (is_array($this->_props) && count($this->_props) > 0) { - $props = array(); - $name = get_class(); - if (isset($data[$name])) { - $props = $data[$name]; - } else { - $props = array(); - } - $props2 = array(); - foreach ($this->_props as $prop => $req) { - if (empty($props[$prop])) { - if ($req) { - return false; - } - } else { - $props2[$prop] = $props[$prop]; - } - } - $this->_props = (count($props2) > 0) ? $props2 : null; - } - return true; - } -} diff --git a/library/Zend/OpenId/Provider.php b/library/Zend/OpenId/Provider.php deleted file mode 100644 index 5c15ad3b8a..0000000000 --- a/library/Zend/OpenId/Provider.php +++ /dev/null @@ -1,803 +0,0 @@ -_loginUrl = $loginUrl; - if ($trustUrl === null) { - $trustUrl = Zend_OpenId::selfUrl() . '?openid.action=trust'; - } else { - $trustUrl = Zend_OpenId::absoluteUrl($trustUrl); - } - $this->_trustUrl = $trustUrl; - if ($user === null) { - #require_once "Zend/OpenId/Provider/User/Session.php"; - $this->_user = new Zend_OpenId_Provider_User_Session(); - } else { - $this->_user = $user; - } - if ($storage === null) { - #require_once "Zend/OpenId/Provider/Storage/File.php"; - $this->_storage = new Zend_OpenId_Provider_Storage_File(); - } else { - $this->_storage = $storage; - } - $this->_sessionTtl = $sessionTtl; - } - - /** - * Sets the OP Endpoint URL - * - * @param string $url the OP Endpoint URL - * @return null - */ - public function setOpEndpoint($url) - { - $this->_opEndpoint = $url; - } - - /** - * Registers a new user with given $id and $password - * Returns true in case of success and false if user with given $id already - * exists - * - * @param string $id user identity URL - * @param string $password encoded user password - * @return bool - */ - public function register($id, $password) - { - if (!Zend_OpenId::normalize($id) || empty($id)) { - return false; - } - return $this->_storage->addUser($id, md5($id.$password)); - } - - /** - * Returns true if user with given $id exists and false otherwise - * - * @param string $id user identity URL - * @return bool - */ - public function hasUser($id) { - if (!Zend_OpenId::normalize($id)) { - return false; - } - return $this->_storage->hasUser($id); - } - - /** - * Performs login of user with given $id and $password - * Returns true in case of success and false otherwise - * - * @param string $id user identity URL - * @param string $password user password - * @return bool - */ - public function login($id, $password) - { - if (!Zend_OpenId::normalize($id)) { - return false; - } - if (!$this->_storage->checkUser($id, md5($id.$password))) { - return false; - } - $this->_user->setLoggedInUser($id); - return true; - } - - /** - * Performs logout. Clears information about logged in user. - * - * @return void - */ - public function logout() - { - $this->_user->delLoggedInUser(); - return true; - } - - /** - * Returns identity URL of current logged in user or false - * - * @return mixed - */ - public function getLoggedInUser() { - return $this->_user->getLoggedInUser(); - } - - /** - * Retrieve consumer's root URL from request query. - * Returns URL or false in case of failure - * - * @param array $params query arguments - * @return mixed - */ - public function getSiteRoot($params) - { - $version = 1.1; - if (isset($params['openid_ns']) && - $params['openid_ns'] == Zend_OpenId::NS_2_0) { - $version = 2.0; - } - if ($version >= 2.0 && isset($params['openid_realm'])) { - $root = $params['openid_realm']; - } else if ($version < 2.0 && isset($params['openid_trust_root'])) { - $root = $params['openid_trust_root']; - } else if (isset($params['openid_return_to'])) { - $root = $params['openid_return_to']; - } else { - return false; - } - if (Zend_OpenId::normalizeUrl($root) && !empty($root)) { - return $root; - } - return false; - } - - /** - * Allows consumer with given root URL to authenticate current logged - * in user. Returns true on success and false on error. - * - * @param string $root root URL - * @param mixed $extensions extension object or array of extensions objects - * @return bool - */ - public function allowSite($root, $extensions=null) - { - $id = $this->getLoggedInUser(); - if ($id === false) { - return false; - } - if ($extensions !== null) { - $data = array(); - Zend_OpenId_Extension::forAll($extensions, 'getTrustData', $data); - } else { - $data = true; - } - $this->_storage->addSite($id, $root, $data); - return true; - } - - /** - * Prohibit consumer with given root URL to authenticate current logged - * in user. Returns true on success and false on error. - * - * @param string $root root URL - * @return bool - */ - public function denySite($root) - { - $id = $this->getLoggedInUser(); - if ($id === false) { - return false; - } - $this->_storage->addSite($id, $root, false); - return true; - } - - /** - * Delete consumer with given root URL from known sites of current logged - * in user. Next time this consumer will try to authenticate the user, - * Provider will ask user's confirmation. - * Returns true on success and false on error. - * - * @param string $root root URL - * @return bool - */ - public function delSite($root) - { - $id = $this->getLoggedInUser(); - if ($id === false) { - return false; - } - $this->_storage->addSite($id, $root, null); - return true; - } - - /** - * Returns list of known consumers for current logged in user or false - * if he is not logged in. - * - * @return mixed - */ - public function getTrustedSites() - { - $id = $this->getLoggedInUser(); - if ($id === false) { - return false; - } - return $this->_storage->getTrustedSites($id); - } - - /** - * Handles HTTP request from consumer - * - * @param array $params GET or POST variables. If this parameter is omited - * or set to null, then $_GET or $_POST superglobal variable is used - * according to REQUEST_METHOD. - * @param mixed $extensions extension object or array of extensions objects - * @param Zend_Controller_Response_Abstract $response an optional response - * object to perform HTTP or HTML form redirection - * @return mixed - */ - public function handle($params=null, $extensions=null, - Zend_Controller_Response_Abstract $response = null) - { - if ($params === null) { - if ($_SERVER["REQUEST_METHOD"] == "GET") { - $params = $_GET; - } else if ($_SERVER["REQUEST_METHOD"] == "POST") { - $params = $_POST; - } else { - return false; - } - } - $version = 1.1; - if (isset($params['openid_ns']) && - $params['openid_ns'] == Zend_OpenId::NS_2_0) { - $version = 2.0; - } - if (isset($params['openid_mode'])) { - if ($params['openid_mode'] == 'associate') { - $response = $this->_associate($version, $params); - $ret = ''; - foreach ($response as $key => $val) { - $ret .= $key . ':' . $val . "\n"; - } - return $ret; - } else if ($params['openid_mode'] == 'checkid_immediate') { - $ret = $this->_checkId($version, $params, 1, $extensions, $response); - if (is_bool($ret)) return $ret; - if (!empty($params['openid_return_to'])) { - Zend_OpenId::redirect($params['openid_return_to'], $ret, $response); - } - return true; - } else if ($params['openid_mode'] == 'checkid_setup') { - $ret = $this->_checkId($version, $params, 0, $extensions, $response); - if (is_bool($ret)) return $ret; - if (!empty($params['openid_return_to'])) { - Zend_OpenId::redirect($params['openid_return_to'], $ret, $response); - } - return true; - } else if ($params['openid_mode'] == 'check_authentication') { - $response = $this->_checkAuthentication($version, $params); - $ret = ''; - foreach ($response as $key => $val) { - $ret .= $key . ':' . $val . "\n"; - } - return $ret; - } - } - return false; - } - - /** - * Generates a secret key for given hash function, returns RAW key or false - * if function is not supported - * - * @param string $func hash function (sha1 or sha256) - * @return mixed - */ - protected function _genSecret($func) - { - if ($func == 'sha1') { - $macLen = 20; /* 160 bit */ - } else if ($func == 'sha256') { - $macLen = 32; /* 256 bit */ - } else { - return false; - } - return Zend_OpenId::randomBytes($macLen); - } - - /** - * Processes association request from OpenID consumerm generates secret - * shared key and send it back using Diffie-Hellman encruption. - * Returns array of variables to push back to consumer. - * - * @param float $version OpenID version - * @param array $params GET or POST request variables - * @return array - */ - protected function _associate($version, $params) - { - $ret = array(); - - if ($version >= 2.0) { - $ret['ns'] = Zend_OpenId::NS_2_0; - } - - if (isset($params['openid_assoc_type']) && - $params['openid_assoc_type'] == 'HMAC-SHA1') { - $macFunc = 'sha1'; - } else if (isset($params['openid_assoc_type']) && - $params['openid_assoc_type'] == 'HMAC-SHA256' && - $version >= 2.0) { - $macFunc = 'sha256'; - } else { - $ret['error'] = 'Wrong "openid.assoc_type"'; - $ret['error-code'] = 'unsupported-type'; - return $ret; - } - - $ret['assoc_type'] = $params['openid_assoc_type']; - - $secret = $this->_genSecret($macFunc); - - if (empty($params['openid_session_type']) || - $params['openid_session_type'] == 'no-encryption') { - $ret['mac_key'] = base64_encode($secret); - } else if (isset($params['openid_session_type']) && - $params['openid_session_type'] == 'DH-SHA1') { - $dhFunc = 'sha1'; - } else if (isset($params['openid_session_type']) && - $params['openid_session_type'] == 'DH-SHA256' && - $version >= 2.0) { - $dhFunc = 'sha256'; - } else { - $ret['error'] = 'Wrong "openid.session_type"'; - $ret['error-code'] = 'unsupported-type'; - return $ret; - } - - if (isset($params['openid_session_type'])) { - $ret['session_type'] = $params['openid_session_type']; - } - - if (isset($dhFunc)) { - if (empty($params['openid_dh_consumer_public'])) { - $ret['error'] = 'Wrong "openid.dh_consumer_public"'; - return $ret; - } - if (empty($params['openid_dh_gen'])) { - $g = pack('H*', Zend_OpenId::DH_G); - } else { - $g = base64_decode($params['openid_dh_gen']); - } - if (empty($params['openid_dh_modulus'])) { - $p = pack('H*', Zend_OpenId::DH_P); - } else { - $p = base64_decode($params['openid_dh_modulus']); - } - - $dh = Zend_OpenId::createDhKey($p, $g); - $dh_details = Zend_OpenId::getDhKeyDetails($dh); - - $sec = Zend_OpenId::computeDhSecret( - base64_decode($params['openid_dh_consumer_public']), $dh); - if ($sec === false) { - $ret['error'] = 'Wrong "openid.session_type"'; - $ret['error-code'] = 'unsupported-type'; - return $ret; - } - $sec = Zend_OpenId::digest($dhFunc, $sec); - $ret['dh_server_public'] = base64_encode( - Zend_OpenId::btwoc($dh_details['pub_key'])); - $ret['enc_mac_key'] = base64_encode($secret ^ $sec); - } - - $handle = uniqid(); - $expiresIn = $this->_sessionTtl; - - $ret['assoc_handle'] = $handle; - $ret['expires_in'] = $expiresIn; - - $this->_storage->addAssociation($handle, - $macFunc, $secret, time() + $expiresIn); - - return $ret; - } - - /** - * Performs authentication (or authentication check). - * - * @param float $version OpenID version - * @param array $params GET or POST request variables - * @param bool $immediate enables or disables interaction with user - * @param mixed $extensions extension object or array of extensions objects - * @param Zend_Controller_Response_Abstract $response - * @return array - */ - protected function _checkId($version, $params, $immediate, $extensions=null, - Zend_Controller_Response_Abstract $response = null) - { - $ret = array(); - - if ($version >= 2.0) { - $ret['openid.ns'] = Zend_OpenId::NS_2_0; - } - $root = $this->getSiteRoot($params); - if ($root === false) { - return false; - } - - if (isset($params['openid_identity']) && - !$this->_storage->hasUser($params['openid_identity'])) { - $ret['openid.mode'] = ($immediate && $version >= 2.0) ? 'setup_needed': 'cancel'; - return $ret; - } - - /* Check if user already logged in into the server */ - if (!isset($params['openid_identity']) || - $this->_user->getLoggedInUser() !== $params['openid_identity']) { - $params2 = array(); - foreach ($params as $key => $val) { - if (strpos($key, 'openid_ns_') === 0) { - $key = 'openid.ns.' . substr($key, strlen('openid_ns_')); - } else if (strpos($key, 'openid_sreg_') === 0) { - $key = 'openid.sreg.' . substr($key, strlen('openid_sreg_')); - } else if (strpos($key, 'openid_') === 0) { - $key = 'openid.' . substr($key, strlen('openid_')); - } - $params2[$key] = $val; - } - if ($immediate) { - $params2['openid.mode'] = 'checkid_setup'; - $ret['openid.mode'] = ($version >= 2.0) ? 'setup_needed': 'id_res'; - $ret['openid.user_setup_url'] = $this->_loginUrl - . (strpos($this->_loginUrl, '?') === false ? '?' : '&') - . Zend_OpenId::paramsToQuery($params2); - return $ret; - } else { - /* Redirect to Server Login Screen */ - Zend_OpenId::redirect($this->_loginUrl, $params2, $response); - return true; - } - } - - if (!Zend_OpenId_Extension::forAll($extensions, 'parseRequest', $params)) { - $ret['openid.mode'] = ($immediate && $version >= 2.0) ? 'setup_needed': 'cancel'; - return $ret; - } - - /* Check if user trusts to the consumer */ - $trusted = null; - $sites = $this->_storage->getTrustedSites($params['openid_identity']); - if (isset($params['openid_return_to'])) { - $root = $params['openid_return_to']; - } - if (isset($sites[$root])) { - $trusted = $sites[$root]; - } else { - foreach ($sites as $site => $t) { - if (strpos($root, $site) === 0) { - $trusted = $t; - break; - } else { - /* OpenID 2.0 (9.2) check for realm wild-card matching */ - $n = strpos($site, '://*.'); - if ($n != false) { - $regex = '/^' - . preg_quote(substr($site, 0, $n+3), '/') - . '[A-Za-z1-9_\.]+?' - . preg_quote(substr($site, $n+4), '/') - . '/'; - if (preg_match($regex, $root)) { - $trusted = $t; - break; - } - } - } - } - } - - if (is_array($trusted)) { - if (!Zend_OpenId_Extension::forAll($extensions, 'checkTrustData', $trusted)) { - $trusted = null; - } - } - - if ($trusted === false) { - $ret['openid.mode'] = 'cancel'; - return $ret; - } else if ($trusted === null) { - /* Redirect to Server Trust Screen */ - $params2 = array(); - foreach ($params as $key => $val) { - if (strpos($key, 'openid_ns_') === 0) { - $key = 'openid.ns.' . substr($key, strlen('openid_ns_')); - } else if (strpos($key, 'openid_sreg_') === 0) { - $key = 'openid.sreg.' . substr($key, strlen('openid_sreg_')); - } else if (strpos($key, 'openid_') === 0) { - $key = 'openid.' . substr($key, strlen('openid_')); - } - $params2[$key] = $val; - } - if ($immediate) { - $params2['openid.mode'] = 'checkid_setup'; - $ret['openid.mode'] = ($version >= 2.0) ? 'setup_needed': 'id_res'; - $ret['openid.user_setup_url'] = $this->_trustUrl - . (strpos($this->_trustUrl, '?') === false ? '?' : '&') - . Zend_OpenId::paramsToQuery($params2); - return $ret; - } else { - Zend_OpenId::redirect($this->_trustUrl, $params2, $response); - return true; - } - } - - return $this->_respond($version, $ret, $params, $extensions); - } - - /** - * Perepares information to send back to consumer's authentication request, - * signs it using shared secret and send back through HTTP redirection - * - * @param array $params GET or POST request variables - * @param mixed $extensions extension object or array of extensions objects - * @param Zend_Controller_Response_Abstract $response an optional response - * object to perform HTTP or HTML form redirection - * @return bool - */ - public function respondToConsumer($params, $extensions=null, - Zend_Controller_Response_Abstract $response = null) - { - $version = 1.1; - if (isset($params['openid_ns']) && - $params['openid_ns'] == Zend_OpenId::NS_2_0) { - $version = 2.0; - } - $ret = array(); - if ($version >= 2.0) { - $ret['openid.ns'] = Zend_OpenId::NS_2_0; - } - $ret = $this->_respond($version, $ret, $params, $extensions); - if (!empty($params['openid_return_to'])) { - Zend_OpenId::redirect($params['openid_return_to'], $ret, $response); - } - return true; - } - - /** - * Perepares information to send back to consumer's authentication request - * and signs it using shared secret. - * - * @param float $version OpenID protcol version - * @param array $ret arguments to be send back to consumer - * @param array $params GET or POST request variables - * @param mixed $extensions extension object or array of extensions objects - * @return array - */ - protected function _respond($version, $ret, $params, $extensions=null) - { - if (empty($params['openid_assoc_handle']) || - !$this->_storage->getAssociation($params['openid_assoc_handle'], - $macFunc, $secret, $expires)) { - /* Use dumb mode */ - if (!empty($params['openid_assoc_handle'])) { - $ret['openid.invalidate_handle'] = $params['openid_assoc_handle']; - } - $macFunc = $version >= 2.0 ? 'sha256' : 'sha1'; - $secret = $this->_genSecret($macFunc); - $handle = uniqid(); - $expiresIn = $this->_sessionTtl; - $this->_storage->addAssociation($handle, - $macFunc, $secret, time() + $expiresIn); - $ret['openid.assoc_handle'] = $handle; - } else { - $ret['openid.assoc_handle'] = $params['openid_assoc_handle']; - } - if (isset($params['openid_return_to'])) { - $ret['openid.return_to'] = $params['openid_return_to']; - } - if (isset($params['openid_claimed_id'])) { - $ret['openid.claimed_id'] = $params['openid_claimed_id']; - } - if (isset($params['openid_identity'])) { - $ret['openid.identity'] = $params['openid_identity']; - } - - if ($version >= 2.0) { - if (!empty($this->_opEndpoint)) { - $ret['openid.op_endpoint'] = $this->_opEndpoint; - } else { - $ret['openid.op_endpoint'] = Zend_OpenId::selfUrl(); - } - } - $ret['openid.response_nonce'] = gmdate('Y-m-d\TH:i:s\Z') . uniqid(); - $ret['openid.mode'] = 'id_res'; - - Zend_OpenId_Extension::forAll($extensions, 'prepareResponse', $ret); - - $signed = ''; - $data = ''; - foreach ($ret as $key => $val) { - if (strpos($key, 'openid.') === 0) { - $key = substr($key, strlen('openid.')); - if (!empty($signed)) { - $signed .= ','; - } - $signed .= $key; - $data .= $key . ':' . $val . "\n"; - } - } - $signed .= ',signed'; - $data .= 'signed:' . $signed . "\n"; - $ret['openid.signed'] = $signed; - - $ret['openid.sig'] = base64_encode( - Zend_OpenId::hashHmac($macFunc, $data, $secret)); - - return $ret; - } - - /** - * Performs authentication validation for dumb consumers - * Returns array of variables to push back to consumer. - * It MUST contain 'is_valid' variable with value 'true' or 'false'. - * - * @param float $version OpenID version - * @param array $params GET or POST request variables - * @return array - */ - protected function _checkAuthentication($version, $params) - { - $ret = array(); - if ($version >= 2.0) { - $ret['ns'] = Zend_OpenId::NS_2_0; - } - $ret['openid.mode'] = 'id_res'; - - if (empty($params['openid_assoc_handle']) || - empty($params['openid_signed']) || - empty($params['openid_sig']) || - !$this->_storage->getAssociation($params['openid_assoc_handle'], - $macFunc, $secret, $expires)) { - $ret['is_valid'] = 'false'; - return $ret; - } - - $signed = explode(',', $params['openid_signed']); - $data = ''; - foreach ($signed as $key) { - $data .= $key . ':'; - if ($key == 'mode') { - $data .= "id_res\n"; - } else { - $data .= $params['openid_' . strtr($key,'.','_')]."\n"; - } - } - if ($this->_secureStringCompare(base64_decode($params['openid_sig']), - Zend_OpenId::hashHmac($macFunc, $data, $secret))) { - $ret['is_valid'] = 'true'; - } else { - $ret['is_valid'] = 'false'; - } - return $ret; - } - - /** - * Securely compare two strings for equality while avoided C level memcmp() - * optimisations capable of leaking timing information useful to an attacker - * attempting to iteratively guess the unknown string (e.g. password) being - * compared against. - * - * @param string $a - * @param string $b - * @return bool - */ - protected function _secureStringCompare($a, $b) - { - if (strlen($a) !== strlen($b)) { - return false; - } - $result = 0; - for ($i = 0; $i < strlen($a); $i++) { - $result |= ord($a[$i]) ^ ord($b[$i]); - } - return $result == 0; - } -} diff --git a/library/Zend/OpenId/Provider/Storage.php b/library/Zend/OpenId/Provider/Storage.php deleted file mode 100644 index f9bbb17037..0000000000 --- a/library/Zend/OpenId/Provider/Storage.php +++ /dev/null @@ -1,106 +0,0 @@ -_dir = $dir; - if (!is_dir($this->_dir)) { - if (!@mkdir($this->_dir, 0700, 1)) { - throw new Zend_OpenId_Exception( - "Cannot access storage directory $dir", - Zend_OpenId_Exception::ERROR_STORAGE); - } - } - if (($f = fopen($this->_dir.'/assoc.lock', 'w+')) === null) { - throw new Zend_OpenId_Exception( - 'Cannot create a lock file in the directory ' . $dir, - Zend_OpenId_Exception::ERROR_STORAGE); - } - fclose($f); - if (($f = fopen($this->_dir.'/user.lock', 'w+')) === null) { - throw new Zend_OpenId_Exception( - 'Cannot create a lock file in the directory ' . $dir, - Zend_OpenId_Exception::ERROR_STORAGE); - } - fclose($f); - } - - /** - * Stores information about session identified by $handle - * - * @param string $handle assiciation handle - * @param string $macFunc HMAC function (sha1 or sha256) - * @param string $secret shared secret - * @param string $expires expiration UNIX time - * @return bool - */ - public function addAssociation($handle, $macFunc, $secret, $expires) - { - $name = $this->_dir . '/assoc_' . md5($handle); - $lock = @fopen($this->_dir . '/assoc.lock', 'w+'); - if ($lock === false) { - return false; - } - if (!flock($lock, LOCK_EX)) { - fclose($lock); - return false; - } - try { - $f = @fopen($name, 'w+'); - if ($f === false) { - fclose($lock); - return false; - } - $data = serialize(array($handle, $macFunc, $secret, $expires)); - fwrite($f, $data); - fclose($f); - fclose($lock); - return true; - } catch (Exception $e) { - fclose($lock); - throw $e; - } - } - - /** - * Gets information about association identified by $handle - * Returns true if given association found and not expired and false - * otherwise - * - * @param string $handle assiciation handle - * @param string &$macFunc HMAC function (sha1 or sha256) - * @param string &$secret shared secret - * @param string &$expires expiration UNIX time - * @return bool - */ - public function getAssociation($handle, &$macFunc, &$secret, &$expires) - { - $name = $this->_dir . '/assoc_' . md5($handle); - $lock = @fopen($this->_dir . '/assoc.lock', 'w+'); - if ($lock === false) { - return false; - } - if (!flock($lock, LOCK_EX)) { - fclose($lock); - return false; - } - try { - $f = @fopen($name, 'r'); - if ($f === false) { - fclose($lock); - return false; - } - $ret = false; - $data = stream_get_contents($f); - if (!empty($data)) { - list($storedHandle, $macFunc, $secret, $expires) = unserialize($data); - if ($handle === $storedHandle && $expires > time()) { - $ret = true; - } else { - fclose($f); - @unlink($name); - fclose($lock); - return false; - } - } - fclose($f); - fclose($lock); - return $ret; - } catch (Exception $e) { - fclose($lock); - throw $e; - } - } - - /** - * Removes information about association identified by $handle - * - * @param string $handle assiciation handle - * @return bool - */ - public function delAssociation($handle) - { - $name = $this->_dir . '/assoc_' . md5($handle); - $lock = @fopen($this->_dir . '/assoc.lock', 'w+'); - if ($lock === false) { - return false; - } - if (!flock($lock, LOCK_EX)) { - fclose($lock); - return false; - } - try { - @unlink($name); - fclose($lock); - return true; - } catch (Exception $e) { - fclose($lock); - throw $e; - } - } - - /** - * Register new user with given $id and $password - * Returns true in case of success and false if user with given $id already - * exists - * - * @param string $id user identity URL - * @param string $password encoded user password - * @return bool - */ - public function addUser($id, $password) - { - $name = $this->_dir . '/user_' . md5($id); - $lock = @fopen($this->_dir . '/user.lock', 'w+'); - if ($lock === false) { - return false; - } - if (!flock($lock, LOCK_EX)) { - fclose($lock); - return false; - } - try { - $f = @fopen($name, 'x'); - if ($f === false) { - fclose($lock); - return false; - } - $data = serialize(array($id, $password, array())); - fwrite($f, $data); - fclose($f); - fclose($lock); - return true; - } catch (Exception $e) { - fclose($lock); - throw $e; - } - } - - /** - * Returns true if user with given $id exists and false otherwise - * - * @param string $id user identity URL - * @return bool - */ - public function hasUser($id) - { - $name = $this->_dir . '/user_' . md5($id); - $lock = @fopen($this->_dir . '/user.lock', 'w+'); - if ($lock === false) { - return false; - } - if (!flock($lock, LOCK_SH)) { - fclose($lock); - return false; - } - try { - $f = @fopen($name, 'r'); - if ($f === false) { - fclose($lock); - return false; - } - $ret = false; - $data = stream_get_contents($f); - if (!empty($data)) { - list($storedId, $storedPassword, $trusted) = unserialize($data); - if ($id === $storedId) { - $ret = true; - } - } - fclose($f); - fclose($lock); - return $ret; - } catch (Exception $e) { - fclose($lock); - throw $e; - } - } - - /** - * Verify if user with given $id exists and has specified $password - * - * @param string $id user identity URL - * @param string $password user password - * @return bool - */ - public function checkUser($id, $password) - { - $name = $this->_dir . '/user_' . md5($id); - $lock = @fopen($this->_dir . '/user.lock', 'w+'); - if ($lock === false) { - return false; - } - if (!flock($lock, LOCK_SH)) { - fclose($lock); - return false; - } - try { - $f = @fopen($name, 'r'); - if ($f === false) { - fclose($lock); - return false; - } - $ret = false; - $data = stream_get_contents($f); - if (!empty($data)) { - list($storedId, $storedPassword, $trusted) = unserialize($data); - if ($id === $storedId && $password === $storedPassword) { - $ret = true; - } - } - fclose($f); - fclose($lock); - return $ret; - } catch (Exception $e) { - fclose($lock); - throw $e; - } - } - - /** - * Removes information abou specified user - * - * @param string $id user identity URL - * @return bool - */ - public function delUser($id) - { - $name = $this->_dir . '/user_' . md5($id); - $lock = @fopen($this->_dir . '/user.lock', 'w+'); - if ($lock === false) { - return false; - } - if (!flock($lock, LOCK_EX)) { - fclose($lock); - return false; - } - try { - @unlink($name); - fclose($lock); - return true; - } catch (Exception $e) { - fclose($lock); - throw $e; - } - } - - /** - * Returns array of all trusted/untrusted sites for given user identified - * by $id - * - * @param string $id user identity URL - * @return array - */ - public function getTrustedSites($id) - { - $name = $this->_dir . '/user_' . md5($id); - $lock = @fopen($this->_dir . '/user.lock', 'w+'); - if ($lock === false) { - return false; - } - if (!flock($lock, LOCK_SH)) { - fclose($lock); - return false; - } - try { - $f = @fopen($name, 'r'); - if ($f === false) { - fclose($lock); - return false; - } - $ret = false; - $data = stream_get_contents($f); - if (!empty($data)) { - list($storedId, $storedPassword, $trusted) = unserialize($data); - if ($id === $storedId) { - $ret = $trusted; - } - } - fclose($f); - fclose($lock); - return $ret; - } catch (Exception $e) { - fclose($lock); - throw $e; - } - } - - /** - * Stores information about trusted/untrusted site for given user - * - * @param string $id user identity URL - * @param string $site site URL - * @param mixed $trusted trust data from extension or just a boolean value - * @return bool - */ - public function addSite($id, $site, $trusted) - { - $name = $this->_dir . '/user_' . md5($id); - $lock = @fopen($this->_dir . '/user.lock', 'w+'); - if ($lock === false) { - return false; - } - if (!flock($lock, LOCK_EX)) { - fclose($lock); - return false; - } - try { - $f = @fopen($name, 'r+'); - if ($f === false) { - fclose($lock); - return false; - } - $ret = false; - $data = stream_get_contents($f); - if (!empty($data)) { - list($storedId, $storedPassword, $sites) = unserialize($data); - if ($id === $storedId) { - if ($trusted === null) { - unset($sites[$site]); - } else { - $sites[$site] = $trusted; - } - rewind($f); - ftruncate($f, 0); - $data = serialize(array($id, $storedPassword, $sites)); - fwrite($f, $data); - $ret = true; - } - } - fclose($f); - fclose($lock); - return $ret; - } catch (Exception $e) { - fclose($lock); - throw $e; - } - } -} diff --git a/library/Zend/OpenId/Provider/User.php b/library/Zend/OpenId/Provider/User.php deleted file mode 100644 index 458c3d4a2e..0000000000 --- a/library/Zend/OpenId/Provider/User.php +++ /dev/null @@ -1,57 +0,0 @@ -_session = new Zend_Session_Namespace("openid"); - } else { - $this->_session = $session; - } - } - - /** - * Stores information about logged in user in session data - * - * @param string $id user identity URL - * @return bool - */ - public function setLoggedInUser($id) - { - $this->_session->logged_in = $id; - return true; - } - - /** - * Returns identity URL of logged in user or false - * - * @return mixed - */ - public function getLoggedInUser() - { - if (isset($this->_session->logged_in)) { - return $this->_session->logged_in; - } - return false; - } - - /** - * Performs logout. Clears information about logged in user. - * - * @return bool - */ - public function delLoggedInUser() - { - unset($this->_session->logged_in); - return true; - } - -} diff --git a/library/Zend/Queue.php b/library/Zend/Queue.php deleted file mode 100644 index 532aaa7dff..0000000000 --- a/library/Zend/Queue.php +++ /dev/null @@ -1,569 +0,0 @@ -createQueue(); - * - * @param string|Zend_Queue_Adapter|array|Zend_Config|null String or adapter instance, or options array or Zend_Config instance - * @param Zend_Config|array $options Zend_Config or a configuration array - * @return void - */ - public function __construct($spec, $options = array()) - { - $adapter = null; - if ($spec instanceof Zend_Queue_Adapter_AdapterInterface) { - $adapter = $spec; - } elseif (is_string($spec)) { - $adapter = $spec; - } elseif ($spec instanceof Zend_Config) { - $options = $spec->toArray(); - } elseif (is_array($spec)) { - $options = $spec; - } - - // last minute error checking - if ((null === $adapter) - && (!is_array($options) && (!$options instanceof Zend_Config)) - ) { - #require_once 'Zend/Queue/Exception.php'; - throw new Zend_Queue_Exception('No valid params passed to constructor'); - } - - // Now continue as we would if we were a normal constructor - if ($options instanceof Zend_Config) { - $options = $options->toArray(); - } elseif (!is_array($options)) { - $options = array(); - } - - // Make sure we have some defaults to work with - if (!isset($options[self::TIMEOUT])) { - $options[self::TIMEOUT] = self::VISIBILITY_TIMEOUT; - } - - // Make sure all defaults are appropriately set. - if (!array_key_exists('timeout', $options)) { - $options[self::TIMEOUT] = self::VISIBILITY_TIMEOUT; - } - if (array_key_exists('messageClass', $options)) { - $this->setMessageClass($options['messageClass']); - } - if (array_key_exists('messageSetClass', $options)) { - $this->setMessageSetClass($options['messageSetClass']); - } - - $this->setOptions($options); - - // if we were passed an adapter we either build the $adapter or use it - if (null !== $adapter) { - $this->setAdapter($adapter); - } - } - - /** - * Set queue options - * - * @param array $options - * @return Zend_Queue - */ - public function setOptions(array $options) - { - $this->_options = array_merge($this->_options, $options); - return $this; - } - - /** - * Set an individual configuration option - * - * @param string $name - * @param mixed $value - * @return Zend_Queue - */ - public function setOption($name, $value) - { - $this->_options[(string) $name] = $value; - return $this; - } - - /** - * Returns the configuration options for the queue - * - * @return array - */ - public function getOptions() - { - return $this->_options; - } - - /** - * Determine if a requested option has been defined - * - * @param string $name - * @return bool - */ - public function hasOption($name) - { - return array_key_exists($name, $this->_options); - } - - /** - * Retrieve a single option - * - * @param string $name - * @return null|mixed Returns null if option does not exist; option value otherwise - */ - public function getOption($name) - { - if ($this->hasOption($name)) { - return $this->_options[$name]; - } - return null; - } - - /** - * Set the adapter for this queue - * - * @param string|Zend_Queue_Adapter_AdapterInterface $adapter - * @return Zend_Queue Provides a fluent interface - */ - public function setAdapter($adapter) - { - if (is_string($adapter)) { - if (null === ($adapterNamespace = $this->getOption('adapterNamespace'))) { - $adapterNamespace = 'Zend_Queue_Adapter'; - } - - $adapterName = str_replace( - ' ', - '_', - ucwords( - str_replace( - '_', - ' ', - strtolower($adapterNamespace . '_' . $adapter) - ) - ) - ); - - if (!class_exists($adapterName)) { - #require_once 'Zend/Loader.php'; - Zend_Loader::loadClass($adapterName); - } - - /* - * Create an instance of the adapter class. - * Pass the configuration to the adapter class constructor. - */ - $adapter = new $adapterName($this->getOptions(), $this); - } - - if (!$adapter instanceof Zend_Queue_Adapter_AdapterInterface) { - #require_once 'Zend/Queue/Exception.php'; - throw new Zend_Queue_Exception("Adapter class '" . get_class($adapterName) . "' does not implement Zend_Queue_Adapter_AdapterInterface"); - } - - $this->_adapter = $adapter; - - $this->_adapter->setQueue($this); - - if (null !== ($name = $this->getOption(self::NAME))) { - $this->_setName($name); - } - - return $this; - } - - /** - * Get the adapter for this queue - * - * @return Zend_Queue_Adapter_AdapterInterface - */ - public function getAdapter() - { - return $this->_adapter; - } - - /** - * @param string $className - * @return Zend_Queue Provides a fluent interface - */ - public function setMessageClass($className) - { - $this->_messageClass = (string) $className; - return $this; - } - - /** - * @return string - */ - public function getMessageClass() - { - return $this->_messageClass; - } - - /** - * @param string $className - * @return Zend_Queue Provides a fluent interface - */ - public function setMessageSetClass($className) - { - $this->_messageSetClass = (string) $className; - return $this; - } - - /** - * @return string - */ - public function getMessageSetClass() - { - return $this->_messageSetClass; - } - - /** - * Get the name of the queue - * - * Note: _setName() used to exist, but it caused confusion with createQueue - * Will evaluate later to see if we should add it back in. - * - * @return string - */ - public function getName() - { - return $this->getOption(self::NAME); - } - - /** - * Create a new queue - * - * @param string $name queue name - * @param integer $timeout default visibility timeout - * @return Zend_Queue|false - * @throws Zend_Queue_Exception - */ - public function createQueue($name, $timeout = null) - { - if (!is_string($name)) { - #require_once 'Zend/Queue/Exception.php'; - throw new Zend_Queue_Exception('$name is not a string'); - } - - if ((null !== $timeout) && !is_integer($timeout)) { - #require_once 'Zend/Queue/Exception.php'; - throw new Zend_Queue_Exception('$timeout must be an integer'); - } - - // Default to standard timeout - if (null === $timeout) { - $timeout = $this->getOption(self::TIMEOUT); - } - - // Some queues allow you to create on the fly, but cannot return - // a list of queues. Stomp protocol for example. - if ($this->isSupported('create')) { - if ($this->getAdapter()->isExists($name)) { - return false; - } - - if (!$this->getAdapter()->create($name, $timeout)) { - return false; - } - } - - $options = array( - self::NAME => $name, - 'timeout' => $timeout - ); - - return new self($this->getAdapter(), $options); - } - - /** - * Delete the queue this object is working on. - * - * This queue is disabled, regardless of the outcome of the deletion - * of the queue, because the programmers intent is to disable this queue. - * - * @return boolean - */ - public function deleteQueue() - { - if ($this->isSupported('delete')) { - $deleted = $this->getAdapter()->delete($this->getName()); - } - else { - $deleted = true; - } - - /** - * @see Zend_Queue_Adapter_Null - */ - #require_once('Zend/Queue/Adapter/Null.php'); - $this->setAdapter(new Zend_Queue_Adapter_Null($this->getOptions())); - - return $deleted; - } - - /** - * Delete a message from the queue - * - * Returns true if the message is deleted, false if the deletion is - * unsuccessful. - * - * Returns true if the adapter doesn't support message deletion. - * - * @param Zend_Queue_Message $message - * @return boolean - * @throws Zend_Queue_Exception - */ - public function deleteMessage(Zend_Queue_Message $message) - { - if ($this->getAdapter()->isSupported('deleteMessage')) { - return $this->getAdapter()->deleteMessage($message); - } - return true; - } - - /** - * Send a message to the queue - * - * @param mixed $message message - * @return Zend_Queue_Message - * @throws Zend_Queue_Exception - */ - public function send($message) - { - return $this->getAdapter()->send($message); - } - - /** - * Returns the approximate number of messages in the queue - * - * @return integer - */ - public function count() - { - if ($this->getAdapter()->isSupported('count')) { - return $this->getAdapter()->count(); - } - return 0; - } - - /** - * Return the first element in the queue - * - * @param integer $maxMessages - * @param integer $timeout - * @return Zend_Queue_Message_Iterator - */ - public function receive($maxMessages=null, $timeout=null) - { - if (($maxMessages !== null) && !is_integer($maxMessages)) { - #require_once 'Zend/Queue/Exception.php'; - throw new Zend_Queue_Exception('$maxMessages must be an integer or null'); - } - - if (($timeout !== null) && !is_integer($timeout)) { - #require_once 'Zend/Queue/Exception.php'; - throw new Zend_Queue_Exception('$timeout must be an integer or null'); - } - - // Default to returning only one message - if ($maxMessages === null) { - $maxMessages = 1; - } - - // Default to standard timeout - if ($timeout === null) { - $timeout = $this->getOption(self::TIMEOUT); - } - - return $this->getAdapter()->receive($maxMessages, $timeout); - } - - /** - * Return a list of queue capabilities functions - * - * $array['function name'] = true or false - * true is supported, false is not supported. - * - * @param string $name - * @return array - */ - public function getCapabilities() - { - return $this->getAdapter()->getCapabilities(); - } - - /** - * Indicates if a function is supported or not. - * - * @param string $name - * @return boolean - */ - public function isSupported($name) - { - $translation = array( - 'deleteQueue' => 'delete', - 'createQueue' => 'create' - ); - - if (isset($translation[$name])) { - $name = $translation[$name]; - } - - return $this->getAdapter()->isSupported($name); - } - - /** - * Get an array of all available queues - * - * @return array - * @throws Zend_Queue_Exception - */ - public function getQueues() - { - if (!$this->isSupported('getQueues')) { - throw new Zend_Queue_Exception( __FUNCTION__ . '() is not supported by ' . get_class($this->getAdapter())); - } - - return $this->getAdapter()->getQueues(); - } - - /** - * Set the name of the queue - * - * This is AN UNSUPPORTED FUNCTION - * - * @param string $name - * @return Zend_Queue|false Provides a fluent interface - */ - protected function _setName($name) - { - if (!is_string($name)) { - /** - * @see Zend_Queue_Exception - */ - #require_once 'Zend/Queue/Exception.php'; - throw new Zend_Queue_Exception("$name is not a string"); - } - - if ($this->getAdapter()->isSupported('create')) { - if (!$this->getAdapter()->isExists($name)) { - $timeout = $this->getOption(self::TIMEOUT); - - if (!$this->getAdapter()->create($name, $timeout)) { - // Unable to create the new queue - return false; - } - } - } - - $this->setOption(self::NAME, $name); - - return $this; - } - - /** - * returns a listing of Zend_Queue details. - * useful for debugging - * - * @return array - */ - public function debugInfo() - { - $info = array(); - $info['self'] = get_class($this); - $info['adapter'] = get_class($this->getAdapter()); - foreach ($this->getAdapter()->getCapabilities() as $feature => $supported) { - $info['adapter-' . $feature] = ($supported) ? 'yes' : 'no'; - } - $info['options'] = $this->getOptions(); - $info['options']['driverOptions'] = '[hidden]'; - $info['currentQueue'] = $this->getName(); - $info['messageClass'] = $this->getMessageClass(); - $info['messageSetClass'] = $this->getMessageSetClass(); - - return $info; - } -} diff --git a/library/Zend/Queue/Adapter/Activemq.php b/library/Zend/Queue/Adapter/Activemq.php deleted file mode 100644 index 1cf56048e5..0000000000 --- a/library/Zend/Queue/Adapter/Activemq.php +++ /dev/null @@ -1,366 +0,0 @@ -_options['driverOptions']; - if (!array_key_exists('scheme', $options)) { - $options['scheme'] = self::DEFAULT_SCHEME; - } - if (!array_key_exists('host', $options)) { - $options['host'] = self::DEFAULT_HOST; - } - if (!array_key_exists('port', $options)) { - $options['port'] = self::DEFAULT_PORT; - } - - if (array_key_exists('stompClient', $options)) { - $this->_client = $options['stompClient']; - } else { - $this->_client = new Zend_Queue_Stomp_Client($options['scheme'], $options['host'], $options['port']); - } - - $connect = $this->_client->createFrame(); - - // Username and password are optional on some messaging servers - // such as Apache's ActiveMQ - $connect->setCommand('CONNECT'); - if (isset($options['username'])) { - $connect->setHeader('login', $options['username']); - $connect->setHeader('passcode', $options['password']); - } - - $response = $this->_client->send($connect)->receive(); - - if ((false !== $response) - && ($response->getCommand() != 'CONNECTED') - ) { - #require_once 'Zend/Queue/Exception.php'; - throw new Zend_Queue_Exception("Unable to authenticate to '".$options['scheme'].'://'.$options['host'].':'.$options['port']."'"); - } - } - - /** - * Close the socket explicitly when destructed - * - * @return void - */ - public function __destruct() - { - // Gracefully disconnect - $frame = $this->_client->createFrame(); - $frame->setCommand('DISCONNECT'); - $this->_client->send($frame); - unset($this->_client); - } - - /** - * Create a new queue - * - * @param string $name queue name - * @param integer $timeout default visibility timeout - * @return void - * @throws Zend_Queue_Exception - */ - public function create($name, $timeout=null) - { - #require_once 'Zend/Queue/Exception.php'; - throw new Zend_Queue_Exception('create() is not supported in ' . get_class($this)); - } - - /** - * Delete a queue and all of its messages - * - * @param string $name queue name - * @return void - * @throws Zend_Queue_Exception - */ - public function delete($name) - { - #require_once 'Zend/Queue/Exception.php'; - throw new Zend_Queue_Exception('delete() is not supported in ' . get_class($this)); - } - - /** - * Delete a message from the queue - * - * Returns true if the message is deleted, false if the deletion is - * unsuccessful. - * - * @param Zend_Queue_Message $message - * @return boolean - */ - public function deleteMessage(Zend_Queue_Message $message) - { - $frame = $this->_client->createFrame(); - $frame->setCommand('ACK'); - $frame->setHeader('message-id', $message->handle); - - $this->_client->send($frame); - - return true; - } - - /** - * Get an array of all available queues - * - * @return void - * @throws Zend_Queue_Exception - */ - public function getQueues() - { - #require_once 'Zend/Queue/Exception.php'; - throw new Zend_Queue_Exception('getQueues() is not supported in this adapter'); - } - - /** - * Checks if the client is subscribed to the queue - * - * @param Zend_Queue $queue - * @return boolean - */ - protected function _isSubscribed(Zend_Queue $queue) - { - return isset($this->_subscribed[$queue->getName()]); - } - - /** - * Subscribes the client to the queue. - * - * @param Zend_Queue $queue - * @return void - */ - protected function _subscribe(Zend_Queue $queue) - { - $frame = $this->_client->createFrame(); - $frame->setCommand('SUBSCRIBE'); - $frame->setHeader('destination', $queue->getName()); - $frame->setHeader('ack', 'client'); - $this->_client->send($frame); - $this->_subscribed[$queue->getName()] = true; - } - - /** - * Return the first element in the queue - * - * @param integer $maxMessages - * @param integer $timeout - * @param Zend_Queue $queue - * @return Zend_Queue_Message_Iterator - */ - public function receive($maxMessages=null, $timeout=null, Zend_Queue $queue=null) - { - if ($maxMessages === null) { - $maxMessages = 1; - } - if ($timeout === null) { - $timeout = self::RECEIVE_TIMEOUT_DEFAULT; - } - if ($queue === null) { - $queue = $this->_queue; - } - - // read - $data = array(); - - // signal that we are reading - if (!$this->_isSubscribed($queue)){ - $this->_subscribe($queue); - } - - if ($maxMessages > 0) { - if ($this->_client->canRead()) { - for ($i = 0; $i < $maxMessages; $i++) { - $response = $this->_client->receive(); - - switch ($response->getCommand()) { - case 'MESSAGE': - $datum = array( - 'message_id' => $response->getHeader('message-id'), - 'handle' => $response->getHeader('message-id'), - 'body' => $response->getBody(), - 'md5' => md5($response->getBody()) - ); - $data[] = $datum; - break; - default: - $block = print_r($response, true); - #require_once 'Zend/Queue/Exception.php'; - throw new Zend_Queue_Exception('Invalid response received: ' . $block); - } - } - } - } - - $options = array( - 'queue' => $queue, - 'data' => $data, - 'messageClass' => $queue->getMessageClass() - ); - - $classname = $queue->getMessageSetClass(); - - if (!class_exists($classname)) { - #require_once 'Zend/Loader.php'; - Zend_Loader::loadClass($classname); - } - return new $classname($options); - } - - /** - * Push an element onto the end of the queue - * - * @param string $message message to send to the queue - * @param Zend_Queue $queue - * @return Zend_Queue_Message - */ - public function send($message, Zend_Queue $queue=null) - { - if ($queue === null) { - $queue = $this->_queue; - } - - $frame = $this->_client->createFrame(); - $frame->setCommand('SEND'); - $frame->setHeader('destination', $queue->getName()); - $frame->setHeader('content-length', strlen($message)); - $frame->setBody((string) $message); - $this->_client->send($frame); - - $data = array( - 'message_id' => null, - 'body' => $message, - 'md5' => md5($message), - 'handle' => null - ); - - $options = array( - 'queue' => $queue, - 'data' => $data - ); - - $classname = $queue->getMessageClass(); - if (!class_exists($classname)) { - #require_once 'Zend/Loader.php'; - Zend_Loader::loadClass($classname); - } - return new $classname($options); - } - - /** - * Returns the length of the queue - * - * @param Zend_Queue $queue - * @return integer - * @throws Zend_Queue_Exception (not supported) - */ - public function count(Zend_Queue $queue=null) - { - #require_once 'Zend/Queue/Exception.php'; - throw new Zend_Queue_Exception('count() is not supported in this adapter'); - } - - /** - * Does a queue already exist? - * - * @param string $name - * @return boolean - * @throws Zend_Queue_Exception (not supported) - */ - public function isExists($name) - { - #require_once 'Zend/Queue/Exception.php'; - throw new Zend_Queue_Exception('isExists() is not supported in this adapter'); - } - - /** - * Return a list of queue capabilities functions - * - * $array['function name'] = true or false - * true is supported, false is not supported. - * - * @param string $name - * @return array - */ - public function getCapabilities() - { - return array( - 'create' => false, - 'delete' => false, - 'send' => true, - 'receive' => true, - 'deleteMessage' => true, - 'getQueues' => false, - 'count' => false, - 'isExists' => false, - ); - } -} diff --git a/library/Zend/Queue/Adapter/AdapterAbstract.php b/library/Zend/Queue/Adapter/AdapterAbstract.php deleted file mode 100644 index fcbb843e27..0000000000 --- a/library/Zend/Queue/Adapter/AdapterAbstract.php +++ /dev/null @@ -1,191 +0,0 @@ - (string) Amazon AWS Access Key - * secret_key => (string) Amazon AWS Secret Key - * dbname => (string) The name of the database to user - * username => (string) Connect to the database as this username. - * password => (string) Password associated with the username. - * host => (string) What host to connect to, defaults to localhost - * port => (string) The port of the database - * - * @param array|Zend_Config $config An array having configuration data - * @param Zend_Queue The Zend_Queue object that created this class - * @return void - * @throws Zend_Queue_Exception - */ - public function __construct($options, Zend_Queue $queue = null) - { - if ($options instanceof Zend_Config) { - $options = $options->toArray(); - } - - /* - * Verify that adapter parameters are in an array. - */ - if (!is_array($options)) { - #require_once 'Zend/Queue/Exception.php'; - throw new Zend_Queue_Exception('Adapter options must be an array or Zend_Config object'); - } - - // set the queue - if ($queue !== null) { - $this->setQueue($queue); - } - - $adapterOptions = array(); - $driverOptions = array(); - - // Normalize the options and merge with the defaults - if (array_key_exists('options', $options)) { - if (!is_array($options['options'])) { - #require_once 'Zend/Queue/Exception.php'; - throw new Zend_Queue_Exception("Configuration array 'options' must be an array"); - } - - // Can't use array_merge() because keys might be integers - foreach ($options['options'] as $key => $value) { - $adapterOptions[$key] = $value; - } - } - if (array_key_exists('driverOptions', $options)) { - // can't use array_merge() because keys might be integers - foreach ((array)$options['driverOptions'] as $key => $value) { - $driverOptions[$key] = $value; - } - } - $this->_options = array_merge($this->_options, $options); - $this->_options['options'] = $adapterOptions; - $this->_options['driverOptions'] = $driverOptions; - } - - /******************************************************************** - * Queue management functions - *********************************************************************/ - /** - * get the Zend_Queue class that is attached to this object - * - * @return Zend_Queue|null - */ - public function getQueue() - { - return $this->_queue; - } - - /** - * set the Zend_Queue class for this object - * - * @param Zend_Queue $queue - * @return Zend_Queue_Adapter_AdapterInterface - */ - public function setQueue(Zend_Queue $queue) - { - $this->_queue = $queue; - return $this; - } - - /** - * Returns the configuration options in this adapter. - * - * @return array - */ - public function getOptions() - { - return $this->_options; - } - - /** - * Indicates if a function is supported or not. - * - * @param string $name - * @return boolean - */ - public function isSupported($name) - { - $list = $this->getCapabilities(); - - return (isset($list[$name]) && $list[$name]); - } -} diff --git a/library/Zend/Queue/Adapter/AdapterInterface.php b/library/Zend/Queue/Adapter/AdapterInterface.php deleted file mode 100644 index 749c714158..0000000000 --- a/library/Zend/Queue/Adapter/AdapterInterface.php +++ /dev/null @@ -1,174 +0,0 @@ -_data); - } - - /** - * Create a new queue - * - * Visibility timeout is how long a message is left in the queue "invisible" - * to other readers. If the message is acknowleged (deleted) before the - * timeout, then the message is deleted. However, if the timeout expires - * then the message will be made available to other queue readers. - * - * @param string $name queue name - * @param integer $timeout default visibility timeout - * @return boolean - */ - public function create($name, $timeout=null) - { - if ($this->isExists($name)) { - return false; - } - if ($timeout === null) { - $timeout = self::CREATE_TIMEOUT_DEFAULT; - } - $this->_data[$name] = array(); - - return true; - } - - /** - * Delete a queue and all of it's messages - * - * Returns false if the queue is not found, true if the queue exists - * - * @param string $name queue name - * @return boolean - */ - public function delete($name) - { - $found = isset($this->_data[$name]); - - if ($found) { - unset($this->_data[$name]); - } - - return $found; - } - - /** - * Get an array of all available queues - * - * Not all adapters support getQueues(), use isSupported('getQueues') - * to determine if the adapter supports this feature. - * - * @return array - */ - public function getQueues() - { - return array_keys($this->_data); - } - - /** - * Return the approximate number of messages in the queue - * - * @param Zend_Queue $queue - * @return integer - * @throws Zend_Queue_Exception - */ - public function count(Zend_Queue $queue=null) - { - if ($queue === null) { - $queue = $this->_queue; - } - - if (!isset($this->_data[$queue->getName()])) { - /** - * @see Zend_Queue_Exception - */ - #require_once 'Zend/Queue/Exception.php'; - throw new Zend_Queue_Exception('Queue does not exist'); - } - - return count($this->_data[$queue->getName()]); - } - - /******************************************************************** - * Messsage management functions - *********************************************************************/ - - /** - * Send a message to the queue - * - * @param string $message Message to send to the active queue - * @param Zend_Queue $queue - * @return Zend_Queue_Message - * @throws Zend_Queue_Exception - */ - public function send($message, Zend_Queue $queue=null) - { - if ($queue === null) { - $queue = $this->_queue; - } - - if (!$this->isExists($queue->getName())) { - #require_once 'Zend/Queue/Exception.php'; - throw new Zend_Queue_Exception('Queue does not exist:' . $queue->getName()); - } - - // create the message - $data = array( - 'message_id' => md5(uniqid(rand(), true)), - 'body' => $message, - 'md5' => md5($message), - 'handle' => null, - 'created' => time(), - 'queue_name' => $queue->getName(), - ); - - // add $data to the "queue" - $this->_data[$queue->getName()][] = $data; - - $options = array( - 'queue' => $queue, - 'data' => $data, - ); - - $classname = $queue->getMessageClass(); - if (!class_exists($classname)) { - #require_once 'Zend/Loader.php'; - Zend_Loader::loadClass($classname); - } - return new $classname($options); - } - - /** - * Get messages in the queue - * - * @param integer $maxMessages Maximum number of messages to return - * @param integer $timeout Visibility timeout for these messages - * @param Zend_Queue $queue - * @return Zend_Queue_Message_Iterator - */ - public function receive($maxMessages = null, $timeout = null, Zend_Queue $queue = null) - { - if ($maxMessages === null) { - $maxMessages = 1; - } - if ($timeout === null) { - $timeout = self::RECEIVE_TIMEOUT_DEFAULT; - } - if ($queue === null) { - $queue = $this->_queue; - } - - $data = array(); - if ($maxMessages > 0) { - $start_time = microtime(true); - - $count = 0; - $temp = &$this->_data[$queue->getName()]; - foreach ($temp as $key=>&$msg) { - // count check has to be first, as someone can ask for 0 messages - // ZF-7650 - if ($count >= $maxMessages) { - break; - } - - if (($msg['handle'] === null) - || ($msg['timeout'] + $timeout < $start_time) - ) { - $msg['handle'] = md5(uniqid(rand(), true)); - $msg['timeout'] = microtime(true); - $data[] = $msg; - $count++; - } - - } - } - - $options = array( - 'queue' => $queue, - 'data' => $data, - 'messageClass' => $queue->getMessageClass(), - ); - - $classname = $queue->getMessageSetClass(); - if (!class_exists($classname)) { - #require_once 'Zend/Loader.php'; - Zend_Loader::loadClass($classname); - } - return new $classname($options); - } - - /** - * Delete a message from the queue - * - * Returns true if the message is deleted, false if the deletion is - * unsuccessful. - * - * @param Zend_Queue_Message $message - * @return boolean - * @throws Zend_Queue_Exception - */ - public function deleteMessage(Zend_Queue_Message $message) - { - // load the queue - $queue = &$this->_data[$message->queue_name]; - - foreach ($queue as $key => &$msg) { - if ($msg['handle'] == $message->handle) { - unset($queue[$key]); - return true; - } - } - - return false; - } - - /******************************************************************** - * Supporting functions - *********************************************************************/ - - /** - * Return a list of queue capabilities functions - * - * $array['function name'] = true or false - * true is supported, false is not supported. - * - * @param string $name - * @return array - */ - public function getCapabilities() - { - return array( - 'create' => true, - 'delete' => true, - 'send' => true, - 'receive' => true, - 'deleteMessage' => true, - 'getQueues' => true, - 'count' => true, - 'isExists' => true, - ); - } - - /******************************************************************** - * Functions that are not part of the Zend_Queue_Adapter_Abstract - *********************************************************************/ - - /** - * serialize - */ - public function __sleep() - { - return array('_data'); - } - - /* - * These functions are debug helpers. - */ - - /** - * returns underlying _data array - * $queue->getAdapter()->getData(); - * - * @return $this; - */ - public function getData() - { - return $this->_data; - } - - /** - * sets the underlying _data array - * $queue->getAdapter()->setData($data); - * - * @param array $data - * @return $this; - */ - public function setData($data) - { - $this->_data = $data; - return $this; - } -} diff --git a/library/Zend/Queue/Adapter/Db.php b/library/Zend/Queue/Adapter/Db.php deleted file mode 100644 index 6d72cab924..0000000000 --- a/library/Zend/Queue/Adapter/Db.php +++ /dev/null @@ -1,536 +0,0 @@ -_options['options'][Zend_Db_Select::FOR_UPDATE])) { - // turn off auto update by default - $this->_options['options'][Zend_Db_Select::FOR_UPDATE] = false; - } - - if (!is_bool($this->_options['options'][Zend_Db_Select::FOR_UPDATE])) { - #require_once 'Zend/Queue/Exception.php'; - throw new Zend_Queue_Exception('Options array item: Zend_Db_Select::FOR_UPDATE must be boolean'); - } - - if (isset($this->_options['dbAdapter']) - && $this->_options['dbAdapter'] instanceof Zend_Db_Adapter_Abstract) { - $db = $this->_options['dbAdapter']; - } else { - $db = $this->_initDbAdapter(); - } - - $this->_queueTable = new Zend_Queue_Adapter_Db_Queue(array( - 'db' => $db, - )); - - $this->_messageTable = new Zend_Queue_Adapter_Db_Message(array( - 'db' => $db, - )); - - } - - /** - * Initialize Db adapter using 'driverOptions' section of the _options array - * - * Throws an exception if the adapter cannot connect to DB. - * - * @return Zend_Db_Adapter_Abstract - * @throws Zend_Queue_Exception - */ - protected function _initDbAdapter() - { - $options = &$this->_options['driverOptions']; - if (!array_key_exists('type', $options)) { - #require_once 'Zend/Queue/Exception.php'; - throw new Zend_Queue_Exception("Configuration array must have a key for 'type' for the database type to use"); - } - - if (!array_key_exists('host', $options)) { - #require_once 'Zend/Queue/Exception.php'; - throw new Zend_Queue_Exception("Configuration array must have a key for 'host' for the host to use"); - } - - if (!array_key_exists('username', $options)) { - #require_once 'Zend/Queue/Exception.php'; - throw new Zend_Queue_Exception("Configuration array must have a key for 'username' for the username to use"); - } - - if (!array_key_exists('password', $options)) { - #require_once 'Zend/Queue/Exception.php'; - throw new Zend_Queue_Exception("Configuration array must have a key for 'password' for the password to use"); - } - - if (!array_key_exists('dbname', $options)) { - #require_once 'Zend/Queue/Exception.php'; - throw new Zend_Queue_Exception("Configuration array must have a key for 'dbname' for the database to use"); - } - - $type = $options['type']; - unset($options['type']); - - try { - $db = Zend_Db::factory($type, $options); - } catch (Zend_Db_Exception $e) { - #require_once 'Zend/Queue/Exception.php'; - throw new Zend_Queue_Exception('Error connecting to database: ' . $e->getMessage(), $e->getCode(), $e); - } - - return $db; - } - - /******************************************************************** - * Queue management functions - *********************************************************************/ - - /** - * Does a queue already exist? - * - * Throws an exception if the adapter cannot determine if a queue exists. - * use isSupported('isExists') to determine if an adapter can test for - * queue existance. - * - * @param string $name - * @return boolean - * @throws Zend_Queue_Exception - */ - public function isExists($name) - { - $id = 0; - - try { - $id = $this->getQueueId($name); - } catch (Zend_Queue_Exception $e) { - return false; - } - - return ($id > 0); - } - - /** - * Create a new queue - * - * Visibility timeout is how long a message is left in the queue "invisible" - * to other readers. If the message is acknowleged (deleted) before the - * timeout, then the message is deleted. However, if the timeout expires - * then the message will be made available to other queue readers. - * - * @param string $name queue name - * @param integer $timeout default visibility timeout - * @return boolean - * @throws Zend_Queue_Exception - database error - */ - public function create($name, $timeout = null) - { - if ($this->isExists($name)) { - return false; - } - - $queue = $this->_queueTable->createRow(); - $queue->queue_name = $name; - $queue->timeout = ($timeout === null) ? self::CREATE_TIMEOUT_DEFAULT : (int)$timeout; - - try { - if ($queue->save()) { - return true; - } - } catch (Exception $e) { - #require_once 'Zend/Queue/Exception.php'; - throw new Zend_Queue_Exception($e->getMessage(), $e->getCode(), $e); - } - - return false; - } - - /** - * Delete a queue and all of it's messages - * - * Returns false if the queue is not found, true if the queue exists - * - * @param string $name queue name - * @return boolean - * @throws Zend_Queue_Exception - database error - */ - public function delete($name) - { - $id = $this->getQueueId($name); // get primary key - - // if the queue does not exist then it must already be deleted. - $list = $this->_queueTable->find($id); - if (count($list) === 0) { - return false; - } - $queue = $list->current(); - - if ($queue instanceof Zend_Db_Table_Row_Abstract) { - try { - $queue->delete(); - } catch (Exception $e) { - #require_once 'Zend/Queue/Exception.php'; - throw new Zend_Queue_Exception($e->getMessage(), $e->getCode(), $e); - } - } - - if (array_key_exists($name, $this->_queues)) { - unset($this->_queues[$name]); - } - - return true; - } - - /* - * Get an array of all available queues - * - * Not all adapters support getQueues(), use isSupported('getQueues') - * to determine if the adapter supports this feature. - * - * @return array - * @throws Zend_Queue_Exception - database error - */ - public function getQueues() - { - $query = $this->_queueTable->select(); - $query->from($this->_queueTable, array('queue_id', 'queue_name')); - - $this->_queues = array(); - foreach ($this->_queueTable->fetchAll($query) as $queue) { - $this->_queues[$queue->queue_name] = (int)$queue->queue_id; - } - - $list = array_keys($this->_queues); - - return $list; - } - - /** - * Return the approximate number of messages in the queue - * - * @param Zend_Queue $queue - * @return integer - * @throws Zend_Queue_Exception - */ - public function count(Zend_Queue $queue = null) - { - if ($queue === null) { - $queue = $this->_queue; - } - - $info = $this->_messageTable->info(); - $db = $this->_messageTable->getAdapter(); - $query = $db->select(); - $query->from($info['name'], array(new Zend_Db_Expr('COUNT(1)'))) - ->where('queue_id=?', $this->getQueueId($queue->getName())); - - // return count results - return (int) $db->fetchOne($query); - } - - /******************************************************************** - * Messsage management functions - *********************************************************************/ - - /** - * Send a message to the queue - * - * @param string $message Message to send to the active queue - * @param Zend_Queue $queue - * @return Zend_Queue_Message - * @throws Zend_Queue_Exception - database error - */ - public function send($message, Zend_Queue $queue = null) - { - if ($this->_messageRow === null) { - $this->_messageRow = $this->_messageTable->createRow(); - } - - if ($queue === null) { - $queue = $this->_queue; - } - - if (is_scalar($message)) { - $message = (string) $message; - } - if (is_string($message)) { - $message = trim($message); - } - - if (!$this->isExists($queue->getName())) { - #require_once 'Zend/Queue/Exception.php'; - throw new Zend_Queue_Exception('Queue does not exist:' . $queue->getName()); - } - - $msg = clone $this->_messageRow; - $msg->queue_id = $this->getQueueId($queue->getName()); - $msg->created = time(); - $msg->body = $message; - $msg->md5 = md5($message); - // $msg->timeout = ??? @TODO - - try { - $msg->save(); - } catch (Exception $e) { - #require_once 'Zend/Queue/Exception.php'; - throw new Zend_Queue_Exception($e->getMessage(), $e->getCode(), $e); - } - - $options = array( - 'queue' => $queue, - 'data' => $msg->toArray(), - ); - - $classname = $queue->getMessageClass(); - if (!class_exists($classname)) { - #require_once 'Zend/Loader.php'; - Zend_Loader::loadClass($classname); - } - return new $classname($options); - } - - /** - * Get messages in the queue - * - * @param integer $maxMessages Maximum number of messages to return - * @param integer $timeout Visibility timeout for these messages - * @param Zend_Queue $queue - * @return Zend_Queue_Message_Iterator - * @throws Zend_Queue_Exception - database error - */ - public function receive($maxMessages = null, $timeout = null, Zend_Queue $queue = null) - { - if ($maxMessages === null) { - $maxMessages = 1; - } - if ($timeout === null) { - $timeout = self::RECEIVE_TIMEOUT_DEFAULT; - } - if ($queue === null) { - $queue = $this->_queue; - } - - $msgs = array(); - $info = $this->_messageTable->info(); - $microtime = microtime(true); // cache microtime - $db = $this->_messageTable->getAdapter(); - - // start transaction handling - try { - if ( $maxMessages > 0 ) { // ZF-7666 LIMIT 0 clause not included. - $db->beginTransaction(); - - $query = $db->select(); - if ($this->_options['options'][Zend_Db_Select::FOR_UPDATE]) { - // turn on forUpdate - $query->forUpdate(); - } - $query->from($info['name'], array('*')) - ->where('queue_id=?', $this->getQueueId($queue->getName())) - ->where('handle IS NULL OR timeout+' . (int)$timeout . ' < ' . (int)$microtime) - ->limit($maxMessages); - - foreach ($db->fetchAll($query) as $data) { - // setup our changes to the message - $data['handle'] = md5(uniqid(rand(), true)); - - $update = array( - 'handle' => $data['handle'], - 'timeout' => $microtime, - ); - - // update the database - $where = array(); - $where[] = $db->quoteInto('message_id=?', $data['message_id']); - $where[] = 'handle IS NULL OR timeout+' . (int)$timeout . ' < ' . (int)$microtime; - - $count = $db->update($info['name'], $update, $where); - - // we check count to make sure no other thread has gotten - // the rows after our select, but before our update. - if ($count > 0) { - $msgs[] = $data; - } - } - $db->commit(); - } - } catch (Exception $e) { - $db->rollBack(); - - #require_once 'Zend/Queue/Exception.php'; - throw new Zend_Queue_Exception($e->getMessage(), $e->getCode(), $e); - } - - $options = array( - 'queue' => $queue, - 'data' => $msgs, - 'messageClass' => $queue->getMessageClass(), - ); - - $classname = $queue->getMessageSetClass(); - if (!class_exists($classname)) { - #require_once 'Zend/Loader.php'; - Zend_Loader::loadClass($classname); - } - return new $classname($options); - } - - /** - * Delete a message from the queue - * - * Returns true if the message is deleted, false if the deletion is - * unsuccessful. - * - * @param Zend_Queue_Message $message - * @return boolean - * @throws Zend_Queue_Exception - database error - */ - public function deleteMessage(Zend_Queue_Message $message) - { - $db = $this->_messageTable->getAdapter(); - $where = $db->quoteInto('handle=?', $message->handle); - - if ($this->_messageTable->delete($where)) { - return true; - } - - return false; - } - - /******************************************************************** - * Supporting functions - *********************************************************************/ - - /** - * Return a list of queue capabilities functions - * - * $array['function name'] = true or false - * true is supported, false is not supported. - * - * @param string $name - * @return array - */ - public function getCapabilities() - { - return array( - 'create' => true, - 'delete' => true, - 'send' => true, - 'receive' => true, - 'deleteMessage' => true, - 'getQueues' => true, - 'count' => true, - 'isExists' => true, - ); - } - - /******************************************************************** - * Functions that are not part of the Zend_Queue_Adapter_Abstract - *********************************************************************/ - /** - * Get the queue ID - * - * Returns the queue's row identifier. - * - * @param string $name - * @return integer|null - * @throws Zend_Queue_Exception - */ - protected function getQueueId($name) - { - if (array_key_exists($name, $this->_queues)) { - return $this->_queues[$name]; - } - - $query = $this->_queueTable->select(); - $query->from($this->_queueTable, array('queue_id')) - ->where('queue_name=?', $name); - - $queue = $this->_queueTable->fetchRow($query); - - if ($queue === null) { - #require_once 'Zend/Queue/Exception.php'; - throw new Zend_Queue_Exception('Queue does not exist: ' . $name); - } - - $this->_queues[$name] = (int)$queue->queue_id; - - return $this->_queues[$name]; - } -} diff --git a/library/Zend/Queue/Adapter/Db/Message.php b/library/Zend/Queue/Adapter/Db/Message.php deleted file mode 100644 index c1c7626987..0000000000 --- a/library/Zend/Queue/Adapter/Db/Message.php +++ /dev/null @@ -1,51 +0,0 @@ -_options['driverOptions']; - - if (!array_key_exists('host', $options)) { - $options['host'] = self::DEFAULT_HOST; - } - if (!array_key_exists('port', $options)) { - $options['port'] = self::DEFAULT_PORT; - } - - $this->_cache = new Memcache(); - - $result = $this->_cache->connect($options['host'], $options['port']); - - if ($result === false) { - #require_once 'Zend/Queue/Exception.php'; - throw new Zend_Queue_Exception('Could not connect to MemcacheQ'); - } - - $this->_host = $options['host']; - $this->_port = (int)$options['port']; - } - - /** - * Destructor - * - * @return void - */ - public function __destruct() - { - if ($this->_cache instanceof Memcache) { - $this->_cache->close(); - } - if (is_resource($this->_socket)) { - $cmd = 'quit' . self::EOL; - fwrite($this->_socket, $cmd); - fclose($this->_socket); - } - } - - /******************************************************************** - * Queue management functions - *********************************************************************/ - - /** - * Does a queue already exist? - * - * Throws an exception if the adapter cannot determine if a queue exists. - * use isSupported('isExists') to determine if an adapter can test for - * queue existance. - * - * @param string $name - * @return boolean - * @throws Zend_Queue_Exception - */ - public function isExists($name) - { - if (empty($this->_queues)) { - $this->getQueues(); - } - - return in_array($name, $this->_queues); - } - - /** - * Create a new queue - * - * Visibility timeout is how long a message is left in the queue "invisible" - * to other readers. If the message is acknowleged (deleted) before the - * timeout, then the message is deleted. However, if the timeout expires - * then the message will be made available to other queue readers. - * - * @param string $name queue name - * @param integer $timeout default visibility timeout - * @return boolean - * @throws Zend_Queue_Exception - */ - public function create($name, $timeout=null) - { - if ($this->isExists($name)) { - return false; - } - if ($timeout === null) { - $timeout = self::CREATE_TIMEOUT_DEFAULT; - } - - // MemcacheQ does not have a method to "create" a queue - // queues are created upon sending a packet. - // We cannot use the send() and receive() functions because those - // depend on the current name. - $result = $this->_cache->set($name, 'creating queue', 0, 15); - $result = $this->_cache->get($name); - - $this->_queues[] = $name; - - return true; - } - - /** - * Delete a queue and all of it's messages - * - * Returns false if the queue is not found, true if the queue exists - * - * @param string $name queue name - * @return boolean - * @throws Zend_Queue_Exception - */ - public function delete($name) - { - $response = $this->_sendCommand('delete ' . $name, array('DELETED', 'NOT_FOUND'), true); - - if (in_array('DELETED', $response)) { - $key = array_search($name, $this->_queues); - - if ($key !== false) { - unset($this->_queues[$key]); - } - return true; - } - - return false; - } - - /** - * Get an array of all available queues - * - * Not all adapters support getQueues(), use isSupported('getQueues') - * to determine if the adapter supports this feature. - * - * @return array - * @throws Zend_Queue_Exception - */ - public function getQueues() - { - $this->_queues = array(); - - $response = $this->_sendCommand('stats queue', array('END')); - - foreach ($response as $i => $line) { - $this->_queues[] = str_replace('STAT ', '', $line); - } - - return $this->_queues; - } - - /** - * Return the approximate number of messages in the queue - * - * @param Zend_Queue $queue - * @return integer - * @throws Zend_Queue_Exception (not supported) - */ - public function count(Zend_Queue $queue=null) - { - #require_once 'Zend/Queue/Exception.php'; - throw new Zend_Queue_Exception('count() is not supported in this adapter'); - } - - /******************************************************************** - * Messsage management functions - *********************************************************************/ - - /** - * Send a message to the queue - * - * @param string $message Message to send to the active queue - * @param Zend_Queue $queue - * @return Zend_Queue_Message - * @throws Zend_Queue_Exception - */ - public function send($message, Zend_Queue $queue=null) - { - if ($queue === null) { - $queue = $this->_queue; - } - - if (!$this->isExists($queue->getName())) { - #require_once 'Zend/Queue/Exception.php'; - throw new Zend_Queue_Exception('Queue does not exist:' . $queue->getName()); - } - - $message = (string) $message; - $data = array( - 'message_id' => md5(uniqid(rand(), true)), - 'handle' => null, - 'body' => $message, - 'md5' => md5($message), - ); - - $result = $this->_cache->set($queue->getName(), $message, 0, 0); - if ($result === false) { - #require_once 'Zend/Queue/Exception.php'; - throw new Zend_Queue_Exception('failed to insert message into queue:' . $queue->getName()); - } - - $options = array( - 'queue' => $queue, - 'data' => $data, - ); - - $classname = $queue->getMessageClass(); - if (!class_exists($classname)) { - #require_once 'Zend/Loader.php'; - Zend_Loader::loadClass($classname); - } - return new $classname($options); - } - - /** - * Get messages in the queue - * - * @param integer $maxMessages Maximum number of messages to return - * @param integer $timeout Visibility timeout for these messages - * @param Zend_Queue $queue - * @return Zend_Queue_Message_Iterator - * @throws Zend_Queue_Exception - */ - public function receive($maxMessages=null, $timeout=null, Zend_Queue $queue=null) - { - if ($maxMessages === null) { - $maxMessages = 1; - } - - if ($timeout === null) { - $timeout = self::RECEIVE_TIMEOUT_DEFAULT; - } - if ($queue === null) { - $queue = $this->_queue; - } - - $msgs = array(); - if ($maxMessages > 0 ) { - for ($i = 0; $i < $maxMessages; $i++) { - $data = array( - 'handle' => md5(uniqid(rand(), true)), - 'body' => $this->_cache->get($queue->getName()), - ); - - $msgs[] = $data; - } - } - - $options = array( - 'queue' => $queue, - 'data' => $msgs, - 'messageClass' => $queue->getMessageClass(), - ); - - $classname = $queue->getMessageSetClass(); - if (!class_exists($classname)) { - #require_once 'Zend/Loader.php'; - Zend_Loader::loadClass($classname); - } - return new $classname($options); - } - - /** - * Delete a message from the queue - * - * Returns true if the message is deleted, false if the deletion is - * unsuccessful. - * - * @param Zend_Queue_Message $message - * @return boolean - * @throws Zend_Queue_Exception (unsupported) - */ - public function deleteMessage(Zend_Queue_Message $message) - { - #require_once 'Zend/Queue/Exception.php'; - throw new Zend_Queue_Exception('deleteMessage() is not supported in ' . get_class($this)); - } - - /******************************************************************** - * Supporting functions - *********************************************************************/ - - /** - * Return a list of queue capabilities functions - * - * $array['function name'] = true or false - * true is supported, false is not supported. - * - * @param string $name - * @return array - */ - public function getCapabilities() - { - return array( - 'create' => true, - 'delete' => true, - 'send' => true, - 'receive' => true, - 'deleteMessage' => false, - 'getQueues' => true, - 'count' => false, - 'isExists' => true, - ); - } - - /******************************************************************** - * Functions that are not part of the Zend_Queue_Adapter_Abstract - *********************************************************************/ - - /** - * sends a command to MemcacheQ - * - * The memcache functions by php cannot handle all types of requests - * supported by MemcacheQ - * Non-standard requests are handled by this function. - * - * @param string $command - command to send to memcacheQ - * @param array $terminator - strings to indicate end of memcacheQ response - * @param boolean $include_term - include terminator in response - * @return array - * @throws Zend_Queue_Exception if connection cannot be opened - */ - protected function _sendCommand($command, array $terminator, $include_term=false) - { - if (!is_resource($this->_socket)) { - $this->_socket = fsockopen($this->_host, $this->_port, $errno, $errstr, 10); - } - if ($this->_socket === false) { - #require_once 'Zend/Queue/Exception.php'; - throw new Zend_Queue_Exception("Could not open a connection to $this->_host:$this->_port errno=$errno : $errstr"); - } - - $response = array(); - - $cmd = $command . self::EOL; - fwrite($this->_socket, $cmd); - - $continue_reading = true; - while (!feof($this->_socket) && $continue_reading) { - $resp = trim(fgets($this->_socket, 1024)); - if (in_array($resp, $terminator)) { - if ($include_term) { - $response[] = $resp; - } - $continue_reading = false; - } else { - $response[] = $resp; - } - } - - return $response; - } -} diff --git a/library/Zend/Queue/Adapter/Null.php b/library/Zend/Queue/Adapter/Null.php deleted file mode 100644 index dc8afa6dbb..0000000000 --- a/library/Zend/Queue/Adapter/Null.php +++ /dev/null @@ -1,174 +0,0 @@ - false, - 'delete' => false, - 'send' => false, - 'receive' => false, - 'deleteMessage' => false, - 'getQueues' => false, - 'count' => false, - 'isExists' => false, - ); - } -} diff --git a/library/Zend/Queue/Adapter/PlatformJobQueue.php b/library/Zend/Queue/Adapter/PlatformJobQueue.php deleted file mode 100644 index 7fc1b55633..0000000000 --- a/library/Zend/Queue/Adapter/PlatformJobQueue.php +++ /dev/null @@ -1,343 +0,0 @@ -_options['daemonOptions'])) { - #require_once 'Zend/Queue/Exception.php'; - throw new Zend_Queue_Exception('Job Queue host and password should be provided'); - } - - $options = $this->_options['daemonOptions']; - - if (!array_key_exists('host', $options)) { - #require_once 'Zend/Queue/Exception.php'; - throw new Zend_Queue_Exception('Platform Job Queue host should be provided'); - } - if (!array_key_exists('password', $options)) { - #require_once 'Zend/Queue/Exception.php'; - throw new Zend_Queue_Exception('Platform Job Queue password should be provided'); - } - - $this->_zendQueue = new ZendApi_Queue($options['host']); - - if (!$this->_zendQueue) { - #require_once 'Zend/Queue/Exception.php'; - throw new Zend_Queue_Exception('Platform Job Queue connection failed'); - } - if (!$this->_zendQueue->login($options['password'])) { - #require_once 'Zend/Queue/Exception.php'; - throw new Zend_Queue_Exception('Job Queue login failed'); - } - - if ($this->_queue) { - $this->_queue->setMessageClass('Zend_Queue_Message_PlatformJob'); - } - } - - /******************************************************************** - * Queue management functions - ********************************************************************/ - - /** - * Does a queue already exist? - * - * @param string $name - * @return boolean - * @throws Zend_Queue_Exception (not supported) - */ - public function isExists($name) - { - #require_once 'Zend/Queue/Exception.php'; - throw new Zend_Queue_Exception('isExists() is not supported in this adapter'); - } - - /** - * Create a new queue - * - * @param string $name queue name - * @param integer $timeout default visibility timeout - * @return void - * @throws Zend_Queue_Exception - */ - public function create($name, $timeout=null) - { - #require_once 'Zend/Queue/Exception.php'; - throw new Zend_Queue_Exception('create() is not supported in ' . get_class($this)); - } - - /** - * Delete a queue and all of its messages - * - * @param string $name queue name - * @return void - * @throws Zend_Queue_Exception - */ - public function delete($name) - { - #require_once 'Zend/Queue/Exception.php'; - throw new Zend_Queue_Exception('delete() is not supported in ' . get_class($this)); - } - - /** - * Get an array of all available queues - * - * @return void - * @throws Zend_Queue_Exception - */ - public function getQueues() - { - #require_once 'Zend/Queue/Exception.php'; - throw new Zend_Queue_Exception('getQueues() is not supported in this adapter'); - } - - /** - * Return the approximate number of messages in the queue - * - * @param Zend_Queue|null $queue - * @return integer - */ - public function count(Zend_Queue $queue = null) - { - if ($queue !== null) { - #require_once 'Zend/Queue/Exception.php'; - throw new Zend_Queue_Exception('Queue parameter is not supported'); - } - - return $this->_zendQueue->getNumOfJobsInQueue(); - } - - /******************************************************************** - * Messsage management functions - ********************************************************************/ - - /** - * Send a message to the queue - * - * @param array | ZendAPI_job $message Message to send to the active queue - * @param Zend_Queue $queue Not supported - * @return Zend_Queue_Message - * @throws Zend_Queue_Exception - */ - public function send($message, Zend_Queue $queue = null) - { - if ($queue !== null) { - #require_once 'Zend/Queue/Exception.php'; - throw new Zend_Queue_Exception('Queue parameter is not supported'); - } - - // This adapter can work only for this message type - $classname = $this->_queue->getMessageClass(); - if (!class_exists($classname)) { - #require_once 'Zend/Loader.php'; - Zend_Loader::loadClass($classname); - } - - if ($message instanceof ZendAPI_Job) { - $message = array('data' => $message); - } - - $zendApiJob = new $classname($message); - - // Unfortunately, the Platform JQ API is PHP4-style... - $platformJob = $zendApiJob->getJob(); - - $jobId = $this->_zendQueue->addJob($platformJob); - - if (!$jobId) { - #require_once 'Zend/Queue/Exception.php'; - throw new Zend_Queue_Exception('Failed to add a job to queue: ' - . $this->_zendQueue->getLastError()); - } - - $zendApiJob->setJobId($jobId); - return $zendApiJob; - } - - /** - * Get messages in the queue - * - * @param integer $maxMessages Maximum number of messages to return - * @param integer $timeout Ignored - * @param Zend_Queue $queue Not supported - * @throws Zend_Queue_Exception - * @return ArrayIterator - */ - public function receive($maxMessages = null, $timeout = null, Zend_Queue $queue = null) - { - if ($maxMessages === null) { - $maxMessages = 1; - } - - if ($queue !== null) { - #require_once 'Zend/Queue/Exception.php'; - throw new Zend_Queue_Exception('Queue shouldn\'t be set'); - } - - $jobs = $this->_zendQueue->getJobsInQueue(null, $maxMessages, true); - - $classname = $this->_queue->getMessageClass(); - if (!class_exists($classname)) { - #require_once 'Zend/Loader.php'; - Zend_Loader::loadClass($classname); - } - - $options = array( - 'queue' => $this->_queue, - 'data' => $jobs, - 'messageClass' => $this->_queue->getMessageClass(), - ); - - $classname = $this->_queue->getMessageSetClass(); - - if (!class_exists($classname)) { - #require_once 'Zend/Loader.php'; - Zend_Loader::loadClass($classname); - } - return new $classname($options); - } - - /** - * Delete a message from the queue - * - * Returns true if the message is deleted, false if the deletion is - * unsuccessful. - * - * @param Zend_Queue_Message $message - * @return boolean - * @throws Zend_Queue_Exception - */ - public function deleteMessage(Zend_Queue_Message $message) - { - if (get_class($message) != $this->_queue->getMessageClass()) { - #require_once 'Zend/Queue/Exception.php'; - throw new Zend_Queue_Exception( - 'Failed to remove job from the queue; only messages of type ' - . 'Zend_Queue_Message_PlatformJob may be used' - ); - } - - return $this->_zendQueue->removeJob($message->getJobId()); - } - - public function isJobIdExist($id) - { - return (($this->_zendQueue->getJob($id))? true : false); - } - - /******************************************************************** - * Supporting functions - ********************************************************************/ - - /** - * Return a list of queue capabilities functions - * - * $array['function name'] = true or false - * true is supported, false is not supported. - * - * @param string $name - * @return array - */ - public function getCapabilities() - { - return array( - 'create' => false, - 'delete' => false, - 'getQueues' => false, - 'isExists' => false, - 'count' => true, - 'send' => true, - 'receive' => true, - 'deleteMessage' => true, - ); - } - - /******************************************************************** - * Functions that are not part of the Zend_Queue_Adapter_AdapterAbstract - ********************************************************************/ - - /** - * Serialize - * - * @return array - */ - public function __sleep() - { - return array('_options'); - } - - /** - * Unserialize - * - * @return void - */ - public function __wakeup() - { - $options = $this->_options['daemonOptions']; - - $this->_zendQueue = new ZendApi_Queue($options['host']); - - if (!$this->_zendQueue) { - #require_once 'Zend/Queue/Exception.php'; - throw new Zend_Queue_Exception('Platform Job Queue connection failed'); - } - if (!$this->_zendQueue->login($options['password'])) { - #require_once 'Zend/Queue/Exception.php'; - throw new Zend_Queue_Exception('Job Queue login failed'); - } - } -} diff --git a/library/Zend/Queue/Exception.php b/library/Zend/Queue/Exception.php deleted file mode 100644 index 349ac4e1c7..0000000000 --- a/library/Zend/Queue/Exception.php +++ /dev/null @@ -1,35 +0,0 @@ -_queue = $options['queue']; - $this->_queueClass = get_class($this->_queue); - } else { - $result = gettype($options['queue']); - if ($result === 'object') { - $result = get_class($options['queue']); - } - - #require_once 'Zend/Queue/Exception.php'; - throw new Zend_Queue_Exception( - '$options[\'queue\'] = ' - . $result - . ': must be instanceof Zend_Queue' - ); - } - } - if (isset($options['data'])) { - if (!is_array($options['data'])) { - #require_once 'Zend/Queue/Exception.php'; - throw new Zend_Queue_Exception('Data must be an array'); - } - $this->_data = $options['data']; - } - } - - /** - * Retrieve message field value - * - * @param string $key The user-specified key name. - * @return string The corresponding key value. - * @throws Zend_Queue_Exception if the $key is not a column in the message. - */ - public function __get($key) - { - if (!array_key_exists($key, $this->_data)) { - #require_once 'Zend/Queue/Exception.php'; - throw new Zend_Queue_Exception("Specified field \"$key\" is not in the message"); - } - return $this->_data[$key]; - } - - /** - * Set message field value - * - * @param string $key The message key. - * @param mixed $value The value for the property. - * @return void - * @throws Zend_Queue_Exception - */ - public function __set($key, $value) - { - if (!array_key_exists($key, $this->_data)) { - #require_once 'Zend/Queue/Exception.php'; - throw new Zend_Queue_Exception("Specified field \"$key\" is not in the message"); - } - $this->_data[$key] = $value; - } - - /** - * Test existence of message field - * - * @param string $key The column key. - * @return boolean - */ - public function __isset($key) - { - return array_key_exists($key, $this->_data); - } - - /* - * Serialize - */ - - /** - * Store queue and data in serialized object - * - * @return array - */ - public function __sleep() - { - return array('_queueClass', '_data'); - } - - /** - * Setup to do on wakeup. - * A de-serialized Message should not be assumed to have access to a live - * queue connection, so set _connected = false. - * - * @return void - */ - public function __wakeup() - { - $this->_connected = false; - } - - /** - * Returns the queue object, or null if this is disconnected message - * - * @return Zend_Queue|null - */ - public function getQueue() - { - return $this->_queue; - } - - /** - * Set the queue object, to re-establish a live connection - * to the queue for a Message that has been de-serialized. - * - * @param Zend_Queue $queue - * @return boolean - */ - public function setQueue(Zend_Queue $queue) - { - $queueClass = get_class($queue); - $this->_queue = $queue; - $this->_queueClass = $queueClass; - $this->_connected = true; - return true; - } - - /** - * Query the class name of the Queue object for which this - * Message was created. - * - * @return string - */ - public function getQueueClass() - { - return $this->_queueClass; - } - - /** - * Returns the column/value data as an array. - * - * @return array - */ - public function toArray() - { - return $this->_data; - } - - /** - * Sets all data in the row from an array. - * - * @param array $data - * @return Zend_Queue_Message Provides a fluent interface - */ - public function setFromArray(array $data) - { - foreach ($data as $columnName => $value) { - $this->$columnName = $value; - } - - return $this; - } -} diff --git a/library/Zend/Queue/Message/Iterator.php b/library/Zend/Queue/Message/Iterator.php deleted file mode 100644 index 74a5e25b9e..0000000000 --- a/library/Zend/Queue/Message/Iterator.php +++ /dev/null @@ -1,285 +0,0 @@ -array()); - * @return void - */ - public function __construct(array $options = array()) - { - if (isset($options['queue'])) { - $this->_queue = $options['queue']; - $this->_queueClass = get_class($this->_queue); - $this->_connected = true; - } else { - $this->_connected = false; - } - if (isset($options['messageClass'])) { - $this->_messageClass = $options['messageClass']; - } - - if (!is_array($options['data'])) { - #require_once 'Zend/Queue/Exception.php'; - throw new Zend_Queue_Exception('array optionsuration must have $options[\'data\'] = array'); - } - - // load the message class - $classname = $this->_messageClass; - if (!class_exists($classname)) { - #require_once 'Zend/Loader.php'; - Zend_Loader::loadClass($classname); - } - - // for each of the messages - foreach ($options['data'] as $data) { - // construct the message parameters - $message = array('data' => $data); - - // If queue has not been set, then use the default. - if (empty($message['queue'])) { - $message['queue'] = $this->_queue; - } - - // construct the message and add it to _data[]; - $this->_data[] = new $classname($message); - } - } - - /** - * Store queue and data in serialized object - * - * @return array - */ - public function __sleep() - { - return array('_data', '_queueClass', '_messageClass', '_pointer'); - } - - /** - * Setup to do on wakeup. - * A de-serialized Message should not be assumed to have access to a live - * queue connection, so set _connected = false. - * - * @return void - */ - public function __wakeup() - { - $this->_connected = false; - } - - /** - * Returns all data as an array. - * - * Used for debugging. - * - * @return array - */ - public function toArray() - { - // @todo This works only if we have iterated through - // the result set once to instantiate the messages. - foreach ($this->_data as $i => $message) { - $this->_data[$i] = $message->toArray(); - } - return $this->_data; - } - - /** - * Returns the queue object, or null if this is disconnected message set - * - * @return Zend_Queue|null - */ - public function getQueue() - { - return $this->_queue; - } - - /** - * Set the queue object, to re-establish a live connection - * to the queue for a Message that has been de-serialized. - * - * @param Zend_Queue_Adapter_AdapterInterface $queue - * @return boolean - * @throws Zend_Queue_Exception - */ - public function setQueue(Zend_Queue $queue) - { - $this->_queue = $queue; - $this->_connected = false; - - // @todo This works only if we have iterated through - // the result set once to instantiate the rows. - foreach ($this->_data as $i => $message) { - $this->_connected = $this->_connected || $message->setQueue($queue); - } - - return $this->_connected; - } - - /** - * Query the class name of the Queue object for which this - * Message was created. - * - * @return string - */ - public function getQueueClass() - { - return $this->_queueClass; - } - - /* - * Iterator implementation - */ - - /** - * Rewind the Iterator to the first element. - * Similar to the reset() function for arrays in PHP. - * Required by interface Iterator. - * - * @return void - */ - public function rewind() - { - $this->_pointer = 0; - } - - /** - * Return the current element. - * Similar to the current() function for arrays in PHP - * Required by interface Iterator. - * - * @return Zend_Queue_Message current element from the collection - */ - public function current() - { - return (($this->valid() === false) - ? null - : $this->_data[$this->_pointer]); // return the messages object - } - - /** - * Return the identifying key of the current element. - * Similar to the key() function for arrays in PHP. - * Required by interface Iterator. - * - * @return integer - */ - public function key() - { - return $this->_pointer; - } - - /** - * Move forward to next element. - * Similar to the next() function for arrays in PHP. - * Required by interface Iterator. - * - * @return void - */ - public function next() - { - ++$this->_pointer; - } - - /** - * Check if there is a current element after calls to rewind() or next(). - * Used to check if we've iterated to the end of the collection. - * Required by interface Iterator. - * - * @return bool False if there's nothing more to iterate over - */ - public function valid() - { - return $this->_pointer < count($this); - } - - /* - * Countable Implementation - */ - - /** - * Returns the number of elements in the collection. - * - * Implements Countable::count() - * - * @return integer - */ - public function count() - { - return count($this->_data); - } -} diff --git a/library/Zend/Queue/Message/PlatformJob.php b/library/Zend/Queue/Message/PlatformJob.php deleted file mode 100644 index c67c88247a..0000000000 --- a/library/Zend/Queue/Message/PlatformJob.php +++ /dev/null @@ -1,194 +0,0 @@ -_job = $options['data']; - parent::__construct($this->_job->getProperties()); - } else { - parent::__construct($options); - - if (!isset($options['script'])) { - #require_once 'Zend/Queue/Exception.php'; - throw new Zend_Queue_Exception('The script is mandatory data'); - } - - $this->_job = new ZendApi_Job($options['script']); - $this->_setJobProperties(); - } - } - - /** - * Set the job identifier - * - * Used within Zend_Queue only. - * - * @param string $id - * @return Zend_Queue_Message_PlatformJob - */ - public function setJobId($id) - { - $this->_id = $id; - return $this; - } - - /** - * Retrieve the job identifier - * - * @return string - */ - public function getJobId() - { - return (($this->_id) ? $this->_id : $this->_job->getID()); - } - - /** - * Retrieve the internal ZendApi_Job instance - * - * @return ZendApi_Job - */ - public function getJob() - { - return $this->_job; - } - - /** - * Store queue and data in serialized object - * - * @return array - */ - public function __sleep() - { - return serialize('_job', '_id', '_data'); - } - - /** - * Query the class name of the Queue object for which this - * Message was created. - * - * @return string - */ - public function getQueueClass() - { - return 'Zend_Queue_Adapter_Platform_JQ'; - } - - /** - * Sets properties on the ZendApi_Job instance - * - * Any options in the {@link $_data} array will be checked. Those matching - * options in ZendApi_Job will be used to set those options in that - * instance. - * - * @return void - */ - protected function _setJobProperties() { - - if (isset($this->_data['script'])) { - $this->_job->setScript($this->_data['script']); - } - - if (isset($this->_data['priority'])) { - $this->_job->setJobPriority($this->_data['priority']); - } - - if (isset($this->_data['name'])) { - $this->_job->setJobName($this->_data['name']); - } - - if (isset($this->_data['predecessor'])) { - $this->_job->setJobDependency($this->_data['predecessor']); - } - - if (isset($this->_data['preserved'])) { - $this->_job->setPreserved($this->_data['preserved']); - } - - if (isset($this->_data['user_variables'])) { - $this->_job->setUserVariables($this->_data['user_variables']); - } - - if (!empty($this->_data['interval'])) { - $endTime = isset($this->_data['end_time']) ? $this->_data['end_time'] : null; - $this->_job->setRecurrenceData($this->_data['interval'], $endTime); - } elseif (isset($this->_data['interval']) && ($this->_data['interval'] === '')) { - $this->_job->setRecurrenceData(0,0); - } - - if (isset($this->_data['scheduled_time'])) { - $this->_job->setScheduledTime($this->_data['scheduled_time']); - } - - if (isset($this->_data['application_id'])) { - $this->_job->setApplicationID($this->_data['application_id']); - } - } -} diff --git a/library/Zend/Queue/Stomp/Client.php b/library/Zend/Queue/Stomp/Client.php deleted file mode 100644 index 338cd6f6ed..0000000000 --- a/library/Zend/Queue/Stomp/Client.php +++ /dev/null @@ -1,173 +0,0 @@ -addConnection($scheme, $host, $port, $connectionClass); - $this->getConnection()->setFrameClass($frameClass); - } - } - - /** - * Shutdown - * - * @return void - */ - public function __destruct() - { - if ($this->getConnection()) { - $this->getConnection()->close(true); - } - } - - /** - * Add a connection to this client. - * - * Attempts to add this class to the client. Returns a boolean value - * indicating success of operation. - * - * You cannot add more than 1 connection to the client at this time. - * - * @param string $scheme ['tcp', 'udp'] - * @param string host - * @param integer port - * @param string class - create a connection with this class; class must support Zend_Queue_Stomp_Client_ConnectionInterface - * @return boolean - */ - public function addConnection($scheme, $host, $port, $class = 'Zend_Queue_Stomp_Client_Connection') - { - if (!class_exists($class)) { - #require_once 'Zend/Loader.php'; - Zend_Loader::loadClass($class); - } - - $connection = new $class(); - - if ($connection->open($scheme, $host, $port)) { - $this->setConnection($connection); - return true; - } - - $connection->close(); - return false; - } - - /** - * Set client connection - * - * @param Zend_Queue_Stomp_Client_ConnectionInterface $connection - * @return void - */ - public function setConnection(Zend_Queue_Stomp_Client_ConnectionInterface $connection) - { - $this->_connection = $connection; - return $this; - } - - /** - * Get client connection - * - * @return Zend_Queue_Stomp_Client_ConnectionInterface|null - */ - public function getConnection() - { - return $this->_connection; - } - - /** - * Send a stomp frame - * - * Returns true if the frame was successfully sent. - * - * @param Zend_Queue_Stomp_FrameInterface $frame - * @return boolean - */ - public function send(Zend_Queue_Stomp_FrameInterface $frame) - { - $this->getConnection()->write($frame); - return $this; - } - - /** - * Receive a frame - * - * Returns a frame or false if none were to be read. - * - * @return Zend_Queue_Stomp_FrameInterface|boolean - */ - public function receive() - { - return $this->getConnection()->read(); - } - - /** - * canRead() - * - * @return boolean - */ - public function canRead() - { - return $this->getConnection()->canRead(); - } - - /** - * creates a frame class - * - * @return Zend_Queue_Stomp_FrameInterface - */ - public function createFrame() - { - return $this->getConnection()->createFrame(); - } -} diff --git a/library/Zend/Queue/Stomp/Client/Connection.php b/library/Zend/Queue/Stomp/Client/Connection.php deleted file mode 100644 index 3a2c4e848c..0000000000 --- a/library/Zend/Queue/Stomp/Client/Connection.php +++ /dev/null @@ -1,280 +0,0 @@ -_socket = fsockopen($str, $port, $errno, $errstr); - - if ($this->_socket === false) { - // aparently there is some reason that fsockopen will return false - // but it normally throws an error. - #require_once 'Zend/Queue/Exception.php'; - throw new Zend_Queue_Exception("Unable to connect to $str; error = $errstr ( errno = $errno )"); - } - - stream_set_blocking($this->_socket, 0); // non blocking - - if (!isset($options['timeout_sec'])) { - $options['timeout_sec'] = self::READ_TIMEOUT_DEFAULT_SEC; - } - if (! isset($options['timeout_usec'])) { - $options['timeout_usec'] = self::READ_TIMEOUT_DEFAULT_USEC; - } - - $this->_options = $options; - - return true; - } - - /** - * Close the socket explicitly when destructed - * - * @return void - */ - public function __destruct() - { - } - - /** - * Close connection - * - * @param boolean $destructor - * @return void - */ - public function close($destructor = false) - { - // Gracefully disconnect - if (!$destructor) { - $frame = $this->createFrame(); - $frame->setCommand('DISCONNECT'); - $this->write($frame); - } - - // @todo: Should be fixed. - // When the socket is "closed", it will trigger the below error when php exits - // Fatal error: Exception thrown without a stack frame in Unknown on line 0 - - // Danlo: I suspect this is because this has already been claimed by the interpeter - // thus trying to shutdown this resources, which is already shutdown is a problem. - if (is_resource($this->_socket)) { - // fclose($this->_socket); - } - - // $this->_socket = null; - } - - /** - * Check whether we are connected to the server - * - * @return true - * @throws Zend_Queue_Exception - */ - public function ping() - { - if (!is_resource($this->_socket)) { - #require_once 'Zend/Queue/Exception.php'; - throw new Zend_Queue_Exception('Not connected to Stomp server'); - } - return true; - } - - /** - * Write a frame to the stomp server - * - * example: $response = $client->write($frame)->read(); - * - * @param Zend_Queue_Stom_FrameInterface $frame - * @return $this - */ - public function write(Zend_Queue_Stomp_FrameInterface $frame) - { - $this->ping(); - $output = $frame->toFrame(); - - $bytes = fwrite($this->_socket, $output, strlen($output)); - if ($bytes === false || $bytes == 0) { - #require_once 'Zend/Queue/Exception.php'; - throw new Zend_Queue_Exception('No bytes written'); - } - - return $this; - } - - /** - * Tests the socket to see if there is data for us - * - * @return boolean - */ - public function canRead() - { - $read = array($this->_socket); - $write = null; - $except = null; - - return stream_select( - $read, - $write, - $except, - $this->_options['timeout_sec'], - $this->_options['timeout_usec'] - ) == 1; - // see http://us.php.net/manual/en/function.stream-select.php - } - - /** - * Reads in a frame from the socket or returns false. - * - * @return Zend_Queue_Stomp_FrameInterface|false - * @throws Zend_Queue_Exception - */ - public function read() - { - $this->ping(); - - $response = ''; - $prev = ''; - - // while not end of file. - while (!feof($this->_socket)) { - // read in one character until "\0\n" is found - $data = fread($this->_socket, 1); - - // check to make sure that the connection is not lost. - if ($data === false) { - #require_once 'Zend/Queue/Exception.php'; - throw new Zend_Queue_Exception('Connection lost'); - } - - // append last character read to $response - $response .= $data; - - // is this \0 (prev) \n (data)? END_OF_FRAME - if (ord($data) == 10 && ord($prev) == 0) { - break; - } - $prev = $data; - } - - if ($response === '') { - return false; - } - - $frame = $this->createFrame(); - $frame->fromFrame($response); - return $frame; - } - - /** - * Set the frameClass to be used - * - * This must be a Zend_Queue_Stomp_FrameInterface. - * - * @param string $classname - class is an instance of Zend_Queue_Stomp_FrameInterface - * @return $this; - */ - public function setFrameClass($classname) - { - $this->_options['frameClass'] = $classname; - return $this; - } - - /** - * Get the frameClass - * - * @return string - */ - public function getFrameClass() - { - return isset($this->_options['frameClass']) - ? $this->_options['frameClass'] - : 'Zend_Queue_Stomp_Frame'; - } - - /** - * Create an empty frame - * - * @return Zend_Queue_Stomp_FrameInterface - */ - public function createFrame() - { - $class = $this->getFrameClass(); - - if (!class_exists($class)) { - #require_once 'Zend/Loader.php'; - Zend_Loader::loadClass($class); - } - - $frame = new $class(); - - if (!$frame instanceof Zend_Queue_Stomp_FrameInterface) { - #require_once 'Zend/Queue/Exception.php'; - throw new Zend_Queue_Exception('Invalid Frame class provided; must implement Zend_Queue_Stomp_FrameInterface'); - } - - return $frame; - } -} diff --git a/library/Zend/Queue/Stomp/Client/ConnectionInterface.php b/library/Zend/Queue/Stomp/Client/ConnectionInterface.php deleted file mode 100644 index a8a8b4a978..0000000000 --- a/library/Zend/Queue/Stomp/Client/ConnectionInterface.php +++ /dev/null @@ -1,103 +0,0 @@ -write($frame)->read(); - * - * @param Zend_Queue_Stomp_FrameInterface $frame - * @return $this - */ - public function write(Zend_Queue_Stomp_FrameInterface $frame); - - /** - * tests the socket to see if there is data for us - */ - public function canRead(); - - /** - * reads in a frame from the socket or returns false. - * - * @return Zend_Queue_Stomp_Frame|false - * @throws Zend_Queue_Exception - */ - public function read(); - - /** - * Set the frame class to be used - * - * This must be a Zend_Queue_Stomp_FrameInterface. - * - * @param string $class - * @return Zend_Queue_Stomp_Client_ConnectionInterface; - */ - public function setFrameClass($class); - - /** - * Get the frameClass - * - * @return string - */ - public function getFrameClass(); - - /** - * create an empty frame - * - * @return Zend_Queue_Stomp_FrameInterface class - */ - public function createFrame(); -} diff --git a/library/Zend/Queue/Stomp/Frame.php b/library/Zend/Queue/Stomp/Frame.php deleted file mode 100644 index c9f78e5eaa..0000000000 --- a/library/Zend/Queue/Stomp/Frame.php +++ /dev/null @@ -1,363 +0,0 @@ -setHeaders(array()); - $this->setBody(null); - $this->setCommand(null); - $this->setAutoContentLength(true); - } - - /** - * get the status of the auto content length - * - * If AutoContentLength is true this code will automatically put the - * content-length header in, even if it is already set by the user. - * - * This is done to make the message sending more reliable. - * - * @return boolean - */ - public function getAutoContentLength() - { - return $this->_autoContentLength; - } - - /** - * setAutoContentLength() - * - * Set the value on or off. - * - * @param boolean $auto - * @return $this; - * @throws Zend_Queue_Exception - */ - public function setAutoContentLength($auto) - { - if (!is_bool($auto)) { - #require_once 'Zend/Queue/Exception.php'; - throw new Zend_Queue_Exception('$auto is not a boolean'); - } - - $this->_autoContentLength = $auto; - return $this; - } - - /** - * Get the headers - * - * @return array - */ - public function getHeaders() - { - return $this->_headers; - } - - /** - * Set the headers - * - * Throws an exception if the array values are not strings. - * - * @param array $headers - * @return $this - * @throws Zend_Queue_Exception - */ - public function setHeaders(array $headers) - { - foreach ($headers as $header => $value) { - $this->setHeader($header, $value); - } - - return $this; - } - - /** - * Sets a value for a header - * - * @param string $header - * @param string $value - * @return Zend_Queue_Stomp_Frame - * @throws Zend_Queue_Exception - */ - public function setHeader($header, $value) { - if (!is_string($header)) { - #require_once 'Zend/Queue/Exception.php'; - throw new Zend_Queue_Exception('$header is not a string: ' . print_r($header, true)); - } - - if (!is_scalar($value)) { - #require_once 'Zend/Queue/Exception.php'; - throw new Zend_Queue_Exception('$value is not a string: ' . print_r($value, true)); - } - - $this->_headers[$header] = $value; - return $this; - } - - - /** - * Returns a value for a header - * - * Returns false if the header does not exist. - * - * @param string $header - * @return string|false - * @throws Zend_Queue_Exception - */ - public function getHeader($header) - { - if (!is_string($header)) { - #require_once 'Zend/Queue/Exception.php'; - throw new Zend_Queue_Exception('$header is not a string'); - } - - return isset($this->_headers[$header]) - ? $this->_headers[$header] - : false; - } - - /** - * Return the body for this frame - * - * Returns false if the body does not exist - * - * @return false|string - */ - public function getBody() - { - return $this->_body === null - ? false - : $this->_body; - } - - /** - * Set the body for this frame - * - * Set to null for no body. - * - * @param string|null $body - * @return Zend_Queue_Stomp_Frame - * @throws Zend_Queue_Exception - */ - public function setBody($body) - { - if (!is_string($body) && $body !== null) { - #require_once 'Zend/Queue/Exception.php'; - throw new Zend_Queue_Exception('$body is not a string or null'); - } - - $this->_body = $body; - return $this; - } - - /** - * Return the command for this frame - * - * Return false if the command does not exist - * - * @return string|false - */ - public function getCommand() - { - return $this->_command === null - ? false - : $this->_command; - } - - /** - * Set the body for this frame - * - * @param string|null - * @return Zend_Queue_Stomp_Frame - * @throws Zend_Queue_Exception - */ - public function setCommand($command) - { - if (!is_string($command) && $command !== null) { - #require_once 'Zend/Queue/Exception.php'; - throw new Zend_Queue_Exception('$command is not a string or null'); - } - - $this->_command = $command; - return $this; - } - - /** - * Takes the current parameters and returns a Stomp Frame - * - * @return string - * @throws Zend_Queue_Exception - */ - public function toFrame() - { - if ($this->getCommand() === false) { - #require_once 'Zend/Queue/Exception.php'; - throw new Zend_Queue_Exception('You must set the command'); - } - - $command = $this->getCommand(); - $headers = $this->getHeaders(); - $body = $this->getBody(); - $frame = ''; - - // add a content-length to the SEND command. - // @see http://stomp.codehaus.org/Protocol - if ($this->getAutoContentLength()) { - $headers[self::CONTENT_LENGTH] = strlen($this->getBody()); - } - - // Command - $frame = $command . self::EOL; - - // Headers - foreach ($headers as $key=>$value) { - $frame .= $key . ': ' . $value . self::EOL; - } - - // Seperator - $frame .= self::EOL; // blank line required by protocol - - // add the body if any - if ($body !== false) { - $frame .= $body; - } - $frame .= self::END_OF_FRAME; - - return $frame; - } - - /** - * @see toFrame() - * @return string - */ - public function __toString() - { - try { - $return = $this->toFrame(); - } catch (Zend_Queue_Exception $e) { - $return = ''; - } - return $return; - } - - /** - * Accepts a frame and deconstructs the frame into its component parts - * - * @param string $frame - a stomp frame - * @return $this - */ - public function fromFrame($frame) - { - if (!is_string($frame)) { - #require_once 'Zend/Queue/Exception.php'; - throw new Zend_Queue_Exception('$frame is not a string'); - } - - $headers = array(); - $body = null; - $command = false; - $header = ''; - - // separate the headers and the body - $match = self::EOL . self::EOL; - if (preg_match('/' . $match . '/', $frame)) { - list ($header, $body) = explode($match, $frame, 2); - } else { - $header = $frame; - } - - // blow up headers - $headers = explode(self::EOL, $header); - unset($header); - - // get the command (first line) - $this->setCommand(array_shift($headers)); - - // set each of the headers. - foreach ($headers as $header) { - if (strpos($header, ':') > 0) { - list($name, $value) = explode(':', $header, 2); - $this->setHeader($name, $value); - } - } - - // crop the body if content-length is present - if ($this->getHeader(self::CONTENT_LENGTH) !== false ) { - $length = (int) $this->getHeader(self::CONTENT_LENGTH); - $body = substr($body, 0, $length); - } - - $this->setBody($body); - return $this; - } -} diff --git a/library/Zend/Queue/Stomp/FrameInterface.php b/library/Zend/Queue/Stomp/FrameInterface.php deleted file mode 100644 index a9ba302b5b..0000000000 --- a/library/Zend/Queue/Stomp/FrameInterface.php +++ /dev/null @@ -1,154 +0,0 @@ -getFileObject('segments.gen', false); - - $format = $genFile->readInt(); - if ($format != (int)0xFFFFFFFE) { - throw new Zend_Search_Lucene_Exception('Wrong segments.gen file format'); - } - - $gen1 = $genFile->readLong(); - $gen2 = $genFile->readLong(); - - if ($gen1 == $gen2) { - return $gen1; - } - - usleep(self::GENERATION_RETRIEVE_PAUSE * 1000); - } - - // All passes are failed - throw new Zend_Search_Lucene_Exception('Index is under processing now'); - } catch (Zend_Search_Lucene_Exception $e) { - if (strpos($e->getMessage(), 'is not readable') !== false) { - try { - // Try to open old style segments file - $segmentsFile = $directory->getFileObject('segments', false); - - // It's pre-2.1 index - return 0; - } catch (Zend_Search_Lucene_Exception $e) { - if (strpos($e->getMessage(), 'is not readable') !== false) { - return -1; - } else { - throw new Zend_Search_Lucene_Exception($e->getMessage(), $e->getCode(), $e); - } - } - } else { - throw new Zend_Search_Lucene_Exception($e->getMessage(), $e->getCode(), $e); - } - } - - return -1; - } - - /** - * Get generation number associated with this index instance - * - * The same generation number in pair with document number or query string - * guarantees to give the same result while index retrieving. - * So it may be used for search result caching. - * - * @return integer - */ - public function getGeneration() - { - return $this->_generation; - } - - - /** - * Get segments file name - * - * @param integer $generation - * @return string - */ - public static function getSegmentFileName($generation) - { - if ($generation == 0) { - return 'segments'; - } - - return 'segments_' . base_convert($generation, 10, 36); - } - - /** - * Get index format version - * - * @return integer - */ - public function getFormatVersion() - { - return $this->_formatVersion; - } - - /** - * Set index format version. - * Index is converted to this format at the nearest upfdate time - * - * @param int $formatVersion - * @throws Zend_Search_Lucene_Exception - */ - public function setFormatVersion($formatVersion) - { - if ($formatVersion != self::FORMAT_PRE_2_1 && - $formatVersion != self::FORMAT_2_1 && - $formatVersion != self::FORMAT_2_3) { - #require_once 'Zend/Search/Lucene/Exception.php'; - throw new Zend_Search_Lucene_Exception('Unsupported index format'); - } - - $this->_formatVersion = $formatVersion; - } - - /** - * Read segments file for pre-2.1 Lucene index format - * - * @throws Zend_Search_Lucene_Exception - */ - private function _readPre21SegmentsFile() - { - $segmentsFile = $this->_directory->getFileObject('segments'); - - $format = $segmentsFile->readInt(); - - if ($format != (int)0xFFFFFFFF) { - #require_once 'Zend/Search/Lucene/Exception.php'; - throw new Zend_Search_Lucene_Exception('Wrong segments file format'); - } - - // read version - $segmentsFile->readLong(); - - // read segment name counter - $segmentsFile->readInt(); - - $segments = $segmentsFile->readInt(); - - $this->_docCount = 0; - - // read segmentInfos - for ($count = 0; $count < $segments; $count++) { - $segName = $segmentsFile->readString(); - $segSize = $segmentsFile->readInt(); - $this->_docCount += $segSize; - - $this->_segmentInfos[$segName] = - new Zend_Search_Lucene_Index_SegmentInfo($this->_directory, - $segName, - $segSize); - } - - // Use 2.1 as a target version. Index will be reorganized at update time. - $this->_formatVersion = self::FORMAT_2_1; - } - - /** - * Read segments file - * - * @throws Zend_Search_Lucene_Exception - */ - private function _readSegmentsFile() - { - $segmentsFile = $this->_directory->getFileObject(self::getSegmentFileName($this->_generation)); - - $format = $segmentsFile->readInt(); - - if ($format == (int)0xFFFFFFFC) { - $this->_formatVersion = self::FORMAT_2_3; - } else if ($format == (int)0xFFFFFFFD) { - $this->_formatVersion = self::FORMAT_2_1; - } else { - #require_once 'Zend/Search/Lucene/Exception.php'; - throw new Zend_Search_Lucene_Exception('Unsupported segments file format'); - } - - // read version - $segmentsFile->readLong(); - - // read segment name counter - $segmentsFile->readInt(); - - $segments = $segmentsFile->readInt(); - - $this->_docCount = 0; - - // read segmentInfos - for ($count = 0; $count < $segments; $count++) { - $segName = $segmentsFile->readString(); - $segSize = $segmentsFile->readInt(); - - // 2.1+ specific properties - $delGen = $segmentsFile->readLong(); - - if ($this->_formatVersion == self::FORMAT_2_3) { - $docStoreOffset = $segmentsFile->readInt(); - - if ($docStoreOffset != (int)0xFFFFFFFF) { - $docStoreSegment = $segmentsFile->readString(); - $docStoreIsCompoundFile = $segmentsFile->readByte(); - - $docStoreOptions = array('offset' => $docStoreOffset, - 'segment' => $docStoreSegment, - 'isCompound' => ($docStoreIsCompoundFile == 1)); - } else { - $docStoreOptions = null; - } - } else { - $docStoreOptions = null; - } - - $hasSingleNormFile = $segmentsFile->readByte(); - $numField = $segmentsFile->readInt(); - - $normGens = array(); - if ($numField != (int)0xFFFFFFFF) { - for ($count1 = 0; $count1 < $numField; $count1++) { - $normGens[] = $segmentsFile->readLong(); - } - - #require_once 'Zend/Search/Lucene/Exception.php'; - throw new Zend_Search_Lucene_Exception('Separate norm files are not supported. Optimize index to use it with Zend_Search_Lucene.'); - } - - $isCompoundByte = $segmentsFile->readByte(); - - if ($isCompoundByte == 0xFF) { - // The segment is not a compound file - $isCompound = false; - } else if ($isCompoundByte == 0x00) { - // The status is unknown - $isCompound = null; - } else if ($isCompoundByte == 0x01) { - // The segment is a compound file - $isCompound = true; - } - - $this->_docCount += $segSize; - - $this->_segmentInfos[$segName] = - new Zend_Search_Lucene_Index_SegmentInfo($this->_directory, - $segName, - $segSize, - $delGen, - $docStoreOptions, - $hasSingleNormFile, - $isCompound); - } - } - - /** - * Opens the index. - * - * IndexReader constructor needs Directory as a parameter. It should be - * a string with a path to the index folder or a Directory object. - * - * @param Zend_Search_Lucene_Storage_Directory_Filesystem|string $directory - * @throws Zend_Search_Lucene_Exception - */ - public function __construct($directory = null, $create = false) - { - if ($directory === null) { - #require_once 'Zend/Search/Lucene/Exception.php'; - throw new Zend_Search_Exception('No index directory specified'); - } - - if (is_string($directory)) { - #require_once 'Zend/Search/Lucene/Storage/Directory/Filesystem.php'; - $this->_directory = new Zend_Search_Lucene_Storage_Directory_Filesystem($directory); - $this->_closeDirOnExit = true; - } else { - $this->_directory = $directory; - $this->_closeDirOnExit = false; - } - - $this->_segmentInfos = array(); - - // Mark index as "under processing" to prevent other processes from premature index cleaning - Zend_Search_Lucene_LockManager::obtainReadLock($this->_directory); - - $this->_generation = self::getActualGeneration($this->_directory); - - if ($create) { - #require_once 'Zend/Search/Lucene/Exception.php'; - try { - Zend_Search_Lucene_LockManager::obtainWriteLock($this->_directory); - } catch (Zend_Search_Lucene_Exception $e) { - Zend_Search_Lucene_LockManager::releaseReadLock($this->_directory); - - if (strpos($e->getMessage(), 'Can\'t obtain exclusive index lock') === false) { - throw new Zend_Search_Lucene_Exception($e->getMessage(), $e->getCode(), $e); - } else { - throw new Zend_Search_Lucene_Exception('Can\'t create index. It\'s under processing now', 0, $e); - } - } - - if ($this->_generation == -1) { - // Directory doesn't contain existing index, start from 1 - $this->_generation = 1; - $nameCounter = 0; - } else { - // Directory contains existing index - $segmentsFile = $this->_directory->getFileObject(self::getSegmentFileName($this->_generation)); - $segmentsFile->seek(12); // 12 = 4 (int, file format marker) + 8 (long, index version) - - $nameCounter = $segmentsFile->readInt(); - $this->_generation++; - } - - #require_once 'Zend/Search/Lucene/Index/Writer.php'; - Zend_Search_Lucene_Index_Writer::createIndex($this->_directory, $this->_generation, $nameCounter); - - Zend_Search_Lucene_LockManager::releaseWriteLock($this->_directory); - } - - if ($this->_generation == -1) { - #require_once 'Zend/Search/Lucene/Exception.php'; - throw new Zend_Search_Lucene_Exception('Index doesn\'t exists in the specified directory.'); - } else if ($this->_generation == 0) { - $this->_readPre21SegmentsFile(); - } else { - $this->_readSegmentsFile(); - } - } - - /** - * Close current index and free resources - */ - private function _close() - { - if ($this->_closed) { - // index is already closed and resources are cleaned up - return; - } - - $this->commit(); - - // Release "under processing" flag - Zend_Search_Lucene_LockManager::releaseReadLock($this->_directory); - - if ($this->_closeDirOnExit) { - $this->_directory->close(); - } - - $this->_directory = null; - $this->_writer = null; - $this->_segmentInfos = null; - - $this->_closed = true; - } - - /** - * Add reference to the index object - * - * @internal - */ - public function addReference() - { - $this->_refCount++; - } - - /** - * Remove reference from the index object - * - * When reference count becomes zero, index is closed and resources are cleaned up - * - * @internal - */ - public function removeReference() - { - $this->_refCount--; - - if ($this->_refCount == 0) { - $this->_close(); - } - } - - /** - * Object destructor - */ - public function __destruct() - { - $this->_close(); - } - - /** - * Returns an instance of Zend_Search_Lucene_Index_Writer for the index - * - * @return Zend_Search_Lucene_Index_Writer - */ - private function _getIndexWriter() - { - if ($this->_writer === null) { - #require_once 'Zend/Search/Lucene/Index/Writer.php'; - $this->_writer = new Zend_Search_Lucene_Index_Writer($this->_directory, - $this->_segmentInfos, - $this->_formatVersion); - } - - return $this->_writer; - } - - - /** - * Returns the Zend_Search_Lucene_Storage_Directory instance for this index. - * - * @return Zend_Search_Lucene_Storage_Directory - */ - public function getDirectory() - { - return $this->_directory; - } - - - /** - * Returns the total number of documents in this index (including deleted documents). - * - * @return integer - */ - public function count() - { - return $this->_docCount; - } - - /** - * Returns one greater than the largest possible document number. - * This may be used to, e.g., determine how big to allocate a structure which will have - * an element for every document number in an index. - * - * @return integer - */ - public function maxDoc() - { - return $this->count(); - } - - /** - * Returns the total number of non-deleted documents in this index. - * - * @return integer - */ - public function numDocs() - { - $numDocs = 0; - - foreach ($this->_segmentInfos as $segmentInfo) { - $numDocs += $segmentInfo->numDocs(); - } - - return $numDocs; - } - - /** - * Checks, that document is deleted - * - * @param integer $id - * @return boolean - * @throws Zend_Search_Lucene_Exception Exception is thrown if $id is out of the range - */ - public function isDeleted($id) - { - $this->commit(); - - if ($id >= $this->_docCount) { - #require_once 'Zend/Search/Lucene/Exception.php'; - throw new Zend_Search_Lucene_Exception('Document id is out of the range.'); - } - - $segmentStartId = 0; - foreach ($this->_segmentInfos as $segmentInfo) { - if ($segmentStartId + $segmentInfo->count() > $id) { - break; - } - - $segmentStartId += $segmentInfo->count(); - } - - return $segmentInfo->isDeleted($id - $segmentStartId); - } - - /** - * Set default search field. - * - * Null means, that search is performed through all fields by default - * - * Default value is null - * - * @param string $fieldName - */ - public static function setDefaultSearchField($fieldName) - { - self::$_defaultSearchField = $fieldName; - } - - /** - * Get default search field. - * - * Null means, that search is performed through all fields by default - * - * @return string - */ - public static function getDefaultSearchField() - { - return self::$_defaultSearchField; - } - - /** - * Set result set limit. - * - * 0 (default) means no limit - * - * @param integer $limit - */ - public static function setResultSetLimit($limit) - { - self::$_resultSetLimit = $limit; - } - - /** - * Get result set limit. - * - * 0 means no limit - * - * @return integer - */ - public static function getResultSetLimit() - { - return self::$_resultSetLimit; - } - - /** - * Set terms per query limit. - * - * 0 means no limit - * - * @param integer $limit - */ - public static function setTermsPerQueryLimit($limit) - { - self::$_termsPerQueryLimit = $limit; - } - - /** - * Get result set limit. - * - * 0 (default) means no limit - * - * @return integer - */ - public static function getTermsPerQueryLimit() - { - return self::$_termsPerQueryLimit; - } - - /** - * Retrieve index maxBufferedDocs option - * - * maxBufferedDocs is a minimal number of documents required before - * the buffered in-memory documents are written into a new Segment - * - * Default value is 10 - * - * @return integer - */ - public function getMaxBufferedDocs() - { - return $this->_getIndexWriter()->maxBufferedDocs; - } - - /** - * Set index maxBufferedDocs option - * - * maxBufferedDocs is a minimal number of documents required before - * the buffered in-memory documents are written into a new Segment - * - * Default value is 10 - * - * @param integer $maxBufferedDocs - */ - public function setMaxBufferedDocs($maxBufferedDocs) - { - $this->_getIndexWriter()->maxBufferedDocs = $maxBufferedDocs; - } - - /** - * Retrieve index maxMergeDocs option - * - * maxMergeDocs is a largest number of documents ever merged by addDocument(). - * Small values (e.g., less than 10,000) are best for interactive indexing, - * as this limits the length of pauses while indexing to a few seconds. - * Larger values are best for batched indexing and speedier searches. - * - * Default value is PHP_INT_MAX - * - * @return integer - */ - public function getMaxMergeDocs() - { - return $this->_getIndexWriter()->maxMergeDocs; - } - - /** - * Set index maxMergeDocs option - * - * maxMergeDocs is a largest number of documents ever merged by addDocument(). - * Small values (e.g., less than 10,000) are best for interactive indexing, - * as this limits the length of pauses while indexing to a few seconds. - * Larger values are best for batched indexing and speedier searches. - * - * Default value is PHP_INT_MAX - * - * @param integer $maxMergeDocs - */ - public function setMaxMergeDocs($maxMergeDocs) - { - $this->_getIndexWriter()->maxMergeDocs = $maxMergeDocs; - } - - /** - * Retrieve index mergeFactor option - * - * mergeFactor determines how often segment indices are merged by addDocument(). - * With smaller values, less RAM is used while indexing, - * and searches on unoptimized indices are faster, - * but indexing speed is slower. - * With larger values, more RAM is used during indexing, - * and while searches on unoptimized indices are slower, - * indexing is faster. - * Thus larger values (> 10) are best for batch index creation, - * and smaller values (< 10) for indices that are interactively maintained. - * - * Default value is 10 - * - * @return integer - */ - public function getMergeFactor() - { - return $this->_getIndexWriter()->mergeFactor; - } - - /** - * Set index mergeFactor option - * - * mergeFactor determines how often segment indices are merged by addDocument(). - * With smaller values, less RAM is used while indexing, - * and searches on unoptimized indices are faster, - * but indexing speed is slower. - * With larger values, more RAM is used during indexing, - * and while searches on unoptimized indices are slower, - * indexing is faster. - * Thus larger values (> 10) are best for batch index creation, - * and smaller values (< 10) for indices that are interactively maintained. - * - * Default value is 10 - * - * @param integer $maxMergeDocs - */ - public function setMergeFactor($mergeFactor) - { - $this->_getIndexWriter()->mergeFactor = $mergeFactor; - } - - /** - * Performs a query against the index and returns an array - * of Zend_Search_Lucene_Search_QueryHit objects. - * Input is a string or Zend_Search_Lucene_Search_Query. - * - * @param Zend_Search_Lucene_Search_QueryParser|string $query - * @return array Zend_Search_Lucene_Search_QueryHit - * @throws Zend_Search_Lucene_Exception - */ - public function find($query) - { - if (is_string($query)) { - #require_once 'Zend/Search/Lucene/Search/QueryParser.php'; - - $query = Zend_Search_Lucene_Search_QueryParser::parse($query); - } - - if (!$query instanceof Zend_Search_Lucene_Search_Query) { - #require_once 'Zend/Search/Lucene/Exception.php'; - throw new Zend_Search_Lucene_Exception('Query must be a string or Zend_Search_Lucene_Search_Query object'); - } - - $this->commit(); - - $hits = array(); - $scores = array(); - $ids = array(); - - $query = $query->rewrite($this)->optimize($this); - - $query->execute($this); - - $topScore = 0; - - /** Zend_Search_Lucene_Search_QueryHit */ - #require_once 'Zend/Search/Lucene/Search/QueryHit.php'; - - foreach ($query->matchedDocs() as $id => $num) { - $docScore = $query->score($id, $this); - if( $docScore != 0 ) { - $hit = new Zend_Search_Lucene_Search_QueryHit($this); - $hit->id = $id; - $hit->score = $docScore; - - $hits[] = $hit; - $ids[] = $id; - $scores[] = $docScore; - - if ($docScore > $topScore) { - $topScore = $docScore; - } - } - - if (self::$_resultSetLimit != 0 && count($hits) >= self::$_resultSetLimit) { - break; - } - } - - if (count($hits) == 0) { - // skip sorting, which may cause a error on empty index - return array(); - } - - if ($topScore > 1) { - foreach ($hits as $hit) { - $hit->score /= $topScore; - } - } - - if (func_num_args() == 1) { - // sort by scores - array_multisort($scores, SORT_DESC, SORT_NUMERIC, - $ids, SORT_ASC, SORT_NUMERIC, - $hits); - } else { - // sort by given field names - - $argList = func_get_args(); - $fieldNames = $this->getFieldNames(); - $sortArgs = array(); - - // PHP 5.3 now expects all arguments to array_multisort be passed by - // reference (if it's invoked through call_user_func_array()); - // since constants can't be passed by reference, create some placeholder variables. - $sortReg = SORT_REGULAR; - $sortAsc = SORT_ASC; - $sortNum = SORT_NUMERIC; - - $sortFieldValues = array(); - - #require_once 'Zend/Search/Lucene/Exception.php'; - for ($count = 1; $count < count($argList); $count++) { - $fieldName = $argList[$count]; - - if (!is_string($fieldName)) { - throw new Zend_Search_Lucene_Exception('Field name must be a string.'); - } - - if (strtolower($fieldName) == 'score') { - $sortArgs[] = &$scores; - } else { - if (!in_array($fieldName, $fieldNames)) { - throw new Zend_Search_Lucene_Exception('Wrong field name.'); - } - - if (!isset($sortFieldValues[$fieldName])) { - $valuesArray = array(); - foreach ($hits as $hit) { - try { - $value = $hit->getDocument()->getFieldValue($fieldName); - } catch (Zend_Search_Lucene_Exception $e) { - if (strpos($e->getMessage(), 'not found') === false) { - throw new Zend_Search_Lucene_Exception($e->getMessage(), $e->getCode(), $e); - } else { - $value = null; - } - } - - $valuesArray[] = $value; - } - - // Collect loaded values in $sortFieldValues - // Required for PHP 5.3 which translates references into values when source - // variable is destroyed - $sortFieldValues[$fieldName] = $valuesArray; - } - - $sortArgs[] = &$sortFieldValues[$fieldName]; - } - - if ($count + 1 < count($argList) && is_integer($argList[$count+1])) { - $count++; - $sortArgs[] = &$argList[$count]; - - if ($count + 1 < count($argList) && is_integer($argList[$count+1])) { - $count++; - $sortArgs[] = &$argList[$count]; - } else { - if ($argList[$count] == SORT_ASC || $argList[$count] == SORT_DESC) { - $sortArgs[] = &$sortReg; - } else { - $sortArgs[] = &$sortAsc; - } - } - } else { - $sortArgs[] = &$sortAsc; - $sortArgs[] = &$sortReg; - } - } - - // Sort by id's if values are equal - $sortArgs[] = &$ids; - $sortArgs[] = &$sortAsc; - $sortArgs[] = &$sortNum; - - // Array to be sorted - $sortArgs[] = &$hits; - - // Do sort - call_user_func_array('array_multisort', $sortArgs); - } - - return $hits; - } - - - /** - * Returns a list of all unique field names that exist in this index. - * - * @param boolean $indexed - * @return array - */ - public function getFieldNames($indexed = false) - { - $result = array(); - foreach( $this->_segmentInfos as $segmentInfo ) { - $result = array_merge($result, $segmentInfo->getFields($indexed)); - } - return $result; - } - - - /** - * Returns a Zend_Search_Lucene_Document object for the document - * number $id in this index. - * - * @param integer|Zend_Search_Lucene_Search_QueryHit $id - * @return Zend_Search_Lucene_Document - * @throws Zend_Search_Lucene_Exception Exception is thrown if $id is out of the range - */ - public function getDocument($id) - { - if ($id instanceof Zend_Search_Lucene_Search_QueryHit) { - /* @var $id Zend_Search_Lucene_Search_QueryHit */ - $id = $id->id; - } - - if ($id >= $this->_docCount) { - #require_once 'Zend/Search/Lucene/Exception.php'; - throw new Zend_Search_Lucene_Exception('Document id is out of the range.'); - } - - $segmentStartId = 0; - foreach ($this->_segmentInfos as $segmentInfo) { - if ($segmentStartId + $segmentInfo->count() > $id) { - break; - } - - $segmentStartId += $segmentInfo->count(); - } - - $fdxFile = $segmentInfo->openCompoundFile('.fdx'); - $fdxFile->seek(($id-$segmentStartId)*8, SEEK_CUR); - $fieldValuesPosition = $fdxFile->readLong(); - - $fdtFile = $segmentInfo->openCompoundFile('.fdt'); - $fdtFile->seek($fieldValuesPosition, SEEK_CUR); - $fieldCount = $fdtFile->readVInt(); - - $doc = new Zend_Search_Lucene_Document(); - for ($count = 0; $count < $fieldCount; $count++) { - $fieldNum = $fdtFile->readVInt(); - $bits = $fdtFile->readByte(); - - $fieldInfo = $segmentInfo->getField($fieldNum); - - if (!($bits & 2)) { // Text data - $field = new Zend_Search_Lucene_Field($fieldInfo->name, - $fdtFile->readString(), - 'UTF-8', - true, - $fieldInfo->isIndexed, - $bits & 1 ); - } else { // Binary data - $field = new Zend_Search_Lucene_Field($fieldInfo->name, - $fdtFile->readBinary(), - '', - true, - $fieldInfo->isIndexed, - $bits & 1, - true ); - } - - $doc->addField($field); - } - - return $doc; - } - - - /** - * Returns true if index contain documents with specified term. - * - * Is used for query optimization. - * - * @param Zend_Search_Lucene_Index_Term $term - * @return boolean - */ - public function hasTerm(Zend_Search_Lucene_Index_Term $term) - { - foreach ($this->_segmentInfos as $segInfo) { - if ($segInfo->getTermInfo($term) !== null) { - return true; - } - } - - return false; - } - - /** - * Returns IDs of all documents containing term. - * - * @param Zend_Search_Lucene_Index_Term $term - * @param Zend_Search_Lucene_Index_DocsFilter|null $docsFilter - * @return array - */ - public function termDocs(Zend_Search_Lucene_Index_Term $term, $docsFilter = null) - { - $subResults = array(); - $segmentStartDocId = 0; - - foreach ($this->_segmentInfos as $segmentInfo) { - $subResults[] = $segmentInfo->termDocs($term, $segmentStartDocId, $docsFilter); - - $segmentStartDocId += $segmentInfo->count(); - } - - if (count($subResults) == 0) { - return array(); - } else if (count($subResults) == 1) { - // Index is optimized (only one segment) - // Do not perform array reindexing - return reset($subResults); - } else { - $result = call_user_func_array('array_merge', $subResults); - } - - return $result; - } - - /** - * Returns documents filter for all documents containing term. - * - * It performs the same operation as termDocs, but return result as - * Zend_Search_Lucene_Index_DocsFilter object - * - * @param Zend_Search_Lucene_Index_Term $term - * @param Zend_Search_Lucene_Index_DocsFilter|null $docsFilter - * @return Zend_Search_Lucene_Index_DocsFilter - */ - public function termDocsFilter(Zend_Search_Lucene_Index_Term $term, $docsFilter = null) - { - $segmentStartDocId = 0; - $result = new Zend_Search_Lucene_Index_DocsFilter(); - - foreach ($this->_segmentInfos as $segmentInfo) { - $subResults[] = $segmentInfo->termDocs($term, $segmentStartDocId, $docsFilter); - - $segmentStartDocId += $segmentInfo->count(); - } - - if (count($subResults) == 0) { - return array(); - } else if (count($subResults) == 1) { - // Index is optimized (only one segment) - // Do not perform array reindexing - return reset($subResults); - } else { - $result = call_user_func_array('array_merge', $subResults); - } - - return $result; - } - - - /** - * Returns an array of all term freqs. - * Result array structure: array(docId => freq, ...) - * - * @param Zend_Search_Lucene_Index_Term $term - * @param Zend_Search_Lucene_Index_DocsFilter|null $docsFilter - * @return integer - */ - public function termFreqs(Zend_Search_Lucene_Index_Term $term, $docsFilter = null) - { - $result = array(); - $segmentStartDocId = 0; - foreach ($this->_segmentInfos as $segmentInfo) { - $result += $segmentInfo->termFreqs($term, $segmentStartDocId, $docsFilter); - - $segmentStartDocId += $segmentInfo->count(); - } - - return $result; - } - - /** - * Returns an array of all term positions in the documents. - * Result array structure: array(docId => array(pos1, pos2, ...), ...) - * - * @param Zend_Search_Lucene_Index_Term $term - * @param Zend_Search_Lucene_Index_DocsFilter|null $docsFilter - * @return array - */ - public function termPositions(Zend_Search_Lucene_Index_Term $term, $docsFilter = null) - { - $result = array(); - $segmentStartDocId = 0; - foreach ($this->_segmentInfos as $segmentInfo) { - $result += $segmentInfo->termPositions($term, $segmentStartDocId, $docsFilter); - - $segmentStartDocId += $segmentInfo->count(); - } - - return $result; - } - - - /** - * Returns the number of documents in this index containing the $term. - * - * @param Zend_Search_Lucene_Index_Term $term - * @return integer - */ - public function docFreq(Zend_Search_Lucene_Index_Term $term) - { - $result = 0; - foreach ($this->_segmentInfos as $segInfo) { - $termInfo = $segInfo->getTermInfo($term); - if ($termInfo !== null) { - $result += $termInfo->docFreq; - } - } - - return $result; - } - - - /** - * Retrive similarity used by index reader - * - * @return Zend_Search_Lucene_Search_Similarity - */ - public function getSimilarity() - { - /** Zend_Search_Lucene_Search_Similarity */ - #require_once 'Zend/Search/Lucene/Search/Similarity.php'; - - return Zend_Search_Lucene_Search_Similarity::getDefault(); - } - - - /** - * Returns a normalization factor for "field, document" pair. - * - * @param integer $id - * @param string $fieldName - * @return float - */ - public function norm($id, $fieldName) - { - if ($id >= $this->_docCount) { - return null; - } - - $segmentStartId = 0; - foreach ($this->_segmentInfos as $segInfo) { - if ($segmentStartId + $segInfo->count() > $id) { - break; - } - - $segmentStartId += $segInfo->count(); - } - - if ($segInfo->isDeleted($id - $segmentStartId)) { - return 0; - } - - return $segInfo->norm($id - $segmentStartId, $fieldName); - } - - /** - * Returns true if any documents have been deleted from this index. - * - * @return boolean - */ - public function hasDeletions() - { - foreach ($this->_segmentInfos as $segmentInfo) { - if ($segmentInfo->hasDeletions()) { - return true; - } - } - - return false; - } - - - /** - * Deletes a document from the index. - * $id is an internal document id - * - * @param integer|Zend_Search_Lucene_Search_QueryHit $id - * @throws Zend_Search_Lucene_Exception - */ - public function delete($id) - { - if ($id instanceof Zend_Search_Lucene_Search_QueryHit) { - /* @var $id Zend_Search_Lucene_Search_QueryHit */ - $id = $id->id; - } - - if ($id >= $this->_docCount) { - #require_once 'Zend/Search/Lucene/Exception.php'; - throw new Zend_Search_Lucene_Exception('Document id is out of the range.'); - } - - $segmentStartId = 0; - foreach ($this->_segmentInfos as $segmentInfo) { - if ($segmentStartId + $segmentInfo->count() > $id) { - break; - } - - $segmentStartId += $segmentInfo->count(); - } - $segmentInfo->delete($id - $segmentStartId); - - $this->_hasChanges = true; - } - - - - /** - * Adds a document to this index. - * - * @param Zend_Search_Lucene_Document $document - */ - public function addDocument(Zend_Search_Lucene_Document $document) - { - $this->_getIndexWriter()->addDocument($document); - $this->_docCount++; - - $this->_hasChanges = true; - } - - - /** - * Update document counter - */ - private function _updateDocCount() - { - $this->_docCount = 0; - foreach ($this->_segmentInfos as $segInfo) { - $this->_docCount += $segInfo->count(); - } - } - - /** - * Commit changes resulting from delete() or undeleteAll() operations. - * - * @todo undeleteAll processing. - */ - public function commit() - { - if ($this->_hasChanges) { - $this->_getIndexWriter()->commit(); - - $this->_updateDocCount(); - - $this->_hasChanges = false; - } - } - - - /** - * Optimize index. - * - * Merges all segments into one - */ - public function optimize() - { - // Commit changes if any changes have been made - $this->commit(); - - if (count($this->_segmentInfos) > 1 || $this->hasDeletions()) { - $this->_getIndexWriter()->optimize(); - $this->_updateDocCount(); - } - } - - - /** - * Returns an array of all terms in this index. - * - * @return array - */ - public function terms() - { - $result = array(); - - /** Zend_Search_Lucene_Index_TermsPriorityQueue */ - #require_once 'Zend/Search/Lucene/Index/TermsPriorityQueue.php'; - - $segmentInfoQueue = new Zend_Search_Lucene_Index_TermsPriorityQueue(); - - foreach ($this->_segmentInfos as $segmentInfo) { - $segmentInfo->resetTermsStream(); - - // Skip "empty" segments - if ($segmentInfo->currentTerm() !== null) { - $segmentInfoQueue->put($segmentInfo); - } - } - - while (($segmentInfo = $segmentInfoQueue->pop()) !== null) { - if ($segmentInfoQueue->top() === null || - $segmentInfoQueue->top()->currentTerm()->key() != - $segmentInfo->currentTerm()->key()) { - // We got new term - $result[] = $segmentInfo->currentTerm(); - } - - if ($segmentInfo->nextTerm() !== null) { - // Put segment back into the priority queue - $segmentInfoQueue->put($segmentInfo); - } - } - - return $result; - } - - - /** - * Terms stream priority queue object - * - * @var Zend_Search_Lucene_TermStreamsPriorityQueue - */ - private $_termsStream = null; - - /** - * Reset terms stream. - */ - public function resetTermsStream() - { - if ($this->_termsStream === null) { - /** Zend_Search_Lucene_TermStreamsPriorityQueue */ - #require_once 'Zend/Search/Lucene/TermStreamsPriorityQueue.php'; - - $this->_termsStream = new Zend_Search_Lucene_TermStreamsPriorityQueue($this->_segmentInfos); - } else { - $this->_termsStream->resetTermsStream(); - } - } - - /** - * Skip terms stream up to the specified term preffix. - * - * Prefix contains fully specified field info and portion of searched term - * - * @param Zend_Search_Lucene_Index_Term $prefix - */ - public function skipTo(Zend_Search_Lucene_Index_Term $prefix) - { - $this->_termsStream->skipTo($prefix); - } - - /** - * Scans terms dictionary and returns next term - * - * @return Zend_Search_Lucene_Index_Term|null - */ - public function nextTerm() - { - return $this->_termsStream->nextTerm(); - } - - /** - * Returns term in current position - * - * @return Zend_Search_Lucene_Index_Term|null - */ - public function currentTerm() - { - return $this->_termsStream->currentTerm(); - } - - /** - * Close terms stream - * - * Should be used for resources clean up if stream is not read up to the end - */ - public function closeTermsStream() - { - $this->_termsStream->closeTermsStream(); - $this->_termsStream = null; - } - - - /************************************************************************* - @todo UNIMPLEMENTED - *************************************************************************/ - /** - * Undeletes all documents currently marked as deleted in this index. - * - * @todo Implementation - */ - public function undeleteAll() - {} -} diff --git a/library/Zend/Search/Lucene/Analysis/Analyzer.php b/library/Zend/Search/Lucene/Analysis/Analyzer.php deleted file mode 100644 index 8c1914ed7b..0000000000 --- a/library/Zend/Search/Lucene/Analysis/Analyzer.php +++ /dev/null @@ -1,175 +0,0 @@ -setInput($data, $encoding); - - $tokenList = array(); - while (($nextToken = $this->nextToken()) !== null) { - $tokenList[] = $nextToken; - } - - return $tokenList; - } - - - /** - * Tokenization stream API - * Set input - * - * @param string $data - */ - public function setInput($data, $encoding = '') - { - $this->_input = $data; - $this->_encoding = $encoding; - $this->reset(); - } - - /** - * Reset token stream - */ - abstract public function reset(); - - /** - * Tokenization stream API - * Get next token - * Returns null at the end of stream - * - * Tokens are returned in UTF-8 (internal Zend_Search_Lucene encoding) - * - * @return Zend_Search_Lucene_Analysis_Token|null - */ - abstract public function nextToken(); - - - - - /** - * Set the default Analyzer implementation used by indexing code. - * - * @param Zend_Search_Lucene_Analysis_Analyzer $similarity - */ - public static function setDefault(Zend_Search_Lucene_Analysis_Analyzer $analyzer) - { - self::$_defaultImpl = $analyzer; - } - - - /** - * Return the default Analyzer implementation used by indexing code. - * - * @return Zend_Search_Lucene_Analysis_Analyzer - */ - public static function getDefault() - { - /** Zend_Search_Lucene_Analysis_Analyzer_Common_Text_CaseInsensitive */ - #require_once 'Zend/Search/Lucene/Analysis/Analyzer/Common/Text/CaseInsensitive.php'; - - if (!self::$_defaultImpl instanceof Zend_Search_Lucene_Analysis_Analyzer) { - self::$_defaultImpl = new Zend_Search_Lucene_Analysis_Analyzer_Common_Text_CaseInsensitive(); - } - - return self::$_defaultImpl; - } -} - diff --git a/library/Zend/Search/Lucene/Analysis/Analyzer/Common.php b/library/Zend/Search/Lucene/Analysis/Analyzer/Common.php deleted file mode 100644 index 7074bd63dc..0000000000 --- a/library/Zend/Search/Lucene/Analysis/Analyzer/Common.php +++ /dev/null @@ -1,94 +0,0 @@ -_filters[] = $filter; - } - - /** - * Apply filters to the token. Can return null when the token was removed. - * - * @param Zend_Search_Lucene_Analysis_Token $token - * @return Zend_Search_Lucene_Analysis_Token - */ - public function normalize(Zend_Search_Lucene_Analysis_Token $token) - { - foreach ($this->_filters as $filter) { - $token = $filter->normalize($token); - - // resulting token can be null if the filter removes it - if ($token === null) { - return null; - } - } - - return $token; - } -} - diff --git a/library/Zend/Search/Lucene/Analysis/Analyzer/Common/Text.php b/library/Zend/Search/Lucene/Analysis/Analyzer/Common/Text.php deleted file mode 100644 index 73b95f9ff9..0000000000 --- a/library/Zend/Search/Lucene/Analysis/Analyzer/Common/Text.php +++ /dev/null @@ -1,96 +0,0 @@ -_position = 0; - - if ($this->_input === null) { - return; - } - - // convert input into ascii - if (PHP_OS != 'AIX') { - $this->_input = iconv($this->_encoding, 'ASCII//TRANSLIT', $this->_input); - } - $this->_encoding = 'ASCII'; - } - - /** - * Tokenization stream API - * Get next token - * Returns null at the end of stream - * - * @return Zend_Search_Lucene_Analysis_Token|null - */ - public function nextToken() - { - if ($this->_input === null) { - return null; - } - - - do { - if (! preg_match('/[a-zA-Z]+/', $this->_input, $match, PREG_OFFSET_CAPTURE, $this->_position)) { - // It covers both cases a) there are no matches (preg_match(...) === 0) - // b) error occured (preg_match(...) === FALSE) - return null; - } - - $str = $match[0][0]; - $pos = $match[0][1]; - $endpos = $pos + strlen($str); - - $this->_position = $endpos; - - $token = $this->normalize(new Zend_Search_Lucene_Analysis_Token($str, $pos, $endpos)); - } while ($token === null); // try again if token is skipped - - return $token; - } -} - diff --git a/library/Zend/Search/Lucene/Analysis/Analyzer/Common/Text/CaseInsensitive.php b/library/Zend/Search/Lucene/Analysis/Analyzer/Common/Text/CaseInsensitive.php deleted file mode 100644 index eaaac57e00..0000000000 --- a/library/Zend/Search/Lucene/Analysis/Analyzer/Common/Text/CaseInsensitive.php +++ /dev/null @@ -1,47 +0,0 @@ -addFilter(new Zend_Search_Lucene_Analysis_TokenFilter_LowerCase()); - } -} - diff --git a/library/Zend/Search/Lucene/Analysis/Analyzer/Common/TextNum.php b/library/Zend/Search/Lucene/Analysis/Analyzer/Common/TextNum.php deleted file mode 100644 index 642a20cf22..0000000000 --- a/library/Zend/Search/Lucene/Analysis/Analyzer/Common/TextNum.php +++ /dev/null @@ -1,95 +0,0 @@ -_position = 0; - - if ($this->_input === null) { - return; - } - - // convert input into ascii - if (PHP_OS != 'AIX') { - $this->_input = iconv($this->_encoding, 'ASCII//TRANSLIT', $this->_input); - } - $this->_encoding = 'ASCII'; - } - - /** - * Tokenization stream API - * Get next token - * Returns null at the end of stream - * - * @return Zend_Search_Lucene_Analysis_Token|null - */ - public function nextToken() - { - if ($this->_input === null) { - return null; - } - - do { - if (! preg_match('/[a-zA-Z0-9]+/', $this->_input, $match, PREG_OFFSET_CAPTURE, $this->_position)) { - // It covers both cases a) there are no matches (preg_match(...) === 0) - // b) error occured (preg_match(...) === FALSE) - return null; - } - - $str = $match[0][0]; - $pos = $match[0][1]; - $endpos = $pos + strlen($str); - - $this->_position = $endpos; - - $token = $this->normalize(new Zend_Search_Lucene_Analysis_Token($str, $pos, $endpos)); - } while ($token === null); // try again if token is skipped - - return $token; - } -} - diff --git a/library/Zend/Search/Lucene/Analysis/Analyzer/Common/TextNum/CaseInsensitive.php b/library/Zend/Search/Lucene/Analysis/Analyzer/Common/TextNum/CaseInsensitive.php deleted file mode 100644 index dec27e79c4..0000000000 --- a/library/Zend/Search/Lucene/Analysis/Analyzer/Common/TextNum/CaseInsensitive.php +++ /dev/null @@ -1,47 +0,0 @@ -addFilter(new Zend_Search_Lucene_Analysis_TokenFilter_LowerCase()); - } -} - diff --git a/library/Zend/Search/Lucene/Analysis/Analyzer/Common/Utf8.php b/library/Zend/Search/Lucene/Analysis/Analyzer/Common/Utf8.php deleted file mode 100644 index 7927257ccb..0000000000 --- a/library/Zend/Search/Lucene/Analysis/Analyzer/Common/Utf8.php +++ /dev/null @@ -1,126 +0,0 @@ -_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'; - } - } - - /** - * Tokenization stream API - * Get next token - * Returns null at the end of stream - * - * @return Zend_Search_Lucene_Analysis_Token|null - */ - public function nextToken() - { - if ($this->_input === null) { - return null; - } - - do { - if (! preg_match('/[\p{L}]+/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; - } -} - diff --git a/library/Zend/Search/Lucene/Analysis/Analyzer/Common/Utf8/CaseInsensitive.php b/library/Zend/Search/Lucene/Analysis/Analyzer/Common/Utf8/CaseInsensitive.php deleted file mode 100644 index d025a3a0e8..0000000000 --- a/library/Zend/Search/Lucene/Analysis/Analyzer/Common/Utf8/CaseInsensitive.php +++ /dev/null @@ -1,49 +0,0 @@ -addFilter(new Zend_Search_Lucene_Analysis_TokenFilter_LowerCaseUtf8()); - } -} - diff --git a/library/Zend/Search/Lucene/Analysis/Analyzer/Common/Utf8Num.php b/library/Zend/Search/Lucene/Analysis/Analyzer/Common/Utf8Num.php deleted file mode 100644 index 32dc483f9e..0000000000 --- a/library/Zend/Search/Lucene/Analysis/Analyzer/Common/Utf8Num.php +++ /dev/null @@ -1,126 +0,0 @@ -_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'; - } - } - - /** - * Tokenization stream API - * Get next token - * Returns null at the end of stream - * - * @return Zend_Search_Lucene_Analysis_Token|null - */ - 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; - } -} - diff --git a/library/Zend/Search/Lucene/Analysis/Analyzer/Common/Utf8Num/CaseInsensitive.php b/library/Zend/Search/Lucene/Analysis/Analyzer/Common/Utf8Num/CaseInsensitive.php deleted file mode 100644 index 4fe433fe40..0000000000 --- a/library/Zend/Search/Lucene/Analysis/Analyzer/Common/Utf8Num/CaseInsensitive.php +++ /dev/null @@ -1,49 +0,0 @@ -addFilter(new Zend_Search_Lucene_Analysis_TokenFilter_LowerCaseUtf8()); - } -} - diff --git a/library/Zend/Search/Lucene/Analysis/Token.php b/library/Zend/Search/Lucene/Analysis/Token.php deleted file mode 100644 index dc900d16c6..0000000000 --- a/library/Zend/Search/Lucene/Analysis/Token.php +++ /dev/null @@ -1,166 +0,0 @@ -_termText = $text; - $this->_startOffset = $start; - $this->_endOffset = $end; - - $this->_positionIncrement = 1; - } - - - /** - * positionIncrement setter - * - * @param integer $positionIncrement - */ - public function setPositionIncrement($positionIncrement) - { - $this->_positionIncrement = $positionIncrement; - } - - /** - * Returns the position increment of this Token. - * - * @return integer - */ - public function getPositionIncrement() - { - return $this->_positionIncrement; - } - - /** - * Returns the Token's term text. - * - * @return string - */ - public function getTermText() - { - return $this->_termText; - } - - /** - * Sets the Token's term text. - * - * @param string $text - * @return this - */ - public function setTermText($text) - { - $this->_termText = $text; - return $this; - } - - /** - * Returns this Token's starting offset, the position of the first character - * corresponding to this token in the source text. - * - * Note: - * The difference between getEndOffset() and getStartOffset() may not be equal - * to strlen(Zend_Search_Lucene_Analysis_Token::getTermText()), as the term text may have been altered - * by a stemmer or some other filter. - * - * @return integer - */ - public function getStartOffset() - { - return $this->_startOffset; - } - - /** - * Returns this Token's ending offset, one greater than the position of the - * last character corresponding to this token in the source text. - * - * @return integer - */ - public function getEndOffset() - { - return $this->_endOffset; - } -} - diff --git a/library/Zend/Search/Lucene/Analysis/TokenFilter.php b/library/Zend/Search/Lucene/Analysis/TokenFilter.php deleted file mode 100644 index c1b1c825a3..0000000000 --- a/library/Zend/Search/Lucene/Analysis/TokenFilter.php +++ /dev/null @@ -1,47 +0,0 @@ -setTermText(strtolower($srcToken->getTermText())); - return $srcToken; - } -} - diff --git a/library/Zend/Search/Lucene/Analysis/TokenFilter/LowerCaseUtf8.php b/library/Zend/Search/Lucene/Analysis/TokenFilter/LowerCaseUtf8.php deleted file mode 100644 index 4bb027fc9b..0000000000 --- a/library/Zend/Search/Lucene/Analysis/TokenFilter/LowerCaseUtf8.php +++ /dev/null @@ -1,64 +0,0 @@ -setTermText(mb_strtolower($srcToken->getTermText(), 'UTF-8')); - return $srcToken; - } -} - diff --git a/library/Zend/Search/Lucene/Analysis/TokenFilter/ShortWords.php b/library/Zend/Search/Lucene/Analysis/TokenFilter/ShortWords.php deleted file mode 100644 index 4a37454894..0000000000 --- a/library/Zend/Search/Lucene/Analysis/TokenFilter/ShortWords.php +++ /dev/null @@ -1,69 +0,0 @@ -length = $length; - } - - /** - * Normalize Token or remove it (if null is returned) - * - * @param Zend_Search_Lucene_Analysis_Token $srcToken - * @return Zend_Search_Lucene_Analysis_Token - */ - public function normalize(Zend_Search_Lucene_Analysis_Token $srcToken) { - if (strlen($srcToken->getTermText()) < $this->length) { - return null; - } else { - return $srcToken; - } - } -} - diff --git a/library/Zend/Search/Lucene/Analysis/TokenFilter/StopWords.php b/library/Zend/Search/Lucene/Analysis/TokenFilter/StopWords.php deleted file mode 100644 index 2d03aafd46..0000000000 --- a/library/Zend/Search/Lucene/Analysis/TokenFilter/StopWords.php +++ /dev/null @@ -1,101 +0,0 @@ - 1, 'an' => '1'); - * - * We do recommend to provide all words in lowercase and concatenate this class after the lowercase filter. - * - * @category Zend - * @package Zend_Search_Lucene - * @subpackage Analysis - * @copyright Copyright (c) 2005-2015 Zend Technologies USA Inc. (http://www.zend.com) - * @license http://framework.zend.com/license/new-bsd New BSD License - */ - -class Zend_Search_Lucene_Analysis_TokenFilter_StopWords extends Zend_Search_Lucene_Analysis_TokenFilter -{ - /** - * Stop Words - * @var array - */ - private $_stopSet; - - /** - * Constructs new instance of this filter. - * - * @param array $stopwords array (set) of words that will be filtered out - */ - public function __construct($stopwords = array()) { - $this->_stopSet = array_flip($stopwords); - } - - /** - * Normalize Token or remove it (if null is returned) - * - * @param Zend_Search_Lucene_Analysis_Token $srcToken - * @return Zend_Search_Lucene_Analysis_Token - */ - public function normalize(Zend_Search_Lucene_Analysis_Token $srcToken) { - if (array_key_exists($srcToken->getTermText(), $this->_stopSet)) { - return null; - } else { - return $srcToken; - } - } - - /** - * Fills stopwords set from a text file. Each line contains one stopword, lines with '#' in the first - * column are ignored (as comments). - * - * You can call this method one or more times. New stopwords are always added to current set. - * - * @param string $filepath full path for text file with stopwords - * @throws Zend_Search_Exception When the file doesn`t exists or is not readable. - */ - public function loadFromFile($filepath = null) { - if (! $filepath || ! file_exists($filepath)) { - #require_once 'Zend/Search/Lucene/Exception.php'; - throw new Zend_Search_Lucene_Exception('You have to provide valid file path'); - } - $fd = fopen($filepath, "r"); - if (! $fd) { - #require_once 'Zend/Search/Lucene/Exception.php'; - throw new Zend_Search_Lucene_Exception('Cannot open file ' . $filepath); - } - while (!feof ($fd)) { - $buffer = trim(fgets($fd)); - if (strlen($buffer) > 0 && $buffer[0] != '#') { - $this->_stopSet[$buffer] = 1; - } - } - if (!fclose($fd)) { - #require_once 'Zend/Search/Lucene/Exception.php'; - throw new Zend_Search_Lucene_Exception('Cannot close file ' . $filepath); - } - } -} - diff --git a/library/Zend/Search/Lucene/Document.php b/library/Zend/Search/Lucene/Document.php deleted file mode 100644 index 4a24288295..0000000000 --- a/library/Zend/Search/Lucene/Document.php +++ /dev/null @@ -1,131 +0,0 @@ -getFieldValue($offset); - } - - - /** - * Add a field object to this document. - * - * @param Zend_Search_Lucene_Field $field - * @return Zend_Search_Lucene_Document - */ - public function addField(Zend_Search_Lucene_Field $field) - { - $this->_fields[$field->name] = $field; - - return $this; - } - - - /** - * Return an array with the names of the fields in this document. - * - * @return array - */ - public function getFieldNames() - { - return array_keys($this->_fields); - } - - - /** - * Returns Zend_Search_Lucene_Field object for a named field in this document. - * - * @param string $fieldName - * @return Zend_Search_Lucene_Field - */ - public function getField($fieldName) - { - if (!array_key_exists($fieldName, $this->_fields)) { - #require_once 'Zend/Search/Lucene/Exception.php'; - throw new Zend_Search_Lucene_Exception("Field name \"$fieldName\" not found in document."); - } - return $this->_fields[$fieldName]; - } - - - /** - * Returns the string value of a named field in this document. - * - * @see __get() - * @return string - */ - public function getFieldValue($fieldName) - { - return $this->getField($fieldName)->value; - } - - /** - * Returns the string value of a named field in UTF-8 encoding. - * - * @see __get() - * @return string - */ - public function getFieldUtf8Value($fieldName) - { - return $this->getField($fieldName)->getUtf8Value(); - } -} diff --git a/library/Zend/Search/Lucene/Document/Docx.php b/library/Zend/Search/Lucene/Document/Docx.php deleted file mode 100644 index 88a00d19d0..0000000000 --- a/library/Zend/Search/Lucene/Document/Docx.php +++ /dev/null @@ -1,154 +0,0 @@ -open($fileName); - - // Read relations and search for officeDocument - $relationsXml = $package->getFromName('_rels/.rels'); - if ($relationsXml === false) { - #require_once 'Zend/Search/Lucene/Exception.php'; - throw new Zend_Search_Lucene_Exception('Invalid archive or corrupted .docx file.'); - } - $relations = Zend_Xml_Security::scan($relationsXml); - foreach($relations->Relationship as $rel) { - if ($rel ["Type"] == Zend_Search_Lucene_Document_OpenXml::SCHEMA_OFFICEDOCUMENT) { - // Found office document! Read in contents... - $contents = Zend_Xml_Security::scan($package->getFromName( - $this->absoluteZipPath(dirname($rel['Target']) - . '/' - . basename($rel['Target'])) - )); - - $contents->registerXPathNamespace('w', Zend_Search_Lucene_Document_Docx::SCHEMA_WORDPROCESSINGML); - $paragraphs = $contents->xpath('//w:body/w:p'); - - foreach ($paragraphs as $paragraph) { - $runs = $paragraph->xpath('.//w:r/*[name() = "w:t" or name() = "w:br"]'); - - if ($runs === false) { - // Paragraph doesn't contain any text or breaks - continue; - } - - foreach ($runs as $run) { - if ($run->getName() == 'br') { - // Break element - $documentBody[] = ' '; - } else { - $documentBody[] = (string)$run; - } - } - - // Add space after each paragraph. So they are not bound together. - $documentBody[] = ' '; - } - - break; - } - } - - // Read core properties - $coreProperties = $this->extractMetaData($package); - - // Close file - $package->close(); - - // Store filename - $this->addField(Zend_Search_Lucene_Field::Text('filename', $fileName, 'UTF-8')); - - // Store contents - if ($storeContent) { - $this->addField(Zend_Search_Lucene_Field::Text('body', implode('', $documentBody), 'UTF-8')); - } else { - $this->addField(Zend_Search_Lucene_Field::UnStored('body', implode('', $documentBody), 'UTF-8')); - } - - // Store meta data properties - foreach ($coreProperties as $key => $value) { - $this->addField(Zend_Search_Lucene_Field::Text($key, $value, 'UTF-8')); - } - - // Store title (if not present in meta data) - if (! isset($coreProperties['title'])) { - $this->addField(Zend_Search_Lucene_Field::Text('title', $fileName, 'UTF-8')); - } - } - - /** - * Load Docx document from a file - * - * @param string $fileName - * @param boolean $storeContent - * @return Zend_Search_Lucene_Document_Docx - * @throws Zend_Search_Lucene_Document_Exception - */ - public static function loadDocxFile($fileName, $storeContent = false) { - if (!is_readable($fileName)) { - #require_once 'Zend/Search/Lucene/Document/Exception.php'; - throw new Zend_Search_Lucene_Document_Exception('Provided file \'' . $fileName . '\' is not readable.'); - } - - return new Zend_Search_Lucene_Document_Docx($fileName, $storeContent); - } -} diff --git a/library/Zend/Search/Lucene/Document/Exception.php b/library/Zend/Search/Lucene/Document/Exception.php deleted file mode 100644 index a617cde1bc..0000000000 --- a/library/Zend/Search/Lucene/Document/Exception.php +++ /dev/null @@ -1,37 +0,0 @@ -_doc = new DOMDocument(); - $this->_doc->substituteEntities = true; - - if ($isFile) { - $htmlData = file_get_contents($data); - } else { - $htmlData = $data; - } - @$this->_doc->loadHTML($htmlData); - - if ($this->_doc->encoding === null) { - // Document encoding is not recognized - - /** @todo improve HTML vs HTML fragment recognition */ - if (preg_match('/]*>/i', $htmlData, $matches, PREG_OFFSET_CAPTURE)) { - // It's an HTML document - // Add additional HEAD section and recognize document - $htmlTagOffset = $matches[0][1] + strlen($matches[0][0]); - - @$this->_doc->loadHTML(iconv($defaultEncoding, 'UTF-8//IGNORE', substr($htmlData, 0, $htmlTagOffset)) - . '' - . iconv($defaultEncoding, 'UTF-8//IGNORE', substr($htmlData, $htmlTagOffset))); - - // Remove additional HEAD section - $xpath = new DOMXPath($this->_doc); - $head = $xpath->query('/html/head')->item(0); - $head->parentNode->removeChild($head); - } else { - // It's an HTML fragment - @$this->_doc->loadHTML('' - . iconv($defaultEncoding, 'UTF-8//IGNORE', $htmlData) - . ''); - } - - } - /** @todo Add correction of wrong HTML encoding recognition processing - * The case is: - * Content-type HTTP-EQUIV meta tag is presented, but ISO-8859-5 encoding is actually used, - * even $this->_doc->encoding demonstrates another recognized encoding - */ - - $xpath = new DOMXPath($this->_doc); - - $docTitle = ''; - $titleNodes = $xpath->query('/html/head/title'); - foreach ($titleNodes as $titleNode) { - // title should always have only one entry, but we process all nodeset entries - $docTitle .= $titleNode->nodeValue . ' '; - } - $this->addField(Zend_Search_Lucene_Field::Text('title', $docTitle, 'UTF-8')); - - $metaNodes = $xpath->query('/html/head/meta[@name]'); - foreach ($metaNodes as $metaNode) { - $this->addField(Zend_Search_Lucene_Field::Text($metaNode->getAttribute('name'), - $metaNode->getAttribute('content'), - 'UTF-8')); - } - - $docBody = ''; - $bodyNodes = $xpath->query('/html/body'); - foreach ($bodyNodes as $bodyNode) { - // body should always have only one entry, but we process all nodeset entries - $this->_retrieveNodeText($bodyNode, $docBody); - } - if ($storeContent) { - $this->addField(Zend_Search_Lucene_Field::Text('body', $docBody, 'UTF-8')); - } else { - $this->addField(Zend_Search_Lucene_Field::UnStored('body', $docBody, 'UTF-8')); - } - - $linkNodes = $this->_doc->getElementsByTagName('a'); - foreach ($linkNodes as $linkNode) { - if (($href = $linkNode->getAttribute('href')) != '' && - (!self::$_excludeNoFollowLinks || strtolower($linkNode->getAttribute('rel')) != 'nofollow' ) - ) { - $this->_links[] = $href; - } - } - $linkNodes = $this->_doc->getElementsByTagName('area'); - foreach ($linkNodes as $linkNode) { - if (($href = $linkNode->getAttribute('href')) != '' && - (!self::$_excludeNoFollowLinks || strtolower($linkNode->getAttribute('rel')) != 'nofollow' ) - ) { - $this->_links[] = $href; - } - } - $this->_links = array_unique($this->_links); - - $linkNodes = $xpath->query('/html/head/link'); - foreach ($linkNodes as $linkNode) { - if (($href = $linkNode->getAttribute('href')) != '') { - $this->_headerLinks[] = $href; - } - } - $this->_headerLinks = array_unique($this->_headerLinks); - } - - /** - * Set exclude nofollow links flag - * - * @param boolean $newValue - */ - public static function setExcludeNoFollowLinks($newValue) - { - self::$_excludeNoFollowLinks = $newValue; - } - - /** - * Get exclude nofollow links flag - * - * @return boolean - */ - public static function getExcludeNoFollowLinks() - { - return self::$_excludeNoFollowLinks; - } - - /** - * Get node text - * - * We should exclude scripts, which may be not included into comment tags, CDATA sections, - * - * @param DOMNode $node - * @param string &$text - */ - private function _retrieveNodeText(DOMNode $node, &$text) - { - if ($node->nodeType == XML_TEXT_NODE) { - $text .= $node->nodeValue; - if(!in_array($node->parentNode->tagName, $this->_inlineTags)) { - $text .= ' '; - } - } else if ($node->nodeType == XML_ELEMENT_NODE && $node->nodeName != 'script') { - foreach ($node->childNodes as $childNode) { - $this->_retrieveNodeText($childNode, $text); - } - } - } - - /** - * Get document HREF links - * - * @return array - */ - public function getLinks() - { - return $this->_links; - } - - /** - * Get document header links - * - * @return array - */ - public function getHeaderLinks() - { - return $this->_headerLinks; - } - - /** - * Load HTML document from a string - * - * @param string $data - * @param boolean $storeContent - * @param string $defaultEncoding HTML encoding, is used if it's not specified using Content-type HTTP-EQUIV meta tag. - * @return Zend_Search_Lucene_Document_Html - */ - public static function loadHTML($data, $storeContent = false, $defaultEncoding = '') - { - return new Zend_Search_Lucene_Document_Html($data, false, $storeContent, $defaultEncoding); - } - - /** - * Load HTML document from a file - * - * @param string $file - * @param boolean $storeContent - * @param string $defaultEncoding HTML encoding, is used if it's not specified using Content-type HTTP-EQUIV meta tag. - * @return Zend_Search_Lucene_Document_Html - */ - public static function loadHTMLFile($file, $storeContent = false, $defaultEncoding = '') - { - return new Zend_Search_Lucene_Document_Html($file, true, $storeContent, $defaultEncoding); - } - - - /** - * Highlight text in text node - * - * @param DOMText $node - * @param array $wordsToHighlight - * @param callback $callback Callback method, used to transform (highlighting) text. - * @param array $params Array of additionall callback parameters (first non-optional parameter is a text to transform) - * @throws Zend_Search_Lucene_Exception - */ - protected function _highlightTextNode(DOMText $node, $wordsToHighlight, $callback, $params) - { - /** Zend_Search_Lucene_Analysis_Analyzer */ - #require_once 'Zend/Search/Lucene/Analysis/Analyzer.php'; - - $analyzer = Zend_Search_Lucene_Analysis_Analyzer::getDefault(); - $analyzer->setInput($node->nodeValue, 'UTF-8'); - - $matchedTokens = array(); - - while (($token = $analyzer->nextToken()) !== null) { - if (isset($wordsToHighlight[$token->getTermText()])) { - $matchedTokens[] = $token; - } - } - - if (count($matchedTokens) == 0) { - return; - } - - $matchedTokens = array_reverse($matchedTokens); - - foreach ($matchedTokens as $token) { - // Cut text after matched token - $node->splitText($token->getEndOffset()); - - // Cut matched node - $matchedWordNode = $node->splitText($token->getStartOffset()); - - // Retrieve HTML string representation for highlihted word - $fullCallbackparamsList = $params; - array_unshift($fullCallbackparamsList, $matchedWordNode->nodeValue); - $highlightedWordNodeSetHtml = call_user_func_array($callback, $fullCallbackparamsList); - - // Transform HTML string to a DOM representation and automatically transform retrieved string - // into valid XHTML (It's automatically done by loadHTML() method) - $highlightedWordNodeSetDomDocument = new DOMDocument('1.0', 'UTF-8'); - $success = @$highlightedWordNodeSetDomDocument-> - loadHTML('' - . $highlightedWordNodeSetHtml - . ''); - if (!$success) { - #require_once 'Zend/Search/Lucene/Exception.php'; - throw new Zend_Search_Lucene_Exception("Error occured while loading highlighted text fragment: '$highlightedWordNodeSetHtml'."); - } - $highlightedWordNodeSetXpath = new DOMXPath($highlightedWordNodeSetDomDocument); - $highlightedWordNodeSet = $highlightedWordNodeSetXpath->query('/html/body')->item(0)->childNodes; - - for ($count = 0; $count < $highlightedWordNodeSet->length; $count++) { - $nodeToImport = $highlightedWordNodeSet->item($count); - $node->parentNode->insertBefore($this->_doc->importNode($nodeToImport, true /* deep copy */), - $matchedWordNode); - } - - $node->parentNode->removeChild($matchedWordNode); - } - } - - - /** - * highlight words in content of the specified node - * - * @param DOMNode $contextNode - * @param array $wordsToHighlight - * @param callback $callback Callback method, used to transform (highlighting) text. - * @param array $params Array of additionall callback parameters (first non-optional parameter is a text to transform) - */ - protected function _highlightNodeRecursive(DOMNode $contextNode, $wordsToHighlight, $callback, $params) - { - $textNodes = array(); - - if (!$contextNode->hasChildNodes()) { - return; - } - - foreach ($contextNode->childNodes as $childNode) { - if ($childNode->nodeType == XML_TEXT_NODE) { - // process node later to leave childNodes structure untouched - $textNodes[] = $childNode; - } else { - // Process node if it's not a script node - if ($childNode->nodeName != 'script') { - $this->_highlightNodeRecursive($childNode, $wordsToHighlight, $callback, $params); - } - } - } - - foreach ($textNodes as $textNode) { - $this->_highlightTextNode($textNode, $wordsToHighlight, $callback, $params); - } - } - - /** - * Standard callback method used to highlight words. - * - * @param string $stringToHighlight - * @return string - * @internal - */ - public function applyColour($stringToHighlight, $colour) - { - return '' . $stringToHighlight . ''; - } - - /** - * Highlight text with specified color - * - * @param string|array $words - * @param string $colour - * @return string - */ - public function highlight($words, $colour = '#66ffff') - { - return $this->highlightExtended($words, array($this, 'applyColour'), array($colour)); - } - - - - /** - * Highlight text using specified View helper or callback function. - * - * @param string|array $words Words to highlight. Words could be organized using the array or string. - * @param callback $callback Callback method, used to transform (highlighting) text. - * @param array $params Array of additionall callback parameters passed through into it - * (first non-optional parameter is an HTML fragment for highlighting) - * @return string - * @throws Zend_Search_Lucene_Exception - */ - public function highlightExtended($words, $callback, $params = array()) - { - /** Zend_Search_Lucene_Analysis_Analyzer */ - #require_once 'Zend/Search/Lucene/Analysis/Analyzer.php'; - - if (!is_array($words)) { - $words = array($words); - } - - $wordsToHighlightList = array(); - $analyzer = Zend_Search_Lucene_Analysis_Analyzer::getDefault(); - foreach ($words as $wordString) { - $wordsToHighlightList[] = $analyzer->tokenize($wordString); - } - $wordsToHighlight = call_user_func_array('array_merge', $wordsToHighlightList); - - if (count($wordsToHighlight) == 0) { - return $this->_doc->saveHTML(); - } - - $wordsToHighlightFlipped = array(); - foreach ($wordsToHighlight as $id => $token) { - $wordsToHighlightFlipped[$token->getTermText()] = $id; - } - - if (!is_callable($callback)) { - #require_once 'Zend/Search/Lucene/Exception.php'; - throw new Zend_Search_Lucene_Exception('$viewHelper parameter must be a View Helper name, View Helper object or callback.'); - } - - $xpath = new DOMXPath($this->_doc); - - $matchedNodes = $xpath->query("/html/body"); - foreach ($matchedNodes as $matchedNode) { - $this->_highlightNodeRecursive($matchedNode, $wordsToHighlightFlipped, $callback, $params); - } - } - - - /** - * Get HTML - * - * @return string - */ - public function getHTML() - { - return $this->_doc->saveHTML(); - } - - /** - * Get HTML body - * - * @return string - */ - public function getHtmlBody() - { - $xpath = new DOMXPath($this->_doc); - $bodyNodes = $xpath->query('/html/body')->item(0)->childNodes; - - $outputFragments = array(); - for ($count = 0; $count < $bodyNodes->length; $count++) { - $outputFragments[] = $this->_doc->saveXML($bodyNodes->item($count)); - } - - return implode($outputFragments); - } -} - diff --git a/library/Zend/Search/Lucene/Document/OpenXml.php b/library/Zend/Search/Lucene/Document/OpenXml.php deleted file mode 100644 index 41716ddf1c..0000000000 --- a/library/Zend/Search/Lucene/Document/OpenXml.php +++ /dev/null @@ -1,131 +0,0 @@ -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 = Zend_Xml_Security::scan( - $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; - } - - /** - * Determine absolute zip path - * - * @param string $path - * @return string - */ - protected function absoluteZipPath($path) { - $path = str_replace(array('/', '\\'), DIRECTORY_SEPARATOR, $path); - $parts = array_filter(explode(DIRECTORY_SEPARATOR, $path), 'strlen'); - $absolutes = array(); - foreach ($parts as $part) { - if ('.' == $part) continue; - if ('..' == $part) { - array_pop($absolutes); - } else { - $absolutes[] = $part; - } - } - return implode('/', $absolutes); - } -} diff --git a/library/Zend/Search/Lucene/Document/Pptx.php b/library/Zend/Search/Lucene/Document/Pptx.php deleted file mode 100644 index 9a6ce43678..0000000000 --- a/library/Zend/Search/Lucene/Document/Pptx.php +++ /dev/null @@ -1,202 +0,0 @@ -open($fileName); - - // Read relations and search for officeDocument - $relationsXml = $package->getFromName('_rels/.rels'); - if ($relationsXml === false) { - #require_once 'Zend/Search/Lucene/Exception.php'; - throw new Zend_Search_Lucene_Exception('Invalid archive or corrupted .pptx file.'); - } - $relations = Zend_Xml_Security::scan($relationsXml); - foreach ($relations->Relationship as $rel) { - if ($rel["Type"] == Zend_Search_Lucene_Document_OpenXml::SCHEMA_OFFICEDOCUMENT) { - // Found office document! Search for slides... - $slideRelations = Zend_Xml_Security::scan($package->getFromName( $this->absoluteZipPath(dirname($rel["Target"]) . "/_rels/" . basename($rel["Target"]) . ".rels")) ); - foreach ($slideRelations->Relationship as $slideRel) { - if ($slideRel["Type"] == Zend_Search_Lucene_Document_Pptx::SCHEMA_SLIDERELATION) { - // Found slide! - $slides[ str_replace( 'rId', '', (string)$slideRel["Id"] ) ] = Zend_Xml_Security::scan( - $package->getFromName( $this->absoluteZipPath(dirname($rel["Target"]) . "/" . dirname($slideRel["Target"]) . "/" . basename($slideRel["Target"])) ) - ); - - // Search for slide notes - $slideNotesRelations = Zend_Xml_Security::scan($package->getFromName( $this->absoluteZipPath(dirname($rel["Target"]) . "/" . dirname($slideRel["Target"]) . "/_rels/" . basename($slideRel["Target"]) . ".rels")) ); - foreach ($slideNotesRelations->Relationship as $slideNoteRel) { - if ($slideNoteRel["Type"] == Zend_Search_Lucene_Document_Pptx::SCHEMA_SLIDENOTESRELATION) { - // Found slide notes! - $slideNotes[ str_replace( 'rId', '', (string)$slideRel["Id"] ) ] = Zend_Xml_Security::scan( - $package->getFromName( $this->absoluteZipPath(dirname($rel["Target"]) . "/" . dirname($slideRel["Target"]) . "/" . dirname($slideNoteRel["Target"]) . "/" . basename($slideNoteRel["Target"])) ) - ); - - break; - } - } - } - } - - break; - } - } - - // Sort slides - ksort($slides); - ksort($slideNotes); - - // Extract contents from slides - foreach ($slides as $slideKey => $slide) { - // Register namespaces - $slide->registerXPathNamespace("p", Zend_Search_Lucene_Document_Pptx::SCHEMA_PRESENTATIONML); - $slide->registerXPathNamespace("a", Zend_Search_Lucene_Document_Pptx::SCHEMA_DRAWINGML); - - // Fetch all text - $textElements = $slide->xpath('//a:t'); - foreach ($textElements as $textElement) { - $documentBody[] = (string)$textElement; - } - - // Extract contents from slide notes - if (isset($slideNotes[$slideKey])) { - // Fetch slide note - $slideNote = $slideNotes[$slideKey]; - - // Register namespaces - $slideNote->registerXPathNamespace("p", Zend_Search_Lucene_Document_Pptx::SCHEMA_PRESENTATIONML); - $slideNote->registerXPathNamespace("a", Zend_Search_Lucene_Document_Pptx::SCHEMA_DRAWINGML); - - // Fetch all text - $textElements = $slideNote->xpath('//a:t'); - foreach ($textElements as $textElement) { - $documentBody[] = (string)$textElement; - } - } - } - - // Read core properties - $coreProperties = $this->extractMetaData($package); - - // Close file - $package->close(); - - // Store filename - $this->addField(Zend_Search_Lucene_Field::Text('filename', $fileName, 'UTF-8')); - - // Store contents - if ($storeContent) { - $this->addField(Zend_Search_Lucene_Field::Text('body', implode(' ', $documentBody), 'UTF-8')); - } else { - $this->addField(Zend_Search_Lucene_Field::UnStored('body', implode(' ', $documentBody), 'UTF-8')); - } - - // Store meta data properties - foreach ($coreProperties as $key => $value) - { - $this->addField(Zend_Search_Lucene_Field::Text($key, $value, 'UTF-8')); - } - - // Store title (if not present in meta data) - if (!isset($coreProperties['title'])) - { - $this->addField(Zend_Search_Lucene_Field::Text('title', $fileName, 'UTF-8')); - } - } - - /** - * Load Pptx document from a file - * - * @param string $fileName - * @param boolean $storeContent - * @return Zend_Search_Lucene_Document_Pptx - */ - public static function loadPptxFile($fileName, $storeContent = false) - { - return new Zend_Search_Lucene_Document_Pptx($fileName, $storeContent); - } -} diff --git a/library/Zend/Search/Lucene/Document/Xlsx.php b/library/Zend/Search/Lucene/Document/Xlsx.php deleted file mode 100644 index 110194964d..0000000000 --- a/library/Zend/Search/Lucene/Document/Xlsx.php +++ /dev/null @@ -1,266 +0,0 @@ -open($fileName); - - // Read relations and search for officeDocument - $relationsXml = $package->getFromName('_rels/.rels'); - if ($relationsXml === false) { - #require_once 'Zend/Search/Lucene/Exception.php'; - throw new Zend_Search_Lucene_Exception('Invalid archive or corrupted .xlsx file.'); - } - $relations = Zend_Xml_Security::scan($relationsXml); - foreach ($relations->Relationship as $rel) { - if ($rel["Type"] == Zend_Search_Lucene_Document_OpenXml::SCHEMA_OFFICEDOCUMENT) { - // Found office document! Read relations for workbook... - $workbookRelations = Zend_Xml_Security::scan($package->getFromName( $this->absoluteZipPath(dirname($rel["Target"]) . "/_rels/" . basename($rel["Target"]) . ".rels")) ); - $workbookRelations->registerXPathNamespace("rel", Zend_Search_Lucene_Document_OpenXml::SCHEMA_RELATIONSHIP); - - // Read shared strings - $sharedStringsPath = $workbookRelations->xpath("rel:Relationship[@Type='" . Zend_Search_Lucene_Document_Xlsx::SCHEMA_SHAREDSTRINGS . "']"); - $sharedStringsPath = (string)$sharedStringsPath[0]['Target']; - $xmlStrings = Zend_Xml_Security::scan($package->getFromName( $this->absoluteZipPath(dirname($rel["Target"]) . "/" . $sharedStringsPath)) ); - if (isset($xmlStrings) && isset($xmlStrings->si)) { - foreach ($xmlStrings->si as $val) { - if (isset($val->t)) { - $sharedStrings[] = (string)$val->t; - } elseif (isset($val->r)) { - $sharedStrings[] = $this->_parseRichText($val); - } - } - } - - // Loop relations for workbook and extract worksheets... - foreach ($workbookRelations->Relationship as $workbookRelation) { - if ($workbookRelation["Type"] == Zend_Search_Lucene_Document_Xlsx::SCHEMA_WORKSHEETRELATION) { - $worksheets[ str_replace( 'rId', '', (string)$workbookRelation["Id"]) ] = Zend_Xml_Security::scan( - $package->getFromName( $this->absoluteZipPath(dirname($rel["Target"]) . "/" . dirname($workbookRelation["Target"]) . "/" . basename($workbookRelation["Target"])) ) - ); - } - } - - break; - } - } - - // Sort worksheets - ksort($worksheets); - - // Extract contents from worksheets - foreach ($worksheets as $sheetKey => $worksheet) { - foreach ($worksheet->sheetData->row as $row) { - foreach ($row->c as $c) { - // Determine data type - $dataType = (string)$c["t"]; - switch ($dataType) { - case "s": - // Value is a shared string - if ((string)$c->v != '') { - $value = $sharedStrings[intval($c->v)]; - } else { - $value = ''; - } - - break; - - case "b": - // Value is boolean - $value = (string)$c->v; - if ($value == '0') { - $value = false; - } else if ($value == '1') { - $value = true; - } else { - $value = (bool)$c->v; - } - - break; - - case "inlineStr": - // Value is rich text inline - $value = $this->_parseRichText($c->is); - - break; - - case "e": - // Value is an error message - if ((string)$c->v != '') { - $value = (string)$c->v; - } else { - $value = ''; - } - - break; - - default: - // Value is a string - $value = (string)$c->v; - - // Check for numeric values - if (is_numeric($value) && $dataType != 's') { - if ($value == (int)$value) $value = (int)$value; - elseif ($value == (float)$value) $value = (float)$value; - elseif ($value == (double)$value) $value = (double)$value; - } - } - - $documentBody[] = $value; - } - } - } - - // Read core properties - $coreProperties = $this->extractMetaData($package); - - // Close file - $package->close(); - - // Store filename - $this->addField(Zend_Search_Lucene_Field::Text('filename', $fileName, 'UTF-8')); - - // Store contents - if ($storeContent) { - $this->addField(Zend_Search_Lucene_Field::Text('body', implode(' ', $documentBody), 'UTF-8')); - } else { - $this->addField(Zend_Search_Lucene_Field::UnStored('body', implode(' ', $documentBody), 'UTF-8')); - } - - // Store meta data properties - foreach ($coreProperties as $key => $value) - { - $this->addField(Zend_Search_Lucene_Field::Text($key, $value, 'UTF-8')); - } - - // Store title (if not present in meta data) - if (!isset($coreProperties['title'])) - { - $this->addField(Zend_Search_Lucene_Field::Text('title', $fileName, 'UTF-8')); - } - } - - /** - * Parse rich text XML - * - * @param SimpleXMLElement $is - * @return string - */ - 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); - } - - /** - * Load Xlsx document from a file - * - * @param string $fileName - * @param boolean $storeContent - * @return Zend_Search_Lucene_Document_Xlsx - */ - public static function loadXlsxFile($fileName, $storeContent = false) - { - return new Zend_Search_Lucene_Document_Xlsx($fileName, $storeContent); - } -} diff --git a/library/Zend/Search/Lucene/Exception.php b/library/Zend/Search/Lucene/Exception.php deleted file mode 100644 index f8ba91001a..0000000000 --- a/library/Zend/Search/Lucene/Exception.php +++ /dev/null @@ -1,37 +0,0 @@ - targetState - * - * @var array - */ - private $_rules = array(); - - /** - * List of entry actions - * Each action executes when entering the state - * - * [state] => action - * - * @var array - */ - private $_entryActions = array(); - - /** - * List of exit actions - * Each action executes when exiting the state - * - * [state] => action - * - * @var array - */ - private $_exitActions = array(); - - /** - * List of input actions - * Each action executes when entering the state - * - * [state][input] => action - * - * @var array - */ - private $_inputActions = array(); - - /** - * List of input actions - * Each action executes when entering the state - * - * [state1][state2] => action - * - * @var array - */ - private $_transitionActions = array(); - - /** - * Finite State machine constructor - * - * $states is an array of integers or strings with a list of possible machine states - * constructor treats fist list element as a sturt state (assignes it to $_current state). - * It may be reassigned by setState() call. - * States list may be empty and can be extended later by addState() or addStates() calls. - * - * $inputAphabet is the same as $states, but represents input alphabet - * it also may be extended later by addInputSymbols() or addInputSymbol() calls. - * - * $rules parameter describes FSM transitions and has a structure: - * array( array(sourseState, input, targetState[, inputAction]), - * array(sourseState, input, targetState[, inputAction]), - * array(sourseState, input, targetState[, inputAction]), - * ... - * ) - * Rules also can be added later by addRules() and addRule() calls. - * - * FSM actions are very flexible and may be defined by addEntryAction(), addExitAction(), - * addInputAction() and addTransitionAction() calls. - * - * @param array $states - * @param array $inputAphabet - * @param array $rules - */ - public function __construct($states = array(), $inputAphabet = array(), $rules = array()) - { - $this->addStates($states); - $this->addInputSymbols($inputAphabet); - $this->addRules($rules); - } - - /** - * Add states to the state machine - * - * @param array $states - */ - public function addStates($states) - { - foreach ($states as $state) { - $this->addState($state); - } - } - - /** - * Add state to the state machine - * - * @param integer|string $state - */ - public function addState($state) - { - $this->_states[$state] = $state; - - if ($this->_currentState === null) { - $this->_currentState = $state; - } - } - - /** - * Set FSM state. - * No any action is invoked - * - * @param integer|string $state - * @throws Zend_Search_Exception - */ - public function setState($state) - { - if (!isset($this->_states[$state])) { - #require_once 'Zend/Search/Exception.php'; - throw new Zend_Search_Exception('State \'' . $state . '\' is not on of the possible FSM states.'); - } - - $this->_currentState = $state; - } - - /** - * Get FSM state. - * - * @return integer|string $state|null - */ - public function getState() - { - return $this->_currentState; - } - - /** - * Add symbols to the input alphabet - * - * @param array $inputAphabet - */ - public function addInputSymbols($inputAphabet) - { - foreach ($inputAphabet as $inputSymbol) { - $this->addInputSymbol($inputSymbol); - } - } - - /** - * Add symbol to the input alphabet - * - * @param integer|string $inputSymbol - */ - public function addInputSymbol($inputSymbol) - { - $this->_inputAphabet[$inputSymbol] = $inputSymbol; - } - - - /** - * Add transition rules - * - * array structure: - * array( array(sourseState, input, targetState[, inputAction]), - * array(sourseState, input, targetState[, inputAction]), - * array(sourseState, input, targetState[, inputAction]), - * ... - * ) - * - * @param array $rules - */ - public function addRules($rules) - { - foreach ($rules as $rule) { - $this->addrule($rule[0], $rule[1], $rule[2], isset($rule[3])?$rule[3]:null); - } - } - - /** - * Add symbol to the input alphabet - * - * @param integer|string $sourceState - * @param integer|string $input - * @param integer|string $targetState - * @param Zend_Search_Lucene_FSMAction|null $inputAction - * @throws Zend_Search_Exception - */ - public function addRule($sourceState, $input, $targetState, $inputAction = null) - { - if (!isset($this->_states[$sourceState])) { - #require_once 'Zend/Search/Exception.php'; - throw new Zend_Search_Exception('Undefined source state (' . $sourceState . ').'); - } - if (!isset($this->_states[$targetState])) { - #require_once 'Zend/Search/Exception.php'; - throw new Zend_Search_Exception('Undefined target state (' . $targetState . ').'); - } - if (!isset($this->_inputAphabet[$input])) { - #require_once 'Zend/Search/Exception.php'; - throw new Zend_Search_Exception('Undefined input symbol (' . $input . ').'); - } - - if (!isset($this->_rules[$sourceState])) { - $this->_rules[$sourceState] = array(); - } - if (isset($this->_rules[$sourceState][$input])) { - #require_once 'Zend/Search/Exception.php'; - throw new Zend_Search_Exception('Rule for {state,input} pair (' . $sourceState . ', '. $input . ') is already defined.'); - } - - $this->_rules[$sourceState][$input] = $targetState; - - - if ($inputAction !== null) { - $this->addInputAction($sourceState, $input, $inputAction); - } - } - - - /** - * Add state entry action. - * Several entry actions are allowed. - * Action execution order is defined by addEntryAction() calls - * - * @param integer|string $state - * @param Zend_Search_Lucene_FSMAction $action - */ - public function addEntryAction($state, Zend_Search_Lucene_FSMAction $action) - { - if (!isset($this->_states[$state])) { - #require_once 'Zend/Search/Exception.php'; - throw new Zend_Search_Exception('Undefined state (' . $state. ').'); - } - - if (!isset($this->_entryActions[$state])) { - $this->_entryActions[$state] = array(); - } - - $this->_entryActions[$state][] = $action; - } - - /** - * Add state exit action. - * Several exit actions are allowed. - * Action execution order is defined by addEntryAction() calls - * - * @param integer|string $state - * @param Zend_Search_Lucene_FSMAction $action - */ - public function addExitAction($state, Zend_Search_Lucene_FSMAction $action) - { - if (!isset($this->_states[$state])) { - #require_once 'Zend/Search/Exception.php'; - throw new Zend_Search_Exception('Undefined state (' . $state. ').'); - } - - if (!isset($this->_exitActions[$state])) { - $this->_exitActions[$state] = array(); - } - - $this->_exitActions[$state][] = $action; - } - - /** - * Add input action (defined by {state, input} pair). - * Several input actions are allowed. - * Action execution order is defined by addInputAction() calls - * - * @param integer|string $state - * @param integer|string $input - * @param Zend_Search_Lucene_FSMAction $action - */ - public function addInputAction($state, $inputSymbol, Zend_Search_Lucene_FSMAction $action) - { - if (!isset($this->_states[$state])) { - #require_once 'Zend/Search/Exception.php'; - throw new Zend_Search_Exception('Undefined state (' . $state. ').'); - } - if (!isset($this->_inputAphabet[$inputSymbol])) { - #require_once 'Zend/Search/Exception.php'; - throw new Zend_Search_Exception('Undefined input symbol (' . $inputSymbol. ').'); - } - - if (!isset($this->_inputActions[$state])) { - $this->_inputActions[$state] = array(); - } - if (!isset($this->_inputActions[$state][$inputSymbol])) { - $this->_inputActions[$state][$inputSymbol] = array(); - } - - $this->_inputActions[$state][$inputSymbol][] = $action; - } - - /** - * Add transition action (defined by {state, input} pair). - * Several transition actions are allowed. - * Action execution order is defined by addTransitionAction() calls - * - * @param integer|string $sourceState - * @param integer|string $targetState - * @param Zend_Search_Lucene_FSMAction $action - */ - public function addTransitionAction($sourceState, $targetState, Zend_Search_Lucene_FSMAction $action) - { - if (!isset($this->_states[$sourceState])) { - #require_once 'Zend/Search/Exception.php'; - throw new Zend_Search_Exception('Undefined source state (' . $sourceState. ').'); - } - if (!isset($this->_states[$targetState])) { - #require_once 'Zend/Search/Exception.php'; - throw new Zend_Search_Exception('Undefined source state (' . $targetState. ').'); - } - - if (!isset($this->_transitionActions[$sourceState])) { - $this->_transitionActions[$sourceState] = array(); - } - if (!isset($this->_transitionActions[$sourceState][$targetState])) { - $this->_transitionActions[$sourceState][$targetState] = array(); - } - - $this->_transitionActions[$sourceState][$targetState][] = $action; - } - - - /** - * Process an input - * - * @param mixed $input - * @throws Zend_Search_Exception - */ - public function process($input) - { - if (!isset($this->_rules[$this->_currentState])) { - #require_once 'Zend/Search/Exception.php'; - throw new Zend_Search_Exception('There is no any rule for current state (' . $this->_currentState . ').'); - } - if (!isset($this->_rules[$this->_currentState][$input])) { - #require_once 'Zend/Search/Exception.php'; - throw new Zend_Search_Exception('There is no any rule for {current state, input} pair (' . $this->_currentState . ', ' . $input . ').'); - } - - $sourceState = $this->_currentState; - $targetState = $this->_rules[$this->_currentState][$input]; - - if ($sourceState != $targetState && isset($this->_exitActions[$sourceState])) { - foreach ($this->_exitActions[$sourceState] as $action) { - $action->doAction(); - } - } - if (isset($this->_inputActions[$sourceState]) && - isset($this->_inputActions[$sourceState][$input])) { - foreach ($this->_inputActions[$sourceState][$input] as $action) { - $action->doAction(); - } - } - - - $this->_currentState = $targetState; - - if (isset($this->_transitionActions[$sourceState]) && - isset($this->_transitionActions[$sourceState][$targetState])) { - foreach ($this->_transitionActions[$sourceState][$targetState] as $action) { - $action->doAction(); - } - } - if ($sourceState != $targetState && isset($this->_entryActions[$targetState])) { - foreach ($this->_entryActions[$targetState] as $action) { - $action->doAction(); - } - } - } - - public function reset() - { - if (count($this->_states) == 0) { - #require_once 'Zend/Search/Exception.php'; - throw new Zend_Search_Exception('There is no any state defined for FSM.'); - } - - $this->_currentState = $this->_states[0]; - } -} - diff --git a/library/Zend/Search/Lucene/FSMAction.php b/library/Zend/Search/Lucene/FSMAction.php deleted file mode 100644 index aee126320e..0000000000 --- a/library/Zend/Search/Lucene/FSMAction.php +++ /dev/null @@ -1,66 +0,0 @@ -_object = $object; - $this->_method = $method; - } - - public function doAction() - { - $methodName = $this->_method; - $this->_object->$methodName(); - } -} - diff --git a/library/Zend/Search/Lucene/Field.php b/library/Zend/Search/Lucene/Field.php deleted file mode 100644 index 2c187dcea2..0000000000 --- a/library/Zend/Search/Lucene/Field.php +++ /dev/null @@ -1,226 +0,0 @@ -name = $name; - $this->value = $value; - - if (!$isBinary) { - $this->encoding = $encoding; - $this->isTokenized = $isTokenized; - } else { - $this->encoding = ''; - $this->isTokenized = false; - } - - $this->isStored = $isStored; - $this->isIndexed = $isIndexed; - $this->isBinary = $isBinary; - - $this->storeTermVector = false; - $this->boost = 1.0; - } - - - /** - * Constructs a String-valued Field that is not tokenized, but is indexed - * and stored. Useful for non-text fields, e.g. date or url. - * - * @param string $name - * @param string $value - * @param string $encoding - * @return Zend_Search_Lucene_Field - */ - public static function keyword($name, $value, $encoding = '') - { - return new self($name, $value, $encoding, true, true, false); - } - - - /** - * Constructs a 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 - */ - public static function unIndexed($name, $value, $encoding = '') - { - return new self($name, $value, $encoding, true, false, false); - } - - - /** - * 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 - */ - public static function binary($name, $value) - { - return new self($name, $value, '', true, false, false, 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 - */ - 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, - * but that is not stored in the index. - * - * @param string $name - * @param string $value - * @param string $encoding - * @return Zend_Search_Lucene_Field - */ - public static function unStored($name, $value, $encoding = '') - { - return new self($name, $value, $encoding, false, true, true); - } - - /** - * Get field value in UTF-8 encoding - * - * @return string - */ - 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); - } - } -} - diff --git a/library/Zend/Search/Lucene/Index/DictionaryLoader.php b/library/Zend/Search/Lucene/Index/DictionaryLoader.php deleted file mode 100644 index a077d3210e..0000000000 --- a/library/Zend/Search/Lucene/Index/DictionaryLoader.php +++ /dev/null @@ -1,268 +0,0 @@ -.tii index file data and - * returns two arrays - term and tremInfo lists. - * - * See Zend_Search_Lucene_Index_SegmintInfo class for details - * - * @param string $data - * @return array - * @throws Zend_Search_Lucene_Exception - */ - public static function load($data) - { - $termDictionary = array(); - $termInfos = array(); - $pos = 0; - - // $tiVersion = $tiiFile->readInt(); - $tiVersion = ord($data[0]) << 24 | ord($data[1]) << 16 | ord($data[2]) << 8 | ord($data[3]); - $pos += 4; - 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 TermInfoIndexFile file format'); - } - - // $indexTermCount = $tiiFile->readLong(); - if (PHP_INT_SIZE > 4) { - $indexTermCount = ord($data[$pos]) << 56 | - ord($data[$pos+1]) << 48 | - ord($data[$pos+2]) << 40 | - ord($data[$pos+3]) << 32 | - ord($data[$pos+4]) << 24 | - ord($data[$pos+5]) << 16 | - ord($data[$pos+6]) << 8 | - ord($data[$pos+7]); - } else { - if ((ord($data[$pos]) != 0) || - (ord($data[$pos+1]) != 0) || - (ord($data[$pos+2]) != 0) || - (ord($data[$pos+3]) != 0) || - ((ord($data[$pos+4]) & 0x80) != 0)) { - #require_once 'Zend/Search/Lucene/Exception.php'; - throw new Zend_Search_Lucene_Exception('Largest supported segment size (for 32-bit mode) is 2Gb'); - } - - $indexTermCount = ord($data[$pos+4]) << 24 | - ord($data[$pos+5]) << 16 | - ord($data[$pos+6]) << 8 | - ord($data[$pos+7]); - } - $pos += 8; - - // $tiiFile->readInt(); // IndexInterval - $pos += 4; - - // $skipInterval = $tiiFile->readInt(); - $skipInterval = ord($data[$pos]) << 24 | ord($data[$pos+1]) << 16 | ord($data[$pos+2]) << 8 | ord($data[$pos+3]); - $pos += 4; - if ($indexTermCount < 1) { - #require_once 'Zend/Search/Lucene/Exception.php'; - throw new Zend_Search_Lucene_Exception('Wrong number of terms in a term dictionary index'); - } - - if ($tiVersion == (int)0xFFFFFFFD /* 2.1+ format */) { - /* Skip MaxSkipLevels value */ - $pos += 4; - } - - $prevTerm = ''; - $freqPointer = 0; - $proxPointer = 0; - $indexPointer = 0; - for ($count = 0; $count < $indexTermCount; $count++) { - //$termPrefixLength = $tiiFile->readVInt(); - $nbyte = ord($data[$pos++]); - $termPrefixLength = $nbyte & 0x7F; - for ($shift=7; ($nbyte & 0x80) != 0; $shift += 7) { - $nbyte = ord($data[$pos++]); - $termPrefixLength |= ($nbyte & 0x7F) << $shift; - } - - // $termSuffix = $tiiFile->readString(); - $nbyte = ord($data[$pos++]); - $len = $nbyte & 0x7F; - for ($shift=7; ($nbyte & 0x80) != 0; $shift += 7) { - $nbyte = ord($data[$pos++]); - $len |= ($nbyte & 0x7F) << $shift; - } - if ($len == 0) { - $termSuffix = ''; - } else { - $termSuffix = substr($data, $pos, $len); - $pos += $len; - for ($count1 = 0; $count1 < $len; $count1++ ) { - if (( ord($termSuffix[$count1]) & 0xC0 ) == 0xC0) { - $addBytes = 1; - if (ord($termSuffix[$count1]) & 0x20 ) { - $addBytes++; - - // Never used for Java Lucene created index. - // Java2 doesn't encode strings in four bytes - if (ord($termSuffix[$count1]) & 0x10 ) { - $addBytes++; - } - } - $termSuffix .= substr($data, $pos, $addBytes); - $pos += $addBytes; - $len += $addBytes; - - // Check for null character. Java2 encodes null character - // in two bytes. - if (ord($termSuffix[$count1]) == 0xC0 && - ord($termSuffix[$count1+1]) == 0x80 ) { - $termSuffix[$count1] = 0; - $termSuffix = substr($termSuffix,0,$count1+1) - . substr($termSuffix,$count1+2); - } - $count1 += $addBytes; - } - } - } - - // $termValue = Zend_Search_Lucene_Index_Term::getPrefix($prevTerm, $termPrefixLength) . $termSuffix; - $pb = 0; $pc = 0; - while ($pb < strlen($prevTerm) && $pc < $termPrefixLength) { - $charBytes = 1; - if ((ord($prevTerm[$pb]) & 0xC0) == 0xC0) { - $charBytes++; - if (ord($prevTerm[$pb]) & 0x20 ) { - $charBytes++; - if (ord($prevTerm[$pb]) & 0x10 ) { - $charBytes++; - } - } - } - - if ($pb + $charBytes > strlen($data)) { - // wrong character - break; - } - - $pc++; - $pb += $charBytes; - } - $termValue = substr($prevTerm, 0, $pb) . $termSuffix; - - // $termFieldNum = $tiiFile->readVInt(); - $nbyte = ord($data[$pos++]); - $termFieldNum = $nbyte & 0x7F; - for ($shift=7; ($nbyte & 0x80) != 0; $shift += 7) { - $nbyte = ord($data[$pos++]); - $termFieldNum |= ($nbyte & 0x7F) << $shift; - } - - // $docFreq = $tiiFile->readVInt(); - $nbyte = ord($data[$pos++]); - $docFreq = $nbyte & 0x7F; - for ($shift=7; ($nbyte & 0x80) != 0; $shift += 7) { - $nbyte = ord($data[$pos++]); - $docFreq |= ($nbyte & 0x7F) << $shift; - } - - // $freqPointer += $tiiFile->readVInt(); - $nbyte = ord($data[$pos++]); - $vint = $nbyte & 0x7F; - for ($shift=7; ($nbyte & 0x80) != 0; $shift += 7) { - $nbyte = ord($data[$pos++]); - $vint |= ($nbyte & 0x7F) << $shift; - } - $freqPointer += $vint; - - // $proxPointer += $tiiFile->readVInt(); - $nbyte = ord($data[$pos++]); - $vint = $nbyte & 0x7F; - for ($shift=7; ($nbyte & 0x80) != 0; $shift += 7) { - $nbyte = ord($data[$pos++]); - $vint |= ($nbyte & 0x7F) << $shift; - } - $proxPointer += $vint; - - if( $docFreq >= $skipInterval ) { - // $skipDelta = $tiiFile->readVInt(); - $nbyte = ord($data[$pos++]); - $vint = $nbyte & 0x7F; - for ($shift=7; ($nbyte & 0x80) != 0; $shift += 7) { - $nbyte = ord($data[$pos++]); - $vint |= ($nbyte & 0x7F) << $shift; - } - $skipDelta = $vint; - } else { - $skipDelta = 0; - } - - // $indexPointer += $tiiFile->readVInt(); - $nbyte = ord($data[$pos++]); - $vint = $nbyte & 0x7F; - for ($shift=7; ($nbyte & 0x80) != 0; $shift += 7) { - $nbyte = ord($data[$pos++]); - $vint |= ($nbyte & 0x7F) << $shift; - } - $indexPointer += $vint; - - - // $this->_termDictionary[] = new Zend_Search_Lucene_Index_Term($termValue, $termFieldNum); - $termDictionary[] = array($termFieldNum, $termValue); - - $termInfos[] = - // new Zend_Search_Lucene_Index_TermInfo($docFreq, $freqPointer, $proxPointer, $skipDelta, $indexPointer); - array($docFreq, $freqPointer, $proxPointer, $skipDelta, $indexPointer); - - $prevTerm = $termValue; - } - - // Check special index entry mark - if ($termDictionary[0][0] != (int)0xFFFFFFFF) { - #require_once 'Zend/Search/Lucene/Exception.php'; - throw new Zend_Search_Lucene_Exception('Wrong TermInfoIndexFile file format'); - } - - if (PHP_INT_SIZE > 4) { - // Treat 64-bit 0xFFFFFFFF as -1 - $termDictionary[0][0] = -1; - } - - return array($termDictionary, $termInfos); - } -} - diff --git a/library/Zend/Search/Lucene/Index/DocsFilter.php b/library/Zend/Search/Lucene/Index/DocsFilter.php deleted file mode 100644 index 17d9e4e29a..0000000000 --- a/library/Zend/Search/Lucene/Index/DocsFilter.php +++ /dev/null @@ -1,59 +0,0 @@ - => array( => , - * => , - * => , - * ... ), - * => array( => , - * => , - * => , - * ... ), - * => array( => , - * => , - * => , - * ... ), - * ... - * ) - * - * @var array - */ - public $segmentFilters = array(); -} - diff --git a/library/Zend/Search/Lucene/Index/FieldInfo.php b/library/Zend/Search/Lucene/Index/FieldInfo.php deleted file mode 100644 index 7eeaba2425..0000000000 --- a/library/Zend/Search/Lucene/Index/FieldInfo.php +++ /dev/null @@ -1,50 +0,0 @@ -name = $name; - $this->isIndexed = $isIndexed; - $this->number = $number; - $this->storeTermVector = $storeTermVector; - $this->normsOmitted = $normsOmitted; - $this->payloadsStored = $payloadsStored; - } -} - diff --git a/library/Zend/Search/Lucene/Index/SegmentInfo.php b/library/Zend/Search/Lucene/Index/SegmentInfo.php deleted file mode 100644 index 105ae926eb..0000000000 --- a/library/Zend/Search/Lucene/Index/SegmentInfo.php +++ /dev/null @@ -1,2132 +0,0 @@ - $termValue - * [1] -> $termFieldNum - * - * Corresponding Zend_Search_Lucene_Index_TermInfo object stored in the $_termDictionaryInfos - * - * @var array - */ - private $_termDictionary; - - /** - * Term Dictionary Index TermInfos - * - * Array of arrays (Zend_Search_Lucene_Index_TermInfo objects are represented as arrays because - * of performance considerations) - * [0] -> $docFreq - * [1] -> $freqPointer - * [2] -> $proxPointer - * [3] -> $skipOffset - * [4] -> $indexPointer - * - * @var array - */ - private $_termDictionaryInfos; - - /** - * Segment fields. Array of Zend_Search_Lucene_Index_FieldInfo objects for this segment - * - * @var array - */ - private $_fields; - - /** - * Field positions in a dictionary. - * (Term dictionary contains filelds ordered by names) - * - * @var array - */ - private $_fieldsDicPositions; - - - /** - * Associative array where the key is the file name and the value is data offset - * in a compound segment file (.csf). - * - * @var array - */ - private $_segFiles; - - /** - * Associative array where the key is the file name and the value is file size (.csf). - * - * @var array - */ - private $_segFileSizes; - - /** - * Delete file generation number - * - * -2 means autodetect latest delete generation - * -1 means 'there is no delete file' - * 0 means pre-2.1 format delete file - * X specifies used delete file - * - * @var integer - */ - private $_delGen; - - /** - * Segment has single norms file - * - * If true then one .nrm file is used for all fields - * Otherwise .fN files are used - * - * @var boolean - */ - private $_hasSingleNormFile; - - /** - * Use compound segment file (*.cfs) to collect all other segment files - * (excluding .del files) - * - * @var boolean - */ - private $_isCompound; - - - /** - * File system adapter. - * - * @var Zend_Search_Lucene_Storage_Directory_Filesystem - */ - private $_directory; - - /** - * Normalization factors. - * An array fieldName => normVector - * normVector is a binary string. - * Each byte corresponds to an indexed document in a segment and - * encodes normalization factor (float value, encoded by - * Zend_Search_Lucene_Search_Similarity::encodeNorm()) - * - * @var array - */ - private $_norms = array(); - - /** - * List of deleted documents. - * bitset if bitset extension is loaded or array otherwise. - * - * @var mixed - */ - private $_deleted = null; - - /** - * $this->_deleted update flag - * - * @var boolean - */ - private $_deletedDirty = false; - - /** - * True if segment uses shared doc store - * - * @var boolean - */ - private $_usesSharedDocStore; - - /* - * Shared doc store options. - * It's an assotiative array with the following items: - * - 'offset' => $docStoreOffset The starting document in the shared doc store files where this segment's documents begin - * - 'segment' => $docStoreSegment The name of the segment that has the shared doc store files. - * - 'isCompound' => $docStoreIsCompoundFile True, if compound file format is used for the shared doc store files (.cfx file). - */ - private $_sharedDocStoreOptions; - - - /** - * Zend_Search_Lucene_Index_SegmentInfo constructor - * - * @param Zend_Search_Lucene_Storage_Directory $directory - * @param string $name - * @param integer $docCount - * @param integer $delGen - * @param array|null $docStoreOptions - * @param boolean $hasSingleNormFile - * @param boolean $isCompound - */ - public function __construct(Zend_Search_Lucene_Storage_Directory $directory, $name, $docCount, $delGen = 0, $docStoreOptions = null, $hasSingleNormFile = false, $isCompound = null) - { - $this->_directory = $directory; - $this->_name = $name; - $this->_docCount = $docCount; - - if ($docStoreOptions !== null) { - $this->_usesSharedDocStore = true; - $this->_sharedDocStoreOptions = $docStoreOptions; - - if ($docStoreOptions['isCompound']) { - $cfxFile = $this->_directory->getFileObject($docStoreOptions['segment'] . '.cfx'); - $cfxFilesCount = $cfxFile->readVInt(); - - $cfxFiles = array(); - $cfxFileSizes = array(); - - for ($count = 0; $count < $cfxFilesCount; $count++) { - $dataOffset = $cfxFile->readLong(); - if ($count != 0) { - $cfxFileSizes[$fileName] = $dataOffset - end($cfxFiles); - } - $fileName = $cfxFile->readString(); - $cfxFiles[$fileName] = $dataOffset; - } - if ($count != 0) { - $cfxFileSizes[$fileName] = $this->_directory->fileLength($docStoreOptions['segment'] . '.cfx') - $dataOffset; - } - - $this->_sharedDocStoreOptions['files'] = $cfxFiles; - $this->_sharedDocStoreOptions['fileSizes'] = $cfxFileSizes; - } - } - - $this->_hasSingleNormFile = $hasSingleNormFile; - $this->_delGen = $delGen; - $this->_termDictionary = null; - - - if ($isCompound !== null) { - $this->_isCompound = $isCompound; - } else { - // It's a pre-2.1 segment or isCompound is set to 'unknown' - // Detect if segment uses compound file - #require_once 'Zend/Search/Lucene/Exception.php'; - try { - // Try to open compound file - $this->_directory->getFileObject($name . '.cfs'); - - // Compound file is found - $this->_isCompound = true; - } catch (Zend_Search_Lucene_Exception $e) { - if (strpos($e->getMessage(), 'is not readable') !== false) { - // Compound file is not found or is not readable - $this->_isCompound = false; - } else { - throw new Zend_Search_Lucene_Exception($e->getMessage(), $e->getCode(), $e); - } - } - } - - $this->_segFiles = array(); - if ($this->_isCompound) { - $cfsFile = $this->_directory->getFileObject($name . '.cfs'); - $segFilesCount = $cfsFile->readVInt(); - - for ($count = 0; $count < $segFilesCount; $count++) { - $dataOffset = $cfsFile->readLong(); - if ($count != 0) { - $this->_segFileSizes[$fileName] = $dataOffset - end($this->_segFiles); - } - $fileName = $cfsFile->readString(); - $this->_segFiles[$fileName] = $dataOffset; - } - if ($count != 0) { - $this->_segFileSizes[$fileName] = $this->_directory->fileLength($name . '.cfs') - $dataOffset; - } - } - - $fnmFile = $this->openCompoundFile('.fnm'); - $fieldsCount = $fnmFile->readVInt(); - $fieldNames = array(); - $fieldNums = array(); - $this->_fields = array(); - - for ($count=0; $count < $fieldsCount; $count++) { - $fieldName = $fnmFile->readString(); - $fieldBits = $fnmFile->readByte(); - $this->_fields[$count] = new Zend_Search_Lucene_Index_FieldInfo($fieldName, - $fieldBits & 0x01 /* field is indexed */, - $count, - $fieldBits & 0x02 /* termvectors are stored */, - $fieldBits & 0x10 /* norms are omitted */, - $fieldBits & 0x20 /* payloads are stored */); - if ($fieldBits & 0x10) { - // norms are omitted for the indexed field - $this->_norms[$count] = str_repeat(chr(Zend_Search_Lucene_Search_Similarity::encodeNorm(1.0)), $docCount); - } - - $fieldNums[$count] = $count; - $fieldNames[$count] = $fieldName; - } - array_multisort($fieldNames, SORT_ASC, SORT_REGULAR, $fieldNums); - $this->_fieldsDicPositions = array_flip($fieldNums); - - if ($this->_delGen == -2) { - // SegmentInfo constructor is invoked from index writer - // Autodetect current delete file generation number - $this->_delGen = $this->_detectLatestDelGen(); - } - - // Load deletions - $this->_deleted = $this->_loadDelFile(); - } - - /** - * Load detetions file - * - * Returns bitset or an array depending on bitset extension availability - * - * @return mixed - * @throws Zend_Search_Lucene_Exception - */ - 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 pre-2.1 detetions file - * - * Returns bitset or an array depending on bitset extension availability - * - * @return mixed - * @throws Zend_Search_Lucene_Exception - */ - 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 2.1+ format detetions file - * - * Returns bitset or an array depending on bitset extension availability - * - * @return mixed - */ - 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; - } - } - } - - /** - * 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 - */ - 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; - } - - /** - * Get compound file length - * - * @param string $extension - * @return integer - */ - 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]; - } - - /** - * Returns field index or -1 if field is not found - * - * @param string $fieldName - * @return integer - */ - public function getFieldNum($fieldName) - { - foreach( $this->_fields as $field ) { - if( $field->name == $fieldName ) { - return $field->number; - } - } - - return -1; - } - - /** - * Returns field info for specified field - * - * @param integer $fieldNum - * @return Zend_Search_Lucene_Index_FieldInfo - */ - public function getField($fieldNum) - { - return $this->_fields[$fieldNum]; - } - - /** - * Returns array of fields. - * if $indexed parameter is true, then returns only indexed fields. - * - * @param boolean $indexed - * @return array - */ - 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 FieldInfo objects. - * - * @return array - */ - public function getFieldInfos() - { - return $this->_fields; - } - - /** - * Returns actual deletions file generation number. - * - * @return integer - */ - public function getDelGen() - { - return $this->_delGen; - } - - /** - * Returns the total number of documents in this segment (including deleted documents). - * - * @return integer - */ - public function count() - { - return $this->_docCount; - } - - /** - * Returns number of deleted documents. - * - * @return integer - */ - 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 the total number of non-deleted documents in this segment. - * - * @return integer - */ - public function numDocs() - { - if ($this->hasDeletions()) { - return $this->_docCount - $this->_deletedCount(); - } else { - return $this->_docCount; - } - } - - /** - * Get field position in a fields dictionary - * - * @param integer $fieldNum - * @return integer - */ - 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; - } - - /** - * Return segment name - * - * @return string - */ - public function getName() - { - return $this->_name; - } - - - /** - * TermInfo cache - * - * Size is 1024. - * Numbers are used instead of class constants because of performance considerations - * - * @var array - */ - private $_termInfoCache = array(); - - private function _cleanUpTermInfoCache() - { - // Clean 256 term infos - foreach ($this->_termInfoCache as $key => $termInfo) { - unset($this->_termInfoCache[$key]); - - // leave 768 last used term infos - if (count($this->_termInfoCache) == 768) { - break; - } - } - } - - /** - * Load terms dictionary index - * - * @throws Zend_Search_Lucene_Exception - */ - 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); - } - - /** - * Scans terms dictionary and returns term info - * - * @param Zend_Search_Lucene_Index_Term $term - * @return Zend_Search_Lucene_Index_TermInfo - */ - 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; - } - - /** - * 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 - */ - 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 term freqs array. - * Result array structure: array(docId => freq, ...) - * - * @param Zend_Search_Lucene_Index_Term $term - * @param integer $shift - * @param Zend_Search_Lucene_Index_DocsFilter|null $docsFilter - * @return Zend_Search_Lucene_Index_TermInfo - */ - public function termFreqs(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); - $result = array(); - $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; - if (isset($filter[$docId])) { - $result[$shift + $docId] = 1; - $updatedFilterData[$docId] = 1; // 1 is just a some constant value, so we don't need additional var dereference here - } - } else { - $docId += $docDelta/2; - $freq = $frqFile->readVInt(); - if (isset($filter[$docId])) { - $result[$shift + $docId] = $freq; - $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; - if (isset($filter[$docId])) { - $result[$shift + $docId] = 1; - $updatedFilterData[$docId] = 1; // 1 is just some constant value, so we don't need additional var dereference here - } - } else { - $docId += $docDelta/2; - $freq = $frqFile->readVInt(); - if (isset($filter[$docId])) { - $result[$shift + $docId] = $freq; - $updatedFilterData[$docId] = 1; // 1 is just some constant value, so we don't need additional var dereference here - } - } - } - $docsFilter->segmentFilters[$this->_name] = $updatedFilterData; - } - } else { - // Filter doesn't has data for current segment - $filterData = array(); - - for ($count = 0; $count < $termInfo->docFreq; $count++) { - $docDelta = $frqFile->readVInt(); - if ($docDelta % 2 == 1) { - $docId += ($docDelta-1)/2; - $result[$shift + $docId] = 1; - $filterData[$docId] = 1; // 1 is just a some constant value, so we don't need additional var dereference here - } else { - $docId += $docDelta/2; - $result[$shift + $docId] = $frqFile->readVInt(); - $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; - $result[$shift + $docId] = 1; - } else { - $docId += $docDelta/2; - $result[$shift + $docId] = $frqFile->readVInt(); - } - } - } - - 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 - */ - 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; - } - - /** - * Load normalizatin factors from an index file - * - * @param integer $fieldNum - * @throws Zend_Search_Lucene_Exception - */ - 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); - } - } - - /** - * Returns normalization factor for specified documents - * - * @param integer $id - * @param string $fieldName - * @return float - */ - 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 norm vector, encoded in a byte string - * - * @param string $fieldName - * @return string - */ - 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 true if any documents have been deleted from this index segment. - * - * @return boolean - */ - public function hasDeletions() - { - return $this->_deleted !== null; - } - - - /** - * Returns true if segment has single norms file. - * - * @return boolean - */ - public function hasSingleNormFile() - { - return $this->_hasSingleNormFile ? true : false; - } - - /** - * Returns true if segment is stored using compound segment file. - * - * @return boolean - */ - public function isCompound() - { - return $this->_isCompound; - } - - /** - * Deletes a document from the index segment. - * $id is an internal document id - * - * @param integer - */ - 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; - } - } - - /** - * Checks, that document is deleted - * - * @param integer - * @return boolean - */ - 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]); - } - } - - /** - * Detect latest delete generation - * - * Is actualy used from writeChanges() method or from the constructor if it's invoked from - * Index writer. In both cases index write lock is already obtained, so we shouldn't care - * about it - * - * @return integer - */ - private function _detectLatestDelGen() - { - $delFileList = array(); - foreach ($this->_directory->fileList() as $file) { - if ($file == $this->_name . '.del') { - // Matches .del file name - $delFileList[] = 0; - } else if (preg_match('/^' . $this->_name . '_([a-zA-Z0-9]+)\.del$/i', $file, $matches)) { - // Matches _NNN.del file names - $delFileList[] = (int)base_convert($matches[1], 36, 10); - } - } - - if (count($delFileList) == 0) { - // There is no deletions file for current segment in the directory - // Set deletions file generation number to 1 - return -1; - } else { - // There are some deletions files for current segment in the directory - // Set deletions file generation number to the highest nuber - return max($delFileList); - } - } - - /** - * 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 - */ - 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; - } - - - /** - * Term Dictionary File object for stream like terms reading - * - * @var Zend_Search_Lucene_Storage_File - */ - private $_tisFile = null; - - /** - * Actual offset of the .tis file data - * - * @var integer - */ - private $_tisFileOffset; - - /** - * Frequencies File object for stream like terms reading - * - * @var Zend_Search_Lucene_Storage_File - */ - private $_frqFile = null; - - /** - * Actual offset of the .frq file data - * - * @var integer - */ - private $_frqFileOffset; - - /** - * Positions File object for stream like terms reading - * - * @var Zend_Search_Lucene_Storage_File - */ - private $_prxFile = null; - - /** - * Actual offset of the .prx file in the compound file - * - * @var integer - */ - private $_prxFileOffset; - - - /** - * Actual number of terms in term stream - * - * @var integer - */ - private $_termCount = 0; - - /** - * Overall number of terms in term stream - * - * @var integer - */ - private $_termNum = 0; - - /** - * Segment index interval - * - * @var integer - */ - private $_indexInterval; - - /** - * Segment skip interval - * - * @var integer - */ - private $_skipInterval; - - /** - * Last TermInfo in a terms stream - * - * @var Zend_Search_Lucene_Index_TermInfo - */ - private $_lastTermInfo = null; - - /** - * Last Term in a terms stream - * - * @var Zend_Search_Lucene_Index_Term - */ - private $_lastTerm = null; - - /** - * Map of the document IDs - * Used to get new docID after removing deleted documents. - * It's not very effective from memory usage point of view, - * but much more faster, then other methods - * - * @var array|null - */ - private $_docMap = null; - - /** - * An array of all term positions in the documents. - * Array structure: array( docId => array( pos1, pos2, ...), ...) - * - * Is set to null if term positions loading has to be skipped - * - * @var array|null - */ - private $_lastTermPositions; - - - /** - * Terms scan mode - * - * Values: - * - * self::SM_TERMS_ONLY - terms are scanned, no additional info is retrieved - * self::SM_FULL_INFO - terms are scanned, frequency and position info is retrieved - * self::SM_MERGE_INFO - terms are scanned, frequency and position info is retrieved - * document numbers are compacted (shifted if segment has deleted documents) - * - * @var integer - */ - private $_termsScanMode; - - /** Scan modes */ - const SM_TERMS_ONLY = 0; // terms are scanned, no additional info is retrieved - const SM_FULL_INFO = 1; // terms are scanned, frequency and position info is retrieved - const SM_MERGE_INFO = 2; // terms are scanned, frequency and position info is retrieved - // document numbers are compacted (shifted if segment contains deleted documents) - - /** - * 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 - */ - 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; - } - - - /** - * Skip terms stream up to the 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 - */ - 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(); - } - } - - - /** - * Scans terms dictionary and returns next term - * - * @return Zend_Search_Lucene_Index_Term|null - */ - 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; - } - - /** - * Close terms stream - * - * Should be used for resources clean up if stream is not read up to the end - */ - public function closeTermsStream() - { - $this->_tisFile = null; - $this->_frqFile = null; - $this->_prxFile = null; - - $this->_lastTerm = null; - $this->_lastTermInfo = null; - $this->_lastTermPositions = null; - - $this->_docMap = null; - } - - - /** - * Returns term in current position - * - * @return Zend_Search_Lucene_Index_Term|null - */ - public function currentTerm() - { - return $this->_lastTerm; - } - - - /** - * Returns an array of all term positions in the documents. - * Return array structure: array( docId => array( pos1, pos2, ...), ...) - * - * @return array - */ - public function currentTermPositions() - { - return $this->_lastTermPositions; - } -} - diff --git a/library/Zend/Search/Lucene/Index/SegmentMerger.php b/library/Zend/Search/Lucene/Index/SegmentMerger.php deleted file mode 100644 index e15bcb85d9..0000000000 --- a/library/Zend/Search/Lucene/Index/SegmentMerger.php +++ /dev/null @@ -1,271 +0,0 @@ -][] => - * - * @var array - */ - private $_fieldsMap = array(); - - - - /** - * Object constructor. - * - * Creates new segment merger with $directory as target to merge segments into - * and $name as a name of new segment - * - * @param Zend_Search_Lucene_Storage_Directory $directory - * @param string $name - */ - public function __construct($directory, $name) - { - /** Zend_Search_Lucene_Index_SegmentWriter_StreamWriter */ - #require_once 'Zend/Search/Lucene/Index/SegmentWriter/StreamWriter.php'; - $this->_writer = new Zend_Search_Lucene_Index_SegmentWriter_StreamWriter($directory, $name); - } - - - /** - * Add segmnet to a collection of segments to be merged - * - * @param Zend_Search_Lucene_Index_SegmentInfo $segment - */ - public function addSource(Zend_Search_Lucene_Index_SegmentInfo $segmentInfo) - { - $this->_segmentInfos[$segmentInfo->getName()] = $segmentInfo; - } - - - /** - * Do merge. - * - * Returns number of documents in newly created segment - * - * @return Zend_Search_Lucene_Index_SegmentInfo - * @throws Zend_Search_Lucene_Exception - */ - public function merge() - { - if ($this->_mergeDone) { - #require_once 'Zend/Search/Lucene/Exception.php'; - throw new Zend_Search_Lucene_Exception('Merge is already done.'); - } - - if (count($this->_segmentInfos) < 1) { - #require_once 'Zend/Search/Lucene/Exception.php'; - throw new Zend_Search_Lucene_Exception('Wrong number of segments to be merged (' - . count($this->_segmentInfos) - . ').'); - } - - $this->_mergeFields(); - $this->_mergeNorms(); - $this->_mergeStoredFields(); - $this->_mergeTerms(); - - $this->_mergeDone = true; - - return $this->_writer->close(); - } - - - /** - * Merge fields information - */ - private function _mergeFields() - { - foreach ($this->_segmentInfos as $segName => $segmentInfo) { - foreach ($segmentInfo->getFieldInfos() as $fieldInfo) { - $this->_fieldsMap[$segName][$fieldInfo->number] = $this->_writer->addFieldInfo($fieldInfo); - } - } - } - - /** - * Merge field's normalization factors - */ - private function _mergeNorms() - { - foreach ($this->_writer->getFieldInfos() as $fieldInfo) { - if ($fieldInfo->isIndexed) { - foreach ($this->_segmentInfos as $segName => $segmentInfo) { - if ($segmentInfo->hasDeletions()) { - $srcNorm = $segmentInfo->normVector($fieldInfo->name); - $norm = ''; - $docs = $segmentInfo->count(); - for ($count = 0; $count < $docs; $count++) { - if (!$segmentInfo->isDeleted($count)) { - $norm .= $srcNorm[$count]; - } - } - $this->_writer->addNorm($fieldInfo->name, $norm); - } else { - $this->_writer->addNorm($fieldInfo->name, $segmentInfo->normVector($fieldInfo->name)); - } - } - } - } - } - - /** - * Merge fields information - */ - private function _mergeStoredFields() - { - $this->_docCount = 0; - - foreach ($this->_segmentInfos as $segName => $segmentInfo) { - $fdtFile = $segmentInfo->openCompoundFile('.fdt'); - - for ($count = 0; $count < $segmentInfo->count(); $count++) { - $fieldCount = $fdtFile->readVInt(); - $storedFields = array(); - - for ($count2 = 0; $count2 < $fieldCount; $count2++) { - $fieldNum = $fdtFile->readVInt(); - $bits = $fdtFile->readByte(); - $fieldInfo = $segmentInfo->getField($fieldNum); - - if (!($bits & 2)) { // Text data - $storedFields[] = - new Zend_Search_Lucene_Field($fieldInfo->name, - $fdtFile->readString(), - 'UTF-8', - true, - $fieldInfo->isIndexed, - $bits & 1 ); - } else { // Binary data - $storedFields[] = - new Zend_Search_Lucene_Field($fieldInfo->name, - $fdtFile->readBinary(), - '', - true, - $fieldInfo->isIndexed, - $bits & 1, - true); - } - } - - if (!$segmentInfo->isDeleted($count)) { - $this->_docCount++; - $this->_writer->addStoredFields($storedFields); - } - } - } - } - - - /** - * Merge fields information - */ - private function _mergeTerms() - { - /** Zend_Search_Lucene_Index_TermsPriorityQueue */ - #require_once 'Zend/Search/Lucene/Index/TermsPriorityQueue.php'; - - $segmentInfoQueue = new Zend_Search_Lucene_Index_TermsPriorityQueue(); - - $segmentStartId = 0; - foreach ($this->_segmentInfos as $segName => $segmentInfo) { - $segmentStartId = $segmentInfo->resetTermsStream($segmentStartId, Zend_Search_Lucene_Index_SegmentInfo::SM_MERGE_INFO); - - // Skip "empty" segments - if ($segmentInfo->currentTerm() !== null) { - $segmentInfoQueue->put($segmentInfo); - } - } - - $this->_writer->initializeDictionaryFiles(); - - $termDocs = array(); - while (($segmentInfo = $segmentInfoQueue->pop()) !== null) { - // Merge positions array - $termDocs += $segmentInfo->currentTermPositions(); - - if ($segmentInfoQueue->top() === null || - $segmentInfoQueue->top()->currentTerm()->key() != - $segmentInfo->currentTerm()->key()) { - // We got new term - ksort($termDocs, SORT_NUMERIC); - - // Add term if it's contained in any document - if (count($termDocs) > 0) { - $this->_writer->addTerm($segmentInfo->currentTerm(), $termDocs); - } - $termDocs = array(); - } - - $segmentInfo->nextTerm(); - // check, if segment dictionary is finished - if ($segmentInfo->currentTerm() !== null) { - // Put segment back into the priority queue - $segmentInfoQueue->put($segmentInfo); - } - } - - $this->_writer->closeDictionaryFiles(); - } -} diff --git a/library/Zend/Search/Lucene/Index/SegmentWriter.php b/library/Zend/Search/Lucene/Index/SegmentWriter.php deleted file mode 100644 index c8e4221e31..0000000000 --- a/library/Zend/Search/Lucene/Index/SegmentWriter.php +++ /dev/null @@ -1,634 +0,0 @@ - normVector - * normVector is a binary string. - * Each byte corresponds to an indexed document in a segment and - * encodes normalization factor (float value, encoded by - * Zend_Search_Lucene_Search_Similarity::encodeNorm()) - * - * @var array - */ - protected $_norms = array(); - - - /** - * '.fdx' file - Stored Fields, the field index. - * - * @var Zend_Search_Lucene_Storage_File - */ - protected $_fdxFile = null; - - /** - * '.fdt' file - Stored Fields, the field data. - * - * @var Zend_Search_Lucene_Storage_File - */ - protected $_fdtFile = null; - - - /** - * Object constructor. - * - * @param Zend_Search_Lucene_Storage_Directory $directory - * @param string $name - */ - public function __construct(Zend_Search_Lucene_Storage_Directory $directory, $name) - { - $this->_directory = $directory; - $this->_name = $name; - } - - - /** - * Add field to the segment - * - * Returns actual field number - * - * @param Zend_Search_Lucene_Field $field - * @return integer - */ - 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 fieldInfo to the segment - * - * Returns actual field number - * - * @param Zend_Search_Lucene_Index_FieldInfo $fieldInfo - * @return integer - */ - 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; - } - } - - /** - * Returns array of FieldInfo objects. - * - * @return array - */ - public function getFieldInfos() - { - return $this->_fields; - } - - /** - * Add stored fields information - * - * @param array $storedFields array of Zend_Search_Lucene_Field objects - */ - 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++; - } - - /** - * Returns the total number of documents in this segment. - * - * @return integer - */ - public function count() - { - return $this->_docCount; - } - - /** - * Return segment name - * - * @return string - */ - public function getName() - { - return $this->_name; - } - - /** - * Dump Field Info (.fnm) segment file - */ - 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'; - } - - - - /** - * Term Dictionary file - * - * @var Zend_Search_Lucene_Storage_File - */ - private $_tisFile = null; - - /** - * Term Dictionary index file - * - * @var Zend_Search_Lucene_Storage_File - */ - private $_tiiFile = null; - - /** - * Frequencies file - * - * @var Zend_Search_Lucene_Storage_File - */ - private $_frqFile = null; - - /** - * Positions file - * - * @var Zend_Search_Lucene_Storage_File - */ - private $_prxFile = null; - - /** - * Number of written terms - * - * @var integer - */ - private $_termCount; - - - /** - * Last saved term - * - * @var Zend_Search_Lucene_Index_Term - */ - private $_prevTerm; - - /** - * Last saved term info - * - * @var Zend_Search_Lucene_Index_TermInfo - */ - private $_prevTermInfo; - - /** - * Last saved index term - * - * @var Zend_Search_Lucene_Index_Term - */ - private $_prevIndexTerm; - - /** - * Last saved index term info - * - * @var Zend_Search_Lucene_Index_TermInfo - */ - private $_prevIndexTermInfo; - - /** - * Last term dictionary file position - * - * @var integer - */ - private $_lastIndexPosition; - - /** - * Create dicrionary, frequency and positions files and write necessary headers - */ - 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; - - } - - /** - * Add term - * - * Term positions is an array( docId => array(pos1, pos2, pos3, ...), ... ) - * - * @param Zend_Search_Lucene_Index_Term $termEntry - * @param array $termDocs - */ - 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++; - } - - /** - * Close dictionary - */ - 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); - } - - - /** - * 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 - */ - 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; - } - - - /** - * Generate compound index file - */ - 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); - } - } - - - /** - * Close segment, write it to disk and return segment info - * - * @return Zend_Search_Lucene_Index_SegmentInfo - */ - abstract public function close(); -} - diff --git a/library/Zend/Search/Lucene/Index/SegmentWriter/DocumentWriter.php b/library/Zend/Search/Lucene/Index/SegmentWriter/DocumentWriter.php deleted file mode 100644 index ec3fb49dd8..0000000000 --- a/library/Zend/Search/Lucene/Index/SegmentWriter/DocumentWriter.php +++ /dev/null @@ -1,230 +0,0 @@ -_termDocs = array(); - $this->_termDictionary = array(); - } - - - /** - * Adds a document to this segment. - * - * @param Zend_Search_Lucene_Document $document - * @throws Zend_Search_Lucene_Exception - */ - public function addDocument(Zend_Search_Lucene_Document $document) - { - /** Zend_Search_Lucene_Search_Similarity */ - #require_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 - */ - #require_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 */ - #require_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); - } - - - /** - * Dump Term Dictionary (.tis) and Term Dictionary Index (.tii) segment files - */ - protected function _dumpDictionary() - { - ksort($this->_termDictionary, SORT_STRING); - - $this->initializeDictionaryFiles(); - - foreach ($this->_termDictionary as $termId => $term) { - $this->addTerm($term, $this->_termDocs[$termId]); - } - - $this->closeDictionaryFiles(); - } - - - /** - * Close segment, write it to disk and return segment info - * - * @return Zend_Search_Lucene_Index_SegmentInfo - */ - public function close() - { - if ($this->_docCount == 0) { - return null; - } - - $this->_dumpFNM(); - $this->_dumpDictionary(); - - $this->_generateCFS(); - - /** Zend_Search_Lucene_Index_SegmentInfo */ - #require_once 'Zend/Search/Lucene/Index/SegmentInfo.php'; - - return new Zend_Search_Lucene_Index_SegmentInfo($this->_directory, - $this->_name, - $this->_docCount, - -1, - null, - true, - true); - } - -} - diff --git a/library/Zend/Search/Lucene/Index/SegmentWriter/StreamWriter.php b/library/Zend/Search/Lucene/Index/SegmentWriter/StreamWriter.php deleted file mode 100644 index 7a630ab44e..0000000000 --- a/library/Zend/Search/Lucene/Index/SegmentWriter/StreamWriter.php +++ /dev/null @@ -1,94 +0,0 @@ -_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'; - } - - public function addNorm($fieldName, $normVector) - { - if (isset($this->_norms[$fieldName])) { - $this->_norms[$fieldName] .= $normVector; - } else { - $this->_norms[$fieldName] = $normVector; - } - } - - /** - * Close segment, write it to disk and return segment info - * - * @return Zend_Search_Lucene_Index_SegmentInfo - */ - public function close() - { - if ($this->_docCount == 0) { - return null; - } - - $this->_dumpFNM(); - $this->_generateCFS(); - - /** Zend_Search_Lucene_Index_SegmentInfo */ - #require_once 'Zend/Search/Lucene/Index/SegmentInfo.php'; - - return new Zend_Search_Lucene_Index_SegmentInfo($this->_directory, - $this->_name, - $this->_docCount, - -1, - null, - true, - true); - } -} - diff --git a/library/Zend/Search/Lucene/Index/Term.php b/library/Zend/Search/Lucene/Index/Term.php deleted file mode 100644 index b2328384dc..0000000000 --- a/library/Zend/Search/Lucene/Index/Term.php +++ /dev/null @@ -1,144 +0,0 @@ -field = ($field === null)? Zend_Search_Lucene::getDefaultSearchField() : $field; - $this->text = $text; - } - - - /** - * Returns term key - * - * @return string - */ - public function key() - { - return $this->field . chr(0) . $this->text; - } - - /** - * Get term prefix - * - * @param string $str - * @param integer $length - * @return string - */ - public static function getPrefix($str, $length) - { - $prefixBytes = 0; - $prefixChars = 0; - while ($prefixBytes < strlen($str) && $prefixChars < $length) { - $charBytes = 1; - if ((ord($str[$prefixBytes]) & 0xC0) == 0xC0) { - $charBytes++; - if (ord($str[$prefixBytes]) & 0x20 ) { - $charBytes++; - if (ord($str[$prefixBytes]) & 0x10 ) { - $charBytes++; - } - } - } - - if ($prefixBytes + $charBytes > strlen($str)) { - // wrong character - break; - } - - $prefixChars++; - $prefixBytes += $charBytes; - } - - return substr($str, 0, $prefixBytes); - } - - /** - * Get UTF-8 string length - * - * @param string $str - * @return string - */ - public static function getLength($str) - { - $bytes = 0; - $chars = 0; - while ($bytes < strlen($str)) { - $charBytes = 1; - if ((ord($str[$bytes]) & 0xC0) == 0xC0) { - $charBytes++; - if (ord($str[$bytes]) & 0x20 ) { - $charBytes++; - if (ord($str[$bytes]) & 0x10 ) { - $charBytes++; - } - } - } - - if ($bytes + $charBytes > strlen($str)) { - // wrong character - break; - } - - $chars++; - $bytes += $charBytes; - } - - return $chars; - } -} - diff --git a/library/Zend/Search/Lucene/Index/TermInfo.php b/library/Zend/Search/Lucene/Index/TermInfo.php deleted file mode 100644 index 824980883a..0000000000 --- a/library/Zend/Search/Lucene/Index/TermInfo.php +++ /dev/null @@ -1,80 +0,0 @@ -docFreq = $docFreq; - $this->freqPointer = $freqPointer; - $this->proxPointer = $proxPointer; - $this->skipOffset = $skipOffset; - $this->indexPointer = $indexPointer; - } -} - diff --git a/library/Zend/Search/Lucene/Index/TermsPriorityQueue.php b/library/Zend/Search/Lucene/Index/TermsPriorityQueue.php deleted file mode 100644 index adb99599a7..0000000000 --- a/library/Zend/Search/Lucene/Index/TermsPriorityQueue.php +++ /dev/null @@ -1,49 +0,0 @@ -currentTerm()->key(), $termsStream2->currentTerm()->key()) < 0; - } - -} diff --git a/library/Zend/Search/Lucene/Index/TermsStream/Interface.php b/library/Zend/Search/Lucene/Index/TermsStream/Interface.php deleted file mode 100644 index 67952bbf8a..0000000000 --- a/library/Zend/Search/Lucene/Index/TermsStream/Interface.php +++ /dev/null @@ -1,66 +0,0 @@ - 10) are best for batch index creation, - * and smaller values (< 10) for indices that are interactively maintained. - * - * Default value is 10 - * - * @var integer - */ - public $mergeFactor = 10; - - /** - * File system adapter. - * - * @var Zend_Search_Lucene_Storage_Directory - */ - private $_directory = null; - - - /** - * Changes counter. - * - * @var integer - */ - private $_versionUpdate = 0; - - /** - * List of the segments, created by index writer - * Array of Zend_Search_Lucene_Index_SegmentInfo objects - * - * @var array - */ - private $_newSegments = array(); - - /** - * List of segments to be deleted on commit - * - * @var array - */ - private $_segmentsToDelete = array(); - - /** - * Current segment to add documents - * - * @var Zend_Search_Lucene_Index_SegmentWriter_DocumentWriter - */ - private $_currentSegment = null; - - /** - * Array of Zend_Search_Lucene_Index_SegmentInfo objects for this index. - * - * It's a reference to the corresponding Zend_Search_Lucene::$_segmentInfos array - * - * @var array Zend_Search_Lucene_Index_SegmentInfo - */ - private $_segmentInfos; - - /** - * Index target format version - * - * @var integer - */ - private $_targetFormatVersion; - - /** - * List of indexfiles extensions - * - * @var array - */ - private static $_indexExtensions = array('.cfs' => '.cfs', - '.cfx' => '.cfx', - '.fnm' => '.fnm', - '.fdx' => '.fdx', - '.fdt' => '.fdt', - '.tis' => '.tis', - '.tii' => '.tii', - '.frq' => '.frq', - '.prx' => '.prx', - '.tvx' => '.tvx', - '.tvd' => '.tvd', - '.tvf' => '.tvf', - '.del' => '.del', - '.sti' => '.sti' ); - - - /** - * Create empty index - * - * @param Zend_Search_Lucene_Storage_Directory $directory - * @param integer $generation - * @param integer $nameCount - */ - public static function createIndex(Zend_Search_Lucene_Storage_Directory $directory, $generation, $nameCount) - { - if ($generation == 0) { - // Create index in pre-2.1 mode - foreach ($directory->fileList() as $file) { - if ($file == 'deletable' || - $file == 'segments' || - isset(self::$_indexExtensions[ substr($file, strlen($file)-4)]) || - preg_match('/\.f\d+$/i', $file) /* matches .f file names */) { - $directory->deleteFile($file); - } - } - - $segmentsFile = $directory->createFile('segments'); - $segmentsFile->writeInt((int)0xFFFFFFFF); - - // write version (initialized by current time) - $segmentsFile->writeLong(round(microtime(true))); - - // write name counter - $segmentsFile->writeInt($nameCount); - // write segment counter - $segmentsFile->writeInt(0); - - $deletableFile = $directory->createFile('deletable'); - // write counter - $deletableFile->writeInt(0); - } else { - $genFile = $directory->createFile('segments.gen'); - - $genFile->writeInt((int)0xFFFFFFFE); - // Write generation two times - $genFile->writeLong($generation); - $genFile->writeLong($generation); - - $segmentsFile = $directory->createFile(Zend_Search_Lucene::getSegmentFileName($generation)); - $segmentsFile->writeInt((int)0xFFFFFFFD); - - // write version (initialized by current time) - $segmentsFile->writeLong(round(microtime(true))); - - // write name counter - $segmentsFile->writeInt($nameCount); - // write segment counter - $segmentsFile->writeInt(0); - } - } - - /** - * Open the index for writing - * - * @param Zend_Search_Lucene_Storage_Directory $directory - * @param array $segmentInfos - * @param integer $targetFormatVersion - * @param Zend_Search_Lucene_Storage_File $cleanUpLock - */ - public function __construct(Zend_Search_Lucene_Storage_Directory $directory, &$segmentInfos, $targetFormatVersion) - { - $this->_directory = $directory; - $this->_segmentInfos = &$segmentInfos; - $this->_targetFormatVersion = $targetFormatVersion; - } - - /** - * Adds a document to this index. - * - * @param Zend_Search_Lucene_Document $document - */ - public function addDocument(Zend_Search_Lucene_Document $document) - { - /** Zend_Search_Lucene_Index_SegmentWriter_DocumentWriter */ - #require_once 'Zend/Search/Lucene/Index/SegmentWriter/DocumentWriter.php'; - - if ($this->_currentSegment === null) { - $this->_currentSegment = - new Zend_Search_Lucene_Index_SegmentWriter_DocumentWriter($this->_directory, $this->_newSegmentName()); - } - $this->_currentSegment->addDocument($document); - - if ($this->_currentSegment->count() >= $this->maxBufferedDocs) { - $this->commit(); - } - - $this->_maybeMergeSegments(); - - $this->_versionUpdate++; - } - - - /** - * Check if we have anything to merge - * - * @return boolean - */ - private function _hasAnythingToMerge() - { - $segmentSizes = array(); - foreach ($this->_segmentInfos as $segName => $segmentInfo) { - $segmentSizes[$segName] = $segmentInfo->count(); - } - - $mergePool = array(); - $poolSize = 0; - $sizeToMerge = $this->maxBufferedDocs; - asort($segmentSizes, SORT_NUMERIC); - foreach ($segmentSizes as $segName => $size) { - // Check, if segment comes into a new merging block - while ($size >= $sizeToMerge) { - // Merge previous block if it's large enough - if ($poolSize >= $sizeToMerge) { - return true; - } - $mergePool = array(); - $poolSize = 0; - - $sizeToMerge *= $this->mergeFactor; - - if ($sizeToMerge > $this->maxMergeDocs) { - return false; - } - } - - $mergePool[] = $this->_segmentInfos[$segName]; - $poolSize += $size; - } - - if ($poolSize >= $sizeToMerge) { - return true; - } - - return false; - } - - /** - * Merge segments if necessary - */ - private function _maybeMergeSegments() - { - if (Zend_Search_Lucene_LockManager::obtainOptimizationLock($this->_directory) === false) { - return; - } - - if (!$this->_hasAnythingToMerge()) { - Zend_Search_Lucene_LockManager::releaseOptimizationLock($this->_directory); - return; - } - - // Update segments list to be sure all segments are not merged yet by another process - // - // Segment merging functionality is concentrated in this class and surrounded - // by optimization lock obtaining/releasing. - // _updateSegments() refreshes segments list from the latest index generation. - // So only new segments can be added to the index while we are merging some already existing - // segments. - // Newly added segments will be also included into the index by the _updateSegments() call - // either by another process or by the current process with the commit() call at the end of _mergeSegments() method. - // That's guaranteed by the serialisation of _updateSegments() execution using exclusive locks. - $this->_updateSegments(); - - // Perform standard auto-optimization procedure - $segmentSizes = array(); - foreach ($this->_segmentInfos as $segName => $segmentInfo) { - $segmentSizes[$segName] = $segmentInfo->count(); - } - - $mergePool = array(); - $poolSize = 0; - $sizeToMerge = $this->maxBufferedDocs; - asort($segmentSizes, SORT_NUMERIC); - foreach ($segmentSizes as $segName => $size) { - // Check, if segment comes into a new merging block - while ($size >= $sizeToMerge) { - // Merge previous block if it's large enough - if ($poolSize >= $sizeToMerge) { - $this->_mergeSegments($mergePool); - } - $mergePool = array(); - $poolSize = 0; - - $sizeToMerge *= $this->mergeFactor; - - if ($sizeToMerge > $this->maxMergeDocs) { - Zend_Search_Lucene_LockManager::releaseOptimizationLock($this->_directory); - return; - } - } - - $mergePool[] = $this->_segmentInfos[$segName]; - $poolSize += $size; - } - - if ($poolSize >= $sizeToMerge) { - $this->_mergeSegments($mergePool); - } - - Zend_Search_Lucene_LockManager::releaseOptimizationLock($this->_directory); - } - - /** - * Merge specified segments - * - * $segments is an array of SegmentInfo objects - * - * @param array $segments - */ - private function _mergeSegments($segments) - { - $newName = $this->_newSegmentName(); - - /** Zend_Search_Lucene_Index_SegmentMerger */ - #require_once 'Zend/Search/Lucene/Index/SegmentMerger.php'; - $merger = new Zend_Search_Lucene_Index_SegmentMerger($this->_directory, - $newName); - foreach ($segments as $segmentInfo) { - $merger->addSource($segmentInfo); - $this->_segmentsToDelete[$segmentInfo->getName()] = $segmentInfo->getName(); - } - - $newSegment = $merger->merge(); - if ($newSegment !== null) { - $this->_newSegments[$newSegment->getName()] = $newSegment; - } - - $this->commit(); - } - - /** - * Update segments file by adding current segment to a list - * - * @throws Zend_Search_Lucene_Exception - */ - private function _updateSegments() - { - // Get an exclusive index lock - Zend_Search_Lucene_LockManager::obtainWriteLock($this->_directory); - - // Write down changes for the segments - foreach ($this->_segmentInfos as $segInfo) { - $segInfo->writeChanges(); - } - - - $generation = Zend_Search_Lucene::getActualGeneration($this->_directory); - $segmentsFile = $this->_directory->getFileObject(Zend_Search_Lucene::getSegmentFileName($generation), false); - $newSegmentFile = $this->_directory->createFile(Zend_Search_Lucene::getSegmentFileName(++$generation), false); - - try { - $genFile = $this->_directory->getFileObject('segments.gen', false); - } catch (Zend_Search_Lucene_Exception $e) { - if (strpos($e->getMessage(), 'is not readable') !== false) { - $genFile = $this->_directory->createFile('segments.gen'); - } else { - throw new Zend_Search_Lucene_Exception($e->getMessage(), $e->getCode(), $e); - } - } - - $genFile->writeInt((int)0xFFFFFFFE); - // Write generation (first copy) - $genFile->writeLong($generation); - - try { - // Write format marker - if ($this->_targetFormatVersion == Zend_Search_Lucene::FORMAT_2_1) { - $newSegmentFile->writeInt((int)0xFFFFFFFD); - } else if ($this->_targetFormatVersion == Zend_Search_Lucene::FORMAT_2_3) { - $newSegmentFile->writeInt((int)0xFFFFFFFC); - } - - // Read src file format identifier - $format = $segmentsFile->readInt(); - if ($format == (int)0xFFFFFFFF) { - $srcFormat = Zend_Search_Lucene::FORMAT_PRE_2_1; - } else if ($format == (int)0xFFFFFFFD) { - $srcFormat = Zend_Search_Lucene::FORMAT_2_1; - } else if ($format == (int)0xFFFFFFFC) { - $srcFormat = Zend_Search_Lucene::FORMAT_2_3; - } else { - throw new Zend_Search_Lucene_Exception('Unsupported segments file format'); - } - - $version = $segmentsFile->readLong() + $this->_versionUpdate; - $this->_versionUpdate = 0; - $newSegmentFile->writeLong($version); - - // Write segment name counter - $newSegmentFile->writeInt($segmentsFile->readInt()); - - // Get number of segments offset - $numOfSegmentsOffset = $newSegmentFile->tell(); - // Write dummy data (segment counter) - $newSegmentFile->writeInt(0); - - // Read number of segemnts - $segmentsCount = $segmentsFile->readInt(); - - $segments = array(); - for ($count = 0; $count < $segmentsCount; $count++) { - $segName = $segmentsFile->readString(); - $segSize = $segmentsFile->readInt(); - - if ($srcFormat == Zend_Search_Lucene::FORMAT_PRE_2_1) { - // pre-2.1 index format - $delGen = 0; - $hasSingleNormFile = false; - $numField = (int)0xFFFFFFFF; - $isCompoundByte = 0; - $docStoreOptions = null; - } else { - $delGen = $segmentsFile->readLong(); - - if ($srcFormat == Zend_Search_Lucene::FORMAT_2_3) { - $docStoreOffset = $segmentsFile->readInt(); - - if ($docStoreOffset != (int)0xFFFFFFFF) { - $docStoreSegment = $segmentsFile->readString(); - $docStoreIsCompoundFile = $segmentsFile->readByte(); - - $docStoreOptions = array('offset' => $docStoreOffset, - 'segment' => $docStoreSegment, - 'isCompound' => ($docStoreIsCompoundFile == 1)); - } else { - $docStoreOptions = null; - } - } else { - $docStoreOptions = null; - } - - $hasSingleNormFile = $segmentsFile->readByte(); - $numField = $segmentsFile->readInt(); - - $normGens = array(); - if ($numField != (int)0xFFFFFFFF) { - for ($count1 = 0; $count1 < $numField; $count1++) { - $normGens[] = $segmentsFile->readLong(); - } - } - $isCompoundByte = $segmentsFile->readByte(); - } - - if (!in_array($segName, $this->_segmentsToDelete)) { - // Load segment if necessary - if (!isset($this->_segmentInfos[$segName])) { - if ($isCompoundByte == 0xFF) { - // The segment is not a compound file - $isCompound = false; - } else if ($isCompoundByte == 0x00) { - // The status is unknown - $isCompound = null; - } else if ($isCompoundByte == 0x01) { - // The segment is a compound file - $isCompound = true; - } - - /** Zend_Search_Lucene_Index_SegmentInfo */ - #require_once 'Zend/Search/Lucene/Index/SegmentInfo.php'; - $this->_segmentInfos[$segName] = - new Zend_Search_Lucene_Index_SegmentInfo($this->_directory, - $segName, - $segSize, - $delGen, - $docStoreOptions, - $hasSingleNormFile, - $isCompound); - } else { - // Retrieve actual deletions file generation number - $delGen = $this->_segmentInfos[$segName]->getDelGen(); - } - - $newSegmentFile->writeString($segName); - $newSegmentFile->writeInt($segSize); - $newSegmentFile->writeLong($delGen); - if ($this->_targetFormatVersion == Zend_Search_Lucene::FORMAT_2_3) { - if ($docStoreOptions !== null) { - $newSegmentFile->writeInt($docStoreOffset); - $newSegmentFile->writeString($docStoreSegment); - $newSegmentFile->writeByte($docStoreIsCompoundFile); - } else { - // Set DocStoreOffset to -1 - $newSegmentFile->writeInt((int)0xFFFFFFFF); - } - } else if ($docStoreOptions !== null) { - // Release index write lock - Zend_Search_Lucene_LockManager::releaseWriteLock($this->_directory); - - throw new Zend_Search_Lucene_Exception('Index conversion to lower format version is not supported.'); - } - - $newSegmentFile->writeByte($hasSingleNormFile); - $newSegmentFile->writeInt($numField); - if ($numField != (int)0xFFFFFFFF) { - foreach ($normGens as $normGen) { - $newSegmentFile->writeLong($normGen); - } - } - $newSegmentFile->writeByte($isCompoundByte); - - $segments[$segName] = $segSize; - } - } - $segmentsFile->close(); - - $segmentsCount = count($segments) + count($this->_newSegments); - - foreach ($this->_newSegments as $segName => $segmentInfo) { - $newSegmentFile->writeString($segName); - $newSegmentFile->writeInt($segmentInfo->count()); - - // delete file generation: -1 (there is no delete file yet) - $newSegmentFile->writeInt((int)0xFFFFFFFF);$newSegmentFile->writeInt((int)0xFFFFFFFF); - if ($this->_targetFormatVersion == Zend_Search_Lucene::FORMAT_2_3) { - // docStoreOffset: -1 (segment doesn't use shared doc store) - $newSegmentFile->writeInt((int)0xFFFFFFFF); - } - // HasSingleNormFile - $newSegmentFile->writeByte($segmentInfo->hasSingleNormFile()); - // NumField - $newSegmentFile->writeInt((int)0xFFFFFFFF); - // IsCompoundFile - $newSegmentFile->writeByte($segmentInfo->isCompound() ? 1 : -1); - - $segments[$segmentInfo->getName()] = $segmentInfo->count(); - $this->_segmentInfos[$segName] = $segmentInfo; - } - $this->_newSegments = array(); - - $newSegmentFile->seek($numOfSegmentsOffset); - $newSegmentFile->writeInt($segmentsCount); // Update segments count - $newSegmentFile->close(); - } catch (Exception $e) { - /** Restore previous index generation */ - $generation--; - $genFile->seek(4, SEEK_SET); - // Write generation number twice - $genFile->writeLong($generation); $genFile->writeLong($generation); - - // Release index write lock - Zend_Search_Lucene_LockManager::releaseWriteLock($this->_directory); - - // Throw the exception - #require_once 'Zend/Search/Lucene/Exception.php'; - throw new Zend_Search_Lucene_Exception($e->getMessage(), $e->getCode(), $e); - } - - // Write generation (second copy) - $genFile->writeLong($generation); - - - // Check if another update or read process is not running now - // If yes, skip clean-up procedure - if (Zend_Search_Lucene_LockManager::escalateReadLock($this->_directory)) { - /** - * Clean-up directory - */ - $filesToDelete = array(); - $filesTypes = array(); - $filesNumbers = array(); - - // list of .del files of currently used segments - // each segment can have several generations of .del files - // only last should not be deleted - $delFiles = array(); - - foreach ($this->_directory->fileList() as $file) { - if ($file == 'deletable') { - // 'deletable' file - $filesToDelete[] = $file; - $filesTypes[] = 0; // delete this file first, since it's not used starting from Lucene v2.1 - $filesNumbers[] = 0; - } else if ($file == 'segments') { - // 'segments' file - $filesToDelete[] = $file; - $filesTypes[] = 1; // second file to be deleted "zero" version of segments file (Lucene pre-2.1) - $filesNumbers[] = 0; - } else if (preg_match('/^segments_[a-zA-Z0-9]+$/i', $file)) { - // 'segments_xxx' file - // Check if it's not a just created generation file - if ($file != Zend_Search_Lucene::getSegmentFileName($generation)) { - $filesToDelete[] = $file; - $filesTypes[] = 2; // first group of files for deletions - $filesNumbers[] = (int)base_convert(substr($file, 9), 36, 10); // ordered by segment generation numbers - } - } else if (preg_match('/(^_([a-zA-Z0-9]+))\.f\d+$/i', $file, $matches)) { - // one of per segment files ('.f') - // Check if it's not one of the segments in the current segments set - if (!isset($segments[$matches[1]])) { - $filesToDelete[] = $file; - $filesTypes[] = 3; // second group of files for deletions - $filesNumbers[] = (int)base_convert($matches[2], 36, 10); // order by segment number - } - } else if (preg_match('/(^_([a-zA-Z0-9]+))(_([a-zA-Z0-9]+))\.del$/i', $file, $matches)) { - // one of per segment files ('_.del' where is '_') - // Check if it's not one of the segments in the current segments set - if (!isset($segments[$matches[1]])) { - $filesToDelete[] = $file; - $filesTypes[] = 3; // second group of files for deletions - $filesNumbers[] = (int)base_convert($matches[2], 36, 10); // order by segment number - } else { - $segmentNumber = (int)base_convert($matches[2], 36, 10); - $delGeneration = (int)base_convert($matches[4], 36, 10); - if (!isset($delFiles[$segmentNumber])) { - $delFiles[$segmentNumber] = array(); - } - $delFiles[$segmentNumber][$delGeneration] = $file; - } - } else if (isset(self::$_indexExtensions[substr($file, strlen($file)-4)])) { - // one of per segment files ('.') - $segmentName = substr($file, 0, strlen($file) - 4); - // Check if it's not one of the segments in the current segments set - if (!isset($segments[$segmentName]) && - ($this->_currentSegment === null || $this->_currentSegment->getName() != $segmentName)) { - $filesToDelete[] = $file; - $filesTypes[] = 3; // second group of files for deletions - $filesNumbers[] = (int)base_convert(substr($file, 1 /* skip '_' */, strlen($file)-5), 36, 10); // order by segment number - } - } - } - - $maxGenNumber = 0; - // process .del files of currently used segments - foreach ($delFiles as $segmentNumber => $segmentDelFiles) { - ksort($delFiles[$segmentNumber], SORT_NUMERIC); - array_pop($delFiles[$segmentNumber]); // remove last delete file generation from candidates for deleting - - end($delFiles[$segmentNumber]); - $lastGenNumber = key($delFiles[$segmentNumber]); - if ($lastGenNumber > $maxGenNumber) { - $maxGenNumber = $lastGenNumber; - } - } - foreach ($delFiles as $segmentNumber => $segmentDelFiles) { - foreach ($segmentDelFiles as $delGeneration => $file) { - $filesToDelete[] = $file; - $filesTypes[] = 4; // third group of files for deletions - $filesNumbers[] = $segmentNumber*$maxGenNumber + $delGeneration; // order by , pair - } - } - - // Reorder files for deleting - array_multisort($filesTypes, SORT_ASC, SORT_NUMERIC, - $filesNumbers, SORT_ASC, SORT_NUMERIC, - $filesToDelete, SORT_ASC, SORT_STRING); - - foreach ($filesToDelete as $file) { - try { - /** Skip shared docstore segments deleting */ - /** @todo Process '.cfx' files to check if them are already unused */ - if (substr($file, strlen($file)-4) != '.cfx') { - $this->_directory->deleteFile($file); - } - } catch (Zend_Search_Lucene_Exception $e) { - if (strpos($e->getMessage(), 'Can\'t delete file') === false) { - // That's not "file is under processing or already deleted" exception - // Pass it through - throw new Zend_Search_Lucene_Exception($e->getMessage(), $e->getCode(), $e); - } - } - } - - // Return read lock into the previous state - Zend_Search_Lucene_LockManager::deEscalateReadLock($this->_directory); - } else { - // Only release resources if another index reader is running now - foreach ($this->_segmentsToDelete as $segName) { - foreach (self::$_indexExtensions as $ext) { - $this->_directory->purgeFile($segName . $ext); - } - } - } - - // Clean-up _segmentsToDelete container - $this->_segmentsToDelete = array(); - - - // Release index write lock - Zend_Search_Lucene_LockManager::releaseWriteLock($this->_directory); - - // Remove unused segments from segments list - foreach ($this->_segmentInfos as $segName => $segmentInfo) { - if (!isset($segments[$segName])) { - unset($this->_segmentInfos[$segName]); - } - } - } - - /** - * Commit current changes - */ - public function commit() - { - if ($this->_currentSegment !== null) { - $newSegment = $this->_currentSegment->close(); - if ($newSegment !== null) { - $this->_newSegments[$newSegment->getName()] = $newSegment; - } - $this->_currentSegment = null; - } - - $this->_updateSegments(); - } - - - /** - * Merges the provided indexes into this index. - * - * @param array $readers - * @return void - */ - public function addIndexes($readers) - { - /** - * @todo implementation - */ - } - - /** - * 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 - */ - 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; - } - - /** - * Get name for new segment - * - * @return string - */ - 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); - } - -} diff --git a/library/Zend/Search/Lucene/Interface.php b/library/Zend/Search/Lucene/Interface.php deleted file mode 100644 index f5e423fa39..0000000000 --- a/library/Zend/Search/Lucene/Interface.php +++ /dev/null @@ -1,417 +0,0 @@ - 10) are best for batch index creation, - * and smaller values (< 10) for indices that are interactively maintained. - * - * Default value is 10 - * - * @return integer - */ - public function getMergeFactor(); - - /** - * Set index mergeFactor option - * - * mergeFactor determines how often segment indices are merged by addDocument(). - * With smaller values, less RAM is used while indexing, - * and searches on unoptimized indices are faster, - * but indexing speed is slower. - * With larger values, more RAM is used during indexing, - * and while searches on unoptimized indices are slower, - * indexing is faster. - * Thus larger values (> 10) are best for batch index creation, - * and smaller values (< 10) for indices that are interactively maintained. - * - * Default value is 10 - * - * @param integer $maxMergeDocs - */ - public function setMergeFactor($mergeFactor); - - /** - * Performs a query against the index and returns an array - * of Zend_Search_Lucene_Search_QueryHit objects. - * Input is a string or Zend_Search_Lucene_Search_Query. - * - * @param mixed $query - * @return array Zend_Search_Lucene_Search_QueryHit - * @throws Zend_Search_Lucene_Exception - */ - public function find($query); - - /** - * Returns a list of all unique field names that exist in this index. - * - * @param boolean $indexed - * @return array - */ - public function getFieldNames($indexed = false); - - /** - * Returns a Zend_Search_Lucene_Document object for the document - * number $id in this index. - * - * @param integer|Zend_Search_Lucene_Search_QueryHit $id - * @return Zend_Search_Lucene_Document - */ - public function getDocument($id); - - /** - * Returns true if index contain documents with specified term. - * - * Is used for query optimization. - * - * @param Zend_Search_Lucene_Index_Term $term - * @return boolean - */ - public function hasTerm(Zend_Search_Lucene_Index_Term $term); - - /** - * Returns IDs of all the documents containing term. - * - * @param Zend_Search_Lucene_Index_Term $term - * @param Zend_Search_Lucene_Index_DocsFilter|null $docsFilter - * @return array - */ - public function termDocs(Zend_Search_Lucene_Index_Term $term, $docsFilter = null); - - /** - * Returns documents filter for all documents containing term. - * - * It performs the same operation as termDocs, but return result as - * Zend_Search_Lucene_Index_DocsFilter object - * - * @param Zend_Search_Lucene_Index_Term $term - * @param Zend_Search_Lucene_Index_DocsFilter|null $docsFilter - * @return Zend_Search_Lucene_Index_DocsFilter - */ - public function termDocsFilter(Zend_Search_Lucene_Index_Term $term, $docsFilter = null); - - /** - * Returns an array of all term freqs. - * Return array structure: array( docId => freq, ...) - * - * @param Zend_Search_Lucene_Index_Term $term - * @param Zend_Search_Lucene_Index_DocsFilter|null $docsFilter - * @return integer - */ - public function termFreqs(Zend_Search_Lucene_Index_Term $term, $docsFilter = null); - - /** - * Returns an array of all term positions in the documents. - * Return array structure: array( docId => array( pos1, pos2, ...), ...) - * - * @param Zend_Search_Lucene_Index_Term $term - * @param Zend_Search_Lucene_Index_DocsFilter|null $docsFilter - * @return array - */ - public function termPositions(Zend_Search_Lucene_Index_Term $term, $docsFilter = null); - - /** - * Returns the number of documents in this index containing the $term. - * - * @param Zend_Search_Lucene_Index_Term $term - * @return integer - */ - public function docFreq(Zend_Search_Lucene_Index_Term $term); - - /** - * Retrive similarity used by index reader - * - * @return Zend_Search_Lucene_Search_Similarity - */ - public function getSimilarity(); - - /** - * Returns a normalization factor for "field, document" pair. - * - * @param integer $id - * @param string $fieldName - * @return float - */ - public function norm($id, $fieldName); - - /** - * Returns true if any documents have been deleted from this index. - * - * @return boolean - */ - public function hasDeletions(); - - /** - * Deletes a document from the index. - * $id is an internal document id - * - * @param integer|Zend_Search_Lucene_Search_QueryHit $id - * @throws Zend_Search_Lucene_Exception - */ - public function delete($id); - - /** - * Adds a document to this index. - * - * @param Zend_Search_Lucene_Document $document - */ - public function addDocument(Zend_Search_Lucene_Document $document); - - /** - * Commit changes resulting from delete() or undeleteAll() operations. - */ - public function commit(); - - /** - * Optimize index. - * - * Merges all segments into one - */ - public function optimize(); - - /** - * Returns an array of all terms in this index. - * - * @return array - */ - public function terms(); - - /** - * Undeletes all documents currently marked as deleted in this index. - */ - public function undeleteAll(); - - - /** - * Add reference to the index object - * - * @internal - */ - public function addReference(); - - /** - * Remove reference from the index object - * - * When reference count becomes zero, index is closed and resources are cleaned up - * - * @internal - */ - public function removeReference(); -} diff --git a/library/Zend/Search/Lucene/Interface/MultiSearcher.php b/library/Zend/Search/Lucene/Interface/MultiSearcher.php deleted file mode 100644 index 5753feffdc..0000000000 --- a/library/Zend/Search/Lucene/Interface/MultiSearcher.php +++ /dev/null @@ -1,25 +0,0 @@ -createFile(self::WRITE_LOCK_FILE); - if (!$lock->lock(LOCK_EX)) { - #require_once 'Zend/Search/Lucene/Exception.php'; - throw new Zend_Search_Lucene_Exception('Can\'t obtain exclusive index lock'); - } - return $lock; - } - - /** - * Release exclusive write lock - * - * @param Zend_Search_Lucene_Storage_Directory $lockDirectory - */ - public static function releaseWriteLock(Zend_Search_Lucene_Storage_Directory $lockDirectory) - { - $lock = $lockDirectory->getFileObject(self::WRITE_LOCK_FILE); - $lock->unlock(); - } - - /** - * Obtain the exclusive "read escalation/de-escalation" lock - * - * Required to protect the escalate/de-escalate read lock process - * on GFS (and potentially other) mounted filesystems. - * - * Why we need this: - * While GFS supports cluster-wide locking via flock(), it's - * implementation isn't quite what it should be. The locking - * semantics that work consistently on a local filesystem tend to - * fail on GFS mounted filesystems. This appears to be a design defect - * in the implementation of GFS. How this manifests itself is that - * conditional promotion of a shared lock to exclusive will always - * fail, lock release requests are honored but not immediately - * processed (causing erratic failures of subsequent conditional - * requests) and the releasing of the exclusive lock before the - * shared lock is set when a lock is demoted (which can open a window - * of opportunity for another process to gain an exclusive lock when - * it shoudln't be allowed to). - * - * @param Zend_Search_Lucene_Storage_Directory $lockDirectory - * @return Zend_Search_Lucene_Storage_File - * @throws Zend_Search_Lucene_Exception - */ - private static function _startReadLockProcessing(Zend_Search_Lucene_Storage_Directory $lockDirectory) - { - $lock = $lockDirectory->createFile(self::READ_LOCK_PROCESSING_LOCK_FILE); - if (!$lock->lock(LOCK_EX)) { - #require_once 'Zend/Search/Lucene/Exception.php'; - throw new Zend_Search_Lucene_Exception('Can\'t obtain exclusive lock for the read lock processing file'); - } - return $lock; - } - - /** - * Release the exclusive "read escalation/de-escalation" lock - * - * Required to protect the escalate/de-escalate read lock process - * on GFS (and potentially other) mounted filesystems. - * - * @param Zend_Search_Lucene_Storage_Directory $lockDirectory - */ - private static function _stopReadLockProcessing(Zend_Search_Lucene_Storage_Directory $lockDirectory) - { - $lock = $lockDirectory->getFileObject(self::READ_LOCK_PROCESSING_LOCK_FILE); - $lock->unlock(); - } - - - /** - * Obtain shared read lock on the index - * - * It doesn't block other read or update processes, but prevent index from the premature cleaning-up - * - * @param Zend_Search_Lucene_Storage_Directory $defaultLockDirectory - * @return Zend_Search_Lucene_Storage_File - * @throws Zend_Search_Lucene_Exception - */ - public static function obtainReadLock(Zend_Search_Lucene_Storage_Directory $lockDirectory) - { - $lock = $lockDirectory->createFile(self::READ_LOCK_FILE); - if (!$lock->lock(LOCK_SH)) { - #require_once 'Zend/Search/Lucene/Exception.php'; - throw new Zend_Search_Lucene_Exception('Can\'t obtain shared reading index lock'); - } - return $lock; - } - - /** - * Release shared read lock - * - * @param Zend_Search_Lucene_Storage_Directory $lockDirectory - */ - public static function releaseReadLock(Zend_Search_Lucene_Storage_Directory $lockDirectory) - { - $lock = $lockDirectory->getFileObject(self::READ_LOCK_FILE); - $lock->unlock(); - } - - /** - * Escalate Read lock to exclusive level - * - * @param Zend_Search_Lucene_Storage_Directory $lockDirectory - * @return boolean - */ - public static function escalateReadLock(Zend_Search_Lucene_Storage_Directory $lockDirectory) - { - self::_startReadLockProcessing($lockDirectory); - - $lock = $lockDirectory->getFileObject(self::READ_LOCK_FILE); - - // First, release the shared lock for the benefit of GFS since - // it will fail the conditional request to promote the lock to - // "exclusive" while the shared lock is held (even when we are - // the only holder). - $lock->unlock(); - - // GFS is really poor. While the above "unlock" returns, GFS - // doesn't clean up it's tables right away (which will potentially - // cause the conditional locking for the "exclusive" lock to fail. - // We will retry the conditional lock request several times on a - // failure to get past this. The performance hit is negligible - // in the grand scheme of things and only will occur with GFS - // filesystems or if another local process has the shared lock - // on local filesystems. - for ($retries = 0; $retries < 10; $retries++) { - if ($lock->lock(LOCK_EX, true)) { - // Exclusive lock is obtained! - self::_stopReadLockProcessing($lockDirectory); - return true; - } - - // wait 1 microsecond - usleep(1); - } - - // Restore lock state - $lock->lock(LOCK_SH); - - self::_stopReadLockProcessing($lockDirectory); - return false; - } - - /** - * De-escalate Read lock to shared level - * - * @param Zend_Search_Lucene_Storage_Directory $lockDirectory - */ - public static function deEscalateReadLock(Zend_Search_Lucene_Storage_Directory $lockDirectory) - { - $lock = $lockDirectory->getFileObject(self::READ_LOCK_FILE); - $lock->lock(LOCK_SH); - } - - /** - * Obtain exclusive optimization lock on the index - * - * Returns lock object on success and false otherwise (doesn't block execution) - * - * @param Zend_Search_Lucene_Storage_Directory $lockDirectory - * @return mixed - */ - public static function obtainOptimizationLock(Zend_Search_Lucene_Storage_Directory $lockDirectory) - { - $lock = $lockDirectory->createFile(self::OPTIMIZATION_LOCK_FILE); - if (!$lock->lock(LOCK_EX, true)) { - return false; - } - return $lock; - } - - /** - * Release exclusive optimization lock - * - * @param Zend_Search_Lucene_Storage_Directory $lockDirectory - */ - public static function releaseOptimizationLock(Zend_Search_Lucene_Storage_Directory $lockDirectory) - { - $lock = $lockDirectory->getFileObject(self::OPTIMIZATION_LOCK_FILE); - $lock->unlock(); - } - -} diff --git a/library/Zend/Search/Lucene/MultiSearcher.php b/library/Zend/Search/Lucene/MultiSearcher.php deleted file mode 100644 index b91dc66a5c..0000000000 --- a/library/Zend/Search/Lucene/MultiSearcher.php +++ /dev/null @@ -1,992 +0,0 @@ -_indices = $indices; - - foreach ($this->_indices as $index) { - if (!$index instanceof Zend_Search_Lucene_Interface) { - #require_once 'Zend/Search/Lucene/Exception.php'; - throw new Zend_Search_Lucene_Exception('sub-index objects have to implement Zend_Search_Lucene_Interface.'); - } - } - } - - /** - * Add index for searching. - * - * @param Zend_Search_Lucene_Interface $index - */ - public function addIndex(Zend_Search_Lucene_Interface $index) - { - $this->_indices[] = $index; - } - - - /** - * Get current generation number - * - * Returns generation number - * 0 means pre-2.1 index format - * -1 means there are no segments files. - * - * @param Zend_Search_Lucene_Storage_Directory $directory - * @return integer - * @throws Zend_Search_Lucene_Exception - */ - public static function getActualGeneration(Zend_Search_Lucene_Storage_Directory $directory) - { - #require_once 'Zend/Search/Lucene/Exception.php'; - throw new Zend_Search_Lucene_Exception("Generation number can't be retrieved for multi-searcher"); - } - - /** - * Get segments file name - * - * @param integer $generation - * @return string - */ - public static function getSegmentFileName($generation) - { - return Zend_Search_Lucene::getSegmentFileName($generation); - } - - /** - * Get index format version - * - * @return integer - * @throws Zend_Search_Lucene_Exception - */ - public function getFormatVersion() - { - #require_once 'Zend/Search/Lucene/Exception.php'; - throw new Zend_Search_Lucene_Exception("Format version can't be retrieved for multi-searcher"); - } - - /** - * Set index format version. - * Index is converted to this format at the nearest upfdate time - * - * @param int $formatVersion - */ - public function setFormatVersion($formatVersion) - { - foreach ($this->_indices as $index) { - $index->setFormatVersion($formatVersion); - } - } - - /** - * Returns the Zend_Search_Lucene_Storage_Directory instance for this index. - * - * @return Zend_Search_Lucene_Storage_Directory - */ - public function getDirectory() - { - #require_once 'Zend/Search/Lucene/Exception.php'; - throw new Zend_Search_Lucene_Exception("Index directory can't be retrieved for multi-searcher"); - } - - /** - * Returns the total number of documents in this index (including deleted documents). - * - * @return integer - */ - public function count() - { - $count = 0; - - foreach ($this->_indices as $index) { - $count += $index->count(); - } - - return $count; - } - - /** - * Returns one greater than the largest possible document number. - * This may be used to, e.g., determine how big to allocate a structure which will have - * an element for every document number in an index. - * - * @return integer - */ - public function maxDoc() - { - return $this->count(); - } - - /** - * Returns the total number of non-deleted documents in this index. - * - * @return integer - */ - public function numDocs() - { - $docs = 0; - - foreach ($this->_indices as $index) { - $docs += $index->numDocs(); - } - - return $docs; - } - - /** - * Checks, that document is deleted - * - * @param integer $id - * @return boolean - * @throws Zend_Search_Lucene_Exception Exception is thrown if $id is out of the range - */ - public function isDeleted($id) - { - foreach ($this->_indices as $index) { - $indexCount = $index->count(); - - if ($indexCount > $id) { - return $index->isDeleted($id); - } - - $id -= $indexCount; - } - - #require_once 'Zend/Search/Lucene/Exception.php'; - throw new Zend_Search_Lucene_Exception('Document id is out of the range.'); - } - - /** - * Set default search field. - * - * Null means, that search is performed through all fields by default - * - * Default value is null - * - * @param string $fieldName - */ - public static function setDefaultSearchField($fieldName) - { - foreach ($this->_indices as $index) { - $index->setDefaultSearchField($fieldName); - } - } - - - /** - * Get default search field. - * - * Null means, that search is performed through all fields by default - * - * @return string - * @throws Zend_Search_Lucene_Exception - */ - public static function getDefaultSearchField() - { - if (count($this->_indices) == 0) { - #require_once 'Zend/Search/Lucene/Exception.php'; - throw new Zend_Search_Lucene_Exception('Indices list is empty'); - } - - $defaultSearchField = reset($this->_indices)->getDefaultSearchField(); - - foreach ($this->_indices as $index) { - if ($index->getDefaultSearchField() !== $defaultSearchField) { - #require_once 'Zend/Search/Lucene/Exception.php'; - throw new Zend_Search_Lucene_Exception('Indices have different default search field.'); - } - } - - return $defaultSearchField; - } - - /** - * Set result set limit. - * - * 0 (default) means no limit - * - * @param integer $limit - */ - public static function setResultSetLimit($limit) - { - foreach ($this->_indices as $index) { - $index->setResultSetLimit($limit); - } - } - - /** - * Set result set limit. - * - * 0 means no limit - * - * @return integer - * @throws Zend_Search_Lucene_Exception - */ - public static function getResultSetLimit() - { - if (count($this->_indices) == 0) { - #require_once 'Zend/Search/Lucene/Exception.php'; - throw new Zend_Search_Lucene_Exception('Indices list is empty'); - } - - $defaultResultSetLimit = reset($this->_indices)->getResultSetLimit(); - - foreach ($this->_indices as $index) { - if ($index->getResultSetLimit() !== $defaultResultSetLimit) { - #require_once 'Zend/Search/Lucene/Exception.php'; - throw new Zend_Search_Lucene_Exception('Indices have different default search field.'); - } - } - - return $defaultResultSetLimit; - } - - /** - * Retrieve index maxBufferedDocs option - * - * maxBufferedDocs is a minimal number of documents required before - * the buffered in-memory documents are written into a new Segment - * - * Default value is 10 - * - * @return integer - * @throws Zend_Search_Lucene_Exception - */ - public function getMaxBufferedDocs() - { - if (count($this->_indices) == 0) { - #require_once 'Zend/Search/Lucene/Exception.php'; - throw new Zend_Search_Lucene_Exception('Indices list is empty'); - } - - $maxBufferedDocs = reset($this->_indices)->getMaxBufferedDocs(); - - foreach ($this->_indices as $index) { - if ($index->getMaxBufferedDocs() !== $maxBufferedDocs) { - #require_once 'Zend/Search/Lucene/Exception.php'; - throw new Zend_Search_Lucene_Exception('Indices have different default search field.'); - } - } - - return $maxBufferedDocs; - } - - /** - * Set index maxBufferedDocs option - * - * maxBufferedDocs is a minimal number of documents required before - * the buffered in-memory documents are written into a new Segment - * - * Default value is 10 - * - * @param integer $maxBufferedDocs - */ - public function setMaxBufferedDocs($maxBufferedDocs) - { - foreach ($this->_indices as $index) { - $index->setMaxBufferedDocs($maxBufferedDocs); - } - } - - /** - * Retrieve index maxMergeDocs option - * - * maxMergeDocs is a largest number of documents ever merged by addDocument(). - * Small values (e.g., less than 10,000) are best for interactive indexing, - * as this limits the length of pauses while indexing to a few seconds. - * Larger values are best for batched indexing and speedier searches. - * - * Default value is PHP_INT_MAX - * - * @return integer - * @throws Zend_Search_Lucene_Exception - */ - public function getMaxMergeDocs() - { - if (count($this->_indices) == 0) { - #require_once 'Zend/Search/Lucene/Exception.php'; - throw new Zend_Search_Lucene_Exception('Indices list is empty'); - } - - $maxMergeDocs = reset($this->_indices)->getMaxMergeDocs(); - - foreach ($this->_indices as $index) { - if ($index->getMaxMergeDocs() !== $maxMergeDocs) { - #require_once 'Zend/Search/Lucene/Exception.php'; - throw new Zend_Search_Lucene_Exception('Indices have different default search field.'); - } - } - - return $maxMergeDocs; - } - - /** - * Set index maxMergeDocs option - * - * maxMergeDocs is a largest number of documents ever merged by addDocument(). - * Small values (e.g., less than 10,000) are best for interactive indexing, - * as this limits the length of pauses while indexing to a few seconds. - * Larger values are best for batched indexing and speedier searches. - * - * Default value is PHP_INT_MAX - * - * @param integer $maxMergeDocs - */ - public function setMaxMergeDocs($maxMergeDocs) - { - foreach ($this->_indices as $index) { - $index->setMaxMergeDocs($maxMergeDocs); - } - } - - /** - * Retrieve index mergeFactor option - * - * mergeFactor determines how often segment indices are merged by addDocument(). - * With smaller values, less RAM is used while indexing, - * and searches on unoptimized indices are faster, - * but indexing speed is slower. - * With larger values, more RAM is used during indexing, - * and while searches on unoptimized indices are slower, - * indexing is faster. - * Thus larger values (> 10) are best for batch index creation, - * and smaller values (< 10) for indices that are interactively maintained. - * - * Default value is 10 - * - * @return integer - * @throws Zend_Search_Lucene_Exception - */ - public function getMergeFactor() - { - if (count($this->_indices) == 0) { - #require_once 'Zend/Search/Lucene/Exception.php'; - throw new Zend_Search_Lucene_Exception('Indices list is empty'); - } - - $mergeFactor = reset($this->_indices)->getMergeFactor(); - - foreach ($this->_indices as $index) { - if ($index->getMergeFactor() !== $mergeFactor) { - #require_once 'Zend/Search/Lucene/Exception.php'; - throw new Zend_Search_Lucene_Exception('Indices have different default search field.'); - } - } - - return $mergeFactor; - } - - /** - * Set index mergeFactor option - * - * mergeFactor determines how often segment indices are merged by addDocument(). - * With smaller values, less RAM is used while indexing, - * and searches on unoptimized indices are faster, - * but indexing speed is slower. - * With larger values, more RAM is used during indexing, - * and while searches on unoptimized indices are slower, - * indexing is faster. - * Thus larger values (> 10) are best for batch index creation, - * and smaller values (< 10) for indices that are interactively maintained. - * - * Default value is 10 - * - * @param integer $maxMergeDocs - */ - public function setMergeFactor($mergeFactor) - { - foreach ($this->_indices as $index) { - $index->setMaxMergeDocs($mergeFactor); - } - } - - /** - * Performs a query against the index and returns an array - * of Zend_Search_Lucene_Search_QueryHit objects. - * Input is a string or Zend_Search_Lucene_Search_Query. - * - * @param mixed $query - * @return array Zend_Search_Lucene_Search_QueryHit - * @throws Zend_Search_Lucene_Exception - */ - public function find($query) - { - if (count($this->_indices) == 0) { - return array(); - } - - $hitsList = array(); - - $indexShift = 0; - foreach ($this->_indices as $index) { - $hits = $index->find($query); - - if ($indexShift != 0) { - foreach ($hits as $hit) { - $hit->id += $indexShift; - } - } - - $indexShift += $index->count(); - $hitsList[] = $hits; - } - - /** @todo Implement advanced sorting */ - - return call_user_func_array('array_merge', $hitsList); - } - - /** - * Returns a list of all unique field names that exist in this index. - * - * @param boolean $indexed - * @return array - */ - public function getFieldNames($indexed = false) - { - $fieldNamesList = array(); - - foreach ($this->_indices as $index) { - $fieldNamesList[] = $index->getFieldNames($indexed); - } - - return array_unique(call_user_func_array('array_merge', $fieldNamesList)); - } - - /** - * Returns a Zend_Search_Lucene_Document object for the document - * number $id in this index. - * - * @param integer|Zend_Search_Lucene_Search_QueryHit $id - * @return Zend_Search_Lucene_Document - * @throws Zend_Search_Lucene_Exception Exception is thrown if $id is out of the range - */ - public function getDocument($id) - { - if ($id instanceof Zend_Search_Lucene_Search_QueryHit) { - /* @var $id Zend_Search_Lucene_Search_QueryHit */ - $id = $id->id; - } - - foreach ($this->_indices as $index) { - $indexCount = $index->count(); - - if ($indexCount > $id) { - return $index->getDocument($id); - } - - $id -= $indexCount; - } - - #require_once 'Zend/Search/Lucene/Exception.php'; - throw new Zend_Search_Lucene_Exception('Document id is out of the range.'); - } - - /** - * Returns true if index contain documents with specified term. - * - * Is used for query optimization. - * - * @param Zend_Search_Lucene_Index_Term $term - * @return boolean - */ - public function hasTerm(Zend_Search_Lucene_Index_Term $term) - { - foreach ($this->_indices as $index) { - if ($index->hasTerm($term)) { - return true; - } - } - - return false; - } - - /** - * Returns IDs of all the documents containing term. - * - * @param Zend_Search_Lucene_Index_Term $term - * @param Zend_Search_Lucene_Index_DocsFilter|null $docsFilter - * @return array - * @throws Zend_Search_Lucene_Exception - */ - public function termDocs(Zend_Search_Lucene_Index_Term $term, $docsFilter = null) - { - if ($docsFilter != null) { - #require_once 'Zend/Search/Lucene/Exception.php'; - throw new Zend_Search_Lucene_Exception('Document filters could not used with multi-searcher'); - } - - $docsList = array(); - - $indexShift = 0; - foreach ($this->_indices as $index) { - $docs = $index->termDocs($term); - - if ($indexShift != 0) { - foreach ($docs as $id => $docId) { - $docs[$id] += $indexShift; - } - } - - $indexShift += $index->count(); - $docsList[] = $docs; - } - - return call_user_func_array('array_merge', $docsList); - } - - /** - * Returns documents filter for all documents containing term. - * - * It performs the same operation as termDocs, but return result as - * Zend_Search_Lucene_Index_DocsFilter object - * - * @param Zend_Search_Lucene_Index_Term $term - * @param Zend_Search_Lucene_Index_DocsFilter|null $docsFilter - * @return Zend_Search_Lucene_Index_DocsFilter - * @throws Zend_Search_Lucene_Exception - */ - public function termDocsFilter(Zend_Search_Lucene_Index_Term $term, $docsFilter = null) - { - #require_once 'Zend/Search/Lucene/Exception.php'; - throw new Zend_Search_Lucene_Exception('Document filters could not used with multi-searcher'); - } - - /** - * Returns an array of all term freqs. - * Return array structure: array( docId => freq, ...) - * - * @param Zend_Search_Lucene_Index_Term $term - * @param Zend_Search_Lucene_Index_DocsFilter|null $docsFilter - * @return integer - * @throws Zend_Search_Lucene_Exception - */ - public function termFreqs(Zend_Search_Lucene_Index_Term $term, $docsFilter = null) - { - if ($docsFilter != null) { - #require_once 'Zend/Search/Lucene/Exception.php'; - throw new Zend_Search_Lucene_Exception('Document filters could not used with multi-searcher'); - } - - $freqsList = array(); - - $indexShift = 0; - foreach ($this->_indices as $index) { - $freqs = $index->termFreqs($term); - - if ($indexShift != 0) { - $freqsShifted = array(); - - foreach ($freqs as $docId => $freq) { - $freqsShifted[$docId + $indexShift] = $freq; - } - $freqs = $freqsShifted; - } - - $indexShift += $index->count(); - $freqsList[] = $freqs; - } - - return call_user_func_array('array_merge', $freqsList); - } - - /** - * Returns an array of all term positions in the documents. - * Return array structure: array( docId => array( pos1, pos2, ...), ...) - * - * @param Zend_Search_Lucene_Index_Term $term - * @param Zend_Search_Lucene_Index_DocsFilter|null $docsFilter - * @return array - * @throws Zend_Search_Lucene_Exception - */ - public function termPositions(Zend_Search_Lucene_Index_Term $term, $docsFilter = null) - { - if ($docsFilter != null) { - #require_once 'Zend/Search/Lucene/Exception.php'; - throw new Zend_Search_Lucene_Exception('Document filters could not used with multi-searcher'); - } - - $termPositionsList = array(); - - $indexShift = 0; - foreach ($this->_indices as $index) { - $termPositions = $index->termPositions($term); - - if ($indexShift != 0) { - $termPositionsShifted = array(); - - foreach ($termPositions as $docId => $positions) { - $termPositions[$docId + $indexShift] = $positions; - } - $termPositions = $termPositionsShifted; - } - - $indexShift += $index->count(); - $termPositionsList[] = $termPositions; - } - - return call_user_func_array('array_merge', $termPositions); - } - - /** - * Returns the number of documents in this index containing the $term. - * - * @param Zend_Search_Lucene_Index_Term $term - * @return integer - */ - public function docFreq(Zend_Search_Lucene_Index_Term $term) - { - $docFreq = 0; - - foreach ($this->_indices as $index) { - $docFreq += $index->docFreq($term); - } - - return $docFreq; - } - - /** - * Retrive similarity used by index reader - * - * @return Zend_Search_Lucene_Search_Similarity - * @throws Zend_Search_Lucene_Exception - */ - public function getSimilarity() - { - if (count($this->_indices) == 0) { - #require_once 'Zend/Search/Lucene/Exception.php'; - throw new Zend_Search_Lucene_Exception('Indices list is empty'); - } - - $similarity = reset($this->_indices)->getSimilarity(); - - foreach ($this->_indices as $index) { - if ($index->getSimilarity() !== $similarity) { - #require_once 'Zend/Search/Lucene/Exception.php'; - throw new Zend_Search_Lucene_Exception('Indices have different similarity.'); - } - } - - return $similarity; - } - - /** - * Returns a normalization factor for "field, document" pair. - * - * @param integer $id - * @param string $fieldName - * @return float - */ - public function norm($id, $fieldName) - { - foreach ($this->_indices as $index) { - $indexCount = $index->count(); - - if ($indexCount > $id) { - return $index->norm($id, $fieldName); - } - - $id -= $indexCount; - } - - return null; - } - - /** - * Returns true if any documents have been deleted from this index. - * - * @return boolean - */ - public function hasDeletions() - { - foreach ($this->_indices as $index) { - if ($index->hasDeletions()) { - return true; - } - } - - return false; - } - - /** - * Deletes a document from the index. - * $id is an internal document id - * - * @param integer|Zend_Search_Lucene_Search_QueryHit $id - * @throws Zend_Search_Lucene_Exception - */ - public function delete($id) - { - foreach ($this->_indices as $index) { - $indexCount = $index->count(); - - if ($indexCount > $id) { - $index->delete($id); - return; - } - - $id -= $indexCount; - } - - #require_once 'Zend/Search/Lucene/Exception.php'; - throw new Zend_Search_Lucene_Exception('Document id is out of the range.'); - } - - - /** - * Callback used to choose target index for new documents - * - * Function/method signature: - * Zend_Search_Lucene_Interface callbackFunction(Zend_Search_Lucene_Document $document, array $indices); - * - * null means "default documents distributing algorithm" - * - * @var callback - */ - protected $_documentDistributorCallBack = null; - - /** - * Set callback for choosing target index. - * - * @param callback $callback - * @throws Zend_Search_Lucene_Exception - */ - public function setDocumentDistributorCallback($callback) - { - if ($callback !== null && !is_callable($callback)) { - #require_once 'Zend/Search/Lucene/Exception.php'; - throw new Zend_Search_Lucene_Exception('$callback parameter must be a valid callback.'); - } - - $this->_documentDistributorCallBack = $callback; - } - - /** - * Get callback for choosing target index. - * - * @return callback - */ - public function getDocumentDistributorCallback() - { - return $this->_documentDistributorCallBack; - } - - /** - * Adds a document to this index. - * - * @param Zend_Search_Lucene_Document $document - * @throws Zend_Search_Lucene_Exception - */ - public function addDocument(Zend_Search_Lucene_Document $document) - { - if ($this->_documentDistributorCallBack !== null) { - $index = call_user_func($this->_documentDistributorCallBack, $document, $this->_indices); - } else { - $index = $this->_indices[array_rand($this->_indices)]; - } - - $index->addDocument($document); - } - - /** - * Commit changes resulting from delete() or undeleteAll() operations. - */ - public function commit() - { - foreach ($this->_indices as $index) { - $index->commit(); - } - } - - /** - * Optimize index. - * - * Merges all segments into one - */ - public function optimize() - { - foreach ($this->_indices as $index) { - $index->optimise(); - } - } - - /** - * Returns an array of all terms in this index. - * - * @return array - */ - public function terms() - { - $termsList = array(); - - foreach ($this->_indices as $index) { - $termsList[] = $index->terms(); - } - - return array_unique(call_user_func_array('array_merge', $termsList)); - } - - - /** - * Terms stream priority queue object - * - * @var Zend_Search_Lucene_TermStreamsPriorityQueue - */ - private $_termsStream = null; - - /** - * Reset terms stream. - */ - public function resetTermsStream() - { - if ($this->_termsStream === null) { - /** Zend_Search_Lucene_TermStreamsPriorityQueue */ - #require_once 'Zend/Search/Lucene/TermStreamsPriorityQueue.php'; - - $this->_termsStream = new Zend_Search_Lucene_TermStreamsPriorityQueue($this->_indices); - } else { - $this->_termsStream->resetTermsStream(); - } - } - - /** - * 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 - */ - public function skipTo(Zend_Search_Lucene_Index_Term $prefix) - { - $this->_termsStream->skipTo($prefix); - } - - /** - * Scans terms dictionary and returns next term - * - * @return Zend_Search_Lucene_Index_Term|null - */ - public function nextTerm() - { - return $this->_termsStream->nextTerm(); - } - - /** - * Returns term in current position - * - * @return Zend_Search_Lucene_Index_Term|null - */ - public function currentTerm() - { - return $this->_termsStream->currentTerm(); - } - - /** - * Close terms stream - * - * Should be used for resources clean up if stream is not read up to the end - */ - public function closeTermsStream() - { - $this->_termsStream->closeTermsStream(); - $this->_termsStream = null; - } - - - /** - * Undeletes all documents currently marked as deleted in this index. - */ - public function undeleteAll() - { - foreach ($this->_indices as $index) { - $index->undeleteAll(); - } - } - - - /** - * Add reference to the index object - * - * @internal - */ - public function addReference() - { - // Do nothing, since it's never referenced by indices - } - - /** - * Remove reference from the index object - * - * When reference count becomes zero, index is closed and resources are cleaned up - * - * @internal - */ - public function removeReference() - { - // Do nothing, since it's never referenced by indices - } -} - -/** - * This class is provided for backwards-compatibility (See ZF-12067) - * - * @category Zend - * @package Zend_Search_Lucene - * @copyright Copyright (c) 2005-2015 Zend Technologies USA Inc. (http://www.zend.com) - * @license http://framework.zend.com/license/new-bsd New BSD License - */ -class Zend_Search_Lucene_Interface_MultiSearcher - extends Zend_Search_Lucene_MultiSearcher -{ -} diff --git a/library/Zend/Search/Lucene/PriorityQueue.php b/library/Zend/Search/Lucene/PriorityQueue.php deleted file mode 100644 index f34c1cbdaa..0000000000 --- a/library/Zend/Search/Lucene/PriorityQueue.php +++ /dev/null @@ -1,171 +0,0 @@ -_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; - } - - - /** - * Return least element of the queue - * - * Constant time - * - * @return mixed - */ - public function top() - { - if (count($this->_heap) == 0) { - return null; - } - - return $this->_heap[0]; - } - - - /** - * Removes and return least element of the queue - * - * O(log(N)) time - * - * @return mixed - */ - 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; - } - - - /** - * Clear queue - */ - public function clear() - { - $this->_heap = array(); - } - - - /** - * Compare elements - * - * Returns true, if $el1 is less than $el2; else otherwise - * - * @param mixed $el1 - * @param mixed $el2 - * @return boolean - */ - abstract protected function _less($el1, $el2); -} - diff --git a/library/Zend/Search/Lucene/Proxy.php b/library/Zend/Search/Lucene/Proxy.php deleted file mode 100644 index 7aff117b1a..0000000000 --- a/library/Zend/Search/Lucene/Proxy.php +++ /dev/null @@ -1,612 +0,0 @@ -_index = $index; - $this->_index->addReference(); - } - - /** - * Object destructor - */ - public function __destruct() - { - if ($this->_index !== null) { - // This code is invoked if Zend_Search_Lucene_Interface object constructor throws an exception - $this->_index->removeReference(); - } - $this->_index = null; - } - - /** - * Get current generation number - * - * Returns generation number - * 0 means pre-2.1 index format - * -1 means there are no segments files. - * - * @param Zend_Search_Lucene_Storage_Directory $directory - * @return integer - * @throws Zend_Search_Lucene_Exception - */ - public static function getActualGeneration(Zend_Search_Lucene_Storage_Directory $directory) - { - Zend_Search_Lucene::getActualGeneration($directory); - } - - /** - * Get segments file name - * - * @param integer $generation - * @return string - */ - public static function getSegmentFileName($generation) - { - Zend_Search_Lucene::getSegmentFileName($generation); - } - - /** - * Get index format version - * - * @return integer - */ - public function getFormatVersion() - { - return $this->_index->getFormatVersion(); - } - - /** - * Set index format version. - * Index is converted to this format at the nearest upfdate time - * - * @param int $formatVersion - * @throws Zend_Search_Lucene_Exception - */ - public function setFormatVersion($formatVersion) - { - $this->_index->setFormatVersion($formatVersion); - } - - /** - * Returns the Zend_Search_Lucene_Storage_Directory instance for this index. - * - * @return Zend_Search_Lucene_Storage_Directory - */ - public function getDirectory() - { - return $this->_index->getDirectory(); - } - - /** - * Returns the total number of documents in this index (including deleted documents). - * - * @return integer - */ - public function count() - { - return $this->_index->count(); - } - - /** - * Returns one greater than the largest possible document number. - * This may be used to, e.g., determine how big to allocate a structure which will have - * an element for every document number in an index. - * - * @return integer - */ - public function maxDoc() - { - return $this->_index->maxDoc(); - } - - /** - * Returns the total number of non-deleted documents in this index. - * - * @return integer - */ - public function numDocs() - { - return $this->_index->numDocs(); - } - - /** - * Checks, that document is deleted - * - * @param integer $id - * @return boolean - * @throws Zend_Search_Lucene_Exception Exception is thrown if $id is out of the range - */ - public function isDeleted($id) - { - return $this->_index->isDeleted($id); - } - - /** - * Set default search field. - * - * Null means, that search is performed through all fields by default - * - * Default value is null - * - * @param string $fieldName - */ - public static function setDefaultSearchField($fieldName) - { - Zend_Search_Lucene::setDefaultSearchField($fieldName); - } - - /** - * Get default search field. - * - * Null means, that search is performed through all fields by default - * - * @return string - */ - public static function getDefaultSearchField() - { - return Zend_Search_Lucene::getDefaultSearchField(); - } - - /** - * Set result set limit. - * - * 0 (default) means no limit - * - * @param integer $limit - */ - public static function setResultSetLimit($limit) - { - Zend_Search_Lucene::setResultSetLimit($limit); - } - - /** - * Set result set limit. - * - * 0 means no limit - * - * @return integer - */ - public static function getResultSetLimit() - { - return Zend_Search_Lucene::getResultSetLimit(); - } - - /** - * Retrieve index maxBufferedDocs option - * - * maxBufferedDocs is a minimal number of documents required before - * the buffered in-memory documents are written into a new Segment - * - * Default value is 10 - * - * @return integer - */ - public function getMaxBufferedDocs() - { - return $this->_index->getMaxBufferedDocs(); - } - - /** - * Set index maxBufferedDocs option - * - * maxBufferedDocs is a minimal number of documents required before - * the buffered in-memory documents are written into a new Segment - * - * Default value is 10 - * - * @param integer $maxBufferedDocs - */ - public function setMaxBufferedDocs($maxBufferedDocs) - { - $this->_index->setMaxBufferedDocs($maxBufferedDocs); - } - - - /** - * Retrieve index maxMergeDocs option - * - * maxMergeDocs is a largest number of documents ever merged by addDocument(). - * Small values (e.g., less than 10,000) are best for interactive indexing, - * as this limits the length of pauses while indexing to a few seconds. - * Larger values are best for batched indexing and speedier searches. - * - * Default value is PHP_INT_MAX - * - * @return integer - */ - public function getMaxMergeDocs() - { - return $this->_index->getMaxMergeDocs(); - } - - /** - * Set index maxMergeDocs option - * - * maxMergeDocs is a largest number of documents ever merged by addDocument(). - * Small values (e.g., less than 10,000) are best for interactive indexing, - * as this limits the length of pauses while indexing to a few seconds. - * Larger values are best for batched indexing and speedier searches. - * - * Default value is PHP_INT_MAX - * - * @param integer $maxMergeDocs - */ - public function setMaxMergeDocs($maxMergeDocs) - { - $this->_index->setMaxMergeDocs($maxMergeDocs); - } - - - /** - * Retrieve index mergeFactor option - * - * mergeFactor determines how often segment indices are merged by addDocument(). - * With smaller values, less RAM is used while indexing, - * and searches on unoptimized indices are faster, - * but indexing speed is slower. - * With larger values, more RAM is used during indexing, - * and while searches on unoptimized indices are slower, - * indexing is faster. - * Thus larger values (> 10) are best for batch index creation, - * and smaller values (< 10) for indices that are interactively maintained. - * - * Default value is 10 - * - * @return integer - */ - public function getMergeFactor() - { - return $this->_index->getMergeFactor(); - } - - /** - * Set index mergeFactor option - * - * mergeFactor determines how often segment indices are merged by addDocument(). - * With smaller values, less RAM is used while indexing, - * and searches on unoptimized indices are faster, - * but indexing speed is slower. - * With larger values, more RAM is used during indexing, - * and while searches on unoptimized indices are slower, - * indexing is faster. - * Thus larger values (> 10) are best for batch index creation, - * and smaller values (< 10) for indices that are interactively maintained. - * - * Default value is 10 - * - * @param integer $maxMergeDocs - */ - public function setMergeFactor($mergeFactor) - { - $this->_index->setMergeFactor($mergeFactor); - } - - /** - * Performs a query against the index and returns an array - * of Zend_Search_Lucene_Search_QueryHit objects. - * Input is a string or Zend_Search_Lucene_Search_Query. - * - * @param mixed $query - * @return array Zend_Search_Lucene_Search_QueryHit - * @throws Zend_Search_Lucene_Exception - */ - public function find($query) - { - // actual parameter list - $parameters = func_get_args(); - - // invoke $this->_index->find() method with specified parameters - return call_user_func_array(array(&$this->_index, 'find'), $parameters); - } - - /** - * Returns a list of all unique field names that exist in this index. - * - * @param boolean $indexed - * @return array - */ - public function getFieldNames($indexed = false) - { - return $this->_index->getFieldNames($indexed); - } - - /** - * Returns a Zend_Search_Lucene_Document object for the document - * number $id in this index. - * - * @param integer|Zend_Search_Lucene_Search_QueryHit $id - * @return Zend_Search_Lucene_Document - */ - public function getDocument($id) - { - return $this->_index->getDocument($id); - } - - /** - * Returns true if index contain documents with specified term. - * - * Is used for query optimization. - * - * @param Zend_Search_Lucene_Index_Term $term - * @return boolean - */ - public function hasTerm(Zend_Search_Lucene_Index_Term $term) - { - return $this->_index->hasTerm($term); - } - - /** - * Returns IDs of all the documents containing term. - * - * @param Zend_Search_Lucene_Index_Term $term - * @param Zend_Search_Lucene_Index_DocsFilter|null $docsFilter - * @return array - */ - public function termDocs(Zend_Search_Lucene_Index_Term $term, $docsFilter = null) - { - return $this->_index->termDocs($term, $docsFilter); - } - - /** - * Returns documents filter for all documents containing term. - * - * It performs the same operation as termDocs, but return result as - * Zend_Search_Lucene_Index_DocsFilter object - * - * @param Zend_Search_Lucene_Index_Term $term - * @param Zend_Search_Lucene_Index_DocsFilter|null $docsFilter - * @return Zend_Search_Lucene_Index_DocsFilter - */ - public function termDocsFilter(Zend_Search_Lucene_Index_Term $term, $docsFilter = null) - { - return $this->_index->termDocsFilter($term, $docsFilter); - } - - /** - * Returns an array of all term freqs. - * Return array structure: array( docId => freq, ...) - * - * @param Zend_Search_Lucene_Index_Term $term - * @param Zend_Search_Lucene_Index_DocsFilter|null $docsFilter - * @return integer - */ - public function termFreqs(Zend_Search_Lucene_Index_Term $term, $docsFilter = null) - { - return $this->_index->termFreqs($term, $docsFilter); - } - - /** - * Returns an array of all term positions in the documents. - * Return array structure: array( docId => array( pos1, pos2, ...), ...) - * - * @param Zend_Search_Lucene_Index_Term $term - * @param Zend_Search_Lucene_Index_DocsFilter|null $docsFilter - * @return array - */ - public function termPositions(Zend_Search_Lucene_Index_Term $term, $docsFilter = null) - { - return $this->_index->termPositions($term, $docsFilter); - } - - /** - * Returns the number of documents in this index containing the $term. - * - * @param Zend_Search_Lucene_Index_Term $term - * @return integer - */ - public function docFreq(Zend_Search_Lucene_Index_Term $term) - { - return $this->_index->docFreq($term); - } - - /** - * Retrive similarity used by index reader - * - * @return Zend_Search_Lucene_Search_Similarity - */ - public function getSimilarity() - { - return $this->_index->getSimilarity(); - } - - /** - * Returns a normalization factor for "field, document" pair. - * - * @param integer $id - * @param string $fieldName - * @return float - */ - public function norm($id, $fieldName) - { - return $this->_index->norm($id, $fieldName); - } - - /** - * Returns true if any documents have been deleted from this index. - * - * @return boolean - */ - public function hasDeletions() - { - return $this->_index->hasDeletions(); - } - - /** - * Deletes a document from the index. - * $id is an internal document id - * - * @param integer|Zend_Search_Lucene_Search_QueryHit $id - * @throws Zend_Search_Lucene_Exception - */ - public function delete($id) - { - return $this->_index->delete($id); - } - - /** - * Adds a document to this index. - * - * @param Zend_Search_Lucene_Document $document - */ - public function addDocument(Zend_Search_Lucene_Document $document) - { - $this->_index->addDocument($document); - } - - /** - * Commit changes resulting from delete() or undeleteAll() operations. - */ - public function commit() - { - $this->_index->commit(); - } - - /** - * Optimize index. - * - * Merges all segments into one - */ - public function optimize() - { - $this->_index->optimize(); - } - - /** - * Returns an array of all terms in this index. - * - * @return array - */ - public function terms() - { - return $this->_index->terms(); - } - - - /** - * Reset terms stream. - */ - public function resetTermsStream() - { - $this->_index->resetTermsStream(); - } - - /** - * 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 - */ - public function skipTo(Zend_Search_Lucene_Index_Term $prefix) - { - return $this->_index->skipTo($prefix); - } - - /** - * Scans terms dictionary and returns next term - * - * @return Zend_Search_Lucene_Index_Term|null - */ - public function nextTerm() - { - return $this->_index->nextTerm(); - } - - /** - * Returns term in current position - * - * @return Zend_Search_Lucene_Index_Term|null - */ - public function currentTerm() - { - return $this->_index->currentTerm(); - } - - /** - * Close terms stream - * - * Should be used for resources clean up if stream is not read up to the end - */ - public function closeTermsStream() - { - $this->_index->closeTermsStream(); - } - - - /** - * Undeletes all documents currently marked as deleted in this index. - */ - public function undeleteAll() - { - return $this->_index->undeleteAll(); - } - - /** - * Add reference to the index object - * - * @internal - */ - public function addReference() - { - return $this->_index->addReference(); - } - - /** - * Remove reference from the index object - * - * When reference count becomes zero, index is closed and resources are cleaned up - * - * @internal - */ - public function removeReference() - { - return $this->_index->removeReference(); - } -} diff --git a/library/Zend/Search/Lucene/Search/BooleanExpressionRecognizer.php b/library/Zend/Search/Lucene/Search/BooleanExpressionRecognizer.php deleted file mode 100644 index b7ef6db261..0000000000 --- a/library/Zend/Search/Lucene/Search/BooleanExpressionRecognizer.php +++ /dev/null @@ -1,278 +0,0 @@ -, ) - * - * So, it has a structure: - * array( array( array(, ), // first literal of first conjuction - * array(, ), // second literal of first conjuction - * ... - * array(, ) - * ), // end of first conjuction - * array( array(, ), // first literal of second conjuction - * array(, ), // second literal of second conjuction - * ... - * array(, ) - * ), // end of second conjuction - * ... - * ) // end of structure - * - * @var array - */ - private $_conjunctions = array(); - - /** - * Current conjuction - * - * @var array - */ - private $_currentConjunction = array(); - - - /** - * Object constructor - */ - public function __construct() - { - parent::__construct( array(self::ST_START, - self::ST_LITERAL, - self::ST_NOT_OPERATOR, - self::ST_AND_OPERATOR, - self::ST_OR_OPERATOR), - array(self::IN_LITERAL, - self::IN_NOT_OPERATOR, - self::IN_AND_OPERATOR, - self::IN_OR_OPERATOR)); - - $emptyOperatorAction = new Zend_Search_Lucene_FSMAction($this, 'emptyOperatorAction'); - $emptyNotOperatorAction = new Zend_Search_Lucene_FSMAction($this, 'emptyNotOperatorAction'); - - $this->addRules(array( array(self::ST_START, self::IN_LITERAL, self::ST_LITERAL), - array(self::ST_START, self::IN_NOT_OPERATOR, self::ST_NOT_OPERATOR), - - array(self::ST_LITERAL, self::IN_AND_OPERATOR, self::ST_AND_OPERATOR), - array(self::ST_LITERAL, self::IN_OR_OPERATOR, self::ST_OR_OPERATOR), - array(self::ST_LITERAL, self::IN_LITERAL, self::ST_LITERAL, $emptyOperatorAction), - array(self::ST_LITERAL, self::IN_NOT_OPERATOR, self::ST_NOT_OPERATOR, $emptyNotOperatorAction), - - array(self::ST_NOT_OPERATOR, self::IN_LITERAL, self::ST_LITERAL), - - array(self::ST_AND_OPERATOR, self::IN_LITERAL, self::ST_LITERAL), - array(self::ST_AND_OPERATOR, self::IN_NOT_OPERATOR, self::ST_NOT_OPERATOR), - - array(self::ST_OR_OPERATOR, self::IN_LITERAL, self::ST_LITERAL), - array(self::ST_OR_OPERATOR, self::IN_NOT_OPERATOR, self::ST_NOT_OPERATOR), - )); - - $notOperatorAction = new Zend_Search_Lucene_FSMAction($this, 'notOperatorAction'); - $orOperatorAction = new Zend_Search_Lucene_FSMAction($this, 'orOperatorAction'); - $literalAction = new Zend_Search_Lucene_FSMAction($this, 'literalAction'); - - - $this->addEntryAction(self::ST_NOT_OPERATOR, $notOperatorAction); - $this->addEntryAction(self::ST_OR_OPERATOR, $orOperatorAction); - $this->addEntryAction(self::ST_LITERAL, $literalAction); - } - - - /** - * Process next operator. - * - * Operators are defined by class constants: IN_AND_OPERATOR, IN_OR_OPERATOR and IN_NOT_OPERATOR - * - * @param integer $operator - */ - public function processOperator($operator) - { - $this->process($operator); - } - - /** - * Process expression literal. - * - * @param integer $operator - */ - public function processLiteral($literal) - { - $this->_literal = $literal; - - $this->process(self::IN_LITERAL); - } - - /** - * Finish an expression and return result - * - * Result is a set of boolean query conjunctions - * - * Each conjunction is an array of conjunction elements - * Each conjunction element is presented with two-elements array: - * array(, ) - * - * So, it has a structure: - * array( array( array(, ), // first literal of first conjuction - * array(, ), // second literal of first conjuction - * ... - * array(, ) - * ), // end of first conjuction - * array( array(, ), // first literal of second conjuction - * array(, ), // second literal of second conjuction - * ... - * array(, ) - * ), // end of second conjuction - * ... - * ) // end of structure - * - * @return array - * @throws Zend_Search_Lucene_Exception - */ - public function finishExpression() - { - if ($this->getState() != self::ST_LITERAL) { - #require_once 'Zend/Search/Lucene/Exception.php'; - throw new Zend_Search_Lucene_Exception('Literal expected.'); - } - - $this->_conjunctions[] = $this->_currentConjunction; - - return $this->_conjunctions; - } - - - - /********************************************************************* - * Actions implementation - *********************************************************************/ - - /** - * default (omitted) operator processing - */ - public function emptyOperatorAction() - { - /** Zend_Search_Lucene_Search_QueryParser */ - #require_once 'Zend/Search/Lucene/Search/QueryParser.php'; - - if (Zend_Search_Lucene_Search_QueryParser::getDefaultOperator() == Zend_Search_Lucene_Search_QueryParser::B_AND) { - // Do nothing - } else { - $this->orOperatorAction(); - } - - // Process literal - $this->literalAction(); - } - - /** - * default (omitted) + NOT operator processing - */ - public function emptyNotOperatorAction() - { - /** Zend_Search_Lucene_Search_QueryParser */ - #require_once 'Zend/Search/Lucene/Search/QueryParser.php'; - - if (Zend_Search_Lucene_Search_QueryParser::getDefaultOperator() == Zend_Search_Lucene_Search_QueryParser::B_AND) { - // Do nothing - } else { - $this->orOperatorAction(); - } - - // Process NOT operator - $this->notOperatorAction(); - } - - - /** - * NOT operator processing - */ - public function notOperatorAction() - { - $this->_negativeLiteral = true; - } - - /** - * OR operator processing - * Close current conjunction - */ - public function orOperatorAction() - { - $this->_conjunctions[] = $this->_currentConjunction; - $this->_currentConjunction = array(); - } - - /** - * Literal processing - */ - public function literalAction() - { - // Add literal to the current conjunction - $this->_currentConjunction[] = array($this->_literal, !$this->_negativeLiteral); - - // Switch off negative signal - $this->_negativeLiteral = false; - } -} diff --git a/library/Zend/Search/Lucene/Search/Highlighter/Default.php b/library/Zend/Search/Lucene/Search/Highlighter/Default.php deleted file mode 100644 index 79fbe53b97..0000000000 --- a/library/Zend/Search/Lucene/Search/Highlighter/Default.php +++ /dev/null @@ -1,94 +0,0 @@ -_doc = $document; - } - - /** - * Get document for highlighting. - * - * @return Zend_Search_Lucene_Document_Html $document - */ - public function getDocument() - { - return $this->_doc; - } - - /** - * Highlight specified words - * - * @param string|array $words Words to highlight. They could be organized using the array or string. - */ - public function highlight($words) - { - $color = $this->_highlightColors[$this->_currentColorIndex]; - $this->_currentColorIndex = ($this->_currentColorIndex + 1) % count($this->_highlightColors); - - $this->_doc->highlight($words, $color); - } - -} diff --git a/library/Zend/Search/Lucene/Search/Highlighter/Interface.php b/library/Zend/Search/Lucene/Search/Highlighter/Interface.php deleted file mode 100644 index 99fe12ee0c..0000000000 --- a/library/Zend/Search/Lucene/Search/Highlighter/Interface.php +++ /dev/null @@ -1,53 +0,0 @@ -_boost; - } - - /** - * Sets the boost for this query clause to $boost. - * - * @param float $boost - */ - public function setBoost($boost) - { - $this->_boost = $boost; - } - - /** - * Score specified document - * - * @param integer $docId - * @param Zend_Search_Lucene_Interface $reader - * @return float - */ - abstract public function score($docId, Zend_Search_Lucene_Interface $reader); - - /** - * Get document ids likely matching the query - * - * It's an array with document ids as keys (performance considerations) - * - * @return array - */ - abstract public function matchedDocs(); - - /** - * Execute query in context of index reader - * It also initializes necessary internal structures - * - * Query specific implementation - * - * @param Zend_Search_Lucene_Interface $reader - * @param Zend_Search_Lucene_Index_DocsFilter|null $docsFilter - */ - abstract public function execute(Zend_Search_Lucene_Interface $reader, $docsFilter = null); - - /** - * Constructs an appropriate Weight implementation for this query. - * - * @param Zend_Search_Lucene_Interface $reader - * @return Zend_Search_Lucene_Search_Weight - */ - abstract public function createWeight(Zend_Search_Lucene_Interface $reader); - - /** - * Constructs an initializes a Weight for a _top-level_query_. - * - * @param Zend_Search_Lucene_Interface $reader - */ - 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); - } - - /** - * Re-write query into primitive queries in the context of specified index - * - * @param Zend_Search_Lucene_Interface $index - * @return Zend_Search_Lucene_Search_Query - */ - abstract public function rewrite(Zend_Search_Lucene_Interface $index); - - /** - * Optimize query in the context of specified index - * - * @param Zend_Search_Lucene_Interface $index - * @return Zend_Search_Lucene_Search_Query - */ - abstract public function optimize(Zend_Search_Lucene_Interface $index); - - /** - * Reset query, so it can be reused within other queries or - * with other indeces - */ - public function reset() - { - $this->_weight = null; - } - - - /** - * Print a query - * - * @return string - */ - abstract public function __toString(); - - /** - * Return query terms - * - * @return array - */ - abstract public function getQueryTerms(); - - /** - * Query specific matches highlighting - * - * @param Zend_Search_Lucene_Search_Highlighter_Interface $highlighter Highlighter object (also contains doc for highlighting) - */ - abstract protected function _highlightMatches(Zend_Search_Lucene_Search_Highlighter_Interface $highlighter); - - /** - * 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 - */ - public function highlightMatches($inputHTML, $defaultEncoding = '', $highlighter = null) - { - if ($highlighter === null) { - #require_once 'Zend/Search/Lucene/Search/Highlighter/Default.php'; - $highlighter = new Zend_Search_Lucene_Search_Highlighter_Default(); - } - - /** Zend_Search_Lucene_Document_Html */ - #require_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 $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 - */ - public function htmlFragmentHighlightMatches($inputHtmlFragment, $encoding = 'UTF-8', $highlighter = null) - { - if ($highlighter === null) { - #require_once 'Zend/Search/Lucene/Search/Highlighter/Default.php'; - $highlighter = new Zend_Search_Lucene_Search_Highlighter_Default(); - } - - $inputHTML = '' - . iconv($encoding, 'UTF-8//IGNORE', $inputHtmlFragment) . ''; - - /** Zend_Search_Lucene_Document_Html */ - #require_once 'Zend/Search/Lucene/Document/Html.php'; - - $doc = Zend_Search_Lucene_Document_Html::loadHTML($inputHTML); - $highlighter->setDocument($doc); - - $this->_highlightMatches($highlighter); - - return $doc->getHtmlBody(); - } -} - diff --git a/library/Zend/Search/Lucene/Search/Query/Boolean.php b/library/Zend/Search/Lucene/Search/Query/Boolean.php deleted file mode 100644 index d3eb104dbe..0000000000 --- a/library/Zend/Search/Lucene/Search/Query/Boolean.php +++ /dev/null @@ -1,815 +0,0 @@ -_subqueries = $subqueries; - - $this->_signs = null; - // Check if all subqueries are required - if (is_array($signs)) { - foreach ($signs as $sign ) { - if ($sign !== true) { - $this->_signs = $signs; - break; - } - } - } - } - } - - - /** - * Add a $subquery (Zend_Search_Lucene_Search_Query) to this query. - * - * The sign is specified as: - * TRUE - subquery is required - * FALSE - subquery is prohibited - * NULL - subquery is neither prohibited, nor required - * - * @param Zend_Search_Lucene_Search_Query $subquery - * @param boolean|null $sign - * @return void - */ - public function addSubquery(Zend_Search_Lucene_Search_Query $subquery, $sign=null) { - if ($sign !== true || $this->_signs !== null) { // Skip, if all subqueries are required - if ($this->_signs === null) { // Check, If all previous subqueries are required - $this->_signs = array(); - foreach ($this->_subqueries as $prevSubquery) { - $this->_signs[] = true; - } - } - $this->_signs[] = $sign; - } - - $this->_subqueries[] = $subquery; - } - - /** - * Re-write queries into primitive queries - * - * @param Zend_Search_Lucene_Interface $index - * @return Zend_Search_Lucene_Search_Query - */ - public function rewrite(Zend_Search_Lucene_Interface $index) - { - $query = new Zend_Search_Lucene_Search_Query_Boolean(); - $query->setBoost($this->getBoost()); - - foreach ($this->_subqueries as $subqueryId => $subquery) { - $query->addSubquery($subquery->rewrite($index), - ($this->_signs === null)? true : $this->_signs[$subqueryId]); - } - - return $query; - } - - /** - * Optimize query in the context of specified index - * - * @param Zend_Search_Lucene_Interface $index - * @return Zend_Search_Lucene_Search_Query - */ - public function optimize(Zend_Search_Lucene_Interface $index) - { - $subqueries = array(); - $signs = array(); - - // Optimize all subqueries - foreach ($this->_subqueries as $id => $subquery) { - $subqueries[] = $subquery->optimize($index); - $signs[] = ($this->_signs === null)? true : $this->_signs[$id]; - } - - // Remove insignificant subqueries - foreach ($subqueries as $id => $subquery) { - if ($subquery instanceof Zend_Search_Lucene_Search_Query_Insignificant) { - // Insignificant subquery has to be removed anyway - unset($subqueries[$id]); - unset($signs[$id]); - } - } - if (count($subqueries) == 0) { - // Boolean query doesn't has non-insignificant subqueries - #require_once 'Zend/Search/Lucene/Search/Query/Insignificant.php'; - return new Zend_Search_Lucene_Search_Query_Insignificant(); - } - // Check if all non-insignificant subqueries are prohibited - $allProhibited = true; - foreach ($signs as $sign) { - if ($sign !== false) { - $allProhibited = false; - break; - } - } - if ($allProhibited) { - #require_once 'Zend/Search/Lucene/Search/Query/Insignificant.php'; - return new Zend_Search_Lucene_Search_Query_Insignificant(); - } - - - // Check for empty subqueries - foreach ($subqueries as $id => $subquery) { - if ($subquery instanceof Zend_Search_Lucene_Search_Query_Empty) { - if ($signs[$id] === true) { - // Matching is required, but is actually empty - #require_once 'Zend/Search/Lucene/Search/Query/Empty.php'; - return new Zend_Search_Lucene_Search_Query_Empty(); - } else { - // Matching is optional or prohibited, but is empty - // Remove it from subqueries and signs list - unset($subqueries[$id]); - unset($signs[$id]); - } - } - } - - // Check, if reduced subqueries list is empty - if (count($subqueries) == 0) { - #require_once 'Zend/Search/Lucene/Search/Query/Empty.php'; - return new Zend_Search_Lucene_Search_Query_Empty(); - } - - // Check if all non-empty subqueries are prohibited - $allProhibited = true; - foreach ($signs as $sign) { - if ($sign !== false) { - $allProhibited = false; - break; - } - } - if ($allProhibited) { - #require_once 'Zend/Search/Lucene/Search/Query/Empty.php'; - return new Zend_Search_Lucene_Search_Query_Empty(); - } - - - // Check, if reduced subqueries list has only one entry - if (count($subqueries) == 1) { - // It's a query with only one required or optional clause - // (it's already checked, that it's not a prohibited clause) - - if ($this->getBoost() == 1) { - return reset($subqueries); - } - - $optimizedQuery = clone reset($subqueries); - $optimizedQuery->setBoost($optimizedQuery->getBoost()*$this->getBoost()); - - return $optimizedQuery; - } - - - // Prepare first candidate for optimized query - $optimizedQuery = new Zend_Search_Lucene_Search_Query_Boolean($subqueries, $signs); - $optimizedQuery->setBoost($this->getBoost()); - - - $terms = array(); - $tsigns = array(); - $boostFactors = array(); - - // Try to decompose term and multi-term subqueries - foreach ($subqueries as $id => $subquery) { - if ($subquery instanceof Zend_Search_Lucene_Search_Query_Term) { - $terms[] = $subquery->getTerm(); - $tsigns[] = $signs[$id]; - $boostFactors[] = $subquery->getBoost(); - - // remove subquery from a subqueries list - unset($subqueries[$id]); - unset($signs[$id]); - } else if ($subquery instanceof Zend_Search_Lucene_Search_Query_MultiTerm) { - $subTerms = $subquery->getTerms(); - $subSigns = $subquery->getSigns(); - - if ($signs[$id] === true) { - // It's a required multi-term subquery. - // Something like '... +(+term1 -term2 term3 ...) ...' - - // Multi-term required subquery can be decomposed only if it contains - // required terms and doesn't contain prohibited terms: - // ... +(+term1 term2 ...) ... => ... +term1 term2 ... - // - // Check this - $hasRequired = false; - $hasProhibited = false; - if ($subSigns === null) { - // All subterms are required - $hasRequired = true; - } else { - foreach ($subSigns as $sign) { - if ($sign === true) { - $hasRequired = true; - } else if ($sign === false) { - $hasProhibited = true; - break; - } - } - } - // Continue if subquery has prohibited terms or doesn't have required terms - if ($hasProhibited || !$hasRequired) { - continue; - } - - foreach ($subTerms as $termId => $term) { - $terms[] = $term; - $tsigns[] = ($subSigns === null)? true : $subSigns[$termId]; - $boostFactors[] = $subquery->getBoost(); - } - - // remove subquery from a subqueries list - unset($subqueries[$id]); - unset($signs[$id]); - - } else { // $signs[$id] === null || $signs[$id] === false - // It's an optional or prohibited multi-term subquery. - // Something like '... (+term1 -term2 term3 ...) ...' - // or - // something like '... -(+term1 -term2 term3 ...) ...' - - // Multi-term optional and required subqueries can be decomposed - // only if all terms are optional. - // - // Check if all terms are optional. - $onlyOptional = true; - if ($subSigns === null) { - // All subterms are required - $onlyOptional = false; - } else { - foreach ($subSigns as $sign) { - if ($sign !== null) { - $onlyOptional = false; - break; - } - } - } - - // Continue if non-optional terms are presented in this multi-term subquery - if (!$onlyOptional) { - continue; - } - - foreach ($subTerms as $termId => $term) { - $terms[] = $term; - $tsigns[] = ($signs[$id] === null)? null /* optional */ : - false /* prohibited */; - $boostFactors[] = $subquery->getBoost(); - } - - // remove subquery from a subqueries list - unset($subqueries[$id]); - unset($signs[$id]); - } - } - } - - - // Check, if there are no decomposed subqueries - if (count($terms) == 0 ) { - // return prepared candidate - return $optimizedQuery; - } - - - // Check, if all subqueries have been decomposed and all terms has the same boost factor - if (count($subqueries) == 0 && count(array_unique($boostFactors)) == 1) { - #require_once 'Zend/Search/Lucene/Search/Query/MultiTerm.php'; - $optimizedQuery = new Zend_Search_Lucene_Search_Query_MultiTerm($terms, $tsigns); - $optimizedQuery->setBoost(reset($boostFactors)*$this->getBoost()); - - return $optimizedQuery; - } - - - // This boolean query can't be transformed to Term/MultiTerm query and still contains - // several subqueries - - // Separate prohibited terms - $prohibitedTerms = array(); - foreach ($terms as $id => $term) { - if ($tsigns[$id] === false) { - $prohibitedTerms[] = $term; - - unset($terms[$id]); - unset($tsigns[$id]); - unset($boostFactors[$id]); - } - } - - if (count($terms) == 1) { - #require_once 'Zend/Search/Lucene/Search/Query/Term.php'; - $clause = new Zend_Search_Lucene_Search_Query_Term(reset($terms)); - $clause->setBoost(reset($boostFactors)); - - $subqueries[] = $clause; - $signs[] = reset($tsigns); - - // Clear terms list - $terms = array(); - } else if (count($terms) > 1 && count(array_unique($boostFactors)) == 1) { - #require_once 'Zend/Search/Lucene/Search/Query/MultiTerm.php'; - $clause = new Zend_Search_Lucene_Search_Query_MultiTerm($terms, $tsigns); - $clause->setBoost(reset($boostFactors)); - - $subqueries[] = $clause; - // Clause sign is 'required' if clause contains required terms. 'Optional' otherwise. - $signs[] = (in_array(true, $tsigns))? true : null; - - // Clear terms list - $terms = array(); - } - - if (count($prohibitedTerms) == 1) { - // (boost factors are not significant for prohibited clauses) - #require_once 'Zend/Search/Lucene/Search/Query/Term.php'; - $subqueries[] = new Zend_Search_Lucene_Search_Query_Term(reset($prohibitedTerms)); - $signs[] = false; - - // Clear prohibited terms list - $prohibitedTerms = array(); - } else if (count($prohibitedTerms) > 1) { - // prepare signs array - $prohibitedSigns = array(); - foreach ($prohibitedTerms as $id => $term) { - // all prohibited term are grouped as optional into multi-term query - $prohibitedSigns[$id] = null; - } - - // (boost factors are not significant for prohibited clauses) - #require_once 'Zend/Search/Lucene/Search/Query/MultiTerm.php'; - $subqueries[] = new Zend_Search_Lucene_Search_Query_MultiTerm($prohibitedTerms, $prohibitedSigns); - // Clause sign is 'prohibited' - $signs[] = false; - - // Clear terms list - $prohibitedTerms = array(); - } - - /** @todo Group terms with the same boost factors together */ - - // Check, that all terms are processed - // Replace candidate for optimized query - if (count($terms) == 0 && count($prohibitedTerms) == 0) { - $optimizedQuery = new Zend_Search_Lucene_Search_Query_Boolean($subqueries, $signs); - $optimizedQuery->setBoost($this->getBoost()); - } - - return $optimizedQuery; - } - - /** - * Returns subqueries - * - * @return array - */ - public function getSubqueries() - { - return $this->_subqueries; - } - - - /** - * Return subqueries signs - * - * @return array - */ - public function getSigns() - { - return $this->_signs; - } - - - /** - * Constructs an appropriate Weight implementation for this query. - * - * @param Zend_Search_Lucene_Interface $reader - * @return Zend_Search_Lucene_Search_Weight - */ - public function createWeight(Zend_Search_Lucene_Interface $reader) - { - #require_once 'Zend/Search/Lucene/Search/Weight/Boolean.php'; - $this->_weight = new Zend_Search_Lucene_Search_Weight_Boolean($this, $reader); - return $this->_weight; - } - - - /** - * Calculate result vector for Conjunction query - * (like ' AND AND ') - */ - private function _calculateConjunctionResult() - { - $this->_resVector = null; - - if (count($this->_subqueries) == 0) { - $this->_resVector = array(); - } - - $resVectors = array(); - $resVectorsSizes = array(); - $resVectorsIds = array(); // is used to prevent arrays comparison - foreach ($this->_subqueries as $subqueryId => $subquery) { - $resVectors[] = $subquery->matchedDocs(); - $resVectorsSizes[] = count(end($resVectors)); - $resVectorsIds[] = $subqueryId; - } - // sort resvectors in order of subquery cardinality increasing - array_multisort($resVectorsSizes, SORT_ASC, SORT_NUMERIC, - $resVectorsIds, SORT_ASC, SORT_NUMERIC, - $resVectors); - - foreach ($resVectors as $nextResVector) { - if($this->_resVector === null) { - $this->_resVector = $nextResVector; - } else { - //$this->_resVector = array_intersect_key($this->_resVector, $nextResVector); - - /** - * This code is used as workaround for array_intersect_key() slowness problem. - */ - $updatedVector = array(); - foreach ($this->_resVector as $id => $value) { - if (isset($nextResVector[$id])) { - $updatedVector[$id] = $value; - } - } - $this->_resVector = $updatedVector; - } - - if (count($this->_resVector) == 0) { - // Empty result set, we don't need to check other terms - break; - } - } - - // ksort($this->_resVector, SORT_NUMERIC); - // Used algorithm doesn't change elements order - } - - - /** - * Calculate result vector for non Conjunction query - * (like ' AND AND NOT OR ') - */ - private function _calculateNonConjunctionResult() - { - $requiredVectors = array(); - $requiredVectorsSizes = array(); - $requiredVectorsIds = array(); // is used to prevent arrays comparison - - $optional = array(); - - foreach ($this->_subqueries as $subqueryId => $subquery) { - if ($this->_signs[$subqueryId] === true) { - // required - $requiredVectors[] = $subquery->matchedDocs(); - $requiredVectorsSizes[] = count(end($requiredVectors)); - $requiredVectorsIds[] = $subqueryId; - } elseif ($this->_signs[$subqueryId] === false) { - // prohibited - // Do nothing. matchedDocs() may include non-matching id's - // Calculating prohibited vector may take significant time, but do not affect the result - // Skipped. - } else { - // neither required, nor prohibited - // array union - $optional += $subquery->matchedDocs(); - } - } - - // 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; - } - - ksort($this->_resVector, SORT_NUMERIC); - } - - - /** - * Score calculator for conjunction queries (all subqueries are required) - * - * @param integer $docId - * @param Zend_Search_Lucene_Interface $reader - * @return float - */ - public function _conjunctionScore($docId, Zend_Search_Lucene_Interface $reader) - { - if ($this->_coord === null) { - $this->_coord = $reader->getSimilarity()->coord(count($this->_subqueries), - count($this->_subqueries) ); - } - - $score = 0; - - foreach ($this->_subqueries as $subquery) { - $subscore = $subquery->score($docId, $reader); - - if ($subscore == 0) { - return 0; - } - - $score += $subquery->score($docId, $reader) * $this->_coord; - } - - return $score * $this->_coord * $this->getBoost(); - } - - - /** - * Score calculator for non conjunction queries (not all subqueries are required) - * - * @param integer $docId - * @param Zend_Search_Lucene_Interface $reader - * @return float - */ - public function _nonConjunctionScore($docId, Zend_Search_Lucene_Interface $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; - $matchedSubqueries = 0; - foreach ($this->_subqueries as $subqueryId => $subquery) { - $subscore = $subquery->score($docId, $reader); - - // Prohibited - if ($this->_signs[$subqueryId] === false && $subscore != 0) { - return 0; - } - - // is required, but doen't match - if ($this->_signs[$subqueryId] === true && $subscore == 0) { - return 0; - } - - if ($subscore != 0) { - $matchedSubqueries++; - $score += $subscore; - } - } - - return $score * $this->_coord[$matchedSubqueries] * $this->getBoost(); - } - - /** - * 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 - */ - public function execute(Zend_Search_Lucene_Interface $reader, $docsFilter = null) - { - // Initialize weight if it's not done yet - $this->_initWeight($reader); - - if ($docsFilter === null) { - // Create local documents filter if it's not provided by upper query - #require_once 'Zend/Search/Lucene/Index/DocsFilter.php'; - $docsFilter = new Zend_Search_Lucene_Index_DocsFilter(); - } - - foreach ($this->_subqueries as $subqueryId => $subquery) { - if ($this->_signs == null || $this->_signs[$subqueryId] === true) { - // Subquery is required - $subquery->execute($reader, $docsFilter); - } else { - $subquery->execute($reader); - } - } - - if ($this->_signs === null) { - $this->_calculateConjunctionResult(); - } else { - $this->_calculateNonConjunctionResult(); - } - } - - - - /** - * Get document ids likely matching the query - * - * It's an array with document ids as keys (performance considerations) - * - * @return array - */ - public function matchedDocs() - { - return $this->_resVector; - } - - /** - * Score specified document - * - * @param integer $docId - * @param Zend_Search_Lucene_Interface $reader - * @return float - */ - public function score($docId, Zend_Search_Lucene_Interface $reader) - { - if (isset($this->_resVector[$docId])) { - if ($this->_signs === null) { - return $this->_conjunctionScore($docId, $reader); - } else { - return $this->_nonConjunctionScore($docId, $reader); - } - } else { - return 0; - } - } - - /** - * Return query terms - * - * @return array - */ - public function getQueryTerms() - { - $terms = array(); - - foreach ($this->_subqueries as $id => $subquery) { - if ($this->_signs === null || $this->_signs[$id] !== false) { - $terms = array_merge($terms, $subquery->getQueryTerms()); - } - } - - return $terms; - } - - /** - * Query specific matches highlighting - * - * @param Zend_Search_Lucene_Search_Highlighter_Interface $highlighter Highlighter object (also contains doc for highlighting) - */ - protected function _highlightMatches(Zend_Search_Lucene_Search_Highlighter_Interface $highlighter) - { - foreach ($this->_subqueries as $id => $subquery) { - if ($this->_signs === null || $this->_signs[$id] !== false) { - $subquery->_highlightMatches($highlighter); - } - } - } - - /** - * Print a query - * - * @return string - */ - public function __toString() - { - // It's used only for query visualisation, so we don't care about characters escaping - - $query = ''; - - foreach ($this->_subqueries as $id => $subquery) { - if ($id != 0) { - $query .= ' '; - } - - if ($this->_signs === null || $this->_signs[$id] === true) { - $query .= '+'; - } else if ($this->_signs[$id] === false) { - $query .= '-'; - } - - $query .= '(' . $subquery->__toString() . ')'; - } - - if ($this->getBoost() != 1) { - $query = '(' . $query . ')^' . round($this->getBoost(), 4); - } - - return $query; - } -} - diff --git a/library/Zend/Search/Lucene/Search/Query/Empty.php b/library/Zend/Search/Lucene/Search/Query/Empty.php deleted file mode 100644 index 91c2c85c08..0000000000 --- a/library/Zend/Search/Lucene/Search/Query/Empty.php +++ /dev/null @@ -1,138 +0,0 @@ -'; - } -} - diff --git a/library/Zend/Search/Lucene/Search/Query/Fuzzy.php b/library/Zend/Search/Lucene/Search/Query/Fuzzy.php deleted file mode 100644 index 663e6232eb..0000000000 --- a/library/Zend/Search/Lucene/Search/Query/Fuzzy.php +++ /dev/null @@ -1,493 +0,0 @@ -= 1) { - #require_once 'Zend/Search/Lucene/Exception.php'; - throw new Zend_Search_Lucene_Exception('minimumSimilarity cannot be greater than or equal to 1'); - } - if ($prefixLength < 0) { - #require_once 'Zend/Search/Lucene/Exception.php'; - throw new Zend_Search_Lucene_Exception('prefixLength cannot be less than 0'); - } - - $this->_term = $term; - $this->_minimumSimilarity = $minimumSimilarity; - $this->_prefixLength = ($prefixLength !== null)? $prefixLength : self::$_defaultPrefixLength; - } - - /** - * Get default non-fuzzy prefix length - * - * @return integer - */ - public static function getDefaultPrefixLength() - { - return self::$_defaultPrefixLength; - } - - /** - * Set default non-fuzzy prefix length - * - * @param integer $defaultPrefixLength - */ - public static function setDefaultPrefixLength($defaultPrefixLength) - { - self::$_defaultPrefixLength = $defaultPrefixLength; - } - - /** - * Calculate maximum distance for specified word length - * - * @param integer $prefixLength - * @param integer $termLength - * @param integer $length - * @return integer - */ - private function _calculateMaxDistance($prefixLength, $termLength, $length) - { - $this->_maxDistances[$length] = (int) ((1 - $this->_minimumSimilarity)*(min($termLength, $length) + $prefixLength)); - return $this->_maxDistances[$length]; - } - - /** - * Re-write query into primitive queries in the context of specified index - * - * @param Zend_Search_Lucene_Interface $index - * @return Zend_Search_Lucene_Search_Query - * @throws Zend_Search_Lucene_Exception - */ - public function rewrite(Zend_Search_Lucene_Interface $index) - { - $this->_matches = array(); - $this->_scores = array(); - $this->_termKeys = array(); - - if ($this->_term->field === null) { - // Search through all fields - $fields = $index->getFieldNames(true /* indexed fields list */); - } else { - $fields = array($this->_term->field); - } - - #require_once 'Zend/Search/Lucene/Index/Term.php'; - $prefix = Zend_Search_Lucene_Index_Term::getPrefix($this->_term->text, $this->_prefixLength); - $prefixByteLength = strlen($prefix); - $prefixUtf8Length = Zend_Search_Lucene_Index_Term::getLength($prefix); - - $termLength = Zend_Search_Lucene_Index_Term::getLength($this->_term->text); - - $termRest = substr($this->_term->text, $prefixByteLength); - // we calculate length of the rest in bytes since levenshtein() is not UTF-8 compatible - $termRestLength = strlen($termRest); - - $scaleFactor = 1/(1 - $this->_minimumSimilarity); - - #require_once 'Zend/Search/Lucene.php'; - $maxTerms = Zend_Search_Lucene::getTermsPerQueryLimit(); - foreach ($fields as $field) { - $index->resetTermsStream(); - - #require_once 'Zend/Search/Lucene/Index/Term.php'; - if ($prefix != '') { - $index->skipTo(new Zend_Search_Lucene_Index_Term($prefix, $field)); - - while ($index->currentTerm() !== null && - $index->currentTerm()->field == $field && - substr($index->currentTerm()->text, 0, $prefixByteLength) == $prefix) { - // Calculate similarity - $target = substr($index->currentTerm()->text, $prefixByteLength); - - $maxDistance = isset($this->_maxDistances[strlen($target)])? - $this->_maxDistances[strlen($target)] : - $this->_calculateMaxDistance($prefixUtf8Length, $termRestLength, strlen($target)); - - if ($termRestLength == 0) { - // we don't have anything to compare. That means if we just add - // the letters for current term we get the new word - $similarity = (($prefixUtf8Length == 0)? 0 : 1 - strlen($target)/$prefixUtf8Length); - } else if (strlen($target) == 0) { - $similarity = (($prefixUtf8Length == 0)? 0 : 1 - $termRestLength/$prefixUtf8Length); - } else if ($maxDistance < abs($termRestLength - strlen($target))){ - //just adding the characters of term to target or vice-versa results in too many edits - //for example "pre" length is 3 and "prefixes" length is 8. We can see that - //given this optimal circumstance, the edit distance cannot be less than 5. - //which is 8-3 or more precisesly abs(3-8). - //if our maximum edit distance is 4, then we can discard this word - //without looking at it. - $similarity = 0; - } else { - $similarity = 1 - levenshtein($termRest, $target)/($prefixUtf8Length + min($termRestLength, strlen($target))); - } - - if ($similarity > $this->_minimumSimilarity) { - $this->_matches[] = $index->currentTerm(); - $this->_termKeys[] = $index->currentTerm()->key(); - $this->_scores[] = ($similarity - $this->_minimumSimilarity)*$scaleFactor; - - if ($maxTerms != 0 && count($this->_matches) > $maxTerms) { - #require_once 'Zend/Search/Lucene/Exception.php'; - throw new Zend_Search_Lucene_Exception('Terms per query limit is reached.'); - } - } - - $index->nextTerm(); - } - } else { - $index->skipTo(new Zend_Search_Lucene_Index_Term('', $field)); - - while ($index->currentTerm() !== null && $index->currentTerm()->field == $field) { - // Calculate similarity - $target = $index->currentTerm()->text; - - $maxDistance = isset($this->_maxDistances[strlen($target)])? - $this->_maxDistances[strlen($target)] : - $this->_calculateMaxDistance(0, $termRestLength, strlen($target)); - - if ($maxDistance < abs($termRestLength - strlen($target))){ - //just adding the characters of term to target or vice-versa results in too many edits - //for example "pre" length is 3 and "prefixes" length is 8. We can see that - //given this optimal circumstance, the edit distance cannot be less than 5. - //which is 8-3 or more precisesly abs(3-8). - //if our maximum edit distance is 4, then we can discard this word - //without looking at it. - $similarity = 0; - } else { - $similarity = 1 - levenshtein($termRest, $target)/min($termRestLength, strlen($target)); - } - - if ($similarity > $this->_minimumSimilarity) { - $this->_matches[] = $index->currentTerm(); - $this->_termKeys[] = $index->currentTerm()->key(); - $this->_scores[] = ($similarity - $this->_minimumSimilarity)*$scaleFactor; - - if ($maxTerms != 0 && count($this->_matches) > $maxTerms) { - #require_once 'Zend/Search/Lucene/Exception.php'; - throw new Zend_Search_Lucene_Exception('Terms per query limit is reached.'); - } - } - - $index->nextTerm(); - } - } - - $index->closeTermsStream(); - } - - if (count($this->_matches) == 0) { - #require_once 'Zend/Search/Lucene/Search/Query/Empty.php'; - return new Zend_Search_Lucene_Search_Query_Empty(); - } else if (count($this->_matches) == 1) { - #require_once 'Zend/Search/Lucene/Search/Query/Term.php'; - return new Zend_Search_Lucene_Search_Query_Term(reset($this->_matches)); - } else { - #require_once 'Zend/Search/Lucene/Search/Query/Boolean.php'; - $rewrittenQuery = new Zend_Search_Lucene_Search_Query_Boolean(); - - array_multisort($this->_scores, SORT_DESC, SORT_NUMERIC, - $this->_termKeys, SORT_ASC, SORT_STRING, - $this->_matches); - - $termCount = 0; - #require_once 'Zend/Search/Lucene/Search/Query/Term.php'; - foreach ($this->_matches as $id => $matchedTerm) { - $subquery = new Zend_Search_Lucene_Search_Query_Term($matchedTerm); - $subquery->setBoost($this->_scores[$id]); - - $rewrittenQuery->addSubquery($subquery); - - $termCount++; - if ($termCount >= self::MAX_CLAUSE_COUNT) { - break; - } - } - - return $rewrittenQuery; - } - } - - /** - * Optimize query in the context of specified index - * - * @param Zend_Search_Lucene_Interface $index - * @return Zend_Search_Lucene_Search_Query - */ - public function optimize(Zend_Search_Lucene_Interface $index) - { - #require_once 'Zend/Search/Lucene/Exception.php'; - throw new Zend_Search_Lucene_Exception('Fuzzy query should not be directly used for search. Use $query->rewrite($index)'); - } - - /** - * Return query terms - * - * @return array - * @throws Zend_Search_Lucene_Exception - */ - public function getQueryTerms() - { - if ($this->_matches === null) { - #require_once 'Zend/Search/Lucene/Exception.php'; - throw new Zend_Search_Lucene_Exception('Search or rewrite operations have to be performed before.'); - } - - return $this->_matches; - } - - /** - * Constructs an appropriate Weight implementation for this query. - * - * @param Zend_Search_Lucene_Interface $reader - * @return Zend_Search_Lucene_Search_Weight - * @throws Zend_Search_Lucene_Exception - */ - public function createWeight(Zend_Search_Lucene_Interface $reader) - { - #require_once 'Zend/Search/Lucene/Exception.php'; - throw new Zend_Search_Lucene_Exception('Fuzzy query should not be directly used for search. Use $query->rewrite($index)'); - } - - - /** - * 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 - * @throws Zend_Search_Lucene_Exception - */ - public function execute(Zend_Search_Lucene_Interface $reader, $docsFilter = null) - { - #require_once 'Zend/Search/Lucene/Exception.php'; - throw new Zend_Search_Lucene_Exception('Fuzzy query should not be directly used for search. Use $query->rewrite($index)'); - } - - /** - * Get document ids likely matching the query - * - * It's an array with document ids as keys (performance considerations) - * - * @return array - * @throws Zend_Search_Lucene_Exception - */ - public function matchedDocs() - { - #require_once 'Zend/Search/Lucene/Exception.php'; - throw new Zend_Search_Lucene_Exception('Fuzzy query should not be directly used for search. Use $query->rewrite($index)'); - } - - /** - * Score specified document - * - * @param integer $docId - * @param Zend_Search_Lucene_Interface $reader - * @return float - * @throws Zend_Search_Lucene_Exception - */ - public function score($docId, Zend_Search_Lucene_Interface $reader) - { - #require_once 'Zend/Search/Lucene/Exception.php'; - throw new Zend_Search_Lucene_Exception('Fuzzy query should not be directly used for search. Use $query->rewrite($index)'); - } - - /** - * Query specific matches highlighting - * - * @param Zend_Search_Lucene_Search_Highlighter_Interface $highlighter Highlighter object (also contains doc for highlighting) - */ - protected function _highlightMatches(Zend_Search_Lucene_Search_Highlighter_Interface $highlighter) - { - $words = array(); - - #require_once 'Zend/Search/Lucene/Index/Term.php'; - $prefix = Zend_Search_Lucene_Index_Term::getPrefix($this->_term->text, $this->_prefixLength); - $prefixByteLength = strlen($prefix); - $prefixUtf8Length = Zend_Search_Lucene_Index_Term::getLength($prefix); - - $termLength = Zend_Search_Lucene_Index_Term::getLength($this->_term->text); - - $termRest = substr($this->_term->text, $prefixByteLength); - // we calculate length of the rest in bytes since levenshtein() is not UTF-8 compatible - $termRestLength = strlen($termRest); - - $scaleFactor = 1/(1 - $this->_minimumSimilarity); - - $docBody = $highlighter->getDocument()->getFieldUtf8Value('body'); - #require_once 'Zend/Search/Lucene/Analysis/Analyzer.php'; - $tokens = Zend_Search_Lucene_Analysis_Analyzer::getDefault()->tokenize($docBody, 'UTF-8'); - foreach ($tokens as $token) { - $termText = $token->getTermText(); - - if (substr($termText, 0, $prefixByteLength) == $prefix) { - // Calculate similarity - $target = substr($termText, $prefixByteLength); - - $maxDistance = isset($this->_maxDistances[strlen($target)])? - $this->_maxDistances[strlen($target)] : - $this->_calculateMaxDistance($prefixUtf8Length, $termRestLength, strlen($target)); - - if ($termRestLength == 0) { - // we don't have anything to compare. That means if we just add - // the letters for current term we get the new word - $similarity = (($prefixUtf8Length == 0)? 0 : 1 - strlen($target)/$prefixUtf8Length); - } else if (strlen($target) == 0) { - $similarity = (($prefixUtf8Length == 0)? 0 : 1 - $termRestLength/$prefixUtf8Length); - } else if ($maxDistance < abs($termRestLength - strlen($target))){ - //just adding the characters of term to target or vice-versa results in too many edits - //for example "pre" length is 3 and "prefixes" length is 8. We can see that - //given this optimal circumstance, the edit distance cannot be less than 5. - //which is 8-3 or more precisesly abs(3-8). - //if our maximum edit distance is 4, then we can discard this word - //without looking at it. - $similarity = 0; - } else { - $similarity = 1 - levenshtein($termRest, $target)/($prefixUtf8Length + min($termRestLength, strlen($target))); - } - - if ($similarity > $this->_minimumSimilarity) { - $words[] = $termText; - } - } - } - - $highlighter->highlight($words); - } - - /** - * Print a query - * - * @return string - */ - public function __toString() - { - // It's used only for query visualisation, so we don't care about characters escaping - return (($this->_term->field === null)? '' : $this->_term->field . ':') - . $this->_term->text . '~' - . (($this->_minimumSimilarity != self::DEFAULT_MIN_SIMILARITY)? round($this->_minimumSimilarity, 4) : '') - . (($this->getBoost() != 1)? '^' . round($this->getBoost(), 4) : ''); - } -} - diff --git a/library/Zend/Search/Lucene/Search/Query/Insignificant.php b/library/Zend/Search/Lucene/Search/Query/Insignificant.php deleted file mode 100644 index 12817f34fa..0000000000 --- a/library/Zend/Search/Lucene/Search/Query/Insignificant.php +++ /dev/null @@ -1,139 +0,0 @@ -'; - } -} - diff --git a/library/Zend/Search/Lucene/Search/Query/MultiTerm.php b/library/Zend/Search/Lucene/Search/Query/MultiTerm.php deleted file mode 100644 index 78a2cb62e8..0000000000 --- a/library/Zend/Search/Lucene/Search/Query/MultiTerm.php +++ /dev/null @@ -1,668 +0,0 @@ - (docId => freq, ...) - * term2Id => (docId => freq, ...) - * - * @var array - */ - private $_termsFreqs = array(); - - - /** - * A score factor based on the fraction of all query terms - * that a document contains. - * float for conjunction queries - * array of float for non conjunction queries - * - * @var mixed - */ - private $_coord = null; - - - /** - * Terms weights - * array of Zend_Search_Lucene_Search_Weight - * - * @var array - */ - private $_weights = array(); - - - /** - * Class constructor. Create a new multi-term query object. - * - * if $signs array is omitted then all terms are required - * it differs from addTerm() behavior, but should never be used - * - * @param array $terms Array of Zend_Search_Lucene_Index_Term objects - * @param array $signs Array of signs. Sign is boolean|null. - * @throws Zend_Search_Lucene_Exception - */ - public function __construct($terms = null, $signs = null) - { - if (is_array($terms)) { - #require_once 'Zend/Search/Lucene.php'; - if (count($terms) > Zend_Search_Lucene::getTermsPerQueryLimit()) { - throw new Zend_Search_Lucene_Exception('Terms per query limit is reached.'); - } - - $this->_terms = $terms; - - $this->_signs = null; - // Check if all terms are required - if (is_array($signs)) { - foreach ($signs as $sign ) { - if ($sign !== true) { - $this->_signs = $signs; - break; - } - } - } - } - } - - - /** - * 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 - */ - 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; - } - - - /** - * Re-write query into primitive queries in the context of specified index - * - * @param Zend_Search_Lucene_Interface $index - * @return Zend_Search_Lucene_Search_Query - */ - public function rewrite(Zend_Search_Lucene_Interface $index) - { - if (count($this->_terms) == 0) { - #require_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. */ - #require_once 'Zend/Search/Lucene/Search/Query/Boolean.php'; - $query = new Zend_Search_Lucene_Search_Query_Boolean(); - $query->setBoost($this->getBoost()); - - #require_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; - } - } - - /** - * Optimize query in the context of specified index - * - * @param Zend_Search_Lucene_Interface $index - * @return Zend_Search_Lucene_Search_Query - */ - 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 - #require_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) { - #require_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 - #require_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) { - #require_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; - } - - - /** - * Returns query term - * - * @return array - */ - public function getTerms() - { - return $this->_terms; - } - - - /** - * Return terms signs - * - * @return array - */ - public function getSigns() - { - return $this->_signs; - } - - - /** - * Set weight for specified term - * - * @param integer $num - * @param Zend_Search_Lucene_Search_Weight_Term $weight - */ - public function setWeight($num, $weight) - { - $this->_weights[$num] = $weight; - } - - - /** - * Constructs an appropriate Weight implementation for this query. - * - * @param Zend_Search_Lucene_Interface $reader - * @return Zend_Search_Lucene_Search_Weight - */ - public function createWeight(Zend_Search_Lucene_Interface $reader) - { - #require_once 'Zend/Search/Lucene/Search/Weight/MultiTerm.php'; - $this->_weight = new Zend_Search_Lucene_Search_Weight_MultiTerm($this, $reader); - return $this->_weight; - } - - - /** - * Calculate result vector for Conjunction query - * (like '+something +another') - * - * @param Zend_Search_Lucene_Interface $reader - */ - 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); - - #require_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 non Conjunction query - * (like '+something -another') - * - * @param Zend_Search_Lucene_Interface $reader - */ - 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); - } - - - /** - * Score calculator for conjunction queries (all terms are required) - * - * @param integer $docId - * @param Zend_Search_Lucene_Interface $reader - * @return float - */ - 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 non conjunction queries (not all terms are required) - * - * @param integer $docId - * @param Zend_Search_Lucene_Interface $reader - * @return float - */ - 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(); - } - - /** - * 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 - */ - 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); - } - - /** - * Get document ids likely matching the query - * - * It's an array with document ids as keys (performance considerations) - * - * @return array - */ - public function matchedDocs() - { - return $this->_resVector; - } - - /** - * Score specified document - * - * @param integer $docId - * @param Zend_Search_Lucene_Interface $reader - * @return float - */ - public function score($docId, Zend_Search_Lucene_Interface $reader) - { - if (isset($this->_resVector[$docId])) { - if ($this->_signs === null) { - return $this->_conjunctionScore($docId, $reader); - } else { - return $this->_nonConjunctionScore($docId, $reader); - } - } else { - return 0; - } - } - - /** - * Return query terms - * - * @return array - */ - 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; - } - - /** - * Query specific matches highlighting - * - * @param Zend_Search_Lucene_Search_Highlighter_Interface $highlighter Highlighter object (also contains doc for highlighting) - */ - 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); - } - - /** - * Print a query - * - * @return string - */ - public function __toString() - { - // It's used only for query visualisation, so we don't care about characters escaping - - $query = ''; - - foreach ($this->_terms as $id => $term) { - if ($id != 0) { - $query .= ' '; - } - - if ($this->_signs === null || $this->_signs[$id] === true) { - $query .= '+'; - } else if ($this->_signs[$id] === false) { - $query .= '-'; - } - - if ($term->field !== null) { - $query .= $term->field . ':'; - } - $query .= $term->text; - } - - if ($this->getBoost() != 1) { - $query = '(' . $query . ')^' . round($this->getBoost(), 4); - } - - return $query; - } -} - diff --git a/library/Zend/Search/Lucene/Search/Query/Phrase.php b/library/Zend/Search/Lucene/Search/Query/Phrase.php deleted file mode 100644 index c54cb51673..0000000000 --- a/library/Zend/Search/Lucene/Search/Query/Phrase.php +++ /dev/null @@ -1,576 +0,0 @@ - (docId => array( pos1, pos2, ... ), ...) - * term2Id => (docId => array( pos1, pos2, ... ), ...) - * - * @var array - */ - private $_termsPositions = array(); - - /** - * Class constructor. Create a new prase query. - * - * @param string $field Field to search. - * @param array $terms Terms to search Array of strings. - * @param array $offsets Relative term positions. Array of integers. - * @throws Zend_Search_Lucene_Exception - */ - public function __construct($terms = null, $offsets = null, $field = null) - { - $this->_slop = 0; - - if (is_array($terms)) { - $this->_terms = array(); - #require_once 'Zend/Search/Lucene/Index/Term.php'; - foreach ($terms as $termId => $termText) { - $this->_terms[$termId] = ($field !== null)? new Zend_Search_Lucene_Index_Term($termText, $field): - new Zend_Search_Lucene_Index_Term($termText); - } - } else if ($terms === null) { - $this->_terms = array(); - } else { - #require_once 'Zend/Search/Lucene/Exception.php'; - throw new Zend_Search_Lucene_Exception('terms argument must be array of strings or null'); - } - - if (is_array($offsets)) { - if (count($this->_terms) != count($offsets)) { - #require_once 'Zend/Search/Lucene/Exception.php'; - throw new Zend_Search_Lucene_Exception('terms and offsets arguments must have the same size.'); - } - $this->_offsets = $offsets; - } else if ($offsets === null) { - $this->_offsets = array(); - foreach ($this->_terms as $termId => $term) { - $position = count($this->_offsets); - $this->_offsets[$termId] = $position; - } - } else { - #require_once 'Zend/Search/Lucene/Exception.php'; - throw new Zend_Search_Lucene_Exception('offsets argument must be array of strings or null'); - } - } - - /** - * Set slop - * - * @param integer $slop - */ - public function setSlop($slop) - { - $this->_slop = $slop; - } - - - /** - * Get slop - * - * @return integer - */ - public function getSlop() - { - return $this->_slop; - } - - - /** - * Adds a term to the end of the query phrase. - * The relative position of the term is specified explicitly or the one immediately - * after the last term added. - * - * @param Zend_Search_Lucene_Index_Term $term - * @param integer $position - */ - public function addTerm(Zend_Search_Lucene_Index_Term $term, $position = null) { - if ((count($this->_terms) != 0)&&(end($this->_terms)->field != $term->field)) { - #require_once 'Zend/Search/Lucene/Exception.php'; - throw new Zend_Search_Lucene_Exception('All phrase terms must be in the same field: ' . - $term->field . ':' . $term->text); - } - - $this->_terms[] = $term; - if ($position !== null) { - $this->_offsets[] = $position; - } else if (count($this->_offsets) != 0) { - $this->_offsets[] = end($this->_offsets) + 1; - } else { - $this->_offsets[] = 0; - } - } - - - /** - * Re-write query into primitive queries in the context of specified index - * - * @param Zend_Search_Lucene_Interface $index - * @return Zend_Search_Lucene_Search_Query - */ - public function rewrite(Zend_Search_Lucene_Interface $index) - { - if (count($this->_terms) == 0) { - #require_once 'Zend/Search/Lucene/Search/Query/Empty.php'; - return new Zend_Search_Lucene_Search_Query_Empty(); - } else if ($this->_terms[0]->field !== null) { - return $this; - } else { - #require_once 'Zend/Search/Lucene/Search/Query/Boolean.php'; - $query = new Zend_Search_Lucene_Search_Query_Boolean(); - $query->setBoost($this->getBoost()); - - foreach ($index->getFieldNames(true) as $fieldName) { - $subquery = new Zend_Search_Lucene_Search_Query_Phrase(); - $subquery->setSlop($this->getSlop()); - - #require_once 'Zend/Search/Lucene/Index/Term.php'; - foreach ($this->_terms as $termId => $term) { - $qualifiedTerm = new Zend_Search_Lucene_Index_Term($term->text, $fieldName); - - $subquery->addTerm($qualifiedTerm, $this->_offsets[$termId]); - } - - $query->addSubquery($subquery); - } - - return $query; - } - } - - /** - * Optimize query in the context of specified index - * - * @param Zend_Search_Lucene_Interface $index - * @return Zend_Search_Lucene_Search_Query - */ - public function optimize(Zend_Search_Lucene_Interface $index) - { - // Check, that index contains all phrase terms - foreach ($this->_terms as $term) { - if (!$index->hasTerm($term)) { - #require_once 'Zend/Search/Lucene/Search/Query/Empty.php'; - return new Zend_Search_Lucene_Search_Query_Empty(); - } - } - - if (count($this->_terms) == 1) { - // It's one term query - #require_once 'Zend/Search/Lucene/Search/Query/Term.php'; - $optimizedQuery = new Zend_Search_Lucene_Search_Query_Term(reset($this->_terms)); - $optimizedQuery->setBoost($this->getBoost()); - - return $optimizedQuery; - } - - if (count($this->_terms) == 0) { - #require_once 'Zend/Search/Lucene/Search/Query/Empty.php'; - return new Zend_Search_Lucene_Search_Query_Empty(); - } - - - return $this; - } - - /** - * Returns query term - * - * @return array - */ - public function getTerms() - { - return $this->_terms; - } - - - /** - * Set weight for specified term - * - * @param integer $num - * @param Zend_Search_Lucene_Search_Weight_Term $weight - */ - public function setWeight($num, $weight) - { - $this->_weights[$num] = $weight; - } - - - /** - * Constructs an appropriate Weight implementation for this query. - * - * @param Zend_Search_Lucene_Interface $reader - * @return Zend_Search_Lucene_Search_Weight - */ - public function createWeight(Zend_Search_Lucene_Interface $reader) - { - #require_once 'Zend/Search/Lucene/Search/Weight/Phrase.php'; - $this->_weight = new Zend_Search_Lucene_Search_Weight_Phrase($this, $reader); - return $this->_weight; - } - - - /** - * Score calculator for exact phrase queries (terms sequence is fixed) - * - * @param integer $docId - * @return float - */ - public function _exactPhraseFreq($docId) - { - $freq = 0; - - // Term Id with lowest cardinality - $lowCardTermId = null; - - // Calculate $lowCardTermId - foreach ($this->_terms as $termId => $term) { - if ($lowCardTermId === null || - count($this->_termsPositions[$termId][$docId]) < - count($this->_termsPositions[$lowCardTermId][$docId]) ) { - $lowCardTermId = $termId; - } - } - - // Walk through positions of the term with lowest cardinality - foreach ($this->_termsPositions[$lowCardTermId][$docId] as $lowCardPos) { - // We expect phrase to be found - $freq++; - - // Walk through other terms - foreach ($this->_terms as $termId => $term) { - if ($termId != $lowCardTermId) { - $expectedPosition = $lowCardPos + - ($this->_offsets[$termId] - - $this->_offsets[$lowCardTermId]); - - if (!in_array($expectedPosition, $this->_termsPositions[$termId][$docId])) { - $freq--; // Phrase wasn't found. - break; - } - } - } - } - - return $freq; - } - - /** - * Score calculator for sloppy phrase queries (terms sequence is fixed) - * - * @param integer $docId - * @param Zend_Search_Lucene_Interface $reader - * @return float - */ - public function _sloppyPhraseFreq($docId, Zend_Search_Lucene_Interface $reader) - { - $freq = 0; - - $phraseQueue = array(); - $phraseQueue[0] = array(); // empty phrase - $lastTerm = null; - - // Walk through the terms to create phrases. - foreach ($this->_terms as $termId => $term) { - $queueSize = count($phraseQueue); - $firstPass = true; - - // Walk through the term positions. - // Each term position produces a set of phrases. - foreach ($this->_termsPositions[$termId][$docId] as $termPosition ) { - if ($firstPass) { - for ($count = 0; $count < $queueSize; $count++) { - $phraseQueue[$count][$termId] = $termPosition; - } - } else { - for ($count = 0; $count < $queueSize; $count++) { - if ($lastTerm !== null && - abs( $termPosition - $phraseQueue[$count][$lastTerm] - - ($this->_offsets[$termId] - $this->_offsets[$lastTerm])) > $this->_slop) { - continue; - } - - $newPhraseId = count($phraseQueue); - $phraseQueue[$newPhraseId] = $phraseQueue[$count]; - $phraseQueue[$newPhraseId][$termId] = $termPosition; - } - - } - - $firstPass = false; - } - $lastTerm = $termId; - } - - - foreach ($phraseQueue as $phrasePos) { - $minDistance = null; - - for ($shift = -$this->_slop; $shift <= $this->_slop; $shift++) { - $distance = 0; - $start = reset($phrasePos) - reset($this->_offsets) + $shift; - - foreach ($this->_terms as $termId => $term) { - $distance += abs($phrasePos[$termId] - $this->_offsets[$termId] - $start); - - if($distance > $this->_slop) { - break; - } - } - - if ($minDistance === null || $distance < $minDistance) { - $minDistance = $distance; - } - } - - if ($minDistance <= $this->_slop) { - $freq += $reader->getSimilarity()->sloppyFreq($minDistance); - } - } - - return $freq; - } - - /** - * 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 - */ - public function execute(Zend_Search_Lucene_Interface $reader, $docsFilter = null) - { - $this->_resVector = null; - - if (count($this->_terms) == 0) { - $this->_resVector = array(); - } - - $resVectors = array(); - $resVectorsSizes = array(); - $resVectorsIds = array(); // is used to prevent arrays comparison - foreach ($this->_terms as $termId => $term) { - $resVectors[] = array_flip($reader->termDocs($term)); - $resVectorsSizes[] = count(end($resVectors)); - $resVectorsIds[] = $termId; - - $this->_termsPositions[$termId] = $reader->termPositions($term); - } - // sort resvectors in order of subquery cardinality increasing - array_multisort($resVectorsSizes, SORT_ASC, SORT_NUMERIC, - $resVectorsIds, SORT_ASC, SORT_NUMERIC, - $resVectors); - - foreach ($resVectors as $nextResVector) { - if($this->_resVector === null) { - $this->_resVector = $nextResVector; - } else { - //$this->_resVector = array_intersect_key($this->_resVector, $nextResVector); - - /** - * This code is used as workaround for array_intersect_key() slowness problem. - */ - $updatedVector = array(); - foreach ($this->_resVector as $id => $value) { - if (isset($nextResVector[$id])) { - $updatedVector[$id] = $value; - } - } - $this->_resVector = $updatedVector; - } - - if (count($this->_resVector) == 0) { - // Empty result set, we don't need to check other terms - break; - } - } - - // ksort($this->_resVector, SORT_NUMERIC); - // Docs are returned ordered. Used algorithm doesn't change elements order. - - // Initialize weight if it's not done yet - $this->_initWeight($reader); - } - - /** - * Get document ids likely matching the query - * - * It's an array with document ids as keys (performance considerations) - * - * @return array - */ - public function matchedDocs() - { - return $this->_resVector; - } - - /** - * Score specified document - * - * @param integer $docId - * @param Zend_Search_Lucene_Interface $reader - * @return float - */ - public function score($docId, Zend_Search_Lucene_Interface $reader) - { - if (isset($this->_resVector[$docId])) { - if ($this->_slop == 0) { - $freq = $this->_exactPhraseFreq($docId); - } else { - $freq = $this->_sloppyPhraseFreq($docId, $reader); - } - - if ($freq != 0) { - $tf = $reader->getSimilarity()->tf($freq); - $weight = $this->_weight->getValue(); - $norm = $reader->norm($docId, reset($this->_terms)->field); - - return $tf * $weight * $norm * $this->getBoost(); - } - - // Included in result, but culculated freq is zero - return 0; - } else { - return 0; - } - } - - /** - * Return query terms - * - * @return array - */ - public function getQueryTerms() - { - return $this->_terms; - } - - /** - * Query specific matches highlighting - * - * @param Zend_Search_Lucene_Search_Highlighter_Interface $highlighter Highlighter object (also contains doc for highlighting) - */ - protected function _highlightMatches(Zend_Search_Lucene_Search_Highlighter_Interface $highlighter) - { - $words = array(); - foreach ($this->_terms as $term) { - $words[] = $term->text; - } - - $highlighter->highlight($words); - } - - /** - * Print a query - * - * @return string - */ - public function __toString() - { - // It's used only for query visualisation, so we don't care about characters escaping - if (isset($this->_terms[0]) && $this->_terms[0]->field !== null) { - $query = $this->_terms[0]->field . ':'; - } else { - $query = ''; - } - - $query .= '"'; - - foreach ($this->_terms as $id => $term) { - if ($id != 0) { - $query .= ' '; - } - $query .= $term->text; - } - - $query .= '"'; - - if ($this->_slop != 0) { - $query .= '~' . $this->_slop; - } - - if ($this->getBoost() != 1) { - $query .= '^' . round($this->getBoost(), 4); - } - - return $query; - } -} - diff --git a/library/Zend/Search/Lucene/Search/Query/Preprocessing.php b/library/Zend/Search/Lucene/Search/Query/Preprocessing.php deleted file mode 100644 index ac2de467e3..0000000000 --- a/library/Zend/Search/Lucene/Search/Query/Preprocessing.php +++ /dev/null @@ -1,127 +0,0 @@ -_word = $word; - $this->_encoding = $encoding; - $this->_field = $fieldName; - $this->_minimumSimilarity = $minimumSimilarity; - } - - /** - * Re-write query into primitive queries in the context of specified index - * - * @param Zend_Search_Lucene_Interface $index - * @return Zend_Search_Lucene_Search_Query - */ - public function rewrite(Zend_Search_Lucene_Interface $index) - { - if ($this->_field === null) { - #require_once 'Zend/Search/Lucene/Search/Query/Boolean.php'; - $query = new Zend_Search_Lucene_Search_Query_Boolean(); - - $hasInsignificantSubqueries = false; - - #require_once 'Zend/Search/Lucene.php'; - if (Zend_Search_Lucene::getDefaultSearchField() === null) { - $searchFields = $index->getFieldNames(true); - } else { - $searchFields = array(Zend_Search_Lucene::getDefaultSearchField()); - } - - #require_once 'Zend/Search/Lucene/Search/Query/Preprocessing/Fuzzy.php'; - foreach ($searchFields as $fieldName) { - $subquery = new Zend_Search_Lucene_Search_Query_Preprocessing_Fuzzy($this->_word, - $this->_encoding, - $fieldName, - $this->_minimumSimilarity); - - $rewrittenSubquery = $subquery->rewrite($index); - - if ( !($rewrittenSubquery instanceof Zend_Search_Lucene_Search_Query_Insignificant || - $rewrittenSubquery instanceof Zend_Search_Lucene_Search_Query_Empty) ) { - $query->addSubquery($rewrittenSubquery); - } - - if ($rewrittenSubquery instanceof Zend_Search_Lucene_Search_Query_Insignificant) { - $hasInsignificantSubqueries = true; - } - } - - $subqueries = $query->getSubqueries(); - - if (count($subqueries) == 0) { - $this->_matches = array(); - if ($hasInsignificantSubqueries) { - #require_once 'Zend/Search/Lucene/Search/Query/Insignificant.php'; - return new Zend_Search_Lucene_Search_Query_Insignificant(); - } else { - #require_once 'Zend/Search/Lucene/Search/Query/Empty.php'; - return new Zend_Search_Lucene_Search_Query_Empty(); - } - } - - if (count($subqueries) == 1) { - $query = reset($subqueries); - } - - $query->setBoost($this->getBoost()); - - $this->_matches = $query->getQueryTerms(); - return $query; - } - - // ------------------------------------- - // Recognize exact term matching (it corresponds to Keyword fields stored in the index) - // encoding is not used since we expect binary matching - #require_once 'Zend/Search/Lucene/Index/Term.php'; - $term = new Zend_Search_Lucene_Index_Term($this->_word, $this->_field); - if ($index->hasTerm($term)) { - #require_once 'Zend/Search/Lucene/Search/Query/Fuzzy.php'; - $query = new Zend_Search_Lucene_Search_Query_Fuzzy($term, $this->_minimumSimilarity); - $query->setBoost($this->getBoost()); - - // Get rewritten query. Important! It also fills terms matching container. - $rewrittenQuery = $query->rewrite($index); - $this->_matches = $query->getQueryTerms(); - - return $rewrittenQuery; - } - - - // ------------------------------------- - // Recognize wildcard queries - - /** @todo check for PCRE unicode support may be performed through Zend_Environment in some future */ - if (@preg_match('/\pL/u', 'a') == 1) { - $subPatterns = preg_split('/[*?]/u', iconv($this->_encoding, 'UTF-8', $this->_word)); - } else { - $subPatterns = preg_split('/[*?]/', $this->_word); - } - if (count($subPatterns) > 1) { - #require_once 'Zend/Search/Lucene/Search/QueryParserException.php'; - throw new Zend_Search_Lucene_Search_QueryParserException('Fuzzy search doesn\'t support wildcards (except within Keyword fields).'); - } - - - // ------------------------------------- - // Recognize one-term multi-term and "insignificant" queries - #require_once 'Zend/Search/Lucene/Analysis/Analyzer.php'; - $tokens = Zend_Search_Lucene_Analysis_Analyzer::getDefault()->tokenize($this->_word, $this->_encoding); - - if (count($tokens) == 0) { - $this->_matches = array(); - #require_once 'Zend/Search/Lucene/Search/Query/Insignificant.php'; - return new Zend_Search_Lucene_Search_Query_Insignificant(); - } - - if (count($tokens) == 1) { - #require_once 'Zend/Search/Lucene/Index/Term.php'; - $term = new Zend_Search_Lucene_Index_Term($tokens[0]->getTermText(), $this->_field); - #require_once 'Zend/Search/Lucene/Search/Query/Fuzzy.php'; - $query = new Zend_Search_Lucene_Search_Query_Fuzzy($term, $this->_minimumSimilarity); - $query->setBoost($this->getBoost()); - - // Get rewritten query. Important! It also fills terms matching container. - $rewrittenQuery = $query->rewrite($index); - $this->_matches = $query->getQueryTerms(); - - return $rewrittenQuery; - } - - // Word is tokenized into several tokens - #require_once 'Zend/Search/Lucene/Search/QueryParserException.php'; - throw new Zend_Search_Lucene_Search_QueryParserException('Fuzzy search is supported only for non-multiple word terms'); - } - - /** - * Query specific matches highlighting - * - * @param Zend_Search_Lucene_Search_Highlighter_Interface $highlighter Highlighter object (also contains doc for highlighting) - */ - protected function _highlightMatches(Zend_Search_Lucene_Search_Highlighter_Interface $highlighter) - { - /** Skip fields detection. We don't need it, since we expect all fields presented in the HTML body and don't differentiate them */ - - /** Skip exact term matching recognition, keyword fields highlighting is not supported */ - - // ------------------------------------- - // Recognize wildcard queries - - /** @todo check for PCRE unicode support may be performed through Zend_Environment in some future */ - if (@preg_match('/\pL/u', 'a') == 1) { - $subPatterns = preg_split('/[*?]/u', iconv($this->_encoding, 'UTF-8', $this->_word)); - } else { - $subPatterns = preg_split('/[*?]/', $this->_word); - } - if (count($subPatterns) > 1) { - // Do nothing - return; - } - - - // ------------------------------------- - // Recognize one-term multi-term and "insignificant" queries - #require_once 'Zend/Search/Lucene/Analysis/Analyzer.php'; - $tokens = Zend_Search_Lucene_Analysis_Analyzer::getDefault()->tokenize($this->_word, $this->_encoding); - if (count($tokens) == 0) { - // Do nothing - return; - } - if (count($tokens) == 1) { - #require_once 'Zend/Search/Lucene/Index/Term.php'; - $term = new Zend_Search_Lucene_Index_Term($tokens[0]->getTermText(), $this->_field); - #require_once 'Zend/Search/Lucene/Search/Query/Fuzzy.php'; - $query = new Zend_Search_Lucene_Search_Query_Fuzzy($term, $this->_minimumSimilarity); - - $query->_highlightMatches($highlighter); - return; - } - - // Word is tokenized into several tokens - // But fuzzy search is supported only for non-multiple word terms - // Do nothing - } - - /** - * Print a query - * - * @return string - */ - public function __toString() - { - // It's used only for query visualisation, so we don't care about characters escaping - if ($this->_field !== null) { - $query = $this->_field . ':'; - } else { - $query = ''; - } - - $query .= $this->_word; - - if ($this->getBoost() != 1) { - $query .= '^' . round($this->getBoost(), 4); - } - - return $query; - } -} diff --git a/library/Zend/Search/Lucene/Search/Query/Preprocessing/Phrase.php b/library/Zend/Search/Lucene/Search/Query/Preprocessing/Phrase.php deleted file mode 100644 index fe2c65d654..0000000000 --- a/library/Zend/Search/Lucene/Search/Query/Preprocessing/Phrase.php +++ /dev/null @@ -1,270 +0,0 @@ -_phrase = $phrase; - $this->_phraseEncoding = $phraseEncoding; - $this->_field = $fieldName; - } - - /** - * Set slop - * - * @param integer $slop - */ - public function setSlop($slop) - { - $this->_slop = $slop; - } - - - /** - * Get slop - * - * @return integer - */ - public function getSlop() - { - return $this->_slop; - } - - /** - * Re-write query into primitive queries in the context of specified index - * - * @param Zend_Search_Lucene_Interface $index - * @return Zend_Search_Lucene_Search_Query - */ - public function rewrite(Zend_Search_Lucene_Interface $index) - { -// Allow to use wildcards within phrases -// They are either removed by text analyzer or used as a part of keyword for keyword fields -// -// if (strpos($this->_phrase, '?') !== false || strpos($this->_phrase, '*') !== false) { -// #require_once 'Zend/Search/Lucene/Search/QueryParserException.php'; -// throw new Zend_Search_Lucene_Search_QueryParserException('Wildcards are only allowed in a single terms.'); -// } - - // Split query into subqueries if field name is not specified - if ($this->_field === null) { - #require_once 'Zend/Search/Lucene/Search/Query/Boolean.php'; - $query = new Zend_Search_Lucene_Search_Query_Boolean(); - $query->setBoost($this->getBoost()); - - #require_once 'Zend/Search/Lucene.php'; - if (Zend_Search_Lucene::getDefaultSearchField() === null) { - $searchFields = $index->getFieldNames(true); - } else { - $searchFields = array(Zend_Search_Lucene::getDefaultSearchField()); - } - - foreach ($searchFields as $fieldName) { - $subquery = new Zend_Search_Lucene_Search_Query_Preprocessing_Phrase($this->_phrase, - $this->_phraseEncoding, - $fieldName); - $subquery->setSlop($this->getSlop()); - - $query->addSubquery($subquery->rewrite($index)); - } - - $this->_matches = $query->getQueryTerms(); - return $query; - } - - // Recognize exact term matching (it corresponds to Keyword fields stored in the index) - // encoding is not used since we expect binary matching - #require_once 'Zend/Search/Lucene/Index/Term.php'; - $term = new Zend_Search_Lucene_Index_Term($this->_phrase, $this->_field); - if ($index->hasTerm($term)) { - #require_once 'Zend/Search/Lucene/Search/Query/Term.php'; - $query = new Zend_Search_Lucene_Search_Query_Term($term); - $query->setBoost($this->getBoost()); - - $this->_matches = $query->getQueryTerms(); - return $query; - } - - - // tokenize phrase using current analyzer and process it as a phrase query - #require_once 'Zend/Search/Lucene/Analysis/Analyzer.php'; - $tokens = Zend_Search_Lucene_Analysis_Analyzer::getDefault()->tokenize($this->_phrase, $this->_phraseEncoding); - - if (count($tokens) == 0) { - $this->_matches = array(); - #require_once 'Zend/Search/Lucene/Search/Query/Insignificant.php'; - return new Zend_Search_Lucene_Search_Query_Insignificant(); - } - - if (count($tokens) == 1) { - #require_once 'Zend/Search/Lucene/Index/Term.php'; - $term = new Zend_Search_Lucene_Index_Term($tokens[0]->getTermText(), $this->_field); - #require_once 'Zend/Search/Lucene/Search/Query/Term.php'; - $query = new Zend_Search_Lucene_Search_Query_Term($term); - $query->setBoost($this->getBoost()); - - $this->_matches = $query->getQueryTerms(); - return $query; - } - - //It's non-trivial phrase query - $position = -1; - #require_once 'Zend/Search/Lucene/Search/Query/Phrase.php'; - $query = new Zend_Search_Lucene_Search_Query_Phrase(); - #require_once 'Zend/Search/Lucene/Index/Term.php'; - foreach ($tokens as $token) { - $position += $token->getPositionIncrement(); - $term = new Zend_Search_Lucene_Index_Term($token->getTermText(), $this->_field); - $query->addTerm($term, $position); - $query->setSlop($this->getSlop()); - } - $this->_matches = $query->getQueryTerms(); - return $query; - } - - /** - * Query specific matches highlighting - * - * @param Zend_Search_Lucene_Search_Highlighter_Interface $highlighter Highlighter object (also contains doc for highlighting) - */ - protected function _highlightMatches(Zend_Search_Lucene_Search_Highlighter_Interface $highlighter) - { - /** Skip fields detection. We don't need it, since we expect all fields presented in the HTML body and don't differentiate them */ - - /** Skip exact term matching recognition, keyword fields highlighting is not supported */ - - /** Skip wildcard queries recognition. Supported wildcards are removed by text analyzer */ - - - // tokenize phrase using current analyzer and process it as a phrase query - #require_once 'Zend/Search/Lucene/Analysis/Analyzer.php'; - $tokens = Zend_Search_Lucene_Analysis_Analyzer::getDefault()->tokenize($this->_phrase, $this->_phraseEncoding); - - if (count($tokens) == 0) { - // Do nothing - return; - } - - if (count($tokens) == 1) { - $highlighter->highlight($tokens[0]->getTermText()); - return; - } - - //It's non-trivial phrase query - $words = array(); - foreach ($tokens as $token) { - $words[] = $token->getTermText(); - } - $highlighter->highlight($words); - } - - /** - * Print a query - * - * @return string - */ - public function __toString() - { - // It's used only for query visualisation, so we don't care about characters escaping - if ($this->_field !== null) { - $query = $this->_field . ':'; - } else { - $query = ''; - } - - $query .= '"' . $this->_phrase . '"'; - - if ($this->_slop != 0) { - $query .= '~' . $this->_slop; - } - - if ($this->getBoost() != 1) { - $query .= '^' . round($this->getBoost(), 4); - } - - return $query; - } -} diff --git a/library/Zend/Search/Lucene/Search/Query/Preprocessing/Term.php b/library/Zend/Search/Lucene/Search/Query/Preprocessing/Term.php deleted file mode 100644 index c9783374c2..0000000000 --- a/library/Zend/Search/Lucene/Search/Query/Preprocessing/Term.php +++ /dev/null @@ -1,341 +0,0 @@ -_word = $word; - $this->_encoding = $encoding; - $this->_field = $fieldName; - } - - /** - * Re-write query into primitive queries in the context of specified index - * - * @param Zend_Search_Lucene_Interface $index - * @return Zend_Search_Lucene_Search_Query - */ - public function rewrite(Zend_Search_Lucene_Interface $index) - { - if ($this->_field === null) { - #require_once 'Zend/Search/Lucene/Search/Query/MultiTerm.php'; - $query = new Zend_Search_Lucene_Search_Query_MultiTerm(); - $query->setBoost($this->getBoost()); - - $hasInsignificantSubqueries = false; - - #require_once 'Zend/Search/Lucene.php'; - if (Zend_Search_Lucene::getDefaultSearchField() === null) { - $searchFields = $index->getFieldNames(true); - } else { - $searchFields = array(Zend_Search_Lucene::getDefaultSearchField()); - } - - #require_once 'Zend/Search/Lucene/Search/Query/Preprocessing/Term.php'; - foreach ($searchFields as $fieldName) { - $subquery = new Zend_Search_Lucene_Search_Query_Preprocessing_Term($this->_word, - $this->_encoding, - $fieldName); - $rewrittenSubquery = $subquery->rewrite($index); - foreach ($rewrittenSubquery->getQueryTerms() as $term) { - $query->addTerm($term); - } - - if ($rewrittenSubquery instanceof Zend_Search_Lucene_Search_Query_Insignificant) { - $hasInsignificantSubqueries = true; - } - } - - if (count($query->getTerms()) == 0) { - $this->_matches = array(); - if ($hasInsignificantSubqueries) { - #require_once 'Zend/Search/Lucene/Search/Query/Insignificant.php'; - return new Zend_Search_Lucene_Search_Query_Insignificant(); - } else { - #require_once 'Zend/Search/Lucene/Search/Query/Empty.php'; - return new Zend_Search_Lucene_Search_Query_Empty(); - } - } - - $this->_matches = $query->getQueryTerms(); - return $query; - } - - // ------------------------------------- - // Recognize exact term matching (it corresponds to Keyword fields stored in the index) - // encoding is not used since we expect binary matching - #require_once 'Zend/Search/Lucene/Index/Term.php'; - $term = new Zend_Search_Lucene_Index_Term($this->_word, $this->_field); - if ($index->hasTerm($term)) { - #require_once 'Zend/Search/Lucene/Search/Query/Term.php'; - $query = new Zend_Search_Lucene_Search_Query_Term($term); - $query->setBoost($this->getBoost()); - - $this->_matches = $query->getQueryTerms(); - return $query; - } - - - // ------------------------------------- - // Recognize wildcard queries - - /** @todo check for PCRE unicode support may be performed through Zend_Environment in some future */ - if (@preg_match('/\pL/u', 'a') == 1) { - $word = iconv($this->_encoding, 'UTF-8', $this->_word); - $wildcardsPattern = '/[*?]/u'; - $subPatternsEncoding = 'UTF-8'; - } else { - $word = $this->_word; - $wildcardsPattern = '/[*?]/'; - $subPatternsEncoding = $this->_encoding; - } - - $subPatterns = preg_split($wildcardsPattern, $word, -1, PREG_SPLIT_OFFSET_CAPTURE); - - if (count($subPatterns) > 1) { - // Wildcard query is recognized - - $pattern = ''; - - #require_once 'Zend/Search/Lucene/Analysis/Analyzer.php'; - foreach ($subPatterns as $id => $subPattern) { - // Append corresponding wildcard character to the pattern before each sub-pattern (except first) - if ($id != 0) { - $pattern .= $word[ $subPattern[1] - 1 ]; - } - - // Check if each subputtern is a single word in terms of current analyzer - $tokens = Zend_Search_Lucene_Analysis_Analyzer::getDefault()->tokenize($subPattern[0], $subPatternsEncoding); - if (count($tokens) > 1) { - #require_once 'Zend/Search/Lucene/Search/QueryParserException.php'; - throw new Zend_Search_Lucene_Search_QueryParserException('Wildcard search is supported only for non-multiple word terms'); - } - foreach ($tokens as $token) { - $pattern .= $token->getTermText(); - } - } - - #require_once 'Zend/Search/Lucene/Index/Term.php'; - $term = new Zend_Search_Lucene_Index_Term($pattern, $this->_field); - #require_once 'Zend/Search/Lucene/Search/Query/Wildcard.php'; - $query = new Zend_Search_Lucene_Search_Query_Wildcard($term); - $query->setBoost($this->getBoost()); - - // Get rewritten query. Important! It also fills terms matching container. - $rewrittenQuery = $query->rewrite($index); - $this->_matches = $query->getQueryTerms(); - - return $rewrittenQuery; - } - - - // ------------------------------------- - // Recognize one-term multi-term and "insignificant" queries - #require_once 'Zend/Search/Lucene/Analysis/Analyzer.php'; - $tokens = Zend_Search_Lucene_Analysis_Analyzer::getDefault()->tokenize($this->_word, $this->_encoding); - - if (count($tokens) == 0) { - $this->_matches = array(); - #require_once 'Zend/Search/Lucene/Search/Query/Insignificant.php'; - return new Zend_Search_Lucene_Search_Query_Insignificant(); - } - - if (count($tokens) == 1) { - #require_once 'Zend/Search/Lucene/Index/Term.php'; - $term = new Zend_Search_Lucene_Index_Term($tokens[0]->getTermText(), $this->_field); - #require_once 'Zend/Search/Lucene/Search/Query/Term.php'; - $query = new Zend_Search_Lucene_Search_Query_Term($term); - $query->setBoost($this->getBoost()); - - $this->_matches = $query->getQueryTerms(); - return $query; - } - - //It's not insignificant or one term query - #require_once 'Zend/Search/Lucene/Search/Query/MultiTerm.php'; - $query = new Zend_Search_Lucene_Search_Query_MultiTerm(); - - /** - * @todo Process $token->getPositionIncrement() to support stemming, synonyms and other - * analizer design features - */ - #require_once 'Zend/Search/Lucene/Index/Term.php'; - foreach ($tokens as $token) { - $term = new Zend_Search_Lucene_Index_Term($token->getTermText(), $this->_field); - $query->addTerm($term, true); // all subterms are required - } - - $query->setBoost($this->getBoost()); - - $this->_matches = $query->getQueryTerms(); - return $query; - } - - /** - * Query specific matches highlighting - * - * @param Zend_Search_Lucene_Search_Highlighter_Interface $highlighter Highlighter object (also contains doc for highlighting) - */ - protected function _highlightMatches(Zend_Search_Lucene_Search_Highlighter_Interface $highlighter) - { - /** Skip fields detection. We don't need it, since we expect all fields presented in the HTML body and don't differentiate them */ - - /** Skip exact term matching recognition, keyword fields highlighting is not supported */ - - // ------------------------------------- - // Recognize wildcard queries - /** @todo check for PCRE unicode support may be performed through Zend_Environment in some future */ - if (@preg_match('/\pL/u', 'a') == 1) { - $word = iconv($this->_encoding, 'UTF-8', $this->_word); - $wildcardsPattern = '/[*?]/u'; - $subPatternsEncoding = 'UTF-8'; - } else { - $word = $this->_word; - $wildcardsPattern = '/[*?]/'; - $subPatternsEncoding = $this->_encoding; - } - $subPatterns = preg_split($wildcardsPattern, $word, -1, PREG_SPLIT_OFFSET_CAPTURE); - if (count($subPatterns) > 1) { - // Wildcard query is recognized - - $pattern = ''; - - #require_once 'Zend/Search/Lucene/Analysis/Analyzer.php'; - foreach ($subPatterns as $id => $subPattern) { - // Append corresponding wildcard character to the pattern before each sub-pattern (except first) - if ($id != 0) { - $pattern .= $word[ $subPattern[1] - 1 ]; - } - - // Check if each subputtern is a single word in terms of current analyzer - $tokens = Zend_Search_Lucene_Analysis_Analyzer::getDefault()->tokenize($subPattern[0], $subPatternsEncoding); - if (count($tokens) > 1) { - // Do nothing (nothing is highlighted) - return; - } - foreach ($tokens as $token) { - $pattern .= $token->getTermText(); - } - } - - #require_once 'Zend/Search/Lucene/Index/Term.php'; - $term = new Zend_Search_Lucene_Index_Term($pattern, $this->_field); - #require_once 'Zend/Search/Lucene/Search/Query/Wildcard.php'; - $query = new Zend_Search_Lucene_Search_Query_Wildcard($term); - - $query->_highlightMatches($highlighter); - return; - } - - - // ------------------------------------- - // Recognize one-term multi-term and "insignificant" queries - #require_once 'Zend/Search/Lucene/Analysis/Analyzer.php'; - $tokens = Zend_Search_Lucene_Analysis_Analyzer::getDefault()->tokenize($this->_word, $this->_encoding); - - if (count($tokens) == 0) { - // Do nothing - return; - } - - if (count($tokens) == 1) { - $highlighter->highlight($tokens[0]->getTermText()); - return; - } - - //It's not insignificant or one term query - $words = array(); - foreach ($tokens as $token) { - $words[] = $token->getTermText(); - } - $highlighter->highlight($words); - } - - /** - * Print a query - * - * @return string - */ - public function __toString() - { - // It's used only for query visualisation, so we don't care about characters escaping - if ($this->_field !== null) { - $query = $this->_field . ':'; - } else { - $query = ''; - } - - $query .= $this->_word; - - if ($this->getBoost() != 1) { - $query .= '^' . round($this->getBoost(), 4); - } - - return $query; - } -} diff --git a/library/Zend/Search/Lucene/Search/Query/Range.php b/library/Zend/Search/Lucene/Search/Query/Range.php deleted file mode 100644 index 0a2fa1bc75..0000000000 --- a/library/Zend/Search/Lucene/Search/Query/Range.php +++ /dev/null @@ -1,377 +0,0 @@ -field != $upperTerm->field) { - #require_once 'Zend/Search/Lucene/Exception.php'; - throw new Zend_Search_Lucene_Exception('Both terms must be for the same field'); - } - - $this->_field = ($lowerTerm !== null)? $lowerTerm->field : $upperTerm->field; - $this->_lowerTerm = $lowerTerm; - $this->_upperTerm = $upperTerm; - $this->_inclusive = $inclusive; - } - - /** - * Get query field name - * - * @return string|null - */ - public function getField() - { - return $this->_field; - } - - /** - * Get lower term - * - * @return Zend_Search_Lucene_Index_Term|null - */ - public function getLowerTerm() - { - return $this->_lowerTerm; - } - - /** - * Get upper term - * - * @return Zend_Search_Lucene_Index_Term|null - */ - public function getUpperTerm() - { - return $this->_upperTerm; - } - - /** - * Get upper term - * - * @return boolean - */ - public function isInclusive() - { - return $this->_inclusive; - } - - /** - * Re-write query into primitive queries in the context of specified index - * - * @param Zend_Search_Lucene_Interface $index - * @return Zend_Search_Lucene_Search_Query - */ - public function rewrite(Zend_Search_Lucene_Interface $index) - { - $this->_matches = array(); - - if ($this->_field === null) { - // Search through all fields - $fields = $index->getFieldNames(true /* indexed fields list */); - } else { - $fields = array($this->_field); - } - - #require_once 'Zend/Search/Lucene.php'; - $maxTerms = Zend_Search_Lucene::getTermsPerQueryLimit(); - foreach ($fields as $field) { - $index->resetTermsStream(); - - #require_once 'Zend/Search/Lucene/Index/Term.php'; - if ($this->_lowerTerm !== null) { - $lowerTerm = new Zend_Search_Lucene_Index_Term($this->_lowerTerm->text, $field); - - $index->skipTo($lowerTerm); - - if (!$this->_inclusive && - $index->currentTerm() == $lowerTerm) { - // Skip lower term - $index->nextTerm(); - } - } else { - $index->skipTo(new Zend_Search_Lucene_Index_Term('', $field)); - } - - - if ($this->_upperTerm !== null) { - // Walk up to the upper term - $upperTerm = new Zend_Search_Lucene_Index_Term($this->_upperTerm->text, $field); - - while ($index->currentTerm() !== null && - $index->currentTerm()->field == $field && - strcmp($index->currentTerm()->text, $upperTerm->text) < 0) { - $this->_matches[] = $index->currentTerm(); - - if ($maxTerms != 0 && count($this->_matches) > $maxTerms) { - #require_once 'Zend/Search/Lucene/Exception.php'; - throw new Zend_Search_Lucene_Exception('Terms per query limit is reached.'); - } - - $index->nextTerm(); - } - - if ($this->_inclusive && $index->currentTerm() == $upperTerm) { - // Include upper term into result - $this->_matches[] = $upperTerm; - } - } else { - // Walk up to the end of field data - while ($index->currentTerm() !== null && $index->currentTerm()->field == $field) { - $this->_matches[] = $index->currentTerm(); - - if ($maxTerms != 0 && count($this->_matches) > $maxTerms) { - #require_once 'Zend/Search/Lucene/Exception.php'; - throw new Zend_Search_Lucene_Exception('Terms per query limit is reached.'); - } - - $index->nextTerm(); - } - } - - $index->closeTermsStream(); - } - - if (count($this->_matches) == 0) { - #require_once 'Zend/Search/Lucene/Search/Query/Empty.php'; - return new Zend_Search_Lucene_Search_Query_Empty(); - } else if (count($this->_matches) == 1) { - #require_once 'Zend/Search/Lucene/Search/Query/Term.php'; - return new Zend_Search_Lucene_Search_Query_Term(reset($this->_matches)); - } else { - #require_once 'Zend/Search/Lucene/Search/Query/MultiTerm.php'; - $rewrittenQuery = new Zend_Search_Lucene_Search_Query_MultiTerm(); - - foreach ($this->_matches as $matchedTerm) { - $rewrittenQuery->addTerm($matchedTerm); - } - - return $rewrittenQuery; - } - } - - /** - * Optimize query in the context of specified index - * - * @param Zend_Search_Lucene_Interface $index - * @return Zend_Search_Lucene_Search_Query - */ - public function optimize(Zend_Search_Lucene_Interface $index) - { - #require_once 'Zend/Search/Lucene/Exception.php'; - throw new Zend_Search_Lucene_Exception('Range query should not be directly used for search. Use $query->rewrite($index)'); - } - - /** - * Return query terms - * - * @return array - * @throws Zend_Search_Lucene_Exception - */ - public function getQueryTerms() - { - if ($this->_matches === null) { - #require_once 'Zend/Search/Lucene/Exception.php'; - throw new Zend_Search_Lucene_Exception('Search or rewrite operations have to be performed before.'); - } - - return $this->_matches; - } - - /** - * Constructs an appropriate Weight implementation for this query. - * - * @param Zend_Search_Lucene_Interface $reader - * @return Zend_Search_Lucene_Search_Weight - * @throws Zend_Search_Lucene_Exception - */ - public function createWeight(Zend_Search_Lucene_Interface $reader) - { - #require_once 'Zend/Search/Lucene/Exception.php'; - throw new Zend_Search_Lucene_Exception('Range query should not be directly used for search. Use $query->rewrite($index)'); - } - - - /** - * 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 - * @throws Zend_Search_Lucene_Exception - */ - public function execute(Zend_Search_Lucene_Interface $reader, $docsFilter = null) - { - #require_once 'Zend/Search/Lucene/Exception.php'; - throw new Zend_Search_Lucene_Exception('Range query should not be directly used for search. Use $query->rewrite($index)'); - } - - /** - * Get document ids likely matching the query - * - * It's an array with document ids as keys (performance considerations) - * - * @return array - * @throws Zend_Search_Lucene_Exception - */ - public function matchedDocs() - { - #require_once 'Zend/Search/Lucene/Exception.php'; - throw new Zend_Search_Lucene_Exception('Range query should not be directly used for search. Use $query->rewrite($index)'); - } - - /** - * Score specified document - * - * @param integer $docId - * @param Zend_Search_Lucene_Interface $reader - * @return float - * @throws Zend_Search_Lucene_Exception - */ - public function score($docId, Zend_Search_Lucene_Interface $reader) - { - #require_once 'Zend/Search/Lucene/Exception.php'; - throw new Zend_Search_Lucene_Exception('Range query should not be directly used for search. Use $query->rewrite($index)'); - } - - /** - * Query specific matches highlighting - * - * @param Zend_Search_Lucene_Search_Highlighter_Interface $highlighter Highlighter object (also contains doc for highlighting) - */ - protected function _highlightMatches(Zend_Search_Lucene_Search_Highlighter_Interface $highlighter) - { - $words = array(); - - $docBody = $highlighter->getDocument()->getFieldUtf8Value('body'); - #require_once 'Zend/Search/Lucene/Analysis/Analyzer.php'; - $tokens = Zend_Search_Lucene_Analysis_Analyzer::getDefault()->tokenize($docBody, 'UTF-8'); - - $lowerTermText = ($this->_lowerTerm !== null)? $this->_lowerTerm->text : null; - $upperTermText = ($this->_upperTerm !== null)? $this->_upperTerm->text : null; - - if ($this->_inclusive) { - foreach ($tokens as $token) { - $termText = $token->getTermText(); - if (($lowerTermText == null || $lowerTermText <= $termText) && - ($upperTermText == null || $termText <= $upperTermText)) { - $words[] = $termText; - } - } - } else { - foreach ($tokens as $token) { - $termText = $token->getTermText(); - if (($lowerTermText == null || $lowerTermText < $termText) && - ($upperTermText == null || $termText < $upperTermText)) { - $words[] = $termText; - } - } - } - - $highlighter->highlight($words); - } - - /** - * Print a query - * - * @return string - */ - public function __toString() - { - // It's used only for query visualisation, so we don't care about characters escaping - return (($this->_field === null)? '' : $this->_field . ':') - . (($this->_inclusive)? '[' : '{') - . (($this->_lowerTerm !== null)? $this->_lowerTerm->text : 'null') - . ' TO ' - . (($this->_upperTerm !== null)? $this->_upperTerm->text : 'null') - . (($this->_inclusive)? ']' : '}') - . (($this->getBoost() != 1)? '^' . round($this->getBoost(), 4) : ''); - } -} - diff --git a/library/Zend/Search/Lucene/Search/Query/Term.php b/library/Zend/Search/Lucene/Search/Query/Term.php deleted file mode 100644 index 37ee7d41ae..0000000000 --- a/library/Zend/Search/Lucene/Search/Query/Term.php +++ /dev/null @@ -1,228 +0,0 @@ - freq, ...) - * - * @var array - */ - private $_termFreqs; - - - /** - * Zend_Search_Lucene_Search_Query_Term constructor - * - * @param Zend_Search_Lucene_Index_Term $term - * @param boolean $sign - */ - public function __construct(Zend_Search_Lucene_Index_Term $term) - { - $this->_term = $term; - } - - /** - * Re-write query into primitive queries in the context of specified index - * - * @param Zend_Search_Lucene_Interface $index - * @return Zend_Search_Lucene_Search_Query - */ - public function rewrite(Zend_Search_Lucene_Interface $index) - { - if ($this->_term->field != null) { - return $this; - } else { - #require_once 'Zend/Search/Lucene/Search/Query/MultiTerm.php'; - $query = new Zend_Search_Lucene_Search_Query_MultiTerm(); - $query->setBoost($this->getBoost()); - - #require_once 'Zend/Search/Lucene/Index/Term.php'; - foreach ($index->getFieldNames(true) as $fieldName) { - $term = new Zend_Search_Lucene_Index_Term($this->_term->text, $fieldName); - - $query->addTerm($term); - } - - return $query->rewrite($index); - } - } - - /** - * Optimize query in the context of specified index - * - * @param Zend_Search_Lucene_Interface $index - * @return Zend_Search_Lucene_Search_Query - */ - public function optimize(Zend_Search_Lucene_Interface $index) - { - // Check, that index contains specified term - if (!$index->hasTerm($this->_term)) { - #require_once 'Zend/Search/Lucene/Search/Query/Empty.php'; - return new Zend_Search_Lucene_Search_Query_Empty(); - } - - return $this; - } - - - /** - * Constructs an appropriate Weight implementation for this query. - * - * @param Zend_Search_Lucene_Interface $reader - * @return Zend_Search_Lucene_Search_Weight - */ - public function createWeight(Zend_Search_Lucene_Interface $reader) - { - #require_once 'Zend/Search/Lucene/Search/Weight/Term.php'; - $this->_weight = new Zend_Search_Lucene_Search_Weight_Term($this->_term, $this, $reader); - return $this->_weight; - } - - /** - * 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 - */ - public function execute(Zend_Search_Lucene_Interface $reader, $docsFilter = null) - { - $this->_docVector = array_flip($reader->termDocs($this->_term, $docsFilter)); - $this->_termFreqs = $reader->termFreqs($this->_term, $docsFilter); - - // Initialize weight if it's not done yet - $this->_initWeight($reader); - } - - /** - * Get document ids likely matching the query - * - * It's an array with document ids as keys (performance considerations) - * - * @return array - */ - public function matchedDocs() - { - return $this->_docVector; - } - - /** - * Score specified document - * - * @param integer $docId - * @param Zend_Search_Lucene_Interface $reader - * @return float - */ - public function score($docId, Zend_Search_Lucene_Interface $reader) - { - if (isset($this->_docVector[$docId])) { - return $reader->getSimilarity()->tf($this->_termFreqs[$docId]) * - $this->_weight->getValue() * - $reader->norm($docId, $this->_term->field) * - $this->getBoost(); - } else { - return 0; - } - } - - /** - * Return query terms - * - * @return array - */ - public function getQueryTerms() - { - return array($this->_term); - } - - /** - * Return query term - * - * @return Zend_Search_Lucene_Index_Term - */ - public function getTerm() - { - return $this->_term; - } - - /** - * Query specific matches highlighting - * - * @param Zend_Search_Lucene_Search_Highlighter_Interface $highlighter Highlighter object (also contains doc for highlighting) - */ - protected function _highlightMatches(Zend_Search_Lucene_Search_Highlighter_Interface $highlighter) - { - $highlighter->highlight($this->_term->text); - } - - /** - * Print a query - * - * @return string - */ - public function __toString() - { - // It's used only for query visualisation, so we don't care about characters escaping - if ($this->_term->field !== null) { - $query = $this->_term->field . ':'; - } else { - $query = ''; - } - - $query .= $this->_term->text; - - if ($this->getBoost() != 1) { - $query = $query . '^' . round($this->getBoost(), 4); - } - - return $query; - } -} - diff --git a/library/Zend/Search/Lucene/Search/Query/Wildcard.php b/library/Zend/Search/Lucene/Search/Query/Wildcard.php deleted file mode 100644 index eebe2a6fbd..0000000000 --- a/library/Zend/Search/Lucene/Search/Query/Wildcard.php +++ /dev/null @@ -1,362 +0,0 @@ -_pattern = $pattern; - } - - /** - * Get minimum prefix length - * - * @return integer - */ - public static function getMinPrefixLength() - { - return self::$_minPrefixLength; - } - - /** - * Set minimum prefix length - * - * @param integer $minPrefixLength - */ - public static function setMinPrefixLength($minPrefixLength) - { - self::$_minPrefixLength = $minPrefixLength; - } - - /** - * Get terms prefix - * - * @param string $word - * @return string - */ - private static function _getPrefix($word) - { - $questionMarkPosition = strpos($word, '?'); - $astrericPosition = strpos($word, '*'); - - if ($questionMarkPosition !== false) { - if ($astrericPosition !== false) { - return substr($word, 0, min($questionMarkPosition, $astrericPosition)); - } - - return substr($word, 0, $questionMarkPosition); - } else if ($astrericPosition !== false) { - return substr($word, 0, $astrericPosition); - } - - return $word; - } - - /** - * Re-write query into primitive queries in the context of specified index - * - * @param Zend_Search_Lucene_Interface $index - * @return Zend_Search_Lucene_Search_Query - * @throws Zend_Search_Lucene_Exception - */ - public function rewrite(Zend_Search_Lucene_Interface $index) - { - $this->_matches = array(); - - if ($this->_pattern->field === null) { - // Search through all fields - $fields = $index->getFieldNames(true /* indexed fields list */); - } else { - $fields = array($this->_pattern->field); - } - - $prefix = self::_getPrefix($this->_pattern->text); - $prefixLength = strlen($prefix); - $matchExpression = '/^' . str_replace(array('\\?', '\\*'), array('.', '.*') , preg_quote($this->_pattern->text, '/')) . '$/'; - - if ($prefixLength < self::$_minPrefixLength) { - #require_once 'Zend/Search/Lucene/Exception.php'; - throw new Zend_Search_Lucene_Exception('At least ' . self::$_minPrefixLength . ' non-wildcard characters are required at the beginning of pattern.'); - } - - /** @todo check for PCRE unicode support may be performed through Zend_Environment in some future */ - if (@preg_match('/\pL/u', 'a') == 1) { - // PCRE unicode support is turned on - // add Unicode modifier to the match expression - $matchExpression .= 'u'; - } - - $maxTerms = Zend_Search_Lucene::getTermsPerQueryLimit(); - foreach ($fields as $field) { - $index->resetTermsStream(); - - #require_once 'Zend/Search/Lucene/Index/Term.php'; - if ($prefix != '') { - $index->skipTo(new Zend_Search_Lucene_Index_Term($prefix, $field)); - - while ($index->currentTerm() !== null && - $index->currentTerm()->field == $field && - substr($index->currentTerm()->text, 0, $prefixLength) == $prefix) { - if (preg_match($matchExpression, $index->currentTerm()->text) === 1) { - $this->_matches[] = $index->currentTerm(); - - if ($maxTerms != 0 && count($this->_matches) > $maxTerms) { - #require_once 'Zend/Search/Lucene/Exception.php'; - throw new Zend_Search_Lucene_Exception('Terms per query limit is reached.'); - } - } - - $index->nextTerm(); - } - } else { - $index->skipTo(new Zend_Search_Lucene_Index_Term('', $field)); - - while ($index->currentTerm() !== null && $index->currentTerm()->field == $field) { - if (preg_match($matchExpression, $index->currentTerm()->text) === 1) { - $this->_matches[] = $index->currentTerm(); - - if ($maxTerms != 0 && count($this->_matches) > $maxTerms) { - #require_once 'Zend/Search/Lucene/Exception.php'; - throw new Zend_Search_Lucene_Exception('Terms per query limit is reached.'); - } - } - - $index->nextTerm(); - } - } - - $index->closeTermsStream(); - } - - if (count($this->_matches) == 0) { - #require_once 'Zend/Search/Lucene/Search/Query/Empty.php'; - return new Zend_Search_Lucene_Search_Query_Empty(); - } else if (count($this->_matches) == 1) { - #require_once 'Zend/Search/Lucene/Search/Query/Term.php'; - return new Zend_Search_Lucene_Search_Query_Term(reset($this->_matches)); - } else { - #require_once 'Zend/Search/Lucene/Search/Query/MultiTerm.php'; - $rewrittenQuery = new Zend_Search_Lucene_Search_Query_MultiTerm(); - - foreach ($this->_matches as $matchedTerm) { - $rewrittenQuery->addTerm($matchedTerm); - } - - return $rewrittenQuery; - } - } - - /** - * Optimize query in the context of specified index - * - * @param Zend_Search_Lucene_Interface $index - * @return Zend_Search_Lucene_Search_Query - */ - public function optimize(Zend_Search_Lucene_Interface $index) - { - #require_once 'Zend/Search/Lucene/Exception.php'; - throw new Zend_Search_Lucene_Exception('Wildcard query should not be directly used for search. Use $query->rewrite($index)'); - } - - - /** - * Returns query pattern - * - * @return Zend_Search_Lucene_Index_Term - */ - public function getPattern() - { - return $this->_pattern; - } - - - /** - * Return query terms - * - * @return array - * @throws Zend_Search_Lucene_Exception - */ - public function getQueryTerms() - { - if ($this->_matches === null) { - #require_once 'Zend/Search/Lucene/Exception.php'; - throw new Zend_Search_Lucene_Exception('Search has to be performed first to get matched terms'); - } - - return $this->_matches; - } - - /** - * Constructs an appropriate Weight implementation for this query. - * - * @param Zend_Search_Lucene_Interface $reader - * @return Zend_Search_Lucene_Search_Weight - * @throws Zend_Search_Lucene_Exception - */ - public function createWeight(Zend_Search_Lucene_Interface $reader) - { - #require_once 'Zend/Search/Lucene/Exception.php'; - throw new Zend_Search_Lucene_Exception('Wildcard query should not be directly used for search. Use $query->rewrite($index)'); - } - - - /** - * 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 - * @throws Zend_Search_Lucene_Exception - */ - public function execute(Zend_Search_Lucene_Interface $reader, $docsFilter = null) - { - #require_once 'Zend/Search/Lucene/Exception.php'; - throw new Zend_Search_Lucene_Exception('Wildcard query should not be directly used for search. Use $query->rewrite($index)'); - } - - /** - * Get document ids likely matching the query - * - * It's an array with document ids as keys (performance considerations) - * - * @return array - * @throws Zend_Search_Lucene_Exception - */ - public function matchedDocs() - { - #require_once 'Zend/Search/Lucene/Exception.php'; - throw new Zend_Search_Lucene_Exception('Wildcard query should not be directly used for search. Use $query->rewrite($index)'); - } - - /** - * Score specified document - * - * @param integer $docId - * @param Zend_Search_Lucene_Interface $reader - * @return float - * @throws Zend_Search_Lucene_Exception - */ - public function score($docId, Zend_Search_Lucene_Interface $reader) - { - #require_once 'Zend/Search/Lucene/Exception.php'; - throw new Zend_Search_Lucene_Exception('Wildcard query should not be directly used for search. Use $query->rewrite($index)'); - } - - /** - * Query specific matches highlighting - * - * @param Zend_Search_Lucene_Search_Highlighter_Interface $highlighter Highlighter object (also contains doc for highlighting) - */ - protected function _highlightMatches(Zend_Search_Lucene_Search_Highlighter_Interface $highlighter) - { - $words = array(); - - $matchExpression = '/^' . str_replace(array('\\?', '\\*'), array('.', '.*') , preg_quote($this->_pattern->text, '/')) . '$/'; - if (@preg_match('/\pL/u', 'a') == 1) { - // PCRE unicode support is turned on - // add Unicode modifier to the match expression - $matchExpression .= 'u'; - } - - $docBody = $highlighter->getDocument()->getFieldUtf8Value('body'); - #require_once 'Zend/Search/Lucene/Analysis/Analyzer.php'; - $tokens = Zend_Search_Lucene_Analysis_Analyzer::getDefault()->tokenize($docBody, 'UTF-8'); - foreach ($tokens as $token) { - if (preg_match($matchExpression, $token->getTermText()) === 1) { - $words[] = $token->getTermText(); - } - } - - $highlighter->highlight($words); - } - - /** - * Print a query - * - * @return string - */ - public function __toString() - { - // It's used only for query visualisation, so we don't care about characters escaping - if ($this->_pattern->field !== null) { - $query = $this->_pattern->field . ':'; - } else { - $query = ''; - } - - $query .= $this->_pattern->text; - - if ($this->getBoost() != 1) { - $query = $query . '^' . round($this->getBoost(), 4); - } - - return $query; - } -} - diff --git a/library/Zend/Search/Lucene/Search/QueryEntry.php b/library/Zend/Search/Lucene/Search/QueryEntry.php deleted file mode 100644 index 5214a40d08..0000000000 --- a/library/Zend/Search/Lucene/Search/QueryEntry.php +++ /dev/null @@ -1,67 +0,0 @@ -_boost *= $boostFactor; - } - - -} diff --git a/library/Zend/Search/Lucene/Search/QueryEntry/Phrase.php b/library/Zend/Search/Lucene/Search/QueryEntry/Phrase.php deleted file mode 100644 index 8d2640490e..0000000000 --- a/library/Zend/Search/Lucene/Search/QueryEntry/Phrase.php +++ /dev/null @@ -1,116 +0,0 @@ -_phrase = $phrase; - $this->_field = $field; - } - - /** - * Process modifier ('~') - * - * @param mixed $parameter - */ - public function processFuzzyProximityModifier($parameter = null) - { - $this->_proximityQuery = true; - - if ($parameter !== null) { - $this->_wordsDistance = $parameter; - } - } - - /** - * Transform entry to a subquery - * - * @param string $encoding - * @return Zend_Search_Lucene_Search_Query - * @throws Zend_Search_Lucene_Search_QueryParserException - */ - public function getQuery($encoding) - { - /** Zend_Search_Lucene_Search_Query_Preprocessing_Phrase */ - #require_once 'Zend/Search/Lucene/Search/Query/Preprocessing/Phrase.php'; - $query = new Zend_Search_Lucene_Search_Query_Preprocessing_Phrase($this->_phrase, - $encoding, - ($this->_field !== null)? - iconv($encoding, 'UTF-8', $this->_field) : - null); - - if ($this->_proximityQuery) { - $query->setSlop($this->_wordsDistance); - } - - $query->setBoost($this->_boost); - - return $query; - } -} diff --git a/library/Zend/Search/Lucene/Search/QueryEntry/Subquery.php b/library/Zend/Search/Lucene/Search/QueryEntry/Subquery.php deleted file mode 100644 index f311d2d8a7..0000000000 --- a/library/Zend/Search/Lucene/Search/QueryEntry/Subquery.php +++ /dev/null @@ -1,77 +0,0 @@ -_query = $query; - } - - /** - * Process modifier ('~') - * - * @param mixed $parameter - * @throws Zend_Search_Lucene_Search_QueryParserException - */ - public function processFuzzyProximityModifier($parameter = null) - { - #require_once 'Zend/Search/Lucene/Search/QueryParserException.php'; - throw new Zend_Search_Lucene_Search_QueryParserException('\'~\' sign must follow term or phrase'); - } - - - /** - * Transform entry to a subquery - * - * @param string $encoding - * @return Zend_Search_Lucene_Search_Query - */ - public function getQuery($encoding) - { - $this->_query->setBoost($this->_boost); - - return $this->_query; - } -} diff --git a/library/Zend/Search/Lucene/Search/QueryEntry/Term.php b/library/Zend/Search/Lucene/Search/QueryEntry/Term.php deleted file mode 100644 index c0fc971c69..0000000000 --- a/library/Zend/Search/Lucene/Search/QueryEntry/Term.php +++ /dev/null @@ -1,130 +0,0 @@ -_term = $term; - $this->_field = $field; - } - - /** - * Process modifier ('~') - * - * @param mixed $parameter - */ - public function processFuzzyProximityModifier($parameter = null) - { - $this->_fuzzyQuery = true; - - if ($parameter !== null) { - $this->_similarity = $parameter; - } else { - /** Zend_Search_Lucene_Search_Query_Fuzzy */ - #require_once 'Zend/Search/Lucene/Search/Query/Fuzzy.php'; - $this->_similarity = Zend_Search_Lucene_Search_Query_Fuzzy::DEFAULT_MIN_SIMILARITY; - } - } - - /** - * Transform entry to a subquery - * - * @param string $encoding - * @return Zend_Search_Lucene_Search_Query - * @throws Zend_Search_Lucene_Search_QueryParserException - */ - public function getQuery($encoding) - { - if ($this->_fuzzyQuery) { - /** Zend_Search_Lucene_Search_Query_Preprocessing_Fuzzy */ - #require_once 'Zend/Search/Lucene/Search/Query/Preprocessing/Fuzzy.php'; - $query = new Zend_Search_Lucene_Search_Query_Preprocessing_Fuzzy($this->_term, - $encoding, - ($this->_field !== null)? - iconv($encoding, 'UTF-8', $this->_field) : - null, - $this->_similarity - ); - $query->setBoost($this->_boost); - return $query; - } - - - /** Zend_Search_Lucene_Search_Query_Preprocessing_Term */ - #require_once 'Zend/Search/Lucene/Search/Query/Preprocessing/Term.php'; - $query = new Zend_Search_Lucene_Search_Query_Preprocessing_Term($this->_term, - $encoding, - ($this->_field !== null)? - iconv($encoding, 'UTF-8', $this->_field) : - null - ); - $query->setBoost($this->_boost); - return $query; - } -} diff --git a/library/Zend/Search/Lucene/Search/QueryHit.php b/library/Zend/Search/Lucene/Search/QueryHit.php deleted file mode 100644 index 2a903d53cb..0000000000 --- a/library/Zend/Search/Lucene/Search/QueryHit.php +++ /dev/null @@ -1,110 +0,0 @@ -_index = new Zend_Search_Lucene_Proxy($index); - } - - - /** - * Convenience function for getting fields from the document - * associated with this hit. - * - * @param string $offset - * @return string - */ - public function __get($offset) - { - return $this->getDocument()->getFieldValue($offset); - } - - - /** - * Return the document object for this hit - * - * @return Zend_Search_Lucene_Document - */ - public function getDocument() - { - if (!$this->_document instanceof Zend_Search_Lucene_Document) { - $this->_document = $this->_index->getDocument($this->id); - } - - return $this->_document; - } - - - /** - * Return the index object for this hit - * - * @return Zend_Search_Lucene_Interface - */ - public function getIndex() - { - return $this->_index; - } -} - diff --git a/library/Zend/Search/Lucene/Search/QueryLexer.php b/library/Zend/Search/Lucene/Search/QueryLexer.php deleted file mode 100644 index 8fb9843a59..0000000000 --- a/library/Zend/Search/Lucene/Search/QueryLexer.php +++ /dev/null @@ -1,510 +0,0 @@ -addRules(array( array(self::ST_WHITE_SPACE, self::IN_WHITE_SPACE, self::ST_WHITE_SPACE), - array(self::ST_WHITE_SPACE, self::IN_SYNT_CHAR, self::ST_SYNT_LEXEME), - array(self::ST_WHITE_SPACE, self::IN_MUTABLE_CHAR, self::ST_SYNT_LEXEME), - array(self::ST_WHITE_SPACE, self::IN_LEXEME_MODIFIER, self::ST_LEXEME_MODIFIER), - array(self::ST_WHITE_SPACE, self::IN_ESCAPE_CHAR, self::ST_ESCAPED_CHAR), - array(self::ST_WHITE_SPACE, self::IN_QUOTE, self::ST_QUOTED_LEXEME), - array(self::ST_WHITE_SPACE, self::IN_DECIMAL_POINT, self::ST_LEXEME), - array(self::ST_WHITE_SPACE, self::IN_ASCII_DIGIT, self::ST_LEXEME), - array(self::ST_WHITE_SPACE, self::IN_CHAR, self::ST_LEXEME) - )); - $this->addRules(array( array(self::ST_SYNT_LEXEME, self::IN_WHITE_SPACE, self::ST_WHITE_SPACE), - array(self::ST_SYNT_LEXEME, self::IN_SYNT_CHAR, self::ST_SYNT_LEXEME), - array(self::ST_SYNT_LEXEME, self::IN_MUTABLE_CHAR, self::ST_SYNT_LEXEME), - array(self::ST_SYNT_LEXEME, self::IN_LEXEME_MODIFIER, self::ST_LEXEME_MODIFIER), - array(self::ST_SYNT_LEXEME, self::IN_ESCAPE_CHAR, self::ST_ESCAPED_CHAR), - array(self::ST_SYNT_LEXEME, self::IN_QUOTE, self::ST_QUOTED_LEXEME), - array(self::ST_SYNT_LEXEME, self::IN_DECIMAL_POINT, self::ST_LEXEME), - array(self::ST_SYNT_LEXEME, self::IN_ASCII_DIGIT, self::ST_LEXEME), - array(self::ST_SYNT_LEXEME, self::IN_CHAR, self::ST_LEXEME) - )); - $this->addRules(array( array(self::ST_LEXEME, self::IN_WHITE_SPACE, self::ST_WHITE_SPACE), - array(self::ST_LEXEME, self::IN_SYNT_CHAR, self::ST_SYNT_LEXEME), - array(self::ST_LEXEME, self::IN_MUTABLE_CHAR, self::ST_LEXEME), - array(self::ST_LEXEME, self::IN_LEXEME_MODIFIER, self::ST_LEXEME_MODIFIER), - array(self::ST_LEXEME, self::IN_ESCAPE_CHAR, self::ST_ESCAPED_CHAR), - - // IN_QUOTE not allowed - array(self::ST_LEXEME, self::IN_QUOTE, self::ST_ERROR, $quoteWithinLexemeErrorAction), - - array(self::ST_LEXEME, self::IN_DECIMAL_POINT, self::ST_LEXEME), - array(self::ST_LEXEME, self::IN_ASCII_DIGIT, self::ST_LEXEME), - array(self::ST_LEXEME, self::IN_CHAR, self::ST_LEXEME) - )); - $this->addRules(array( array(self::ST_QUOTED_LEXEME, self::IN_WHITE_SPACE, self::ST_QUOTED_LEXEME), - array(self::ST_QUOTED_LEXEME, self::IN_SYNT_CHAR, self::ST_QUOTED_LEXEME), - array(self::ST_QUOTED_LEXEME, self::IN_MUTABLE_CHAR, self::ST_QUOTED_LEXEME), - array(self::ST_QUOTED_LEXEME, self::IN_LEXEME_MODIFIER, self::ST_QUOTED_LEXEME), - array(self::ST_QUOTED_LEXEME, self::IN_ESCAPE_CHAR, self::ST_ESCAPED_QCHAR), - array(self::ST_QUOTED_LEXEME, self::IN_QUOTE, self::ST_WHITE_SPACE), - array(self::ST_QUOTED_LEXEME, self::IN_DECIMAL_POINT, self::ST_QUOTED_LEXEME), - array(self::ST_QUOTED_LEXEME, self::IN_ASCII_DIGIT, self::ST_QUOTED_LEXEME), - array(self::ST_QUOTED_LEXEME, self::IN_CHAR, self::ST_QUOTED_LEXEME) - )); - $this->addRules(array( array(self::ST_ESCAPED_CHAR, self::IN_WHITE_SPACE, self::ST_LEXEME), - array(self::ST_ESCAPED_CHAR, self::IN_SYNT_CHAR, self::ST_LEXEME), - array(self::ST_ESCAPED_CHAR, self::IN_MUTABLE_CHAR, self::ST_LEXEME), - array(self::ST_ESCAPED_CHAR, self::IN_LEXEME_MODIFIER, self::ST_LEXEME), - array(self::ST_ESCAPED_CHAR, self::IN_ESCAPE_CHAR, self::ST_LEXEME), - array(self::ST_ESCAPED_CHAR, self::IN_QUOTE, self::ST_LEXEME), - array(self::ST_ESCAPED_CHAR, self::IN_DECIMAL_POINT, self::ST_LEXEME), - array(self::ST_ESCAPED_CHAR, self::IN_ASCII_DIGIT, self::ST_LEXEME), - array(self::ST_ESCAPED_CHAR, self::IN_CHAR, self::ST_LEXEME) - )); - $this->addRules(array( array(self::ST_ESCAPED_QCHAR, self::IN_WHITE_SPACE, self::ST_QUOTED_LEXEME), - array(self::ST_ESCAPED_QCHAR, self::IN_SYNT_CHAR, self::ST_QUOTED_LEXEME), - array(self::ST_ESCAPED_QCHAR, self::IN_MUTABLE_CHAR, self::ST_QUOTED_LEXEME), - array(self::ST_ESCAPED_QCHAR, self::IN_LEXEME_MODIFIER, self::ST_QUOTED_LEXEME), - array(self::ST_ESCAPED_QCHAR, self::IN_ESCAPE_CHAR, self::ST_QUOTED_LEXEME), - array(self::ST_ESCAPED_QCHAR, self::IN_QUOTE, self::ST_QUOTED_LEXEME), - array(self::ST_ESCAPED_QCHAR, self::IN_DECIMAL_POINT, self::ST_QUOTED_LEXEME), - array(self::ST_ESCAPED_QCHAR, self::IN_ASCII_DIGIT, self::ST_QUOTED_LEXEME), - array(self::ST_ESCAPED_QCHAR, self::IN_CHAR, self::ST_QUOTED_LEXEME) - )); - $this->addRules(array( array(self::ST_LEXEME_MODIFIER, self::IN_WHITE_SPACE, self::ST_WHITE_SPACE), - array(self::ST_LEXEME_MODIFIER, self::IN_SYNT_CHAR, self::ST_SYNT_LEXEME), - array(self::ST_LEXEME_MODIFIER, self::IN_MUTABLE_CHAR, self::ST_SYNT_LEXEME), - array(self::ST_LEXEME_MODIFIER, self::IN_LEXEME_MODIFIER, self::ST_LEXEME_MODIFIER), - - // IN_ESCAPE_CHAR not allowed - array(self::ST_LEXEME_MODIFIER, self::IN_ESCAPE_CHAR, self::ST_ERROR, $lexemeModifierErrorAction), - - // IN_QUOTE not allowed - array(self::ST_LEXEME_MODIFIER, self::IN_QUOTE, self::ST_ERROR, $lexemeModifierErrorAction), - - - array(self::ST_LEXEME_MODIFIER, self::IN_DECIMAL_POINT, self::ST_MANTISSA), - array(self::ST_LEXEME_MODIFIER, self::IN_ASCII_DIGIT, self::ST_NUMBER), - - // IN_CHAR not allowed - array(self::ST_LEXEME_MODIFIER, self::IN_CHAR, self::ST_ERROR, $lexemeModifierErrorAction), - )); - $this->addRules(array( array(self::ST_NUMBER, self::IN_WHITE_SPACE, self::ST_WHITE_SPACE), - array(self::ST_NUMBER, self::IN_SYNT_CHAR, self::ST_SYNT_LEXEME), - array(self::ST_NUMBER, self::IN_MUTABLE_CHAR, self::ST_SYNT_LEXEME), - array(self::ST_NUMBER, self::IN_LEXEME_MODIFIER, self::ST_LEXEME_MODIFIER), - - // IN_ESCAPE_CHAR not allowed - array(self::ST_NUMBER, self::IN_ESCAPE_CHAR, self::ST_ERROR, $wrongNumberErrorAction), - - // IN_QUOTE not allowed - array(self::ST_NUMBER, self::IN_QUOTE, self::ST_ERROR, $wrongNumberErrorAction), - - array(self::ST_NUMBER, self::IN_DECIMAL_POINT, self::ST_MANTISSA), - array(self::ST_NUMBER, self::IN_ASCII_DIGIT, self::ST_NUMBER), - - // IN_CHAR not allowed - array(self::ST_NUMBER, self::IN_CHAR, self::ST_ERROR, $wrongNumberErrorAction), - )); - $this->addRules(array( array(self::ST_MANTISSA, self::IN_WHITE_SPACE, self::ST_WHITE_SPACE), - array(self::ST_MANTISSA, self::IN_SYNT_CHAR, self::ST_SYNT_LEXEME), - array(self::ST_MANTISSA, self::IN_MUTABLE_CHAR, self::ST_SYNT_LEXEME), - array(self::ST_MANTISSA, self::IN_LEXEME_MODIFIER, self::ST_LEXEME_MODIFIER), - - // IN_ESCAPE_CHAR not allowed - array(self::ST_MANTISSA, self::IN_ESCAPE_CHAR, self::ST_ERROR, $wrongNumberErrorAction), - - // IN_QUOTE not allowed - array(self::ST_MANTISSA, self::IN_QUOTE, self::ST_ERROR, $wrongNumberErrorAction), - - // IN_DECIMAL_POINT not allowed - array(self::ST_MANTISSA, self::IN_DECIMAL_POINT, self::ST_ERROR, $wrongNumberErrorAction), - - array(self::ST_MANTISSA, self::IN_ASCII_DIGIT, self::ST_MANTISSA), - - // IN_CHAR not allowed - array(self::ST_MANTISSA, self::IN_CHAR, self::ST_ERROR, $wrongNumberErrorAction), - )); - - - /** Actions */ - $syntaxLexemeAction = new Zend_Search_Lucene_FSMAction($this, 'addQuerySyntaxLexeme'); - $lexemeModifierAction = new Zend_Search_Lucene_FSMAction($this, 'addLexemeModifier'); - $addLexemeAction = new Zend_Search_Lucene_FSMAction($this, 'addLexeme'); - $addQuotedLexemeAction = new Zend_Search_Lucene_FSMAction($this, 'addQuotedLexeme'); - $addNumberLexemeAction = new Zend_Search_Lucene_FSMAction($this, 'addNumberLexeme'); - $addLexemeCharAction = new Zend_Search_Lucene_FSMAction($this, 'addLexemeChar'); - - - /** Syntax lexeme */ - $this->addEntryAction(self::ST_SYNT_LEXEME, $syntaxLexemeAction); - // Two lexemes in succession - $this->addTransitionAction(self::ST_SYNT_LEXEME, self::ST_SYNT_LEXEME, $syntaxLexemeAction); - - - /** Lexeme */ - $this->addEntryAction(self::ST_LEXEME, $addLexemeCharAction); - $this->addTransitionAction(self::ST_LEXEME, self::ST_LEXEME, $addLexemeCharAction); - // ST_ESCAPED_CHAR => ST_LEXEME transition is covered by ST_LEXEME entry action - - $this->addTransitionAction(self::ST_LEXEME, self::ST_WHITE_SPACE, $addLexemeAction); - $this->addTransitionAction(self::ST_LEXEME, self::ST_SYNT_LEXEME, $addLexemeAction); - $this->addTransitionAction(self::ST_LEXEME, self::ST_QUOTED_LEXEME, $addLexemeAction); - $this->addTransitionAction(self::ST_LEXEME, self::ST_LEXEME_MODIFIER, $addLexemeAction); - $this->addTransitionAction(self::ST_LEXEME, self::ST_NUMBER, $addLexemeAction); - $this->addTransitionAction(self::ST_LEXEME, self::ST_MANTISSA, $addLexemeAction); - - - /** Quoted lexeme */ - // We don't need entry action (skeep quote) - $this->addTransitionAction(self::ST_QUOTED_LEXEME, self::ST_QUOTED_LEXEME, $addLexemeCharAction); - $this->addTransitionAction(self::ST_ESCAPED_QCHAR, self::ST_QUOTED_LEXEME, $addLexemeCharAction); - // Closing quote changes state to the ST_WHITE_SPACE other states are not used - $this->addTransitionAction(self::ST_QUOTED_LEXEME, self::ST_WHITE_SPACE, $addQuotedLexemeAction); - - - /** Lexeme modifier */ - $this->addEntryAction(self::ST_LEXEME_MODIFIER, $lexemeModifierAction); - - - /** Number */ - $this->addEntryAction(self::ST_NUMBER, $addLexemeCharAction); - $this->addEntryAction(self::ST_MANTISSA, $addLexemeCharAction); - $this->addTransitionAction(self::ST_NUMBER, self::ST_NUMBER, $addLexemeCharAction); - // ST_NUMBER => ST_MANTISSA transition is covered by ST_MANTISSA entry action - $this->addTransitionAction(self::ST_MANTISSA, self::ST_MANTISSA, $addLexemeCharAction); - - $this->addTransitionAction(self::ST_NUMBER, self::ST_WHITE_SPACE, $addNumberLexemeAction); - $this->addTransitionAction(self::ST_NUMBER, self::ST_SYNT_LEXEME, $addNumberLexemeAction); - $this->addTransitionAction(self::ST_NUMBER, self::ST_LEXEME_MODIFIER, $addNumberLexemeAction); - $this->addTransitionAction(self::ST_MANTISSA, self::ST_WHITE_SPACE, $addNumberLexemeAction); - $this->addTransitionAction(self::ST_MANTISSA, self::ST_SYNT_LEXEME, $addNumberLexemeAction); - $this->addTransitionAction(self::ST_MANTISSA, self::ST_LEXEME_MODIFIER, $addNumberLexemeAction); - } - - - - - /** - * Translate input char to an input symbol of state machine - * - * @param string $char - * @return integer - */ - private function _translateInput($char) - { - if (strpos(self::QUERY_WHITE_SPACE_CHARS, $char) !== false) { return self::IN_WHITE_SPACE; - } else if (strpos(self::QUERY_SYNT_CHARS, $char) !== false) { return self::IN_SYNT_CHAR; - } else if (strpos(self::QUERY_MUTABLE_CHARS, $char) !== false) { return self::IN_MUTABLE_CHAR; - } else if (strpos(self::QUERY_LEXEMEMODIFIER_CHARS, $char) !== false) { return self::IN_LEXEME_MODIFIER; - } else if (strpos(self::QUERY_ASCIIDIGITS_CHARS, $char) !== false) { return self::IN_ASCII_DIGIT; - } else if ($char === '"' ) { return self::IN_QUOTE; - } else if ($char === '.' ) { return self::IN_DECIMAL_POINT; - } else if ($char === '\\') { return self::IN_ESCAPE_CHAR; - } else { return self::IN_CHAR; - } - } - - - /** - * This method is used to tokenize query string into lexemes - * - * @param string $inputString - * @param string $encoding - * @return array - * @throws Zend_Search_Lucene_Search_QueryParserException - */ - public function tokenize($inputString, $encoding) - { - $this->reset(); - - $this->_lexemes = array(); - $this->_queryString = array(); - - if (PHP_OS == 'AIX' && $encoding == '') { - $encoding = 'ISO8859-1'; - } - $strLength = iconv_strlen($inputString, $encoding); - - // Workaround for iconv_substr bug - $inputString .= ' '; - - for ($count = 0; $count < $strLength; $count++) { - $this->_queryString[$count] = iconv_substr($inputString, $count, 1, $encoding); - } - - for ($this->_queryStringPosition = 0; - $this->_queryStringPosition < count($this->_queryString); - $this->_queryStringPosition++) { - $this->process($this->_translateInput($this->_queryString[$this->_queryStringPosition])); - } - - $this->process(self::IN_WHITE_SPACE); - - if ($this->getState() != self::ST_WHITE_SPACE) { - #require_once 'Zend/Search/Lucene/Search/QueryParserException.php'; - throw new Zend_Search_Lucene_Search_QueryParserException('Unexpected end of query'); - } - - $this->_queryString = null; - - return $this->_lexemes; - } - - - - /********************************************************************* - * Actions implementation - * - * Actions affect on recognized lexemes list - *********************************************************************/ - - /** - * Add query syntax lexeme - * - * @throws Zend_Search_Lucene_Search_QueryParserException - */ - public function addQuerySyntaxLexeme() - { - $lexeme = $this->_queryString[$this->_queryStringPosition]; - - // Process two char lexemes - if (strpos(self::QUERY_DOUBLECHARLEXEME_CHARS, $lexeme) !== false) { - // increase current position in a query string - $this->_queryStringPosition++; - - // check, - if ($this->_queryStringPosition == count($this->_queryString) || - $this->_queryString[$this->_queryStringPosition] != $lexeme) { - #require_once 'Zend/Search/Lucene/Search/QueryParserException.php'; - throw new Zend_Search_Lucene_Search_QueryParserException('Two chars lexeme expected. ' . $this->_positionMsg()); - } - - // duplicate character - $lexeme .= $lexeme; - } - - $token = new Zend_Search_Lucene_Search_QueryToken( - Zend_Search_Lucene_Search_QueryToken::TC_SYNTAX_ELEMENT, - $lexeme, - $this->_queryStringPosition); - - // Skip this lexeme if it's a field indicator ':' and treat previous as 'field' instead of 'word' - if ($token->type == Zend_Search_Lucene_Search_QueryToken::TT_FIELD_INDICATOR) { - $token = array_pop($this->_lexemes); - if ($token === null || $token->type != Zend_Search_Lucene_Search_QueryToken::TT_WORD) { - #require_once 'Zend/Search/Lucene/Search/QueryParserException.php'; - throw new Zend_Search_Lucene_Search_QueryParserException('Field mark \':\' must follow field name. ' . $this->_positionMsg()); - } - - $token->type = Zend_Search_Lucene_Search_QueryToken::TT_FIELD; - } - - $this->_lexemes[] = $token; - } - - /** - * Add lexeme modifier - */ - public function addLexemeModifier() - { - $this->_lexemes[] = new Zend_Search_Lucene_Search_QueryToken( - Zend_Search_Lucene_Search_QueryToken::TC_SYNTAX_ELEMENT, - $this->_queryString[$this->_queryStringPosition], - $this->_queryStringPosition); - } - - - /** - * Add lexeme - */ - public function addLexeme() - { - $this->_lexemes[] = new Zend_Search_Lucene_Search_QueryToken( - Zend_Search_Lucene_Search_QueryToken::TC_WORD, - $this->_currentLexeme, - $this->_queryStringPosition - 1); - - $this->_currentLexeme = ''; - } - - /** - * Add quoted lexeme - */ - public function addQuotedLexeme() - { - $this->_lexemes[] = new Zend_Search_Lucene_Search_QueryToken( - Zend_Search_Lucene_Search_QueryToken::TC_PHRASE, - $this->_currentLexeme, - $this->_queryStringPosition); - - $this->_currentLexeme = ''; - } - - /** - * Add number lexeme - */ - public function addNumberLexeme() - { - $this->_lexemes[] = new Zend_Search_Lucene_Search_QueryToken( - Zend_Search_Lucene_Search_QueryToken::TC_NUMBER, - $this->_currentLexeme, - $this->_queryStringPosition - 1); - $this->_currentLexeme = ''; - } - - /** - * Extend lexeme by one char - */ - public function addLexemeChar() - { - $this->_currentLexeme .= $this->_queryString[$this->_queryStringPosition]; - } - - - /** - * Position message - * - * @return string - */ - private function _positionMsg() - { - return 'Position is ' . $this->_queryStringPosition . '.'; - } - - - /********************************************************************* - * Syntax errors actions - *********************************************************************/ - public function lexModifierErrException() - { - #require_once 'Zend/Search/Lucene/Search/QueryParserException.php'; - throw new Zend_Search_Lucene_Search_QueryParserException('Lexeme modifier character can be followed only by number, white space or query syntax element. ' . $this->_positionMsg()); - } - public function quoteWithinLexemeErrException() - { - #require_once 'Zend/Search/Lucene/Search/QueryParserException.php'; - throw new Zend_Search_Lucene_Search_QueryParserException('Quote within lexeme must be escaped by \'\\\' char. ' . $this->_positionMsg()); - } - public function wrongNumberErrException() - { - #require_once 'Zend/Search/Lucene/Search/QueryParserException.php'; - throw new Zend_Search_Lucene_Search_QueryParserException('Wrong number syntax.' . $this->_positionMsg()); - } -} - diff --git a/library/Zend/Search/Lucene/Search/QueryParser.php b/library/Zend/Search/Lucene/Search/QueryParser.php deleted file mode 100644 index 4eea3f2785..0000000000 --- a/library/Zend/Search/Lucene/Search/QueryParser.php +++ /dev/null @@ -1,635 +0,0 @@ -addRules( - array(array(self::ST_COMMON_QUERY_ELEMENT, Zend_Search_Lucene_Search_QueryToken::TT_WORD, self::ST_COMMON_QUERY_ELEMENT), - array(self::ST_COMMON_QUERY_ELEMENT, Zend_Search_Lucene_Search_QueryToken::TT_PHRASE, self::ST_COMMON_QUERY_ELEMENT), - array(self::ST_COMMON_QUERY_ELEMENT, Zend_Search_Lucene_Search_QueryToken::TT_FIELD, self::ST_COMMON_QUERY_ELEMENT), - array(self::ST_COMMON_QUERY_ELEMENT, Zend_Search_Lucene_Search_QueryToken::TT_REQUIRED, self::ST_COMMON_QUERY_ELEMENT), - array(self::ST_COMMON_QUERY_ELEMENT, Zend_Search_Lucene_Search_QueryToken::TT_PROHIBITED, self::ST_COMMON_QUERY_ELEMENT), - array(self::ST_COMMON_QUERY_ELEMENT, Zend_Search_Lucene_Search_QueryToken::TT_FUZZY_PROX_MARK, self::ST_COMMON_QUERY_ELEMENT), - array(self::ST_COMMON_QUERY_ELEMENT, Zend_Search_Lucene_Search_QueryToken::TT_BOOSTING_MARK, self::ST_COMMON_QUERY_ELEMENT), - array(self::ST_COMMON_QUERY_ELEMENT, Zend_Search_Lucene_Search_QueryToken::TT_RANGE_INCL_START, self::ST_CLOSEDINT_RQ_START), - array(self::ST_COMMON_QUERY_ELEMENT, Zend_Search_Lucene_Search_QueryToken::TT_RANGE_EXCL_START, self::ST_OPENEDINT_RQ_START), - array(self::ST_COMMON_QUERY_ELEMENT, Zend_Search_Lucene_Search_QueryToken::TT_SUBQUERY_START, self::ST_COMMON_QUERY_ELEMENT), - array(self::ST_COMMON_QUERY_ELEMENT, Zend_Search_Lucene_Search_QueryToken::TT_SUBQUERY_END, self::ST_COMMON_QUERY_ELEMENT), - array(self::ST_COMMON_QUERY_ELEMENT, Zend_Search_Lucene_Search_QueryToken::TT_AND_LEXEME, self::ST_COMMON_QUERY_ELEMENT), - array(self::ST_COMMON_QUERY_ELEMENT, Zend_Search_Lucene_Search_QueryToken::TT_OR_LEXEME, self::ST_COMMON_QUERY_ELEMENT), - array(self::ST_COMMON_QUERY_ELEMENT, Zend_Search_Lucene_Search_QueryToken::TT_NOT_LEXEME, self::ST_COMMON_QUERY_ELEMENT), - array(self::ST_COMMON_QUERY_ELEMENT, Zend_Search_Lucene_Search_QueryToken::TT_NUMBER, self::ST_COMMON_QUERY_ELEMENT) - )); - $this->addRules( - array(array(self::ST_CLOSEDINT_RQ_START, Zend_Search_Lucene_Search_QueryToken::TT_WORD, self::ST_CLOSEDINT_RQ_FIRST_TERM), - array(self::ST_CLOSEDINT_RQ_FIRST_TERM, Zend_Search_Lucene_Search_QueryToken::TT_TO_LEXEME, self::ST_CLOSEDINT_RQ_TO_TERM), - array(self::ST_CLOSEDINT_RQ_TO_TERM, Zend_Search_Lucene_Search_QueryToken::TT_WORD, self::ST_CLOSEDINT_RQ_LAST_TERM), - array(self::ST_CLOSEDINT_RQ_LAST_TERM, Zend_Search_Lucene_Search_QueryToken::TT_RANGE_INCL_END, self::ST_COMMON_QUERY_ELEMENT) - )); - $this->addRules( - array(array(self::ST_OPENEDINT_RQ_START, Zend_Search_Lucene_Search_QueryToken::TT_WORD, self::ST_OPENEDINT_RQ_FIRST_TERM), - array(self::ST_OPENEDINT_RQ_FIRST_TERM, Zend_Search_Lucene_Search_QueryToken::TT_TO_LEXEME, self::ST_OPENEDINT_RQ_TO_TERM), - array(self::ST_OPENEDINT_RQ_TO_TERM, Zend_Search_Lucene_Search_QueryToken::TT_WORD, self::ST_OPENEDINT_RQ_LAST_TERM), - array(self::ST_OPENEDINT_RQ_LAST_TERM, Zend_Search_Lucene_Search_QueryToken::TT_RANGE_EXCL_END, self::ST_COMMON_QUERY_ELEMENT) - )); - - - - $addTermEntryAction = new Zend_Search_Lucene_FSMAction($this, 'addTermEntry'); - $addPhraseEntryAction = new Zend_Search_Lucene_FSMAction($this, 'addPhraseEntry'); - $setFieldAction = new Zend_Search_Lucene_FSMAction($this, 'setField'); - $setSignAction = new Zend_Search_Lucene_FSMAction($this, 'setSign'); - $setFuzzyProxAction = new Zend_Search_Lucene_FSMAction($this, 'processFuzzyProximityModifier'); - $processModifierParameterAction = new Zend_Search_Lucene_FSMAction($this, 'processModifierParameter'); - $subqueryStartAction = new Zend_Search_Lucene_FSMAction($this, 'subqueryStart'); - $subqueryEndAction = new Zend_Search_Lucene_FSMAction($this, 'subqueryEnd'); - $logicalOperatorAction = new Zend_Search_Lucene_FSMAction($this, 'logicalOperator'); - $openedRQFirstTermAction = new Zend_Search_Lucene_FSMAction($this, 'openedRQFirstTerm'); - $openedRQLastTermAction = new Zend_Search_Lucene_FSMAction($this, 'openedRQLastTerm'); - $closedRQFirstTermAction = new Zend_Search_Lucene_FSMAction($this, 'closedRQFirstTerm'); - $closedRQLastTermAction = new Zend_Search_Lucene_FSMAction($this, 'closedRQLastTerm'); - - - $this->addInputAction(self::ST_COMMON_QUERY_ELEMENT, Zend_Search_Lucene_Search_QueryToken::TT_WORD, $addTermEntryAction); - $this->addInputAction(self::ST_COMMON_QUERY_ELEMENT, Zend_Search_Lucene_Search_QueryToken::TT_PHRASE, $addPhraseEntryAction); - $this->addInputAction(self::ST_COMMON_QUERY_ELEMENT, Zend_Search_Lucene_Search_QueryToken::TT_FIELD, $setFieldAction); - $this->addInputAction(self::ST_COMMON_QUERY_ELEMENT, Zend_Search_Lucene_Search_QueryToken::TT_REQUIRED, $setSignAction); - $this->addInputAction(self::ST_COMMON_QUERY_ELEMENT, Zend_Search_Lucene_Search_QueryToken::TT_PROHIBITED, $setSignAction); - $this->addInputAction(self::ST_COMMON_QUERY_ELEMENT, Zend_Search_Lucene_Search_QueryToken::TT_FUZZY_PROX_MARK, $setFuzzyProxAction); - $this->addInputAction(self::ST_COMMON_QUERY_ELEMENT, Zend_Search_Lucene_Search_QueryToken::TT_NUMBER, $processModifierParameterAction); - $this->addInputAction(self::ST_COMMON_QUERY_ELEMENT, Zend_Search_Lucene_Search_QueryToken::TT_SUBQUERY_START, $subqueryStartAction); - $this->addInputAction(self::ST_COMMON_QUERY_ELEMENT, Zend_Search_Lucene_Search_QueryToken::TT_SUBQUERY_END, $subqueryEndAction); - $this->addInputAction(self::ST_COMMON_QUERY_ELEMENT, Zend_Search_Lucene_Search_QueryToken::TT_AND_LEXEME, $logicalOperatorAction); - $this->addInputAction(self::ST_COMMON_QUERY_ELEMENT, Zend_Search_Lucene_Search_QueryToken::TT_OR_LEXEME, $logicalOperatorAction); - $this->addInputAction(self::ST_COMMON_QUERY_ELEMENT, Zend_Search_Lucene_Search_QueryToken::TT_NOT_LEXEME, $logicalOperatorAction); - - $this->addEntryAction(self::ST_OPENEDINT_RQ_FIRST_TERM, $openedRQFirstTermAction); - $this->addEntryAction(self::ST_OPENEDINT_RQ_LAST_TERM, $openedRQLastTermAction); - $this->addEntryAction(self::ST_CLOSEDINT_RQ_FIRST_TERM, $closedRQFirstTermAction); - $this->addEntryAction(self::ST_CLOSEDINT_RQ_LAST_TERM, $closedRQLastTermAction); - - - #require_once 'Zend/Search/Lucene/Search/QueryLexer.php'; - $this->_lexer = new Zend_Search_Lucene_Search_QueryLexer(); - } - - /** - * Get query parser instance - * - * @return Zend_Search_Lucene_Search_QueryParser - */ - private static function _getInstance() - { - if (self::$_instance === null) { - self::$_instance = new self(); - } - return self::$_instance; - } - - /** - * Set query string default encoding - * - * @param string $encoding - */ - public static function setDefaultEncoding($encoding) - { - self::_getInstance()->_defaultEncoding = $encoding; - } - - /** - * Get query string default encoding - * - * @return string - */ - public static function getDefaultEncoding() - { - return self::_getInstance()->_defaultEncoding; - } - - /** - * Set default boolean operator - * - * @param integer $operator - */ - public static function setDefaultOperator($operator) - { - self::_getInstance()->_defaultOperator = $operator; - } - - /** - * Get default boolean operator - * - * @return integer - */ - public static function getDefaultOperator() - { - return self::_getInstance()->_defaultOperator; - } - - /** - * Turn on 'suppress query parser exceptions' mode. - */ - public static function suppressQueryParsingExceptions() - { - self::_getInstance()->_suppressQueryParsingExceptions = true; - } - /** - * Turn off 'suppress query parser exceptions' mode. - */ - public static function dontSuppressQueryParsingExceptions() - { - self::_getInstance()->_suppressQueryParsingExceptions = false; - } - /** - * Check 'suppress query parser exceptions' mode. - * @return boolean - */ - public static function queryParsingExceptionsSuppressed() - { - return self::_getInstance()->_suppressQueryParsingExceptions; - } - - - /** - * Escape keyword to force it to be parsed as one term - * - * @param string $keyword - * @return string - */ - public static function escape($keyword) - { - return '\\' . implode('\\', str_split($keyword)); - } - - /** - * Parses a query string - * - * @param string $strQuery - * @param string $encoding - * @return Zend_Search_Lucene_Search_Query - * @throws Zend_Search_Lucene_Search_QueryParserException - */ - public static function parse($strQuery, $encoding = null) - { - self::_getInstance(); - - // Reset FSM if previous parse operation didn't return it into a correct state - self::$_instance->reset(); - - #require_once 'Zend/Search/Lucene/Search/QueryParserException.php'; - try { - #require_once 'Zend/Search/Lucene/Search/QueryParserContext.php'; - - self::$_instance->_encoding = ($encoding !== null) ? $encoding : self::$_instance->_defaultEncoding; - self::$_instance->_lastToken = null; - self::$_instance->_context = new Zend_Search_Lucene_Search_QueryParserContext(self::$_instance->_encoding); - self::$_instance->_contextStack = array(); - self::$_instance->_tokens = self::$_instance->_lexer->tokenize($strQuery, self::$_instance->_encoding); - - // Empty query - if (count(self::$_instance->_tokens) == 0) { - #require_once 'Zend/Search/Lucene/Search/Query/Insignificant.php'; - return new Zend_Search_Lucene_Search_Query_Insignificant(); - } - - - foreach (self::$_instance->_tokens as $token) { - try { - self::$_instance->_currentToken = $token; - self::$_instance->process($token->type); - - self::$_instance->_lastToken = $token; - } catch (Exception $e) { - if (strpos($e->getMessage(), 'There is no any rule for') !== false) { - throw new Zend_Search_Lucene_Search_QueryParserException( 'Syntax error at char position ' . $token->position . '.', 0, $e); - } - - #require_once 'Zend/Search/Lucene/Exception.php'; - throw new Zend_Search_Lucene_Exception($e->getMessage(), $e->getCode(), $e); - } - } - - if (count(self::$_instance->_contextStack) != 0) { - throw new Zend_Search_Lucene_Search_QueryParserException('Syntax Error: mismatched parentheses, every opening must have closing.' ); - } - - return self::$_instance->_context->getQuery(); - } catch (Zend_Search_Lucene_Search_QueryParserException $e) { - if (self::$_instance->_suppressQueryParsingExceptions) { - $queryTokens = Zend_Search_Lucene_Analysis_Analyzer::getDefault()->tokenize($strQuery, self::$_instance->_encoding); - - #require_once 'Zend/Search/Lucene/Search/Query/MultiTerm.php'; - $query = new Zend_Search_Lucene_Search_Query_MultiTerm(); - $termsSign = (self::$_instance->_defaultOperator == self::B_AND) ? true /* required term */ : - null /* optional term */; - - #require_once 'Zend/Search/Lucene/Index/Term.php'; - foreach ($queryTokens as $token) { - $query->addTerm(new Zend_Search_Lucene_Index_Term($token->getTermText()), $termsSign); - } - - - return $query; - } else { - #require_once 'Zend/Search/Lucene/Exception.php'; - throw new Zend_Search_Lucene_Exception($e->getMessage(), $e->getCode(), $e); - } - } - } - - /********************************************************************* - * Actions implementation - * - * Actions affect on recognized lexemes list - *********************************************************************/ - - /** - * Add term to a query - */ - public function addTermEntry() - { - #require_once 'Zend/Search/Lucene/Search/QueryEntry/Term.php'; - $entry = new Zend_Search_Lucene_Search_QueryEntry_Term($this->_currentToken->text, $this->_context->getField()); - $this->_context->addEntry($entry); - } - - /** - * Add phrase to a query - */ - public function addPhraseEntry() - { - #require_once 'Zend/Search/Lucene/Search/QueryEntry/Phrase.php'; - $entry = new Zend_Search_Lucene_Search_QueryEntry_Phrase($this->_currentToken->text, $this->_context->getField()); - $this->_context->addEntry($entry); - } - - /** - * Set entry field - */ - public function setField() - { - $this->_context->setNextEntryField($this->_currentToken->text); - } - - /** - * Set entry sign - */ - public function setSign() - { - $this->_context->setNextEntrySign($this->_currentToken->type); - } - - - /** - * Process fuzzy search/proximity modifier - '~' - */ - public function processFuzzyProximityModifier() - { - $this->_context->processFuzzyProximityModifier(); - } - - /** - * Process modifier parameter - * - * @throws Zend_Search_Lucene_Exception - */ - public function processModifierParameter() - { - if ($this->_lastToken === null) { - #require_once 'Zend/Search/Lucene/Search/QueryParserException.php'; - throw new Zend_Search_Lucene_Search_QueryParserException('Lexeme modifier parameter must follow lexeme modifier. Char position 0.' ); - } - - switch ($this->_lastToken->type) { - case Zend_Search_Lucene_Search_QueryToken::TT_FUZZY_PROX_MARK: - $this->_context->processFuzzyProximityModifier($this->_currentToken->text); - break; - - case Zend_Search_Lucene_Search_QueryToken::TT_BOOSTING_MARK: - $this->_context->boost($this->_currentToken->text); - break; - - default: - // It's not a user input exception - #require_once 'Zend/Search/Lucene/Exception.php'; - throw new Zend_Search_Lucene_Exception('Lexeme modifier parameter must follow lexeme modifier. Char position 0.' ); - } - } - - - /** - * Start subquery - */ - public function subqueryStart() - { - #require_once 'Zend/Search/Lucene/Search/QueryParserContext.php'; - - $this->_contextStack[] = $this->_context; - $this->_context = new Zend_Search_Lucene_Search_QueryParserContext($this->_encoding, $this->_context->getField()); - } - - /** - * End subquery - */ - public function subqueryEnd() - { - if (count($this->_contextStack) == 0) { - #require_once 'Zend/Search/Lucene/Search/QueryParserException.php'; - throw new Zend_Search_Lucene_Search_QueryParserException('Syntax Error: mismatched parentheses, every opening must have closing. Char position ' . $this->_currentToken->position . '.' ); - } - - $query = $this->_context->getQuery(); - $this->_context = array_pop($this->_contextStack); - - #require_once 'Zend/Search/Lucene/Search/QueryEntry/Subquery.php'; - $this->_context->addEntry(new Zend_Search_Lucene_Search_QueryEntry_Subquery($query)); - } - - /** - * Process logical operator - */ - public function logicalOperator() - { - $this->_context->addLogicalOperator($this->_currentToken->type); - } - - /** - * Process first range query term (opened interval) - */ - public function openedRQFirstTerm() - { - $this->_rqFirstTerm = $this->_currentToken->text; - } - - /** - * Process last range query term (opened interval) - * - * @throws Zend_Search_Lucene_Search_QueryParserException - */ - public function openedRQLastTerm() - { - $tokens = Zend_Search_Lucene_Analysis_Analyzer::getDefault()->tokenize($this->_rqFirstTerm, $this->_encoding); - if (count($tokens) > 1) { - #require_once 'Zend/Search/Lucene/Search/QueryParserException.php'; - throw new Zend_Search_Lucene_Search_QueryParserException('Range query boundary terms must be non-multiple word terms'); - } else if (count($tokens) == 1) { - #require_once 'Zend/Search/Lucene/Index/Term.php'; - $from = new Zend_Search_Lucene_Index_Term(reset($tokens)->getTermText(), $this->_context->getField()); - } else { - $from = null; - } - - $tokens = Zend_Search_Lucene_Analysis_Analyzer::getDefault()->tokenize($this->_currentToken->text, $this->_encoding); - if (count($tokens) > 1) { - #require_once 'Zend/Search/Lucene/Search/QueryParserException.php'; - throw new Zend_Search_Lucene_Search_QueryParserException('Range query boundary terms must be non-multiple word terms'); - } else if (count($tokens) == 1) { - #require_once 'Zend/Search/Lucene/Index/Term.php'; - $to = new Zend_Search_Lucene_Index_Term(reset($tokens)->getTermText(), $this->_context->getField()); - } else { - $to = null; - } - - if ($from === null && $to === null) { - #require_once 'Zend/Search/Lucene/Search/QueryParserException.php'; - throw new Zend_Search_Lucene_Search_QueryParserException('At least one range query boundary term must be non-empty term'); - } - - #require_once 'Zend/Search/Lucene/Search/Query/Range.php'; - $rangeQuery = new Zend_Search_Lucene_Search_Query_Range($from, $to, false); - #require_once 'Zend/Search/Lucene/Search/QueryEntry/Subquery.php'; - $entry = new Zend_Search_Lucene_Search_QueryEntry_Subquery($rangeQuery); - $this->_context->addEntry($entry); - } - - /** - * Process first range query term (closed interval) - */ - public function closedRQFirstTerm() - { - $this->_rqFirstTerm = $this->_currentToken->text; - } - - /** - * Process last range query term (closed interval) - * - * @throws Zend_Search_Lucene_Search_QueryParserException - */ - public function closedRQLastTerm() - { - $tokens = Zend_Search_Lucene_Analysis_Analyzer::getDefault()->tokenize($this->_rqFirstTerm, $this->_encoding); - if (count($tokens) > 1) { - #require_once 'Zend/Search/Lucene/Search/QueryParserException.php'; - throw new Zend_Search_Lucene_Search_QueryParserException('Range query boundary terms must be non-multiple word terms'); - } else if (count($tokens) == 1) { - #require_once 'Zend/Search/Lucene/Index/Term.php'; - $from = new Zend_Search_Lucene_Index_Term(reset($tokens)->getTermText(), $this->_context->getField()); - } else { - $from = null; - } - - $tokens = Zend_Search_Lucene_Analysis_Analyzer::getDefault()->tokenize($this->_currentToken->text, $this->_encoding); - if (count($tokens) > 1) { - #require_once 'Zend/Search/Lucene/Search/QueryParserException.php'; - throw new Zend_Search_Lucene_Search_QueryParserException('Range query boundary terms must be non-multiple word terms'); - } else if (count($tokens) == 1) { - #require_once 'Zend/Search/Lucene/Index/Term.php'; - $to = new Zend_Search_Lucene_Index_Term(reset($tokens)->getTermText(), $this->_context->getField()); - } else { - $to = null; - } - - if ($from === null && $to === null) { - #require_once 'Zend/Search/Lucene/Search/QueryParserException.php'; - throw new Zend_Search_Lucene_Search_QueryParserException('At least one range query boundary term must be non-empty term'); - } - - #require_once 'Zend/Search/Lucene/Search/Query/Range.php'; - $rangeQuery = new Zend_Search_Lucene_Search_Query_Range($from, $to, true); - #require_once 'Zend/Search/Lucene/Search/QueryEntry/Subquery.php'; - $entry = new Zend_Search_Lucene_Search_QueryEntry_Subquery($rangeQuery); - $this->_context->addEntry($entry); - } -} - diff --git a/library/Zend/Search/Lucene/Search/QueryParserContext.php b/library/Zend/Search/Lucene/Search/QueryParserContext.php deleted file mode 100644 index 636a3dc71d..0000000000 --- a/library/Zend/Search/Lucene/Search/QueryParserContext.php +++ /dev/null @@ -1,401 +0,0 @@ -_encoding = $encoding; - $this->_defaultField = $defaultField; - } - - - /** - * Get context default field - * - * @return string|null - */ - public function getField() - { - return ($this->_nextEntryField !== null) ? $this->_nextEntryField : $this->_defaultField; - } - - /** - * Set field for next entry - * - * @param string $field - */ - public function setNextEntryField($field) - { - $this->_nextEntryField = $field; - } - - - /** - * Set sign for next entry - * - * @param integer $sign - * @throws Zend_Search_Lucene_Exception - */ - public function setNextEntrySign($sign) - { - if ($this->_mode === self::GM_BOOLEAN) { - #require_once 'Zend/Search/Lucene/Search/QueryParserException.php'; - throw new Zend_Search_Lucene_Search_QueryParserException('It\'s not allowed to mix boolean and signs styles in the same subquery.'); - } - - $this->_mode = self::GM_SIGNS; - - if ($sign == Zend_Search_Lucene_Search_QueryToken::TT_REQUIRED) { - $this->_nextEntrySign = true; - } else if ($sign == Zend_Search_Lucene_Search_QueryToken::TT_PROHIBITED) { - $this->_nextEntrySign = false; - } else { - #require_once 'Zend/Search/Lucene/Exception.php'; - throw new Zend_Search_Lucene_Exception('Unrecognized sign type.'); - } - } - - - /** - * Add entry to a query - * - * @param Zend_Search_Lucene_Search_QueryEntry $entry - */ - public function addEntry(Zend_Search_Lucene_Search_QueryEntry $entry) - { - if ($this->_mode !== self::GM_BOOLEAN) { - $this->_signs[] = $this->_nextEntrySign; - } - - $this->_entries[] = $entry; - - $this->_nextEntryField = null; - $this->_nextEntrySign = null; - } - - - /** - * Process fuzzy search or proximity search modifier - * - * @throws Zend_Search_Lucene_Search_QueryParserException - */ - public function processFuzzyProximityModifier($parameter = null) - { - // Check, that modifier has came just after word or phrase - if ($this->_nextEntryField !== null || $this->_nextEntrySign !== null) { - #require_once 'Zend/Search/Lucene/Search/QueryParserException.php'; - throw new Zend_Search_Lucene_Search_QueryParserException('\'~\' modifier must follow word or phrase.'); - } - - $lastEntry = array_pop($this->_entries); - - if (!$lastEntry instanceof Zend_Search_Lucene_Search_QueryEntry) { - // there are no entries or last entry is boolean operator - #require_once 'Zend/Search/Lucene/Search/QueryParserException.php'; - throw new Zend_Search_Lucene_Search_QueryParserException('\'~\' modifier must follow word or phrase.'); - } - - $lastEntry->processFuzzyProximityModifier($parameter); - - $this->_entries[] = $lastEntry; - } - - /** - * Set boost factor to the entry - * - * @param float $boostFactor - */ - public function boost($boostFactor) - { - // Check, that modifier has came just after word or phrase - if ($this->_nextEntryField !== null || $this->_nextEntrySign !== null) { - #require_once 'Zend/Search/Lucene/Search/QueryParserException.php'; - throw new Zend_Search_Lucene_Search_QueryParserException('\'^\' modifier must follow word, phrase or subquery.'); - } - - $lastEntry = array_pop($this->_entries); - - if (!$lastEntry instanceof Zend_Search_Lucene_Search_QueryEntry) { - // there are no entries or last entry is boolean operator - #require_once 'Zend/Search/Lucene/Search/QueryParserException.php'; - throw new Zend_Search_Lucene_Search_QueryParserException('\'^\' modifier must follow word, phrase or subquery.'); - } - - $lastEntry->boost($boostFactor); - - $this->_entries[] = $lastEntry; - } - - /** - * Process logical operator - * - * @param integer $operator - */ - public function addLogicalOperator($operator) - { - if ($this->_mode === self::GM_SIGNS) { - #require_once 'Zend/Search/Lucene/Search/QueryParserException.php'; - throw new Zend_Search_Lucene_Search_QueryParserException('It\'s not allowed to mix boolean and signs styles in the same subquery.'); - } - - $this->_mode = self::GM_BOOLEAN; - - $this->_entries[] = $operator; - } - - - /** - * Generate 'signs style' query from the context - * '+term1 term2 -term3 +() ...' - * - * @return Zend_Search_Lucene_Search_Query - */ - public function _signStyleExpressionQuery() - { - #require_once 'Zend/Search/Lucene/Search/Query/Boolean.php'; - $query = new Zend_Search_Lucene_Search_Query_Boolean(); - - #require_once 'Zend/Search/Lucene/Search/QueryParser.php'; - if (Zend_Search_Lucene_Search_QueryParser::getDefaultOperator() == Zend_Search_Lucene_Search_QueryParser::B_AND) { - $defaultSign = true; // required - } else { - // Zend_Search_Lucene_Search_QueryParser::B_OR - $defaultSign = null; // optional - } - - foreach ($this->_entries as $entryId => $entry) { - $sign = ($this->_signs[$entryId] !== null) ? $this->_signs[$entryId] : $defaultSign; - $query->addSubquery($entry->getQuery($this->_encoding), $sign); - } - - return $query; - } - - - /** - * Generate 'boolean style' query from the context - * 'term1 and term2 or term3 and () and not ()' - * - * @return Zend_Search_Lucene_Search_Query - * @throws Zend_Search_Lucene - */ - private function _booleanExpressionQuery() - { - /** - * We treat each level of an expression as a boolean expression in - * a Disjunctive Normal Form - * - * AND operator has higher precedence than OR - * - * Thus logical query is a disjunction of one or more conjunctions of - * one or more query entries - */ - - #require_once 'Zend/Search/Lucene/Search/BooleanExpressionRecognizer.php'; - $expressionRecognizer = new Zend_Search_Lucene_Search_BooleanExpressionRecognizer(); - - #require_once 'Zend/Search/Lucene/Exception.php'; - try { - foreach ($this->_entries as $entry) { - if ($entry instanceof Zend_Search_Lucene_Search_QueryEntry) { - $expressionRecognizer->processLiteral($entry); - } else { - switch ($entry) { - case Zend_Search_Lucene_Search_QueryToken::TT_AND_LEXEME: - $expressionRecognizer->processOperator(Zend_Search_Lucene_Search_BooleanExpressionRecognizer::IN_AND_OPERATOR); - break; - - case Zend_Search_Lucene_Search_QueryToken::TT_OR_LEXEME: - $expressionRecognizer->processOperator(Zend_Search_Lucene_Search_BooleanExpressionRecognizer::IN_OR_OPERATOR); - break; - - case Zend_Search_Lucene_Search_QueryToken::TT_NOT_LEXEME: - $expressionRecognizer->processOperator(Zend_Search_Lucene_Search_BooleanExpressionRecognizer::IN_NOT_OPERATOR); - break; - - default: - throw new Zend_Search_Lucene('Boolean expression error. Unknown operator type.'); - } - } - } - - $conjuctions = $expressionRecognizer->finishExpression(); - } catch (Zend_Search_Exception $e) { - // throw new Zend_Search_Lucene_Search_QueryParserException('Boolean expression error. Error message: \'' . - // $e->getMessage() . '\'.' ); - // It's query syntax error message and it should be user friendly. So FSM message is omitted - #require_once 'Zend/Search/Lucene/Search/QueryParserException.php'; - throw new Zend_Search_Lucene_Search_QueryParserException('Boolean expression error.', 0, $e); - } - - // Remove 'only negative' conjunctions - foreach ($conjuctions as $conjuctionId => $conjuction) { - $nonNegativeEntryFound = false; - - foreach ($conjuction as $conjuctionEntry) { - if ($conjuctionEntry[1]) { - $nonNegativeEntryFound = true; - break; - } - } - - if (!$nonNegativeEntryFound) { - unset($conjuctions[$conjuctionId]); - } - } - - - $subqueries = array(); - foreach ($conjuctions as $conjuction) { - // Check, if it's a one term conjuction - if (count($conjuction) == 1) { - $subqueries[] = $conjuction[0][0]->getQuery($this->_encoding); - } else { - #require_once 'Zend/Search/Lucene/Search/Query/Boolean.php'; - $subquery = new Zend_Search_Lucene_Search_Query_Boolean(); - - foreach ($conjuction as $conjuctionEntry) { - $subquery->addSubquery($conjuctionEntry[0]->getQuery($this->_encoding), $conjuctionEntry[1]); - } - - $subqueries[] = $subquery; - } - } - - if (count($subqueries) == 0) { - #require_once 'Zend/Search/Lucene/Search/Query/Insignificant.php'; - return new Zend_Search_Lucene_Search_Query_Insignificant(); - } - - if (count($subqueries) == 1) { - return $subqueries[0]; - } - - - #require_once 'Zend/Search/Lucene/Search/Query/Boolean.php'; - $query = new Zend_Search_Lucene_Search_Query_Boolean(); - - foreach ($subqueries as $subquery) { - // Non-requirered entry/subquery - $query->addSubquery($subquery); - } - - return $query; - } - - /** - * Generate query from current context - * - * @return Zend_Search_Lucene_Search_Query - */ - public function getQuery() - { - if ($this->_mode === self::GM_BOOLEAN) { - return $this->_booleanExpressionQuery(); - } else { - return $this->_signStyleExpressionQuery(); - } - } -} diff --git a/library/Zend/Search/Lucene/Search/QueryParserException.php b/library/Zend/Search/Lucene/Search/QueryParserException.php deleted file mode 100644 index 6d95adbc85..0000000000 --- a/library/Zend/Search/Lucene/Search/QueryParserException.php +++ /dev/null @@ -1,41 +0,0 @@ - or field:() pairs - const TT_FIELD_INDICATOR = 3; // ':' - const TT_REQUIRED = 4; // '+' - const TT_PROHIBITED = 5; // '-' - const TT_FUZZY_PROX_MARK = 6; // '~' - const TT_BOOSTING_MARK = 7; // '^' - const TT_RANGE_INCL_START = 8; // '[' - const TT_RANGE_INCL_END = 9; // ']' - const TT_RANGE_EXCL_START = 10; // '{' - const TT_RANGE_EXCL_END = 11; // '}' - const TT_SUBQUERY_START = 12; // '(' - const TT_SUBQUERY_END = 13; // ')' - const TT_AND_LEXEME = 14; // 'AND' or 'and' - const TT_OR_LEXEME = 15; // 'OR' or 'or' - const TT_NOT_LEXEME = 16; // 'NOT' or 'not' - const TT_TO_LEXEME = 17; // 'TO' or 'to' - const TT_NUMBER = 18; // Number, like: 10, 0.8, .64, .... - - - /** - * Returns all possible lexeme types. - * It's used for syntax analyzer state machine initialization - * - * @return array - */ - public static function getTypes() - { - return array( self::TT_WORD, - self::TT_PHRASE, - self::TT_FIELD, - self::TT_FIELD_INDICATOR, - self::TT_REQUIRED, - self::TT_PROHIBITED, - self::TT_FUZZY_PROX_MARK, - self::TT_BOOSTING_MARK, - self::TT_RANGE_INCL_START, - self::TT_RANGE_INCL_END, - self::TT_RANGE_EXCL_START, - self::TT_RANGE_EXCL_END, - self::TT_SUBQUERY_START, - self::TT_SUBQUERY_END, - self::TT_AND_LEXEME, - self::TT_OR_LEXEME, - self::TT_NOT_LEXEME, - self::TT_TO_LEXEME, - self::TT_NUMBER - ); - } - - - /** - * TokenCategories - */ - const TC_WORD = 0; // Word - const TC_PHRASE = 1; // Phrase (one or several quoted words) - const TC_NUMBER = 2; // Nubers, which are used with syntax elements. Ex. roam~0.8 - const TC_SYNTAX_ELEMENT = 3; // + - ( ) [ ] { } ! || && ~ ^ - - - /** - * Token type. - * - * @var integer - */ - public $type; - - /** - * Token text. - * - * @var integer - */ - public $text; - - /** - * Token position within query. - * - * @var integer - */ - public $position; - - - /** - * IndexReader constructor needs token type and token text as a parameters. - * - * @param integer $tokenCategory - * @param string $tokText - * @param integer $position - */ - public function __construct($tokenCategory, $tokenText, $position) - { - $this->text = $tokenText; - $this->position = $position + 1; // Start from 1 - - switch ($tokenCategory) { - case self::TC_WORD: - if ( strtolower($tokenText) == 'and') { - $this->type = self::TT_AND_LEXEME; - } else if (strtolower($tokenText) == 'or') { - $this->type = self::TT_OR_LEXEME; - } else if (strtolower($tokenText) == 'not') { - $this->type = self::TT_NOT_LEXEME; - } else if (strtolower($tokenText) == 'to') { - $this->type = self::TT_TO_LEXEME; - } else { - $this->type = self::TT_WORD; - } - break; - - case self::TC_PHRASE: - $this->type = self::TT_PHRASE; - break; - - case self::TC_NUMBER: - $this->type = self::TT_NUMBER; - break; - - case self::TC_SYNTAX_ELEMENT: - switch ($tokenText) { - case ':': - $this->type = self::TT_FIELD_INDICATOR; - break; - - case '+': - $this->type = self::TT_REQUIRED; - break; - - case '-': - $this->type = self::TT_PROHIBITED; - break; - - case '~': - $this->type = self::TT_FUZZY_PROX_MARK; - break; - - case '^': - $this->type = self::TT_BOOSTING_MARK; - break; - - case '[': - $this->type = self::TT_RANGE_INCL_START; - break; - - case ']': - $this->type = self::TT_RANGE_INCL_END; - break; - - case '{': - $this->type = self::TT_RANGE_EXCL_START; - break; - - case '}': - $this->type = self::TT_RANGE_EXCL_END; - break; - - case '(': - $this->type = self::TT_SUBQUERY_START; - break; - - case ')': - $this->type = self::TT_SUBQUERY_END; - break; - - case '!': - $this->type = self::TT_NOT_LEXEME; - break; - - case '&&': - $this->type = self::TT_AND_LEXEME; - break; - - case '||': - $this->type = self::TT_OR_LEXEME; - break; - - default: - #require_once 'Zend/Search/Lucene/Exception.php'; - throw new Zend_Search_Lucene_Exception('Unrecognized query syntax lexeme: \'' . $tokenText . '\''); - } - break; - - case self::TC_NUMBER: - $this->type = self::TT_NUMBER; - - default: - #require_once 'Zend/Search/Lucene/Exception.php'; - throw new Zend_Search_Lucene_Exception('Unrecognized lexeme type: \'' . $tokenCategory . '\''); - } - } -} diff --git a/library/Zend/Search/Lucene/Search/Similarity.php b/library/Zend/Search/Lucene/Search/Similarity.php deleted file mode 100644 index 664697097a..0000000000 --- a/library/Zend/Search/Lucene/Search/Similarity.php +++ /dev/null @@ -1,551 +0,0 @@ - 0.0, - 1 => 5.820766E-10, - 2 => 6.9849193E-10, - 3 => 8.1490725E-10, - 4 => 9.313226E-10, - 5 => 1.1641532E-9, - 6 => 1.3969839E-9, - 7 => 1.6298145E-9, - 8 => 1.8626451E-9, - 9 => 2.3283064E-9, - 10 => 2.7939677E-9, - 11 => 3.259629E-9, - 12 => 3.7252903E-9, - 13 => 4.656613E-9, - 14 => 5.5879354E-9, - 15 => 6.519258E-9, - 16 => 7.4505806E-9, - 17 => 9.313226E-9, - 18 => 1.1175871E-8, - 19 => 1.3038516E-8, - 20 => 1.4901161E-8, - 21 => 1.8626451E-8, - 22 => 2.2351742E-8, - 23 => 2.6077032E-8, - 24 => 2.9802322E-8, - 25 => 3.7252903E-8, - 26 => 4.4703484E-8, - 27 => 5.2154064E-8, - 28 => 5.9604645E-8, - 29 => 7.4505806E-8, - 30 => 8.940697E-8, - 31 => 1.0430813E-7, - 32 => 1.1920929E-7, - 33 => 1.4901161E-7, - 34 => 1.7881393E-7, - 35 => 2.0861626E-7, - 36 => 2.3841858E-7, - 37 => 2.9802322E-7, - 38 => 3.5762787E-7, - 39 => 4.172325E-7, - 40 => 4.7683716E-7, - 41 => 5.9604645E-7, - 42 => 7.1525574E-7, - 43 => 8.34465E-7, - 44 => 9.536743E-7, - 45 => 1.1920929E-6, - 46 => 1.4305115E-6, - 47 => 1.66893E-6, - 48 => 1.9073486E-6, - 49 => 2.3841858E-6, - 50 => 2.861023E-6, - 51 => 3.33786E-6, - 52 => 3.8146973E-6, - 53 => 4.7683716E-6, - 54 => 5.722046E-6, - 55 => 6.67572E-6, - 56 => 7.6293945E-6, - 57 => 9.536743E-6, - 58 => 1.1444092E-5, - 59 => 1.335144E-5, - 60 => 1.5258789E-5, - 61 => 1.9073486E-5, - 62 => 2.2888184E-5, - 63 => 2.670288E-5, - 64 => 3.0517578E-5, - 65 => 3.8146973E-5, - 66 => 4.5776367E-5, - 67 => 5.340576E-5, - 68 => 6.1035156E-5, - 69 => 7.6293945E-5, - 70 => 9.1552734E-5, - 71 => 1.0681152E-4, - 72 => 1.2207031E-4, - 73 => 1.5258789E-4, - 74 => 1.8310547E-4, - 75 => 2.1362305E-4, - 76 => 2.4414062E-4, - 77 => 3.0517578E-4, - 78 => 3.6621094E-4, - 79 => 4.272461E-4, - 80 => 4.8828125E-4, - 81 => 6.1035156E-4, - 82 => 7.324219E-4, - 83 => 8.544922E-4, - 84 => 9.765625E-4, - 85 => 0.0012207031, - 86 => 0.0014648438, - 87 => 0.0017089844, - 88 => 0.001953125, - 89 => 0.0024414062, - 90 => 0.0029296875, - 91 => 0.0034179688, - 92 => 0.00390625, - 93 => 0.0048828125, - 94 => 0.005859375, - 95 => 0.0068359375, - 96 => 0.0078125, - 97 => 0.009765625, - 98 => 0.01171875, - 99 => 0.013671875, - 100 => 0.015625, - 101 => 0.01953125, - 102 => 0.0234375, - 103 => 0.02734375, - 104 => 0.03125, - 105 => 0.0390625, - 106 => 0.046875, - 107 => 0.0546875, - 108 => 0.0625, - 109 => 0.078125, - 110 => 0.09375, - 111 => 0.109375, - 112 => 0.125, - 113 => 0.15625, - 114 => 0.1875, - 115 => 0.21875, - 116 => 0.25, - 117 => 0.3125, - 118 => 0.375, - 119 => 0.4375, - 120 => 0.5, - 121 => 0.625, - 122 => 0.75, - 123 => 0.875, - 124 => 1.0, - 125 => 1.25, - 126 => 1.5, - 127 => 1.75, - 128 => 2.0, - 129 => 2.5, - 130 => 3.0, - 131 => 3.5, - 132 => 4.0, - 133 => 5.0, - 134 => 6.0, - 135 => 7.0, - 136 => 8.0, - 137 => 10.0, - 138 => 12.0, - 139 => 14.0, - 140 => 16.0, - 141 => 20.0, - 142 => 24.0, - 143 => 28.0, - 144 => 32.0, - 145 => 40.0, - 146 => 48.0, - 147 => 56.0, - 148 => 64.0, - 149 => 80.0, - 150 => 96.0, - 151 => 112.0, - 152 => 128.0, - 153 => 160.0, - 154 => 192.0, - 155 => 224.0, - 156 => 256.0, - 157 => 320.0, - 158 => 384.0, - 159 => 448.0, - 160 => 512.0, - 161 => 640.0, - 162 => 768.0, - 163 => 896.0, - 164 => 1024.0, - 165 => 1280.0, - 166 => 1536.0, - 167 => 1792.0, - 168 => 2048.0, - 169 => 2560.0, - 170 => 3072.0, - 171 => 3584.0, - 172 => 4096.0, - 173 => 5120.0, - 174 => 6144.0, - 175 => 7168.0, - 176 => 8192.0, - 177 => 10240.0, - 178 => 12288.0, - 179 => 14336.0, - 180 => 16384.0, - 181 => 20480.0, - 182 => 24576.0, - 183 => 28672.0, - 184 => 32768.0, - 185 => 40960.0, - 186 => 49152.0, - 187 => 57344.0, - 188 => 65536.0, - 189 => 81920.0, - 190 => 98304.0, - 191 => 114688.0, - 192 => 131072.0, - 193 => 163840.0, - 194 => 196608.0, - 195 => 229376.0, - 196 => 262144.0, - 197 => 327680.0, - 198 => 393216.0, - 199 => 458752.0, - 200 => 524288.0, - 201 => 655360.0, - 202 => 786432.0, - 203 => 917504.0, - 204 => 1048576.0, - 205 => 1310720.0, - 206 => 1572864.0, - 207 => 1835008.0, - 208 => 2097152.0, - 209 => 2621440.0, - 210 => 3145728.0, - 211 => 3670016.0, - 212 => 4194304.0, - 213 => 5242880.0, - 214 => 6291456.0, - 215 => 7340032.0, - 216 => 8388608.0, - 217 => 1.048576E7, - 218 => 1.2582912E7, - 219 => 1.4680064E7, - 220 => 1.6777216E7, - 221 => 2.097152E7, - 222 => 2.5165824E7, - 223 => 2.9360128E7, - 224 => 3.3554432E7, - 225 => 4.194304E7, - 226 => 5.0331648E7, - 227 => 5.8720256E7, - 228 => 6.7108864E7, - 229 => 8.388608E7, - 230 => 1.00663296E8, - 231 => 1.17440512E8, - 232 => 1.34217728E8, - 233 => 1.6777216E8, - 234 => 2.01326592E8, - 235 => 2.34881024E8, - 236 => 2.68435456E8, - 237 => 3.3554432E8, - 238 => 4.02653184E8, - 239 => 4.69762048E8, - 240 => 5.3687091E8, - 241 => 6.7108864E8, - 242 => 8.0530637E8, - 243 => 9.395241E8, - 244 => 1.07374182E9, - 245 => 1.34217728E9, - 246 => 1.61061274E9, - 247 => 1.87904819E9, - 248 => 2.14748365E9, - 249 => 2.68435456E9, - 250 => 3.22122547E9, - 251 => 3.75809638E9, - 252 => 4.2949673E9, - 253 => 5.3687091E9, - 254 => 6.4424509E9, - 255 => 7.5161928E9 ); - - - /** - * Set the default Similarity implementation used by indexing and search - * code. - * - * @param Zend_Search_Lucene_Search_Similarity $similarity - */ - public static function setDefault(Zend_Search_Lucene_Search_Similarity $similarity) - { - self::$_defaultImpl = $similarity; - } - - - /** - * Return the default Similarity implementation used by indexing and search - * code. - * - * @return Zend_Search_Lucene_Search_Similarity - */ - public static function getDefault() - { - if (!self::$_defaultImpl instanceof Zend_Search_Lucene_Search_Similarity) { - #require_once 'Zend/Search/Lucene/Search/Similarity/Default.php'; - self::$_defaultImpl = new Zend_Search_Lucene_Search_Similarity_Default(); - } - - return self::$_defaultImpl; - } - - - /** - * Computes the normalization value for a field given the total number of - * terms contained in a field. These values, together with field boosts, are - * stored in an index and multipled into scores for hits on each field by the - * search code. - * - * Matches in longer fields are less precise, so implemenations of this - * method usually return smaller values when 'numTokens' is large, - * and larger values when 'numTokens' is small. - * - * That these values are computed under - * IndexWriter::addDocument(Document) and stored then using - * encodeNorm(float). Thus they have limited precision, and documents - * must be re-indexed if this method is altered. - * - * fieldName - name of field - * numTokens - the total number of tokens contained in fields named - * 'fieldName' of 'doc'. - * Returns a normalization factor for hits on this field of this document - * - * @param string $fieldName - * @param integer $numTokens - * @return float - */ - abstract public function lengthNorm($fieldName, $numTokens); - - /** - * Computes the normalization value for a query given the sum of the squared - * weights of each of the query terms. This value is then multipled into the - * weight of each query term. - * - * This does not affect ranking, but rather just attempts to make scores - * from different queries comparable. - * - * sumOfSquaredWeights - the sum of the squares of query term weights - * Returns a normalization factor for query weights - * - * @param float $sumOfSquaredWeights - * @return float - */ - abstract public function queryNorm($sumOfSquaredWeights); - - - /** - * Decodes a normalization factor stored in an index. - * - * @param integer $byte - * @return float - */ - public static function decodeNorm($byte) - { - return self::$_normTable[$byte & 0xFF]; - } - - - /** - * Encodes a normalization factor for storage in an index. - * - * The encoding uses a five-bit exponent and three-bit mantissa, thus - * representing values from around 7x10^9 to 2x10^-9 with about one - * significant decimal digit of accuracy. Zero is also represented. - * Negative numbers are rounded up to zero. Values too large to represent - * are rounded down to the largest representable value. Positive values too - * small to represent are rounded up to the smallest positive representable - * value. - * - * @param float $f - * @return integer - */ - static function encodeNorm($f) - { - return self::_floatToByte($f); - } - - /** - * Float to byte conversion - * - * @param integer $b - * @return float - */ - 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; - } - } - - - /** - * Computes a score factor based on a term or phrase's frequency in a - * document. This value is multiplied by the idf(Term, Searcher) - * factor for each term in the query and these products are then summed to - * form the initial score for a document. - * - * Terms and phrases repeated in a document indicate the topic of the - * document, so implementations of this method usually return larger values - * when 'freq' is large, and smaller values when 'freq' - * is small. - * - * freq - the frequency of a term within a document - * Returns a score factor based on a term's within-document frequency - * - * @param float $freq - * @return float - */ - abstract public function tf($freq); - - /** - * Computes the amount of a sloppy phrase match, based on an edit distance. - * This value is summed for each sloppy phrase match in a document to form - * the frequency that is passed to tf(float). - * - * A phrase match with a small edit distance to a document passage more - * closely matches the document, so implementations of this method usually - * return larger values when the edit distance is small and smaller values - * when it is large. - * - * distance - the edit distance of this sloppy phrase match - * Returns the frequency increment for this match - * - * @param integer $distance - * @return float - */ - abstract public function sloppyFreq($distance); - - - /** - * 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 - */ - 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 based on a term's document frequency (the number - * of documents which contain the term). This value is multiplied by the - * tf(int) factor for each term in the query and these products are - * then summed to form the initial score for a document. - * - * Terms that occur in fewer documents are better indicators of topic, so - * implemenations of this method usually return larger values for rare terms, - * and smaller values for common terms. - * - * docFreq - the number of documents which contain the term - * numDocs - the total number of documents in the collection - * Returns a score factor based on the term's document frequency - * - * @param integer $docFreq - * @param integer $numDocs - * @return float - */ - abstract public function idfFreq($docFreq, $numDocs); - - /** - * Computes a score factor based on the fraction of all query terms that a - * document contains. This value is multiplied into scores. - * - * The presence of a large portion of the query terms indicates a better - * match with the query, so implemenations of this method usually return - * larger values when the ratio between these parameters is large and smaller - * values when the ratio between them is small. - * - * overlap - the number of query terms matched in the document - * maxOverlap - the total number of terms in the query - * Returns a score factor based on term overlap with the query - * - * @param integer $overlap - * @param integer $maxOverlap - * @return float - */ - abstract public function coord($overlap, $maxOverlap); -} - diff --git a/library/Zend/Search/Lucene/Search/Similarity/Default.php b/library/Zend/Search/Lucene/Search/Similarity/Default.php deleted file mode 100644 index 814e43379f..0000000000 --- a/library/Zend/Search/Lucene/Search/Similarity/Default.php +++ /dev/null @@ -1,110 +0,0 @@ -createWeight(). - * The sumOfSquaredWeights() method is then called on the top-level - * query to compute the query normalization factor Similarity->queryNorm(float). - * This factor is then passed to normalize(float). At this point the weighting - * is complete. - * - * @category Zend - * @package Zend_Search_Lucene - * @subpackage Search - * @copyright Copyright (c) 2005-2015 Zend Technologies USA Inc. (http://www.zend.com) - * @license http://framework.zend.com/license/new-bsd New BSD License - */ -abstract class Zend_Search_Lucene_Search_Weight -{ - /** - * Normalization factor. - * This value is stored only for query expanation purpose and not used in any other place - * - * @var float - */ - protected $_queryNorm; - - /** - * Weight value - * - * Weight value may be initialized in sumOfSquaredWeights() or normalize() - * because they both are invoked either in Query::_initWeight (for top-level query) or - * in corresponding methods of parent query's weights - * - * @var float - */ - protected $_value; - - - /** - * The weight for this query. - * - * @return float - */ - public function getValue() - { - return $this->_value; - } - - /** - * The sum of squared weights of contained query clauses. - * - * @return float - */ - abstract public function sumOfSquaredWeights(); - - /** - * Assigns the query normalization factor to this. - * - * @param float $norm - */ - abstract public function normalize($norm); -} - diff --git a/library/Zend/Search/Lucene/Search/Weight/Boolean.php b/library/Zend/Search/Lucene/Search/Weight/Boolean.php deleted file mode 100644 index c93bd6e7a9..0000000000 --- a/library/Zend/Search/Lucene/Search/Weight/Boolean.php +++ /dev/null @@ -1,137 +0,0 @@ -_query = $query; - $this->_reader = $reader; - $this->_weights = array(); - - $signs = $query->getSigns(); - - foreach ($query->getSubqueries() as $num => $subquery) { - if ($signs === null || $signs[$num] === null || $signs[$num]) { - $this->_weights[$num] = $subquery->createWeight($reader); - } - } - } - - - /** - * The weight for this query - * Standard Weight::$_value is not used for boolean queries - * - * @return float - */ - public function getValue() - { - return $this->_query->getBoost(); - } - - - /** - * The sum of squared weights of contained query clauses. - * - * @return float - */ - public function sumOfSquaredWeights() - { - $sum = 0; - foreach ($this->_weights as $weight) { - // sum sub weights - $sum += $weight->sumOfSquaredWeights(); - } - - // boost each sub-weight - $sum *= $this->_query->getBoost() * $this->_query->getBoost(); - - // check for empty query (like '-something -another') - if ($sum == 0) { - $sum = 1.0; - } - return $sum; - } - - - /** - * Assigns the query normalization factor to this. - * - * @param float $queryNorm - */ - public function normalize($queryNorm) - { - // incorporate boost - $queryNorm *= $this->_query->getBoost(); - - foreach ($this->_weights as $weight) { - $weight->normalize($queryNorm); - } - } -} - - diff --git a/library/Zend/Search/Lucene/Search/Weight/Empty.php b/library/Zend/Search/Lucene/Search/Weight/Empty.php deleted file mode 100644 index 77ea34c3ef..0000000000 --- a/library/Zend/Search/Lucene/Search/Weight/Empty.php +++ /dev/null @@ -1,57 +0,0 @@ -_query = $query; - $this->_reader = $reader; - $this->_weights = array(); - - $signs = $query->getSigns(); - - foreach ($query->getTerms() as $id => $term) { - if ($signs === null || $signs[$id] === null || $signs[$id]) { - #require_once 'Zend/Search/Lucene/Search/Weight/Term.php'; - $this->_weights[$id] = new Zend_Search_Lucene_Search_Weight_Term($term, $query, $reader); - $query->setWeight($id, $this->_weights[$id]); - } - } - } - - - /** - * The weight for this query - * Standard Weight::$_value is not used for boolean queries - * - * @return float - */ - public function getValue() - { - return $this->_query->getBoost(); - } - - - /** - * The sum of squared weights of contained query clauses. - * - * @return float - */ - public function sumOfSquaredWeights() - { - $sum = 0; - foreach ($this->_weights as $weight) { - // sum sub weights - $sum += $weight->sumOfSquaredWeights(); - } - - // boost each sub-weight - $sum *= $this->_query->getBoost() * $this->_query->getBoost(); - - // check for empty query (like '-something -another') - if ($sum == 0) { - $sum = 1.0; - } - return $sum; - } - - - /** - * Assigns the query normalization factor to this. - * - * @param float $queryNorm - */ - public function normalize($queryNorm) - { - // incorporate boost - $queryNorm *= $this->_query->getBoost(); - - foreach ($this->_weights as $weight) { - $weight->normalize($queryNorm); - } - } -} - - diff --git a/library/Zend/Search/Lucene/Search/Weight/Phrase.php b/library/Zend/Search/Lucene/Search/Weight/Phrase.php deleted file mode 100644 index 9df6011df2..0000000000 --- a/library/Zend/Search/Lucene/Search/Weight/Phrase.php +++ /dev/null @@ -1,108 +0,0 @@ -_query = $query; - $this->_reader = $reader; - } - - /** - * The sum of squared weights of contained query clauses. - * - * @return float - */ - 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; - } - - - /** - * Assigns the query normalization factor to this. - * - * @param float $queryNorm - */ - public function normalize($queryNorm) - { - $this->_queryNorm = $queryNorm; - - // normalize query weight - $this->_queryWeight *= $queryNorm; - - // idf for documents - $this->_value = $this->_queryWeight * $this->_idf; - } -} - - diff --git a/library/Zend/Search/Lucene/Search/Weight/Term.php b/library/Zend/Search/Lucene/Search/Weight/Term.php deleted file mode 100644 index 40edbab393..0000000000 --- a/library/Zend/Search/Lucene/Search/Weight/Term.php +++ /dev/null @@ -1,125 +0,0 @@ -_term = $term; - $this->_query = $query; - $this->_reader = $reader; - } - - - /** - * The sum of squared weights of contained query clauses. - * - * @return float - */ - public function sumOfSquaredWeights() - { - // compute idf - $this->_idf = $this->_reader->getSimilarity()->idf($this->_term, $this->_reader); - - // compute query weight - $this->_queryWeight = $this->_idf * $this->_query->getBoost(); - - // square it - return $this->_queryWeight * $this->_queryWeight; - } - - - /** - * Assigns the query normalization factor to this. - * - * @param float $queryNorm - */ - public function normalize($queryNorm) - { - $this->_queryNorm = $queryNorm; - - // normalize query weight - $this->_queryWeight *= $queryNorm; - - // idf for documents - $this->_value = $this->_queryWeight * $this->_idf; - } -} - diff --git a/library/Zend/Search/Lucene/Storage/Directory.php b/library/Zend/Search/Lucene/Storage/Directory.php deleted file mode 100644 index 1dd550520c..0000000000 --- a/library/Zend/Search/Lucene/Storage/Directory.php +++ /dev/null @@ -1,136 +0,0 @@ - Zend_Search_Lucene_Storage_File object - * - * @var array - * @throws Zend_Search_Lucene_Exception - */ - protected $_fileHandlers; - - /** - * Default file permissions - * - * @var integer - */ - protected static $_defaultFilePermissions = 0666; - - - /** - * Get default file permissions - * - * @return integer - */ - public static function getDefaultFilePermissions() - { - return self::$_defaultFilePermissions; - } - - /** - * Set default file permissions - * - * @param integer $mode - */ - public static function setDefaultFilePermissions($mode) - { - self::$_defaultFilePermissions = $mode; - } - - - /** - * Utility function to recursive directory creation - * - * @param string $dir - * @param integer $mode - * @param boolean $recursive - * @return boolean - */ - - public static function mkdirs($dir, $mode = 0775, $recursive = true) - { - $mode = $mode & ~0002; - - if (($dir === null) || $dir === '') { - return false; - } - if (is_dir($dir) || $dir === '/') { - return true; - } - if (self::mkdirs(dirname($dir), $mode, $recursive)) { - return mkdir($dir, $mode); - } - return false; - } - - - /** - * Object constructor - * Checks if $path is a directory or tries to create it. - * - * @param string $path - * @throws Zend_Search_Lucene_Exception - */ - public function __construct($path) - { - if (!is_dir($path)) { - if (file_exists($path)) { - #require_once 'Zend/Search/Lucene/Exception.php'; - throw new Zend_Search_Lucene_Exception('Path exists, but it\'s not a directory'); - } else { - if (!self::mkdirs($path)) { - #require_once 'Zend/Search/Lucene/Exception.php'; - throw new Zend_Search_Lucene_Exception("Can't create directory '$path'."); - } - } - } - $this->_dirPath = $path; - $this->_fileHandlers = array(); - } - - - /** - * Closes the store. - * - * @return void - */ - public function close() - { - foreach ($this->_fileHandlers as $fileObject) { - $fileObject->close(); - } - - $this->_fileHandlers = array(); - } - - - /** - * Returns an array of strings, one for each file in the directory. - * - * @return array - */ - public function fileList() - { - $result = array(); - - $dirContent = opendir( $this->_dirPath ); - while (($file = readdir($dirContent)) !== false) { - if (($file == '..')||($file == '.')) continue; - - if( !is_dir($this->_dirPath . '/' . $file) ) { - $result[] = $file; - } - } - closedir($dirContent); - - return $result; - } - - /** - * Creates a new, empty file in the directory with the given $filename. - * - * @param string $filename - * @return Zend_Search_Lucene_Storage_File - * @throws Zend_Search_Lucene_Exception - */ - public function createFile($filename) - { - if (isset($this->_fileHandlers[$filename])) { - $this->_fileHandlers[$filename]->close(); - } - unset($this->_fileHandlers[$filename]); - #require_once 'Zend/Search/Lucene/Storage/File/Filesystem.php'; - $this->_fileHandlers[$filename] = new Zend_Search_Lucene_Storage_File_Filesystem($this->_dirPath . '/' . $filename, 'w+b'); - - // Set file permissions, but don't care about any possible failures, since file may be already - // created by anther user which has to care about right permissions - @chmod($this->_dirPath . '/' . $filename, self::$_defaultFilePermissions); - - return $this->_fileHandlers[$filename]; - } - - - /** - * Removes an existing $filename in the directory. - * - * @param string $filename - * @return void - * @throws Zend_Search_Lucene_Exception - */ - public function deleteFile($filename) - { - if (isset($this->_fileHandlers[$filename])) { - $this->_fileHandlers[$filename]->close(); - } - unset($this->_fileHandlers[$filename]); - - global $php_errormsg; - $trackErrors = ini_get('track_errors'); - ini_set('track_errors', '1'); - if (!@unlink($this->_dirPath . '/' . $filename)) { - ini_set('track_errors', $trackErrors); - #require_once 'Zend/Search/Lucene/Exception.php'; - throw new Zend_Search_Lucene_Exception('Can\'t delete file: ' . $php_errormsg); - } - ini_set('track_errors', $trackErrors); - } - - /** - * Purge file if it's cached by directory object - * - * Method is used to prevent 'too many open files' error - * - * @param string $filename - * @return void - */ - public function purgeFile($filename) - { - if (isset($this->_fileHandlers[$filename])) { - $this->_fileHandlers[$filename]->close(); - } - unset($this->_fileHandlers[$filename]); - } - - - /** - * Returns true if a file with the given $filename exists. - * - * @param string $filename - * @return boolean - */ - public function fileExists($filename) - { - return isset($this->_fileHandlers[$filename]) || - file_exists($this->_dirPath . '/' . $filename); - } - - - /** - * Returns the length of a $filename in the directory. - * - * @param string $filename - * @return integer - */ - public function fileLength($filename) - { - if (isset( $this->_fileHandlers[$filename] )) { - return $this->_fileHandlers[$filename]->size(); - } - return filesize($this->_dirPath .'/'. $filename); - } - - - /** - * Returns the UNIX timestamp $filename was last modified. - * - * @param string $filename - * @return integer - */ - public function fileModified($filename) - { - return filemtime($this->_dirPath .'/'. $filename); - } - - - /** - * Renames an existing file in the directory. - * - * @param string $from - * @param string $to - * @return void - * @throws Zend_Search_Lucene_Exception - */ - public function renameFile($from, $to) - { - global $php_errormsg; - - if (isset($this->_fileHandlers[$from])) { - $this->_fileHandlers[$from]->close(); - } - unset($this->_fileHandlers[$from]); - - if (isset($this->_fileHandlers[$to])) { - $this->_fileHandlers[$to]->close(); - } - unset($this->_fileHandlers[$to]); - - if (file_exists($this->_dirPath . '/' . $to)) { - if (!unlink($this->_dirPath . '/' . $to)) { - #require_once 'Zend/Search/Lucene/Exception.php'; - throw new Zend_Search_Lucene_Exception('Delete operation failed'); - } - } - - $trackErrors = ini_get('track_errors'); - ini_set('track_errors', '1'); - - $success = @rename($this->_dirPath . '/' . $from, $this->_dirPath . '/' . $to); - if (!$success) { - ini_set('track_errors', $trackErrors); - #require_once 'Zend/Search/Lucene/Exception.php'; - throw new Zend_Search_Lucene_Exception($php_errormsg); - } - - ini_set('track_errors', $trackErrors); - - return $success; - } - - - /** - * Sets the modified time of $filename to now. - * - * @param string $filename - * @return void - */ - public function touchFile($filename) - { - return touch($this->_dirPath .'/'. $filename); - } - - - /** - * Returns a Zend_Search_Lucene_Storage_File object for a given $filename in the directory. - * - * If $shareHandler option is true, then file handler can be shared between File Object - * requests. It speed-ups performance, but makes problems with file position. - * Shared handler are good for short atomic requests. - * Non-shared handlers are useful for stream file reading (especial for compound files). - * - * @param string $filename - * @param boolean $shareHandler - * @return Zend_Search_Lucene_Storage_File - */ - public function getFileObject($filename, $shareHandler = true) - { - $fullFilename = $this->_dirPath . '/' . $filename; - - #require_once 'Zend/Search/Lucene/Storage/File/Filesystem.php'; - if (!$shareHandler) { - return new Zend_Search_Lucene_Storage_File_Filesystem($fullFilename); - } - - if (isset( $this->_fileHandlers[$filename] )) { - $this->_fileHandlers[$filename]->seek(0); - return $this->_fileHandlers[$filename]; - } - - $this->_fileHandlers[$filename] = new Zend_Search_Lucene_Storage_File_Filesystem($fullFilename); - return $this->_fileHandlers[$filename]; - } -} diff --git a/library/Zend/Search/Lucene/Storage/File.php b/library/Zend/Search/Lucene/Storage/File.php deleted file mode 100644 index e39235f137..0000000000 --- a/library/Zend/Search/Lucene/Storage/File.php +++ /dev/null @@ -1,473 +0,0 @@ -_fread(1)); - } - - /** - * Writes a byte to the end of the file. - * - * @param integer $byte - */ - public function writeByte($byte) - { - return $this->_fwrite(chr($byte), 1); - } - - /** - * Read num bytes from the current position in the file - * and advances the file pointer. - * - * @param integer $num - * @return string - */ - public function readBytes($num) - { - return $this->_fread($num); - } - - /** - * Writes num bytes of data (all, if $num===null) to the end - * of the string. - * - * @param string $data - * @param integer $num - */ - public function writeBytes($data, $num=null) - { - $this->_fwrite($data, $num); - } - - - /** - * Reads an integer from the current position in the file - * and advances the file pointer. - * - * @return integer - */ - public function readInt() - { - $str = $this->_fread(4); - - return ord($str[0]) << 24 | - ord($str[1]) << 16 | - ord($str[2]) << 8 | - ord($str[3]); - } - - - /** - * Writes an integer to the end of file. - * - * @param integer $value - */ - public function writeInt($value) - { - settype($value, 'integer'); - $this->_fwrite( chr($value>>24 & 0xFF) . - chr($value>>16 & 0xFF) . - chr($value>>8 & 0xFF) . - chr($value & 0xFF), 4 ); - } - - - /** - * Returns a long integer from the current position in the file - * and advances the file pointer. - * - * @return integer|float - * @throws Zend_Search_Lucene_Exception - */ - public function readLong() - { - /** - * Check, that we work in 64-bit mode. - * fseek() uses long for offset. Thus, largest index segment file size in 32bit mode is 2Gb - */ - if (PHP_INT_SIZE > 4) { - $str = $this->_fread(8); - - return ord($str[0]) << 56 | - ord($str[1]) << 48 | - ord($str[2]) << 40 | - ord($str[3]) << 32 | - ord($str[4]) << 24 | - ord($str[5]) << 16 | - ord($str[6]) << 8 | - ord($str[7]); - } else { - return $this->readLong32Bit(); - } - } - - /** - * Writes long integer to the end of file - * - * @param integer $value - * @throws Zend_Search_Lucene_Exception - */ - public function writeLong($value) - { - /** - * Check, that we work in 64-bit mode. - * fseek() and ftell() use long for offset. Thus, largest index segment file size in 32bit mode is 2Gb - */ - if (PHP_INT_SIZE > 4) { - settype($value, 'integer'); - $this->_fwrite( chr($value>>56 & 0xFF) . - chr($value>>48 & 0xFF) . - chr($value>>40 & 0xFF) . - chr($value>>32 & 0xFF) . - chr($value>>24 & 0xFF) . - chr($value>>16 & 0xFF) . - chr($value>>8 & 0xFF) . - chr($value & 0xFF), 8 ); - } else { - $this->writeLong32Bit($value); - } - } - - - /** - * Returns a long integer from the current position in the file, - * advances the file pointer and return it as float (for 32-bit platforms). - * - * @return integer|float - * @throws Zend_Search_Lucene_Exception - */ - public function readLong32Bit() - { - $wordHigh = $this->readInt(); - $wordLow = $this->readInt(); - - if ($wordHigh & (int)0x80000000) { - // It's a negative value since the highest bit is set - if ($wordHigh == (int)0xFFFFFFFF && ($wordLow & (int)0x80000000)) { - return $wordLow; - } else { - #require_once 'Zend/Search/Lucene/Exception.php'; - throw new Zend_Search_Lucene_Exception('Long integers lower than -2147483648 (0x80000000) are not supported on 32-bit platforms.'); - } - - } - - if ($wordLow < 0) { - // Value is large than 0x7FFF FFFF. Represent low word as float. - $wordLow &= 0x7FFFFFFF; - $wordLow += (float)0x80000000; - } - - if ($wordHigh == 0) { - // Return value as integer if possible - return $wordLow; - } - - return $wordHigh*(float)0x100000000/* 0x00000001 00000000 */ + $wordLow; - } - - - /** - * Writes long integer to the end of file (32-bit platforms implementation) - * - * @param integer|float $value - * @throws Zend_Search_Lucene_Exception - */ - public function writeLong32Bit($value) - { - if ($value < (int)0x80000000) { - #require_once 'Zend/Search/Lucene/Exception.php'; - throw new Zend_Search_Lucene_Exception('Long integers lower than -2147483648 (0x80000000) are not supported on 32-bit platforms.'); - } - - if ($value < 0) { - $wordHigh = (int)0xFFFFFFFF; - $wordLow = (int)$value; - } else { - $wordHigh = (int)($value/(float)0x100000000/* 0x00000001 00000000 */); - $wordLow = $value - $wordHigh*(float)0x100000000/* 0x00000001 00000000 */; - - if ($wordLow > 0x7FFFFFFF) { - // Highest bit of low word is set. Translate it to the corresponding negative integer value - $wordLow -= 0x80000000; - $wordLow |= 0x80000000; - } - } - - $this->writeInt($wordHigh); - $this->writeInt($wordLow); - } - - - /** - * Returns a variable-length integer from the current - * position in the file and advances the file pointer. - * - * @return integer - */ - public function readVInt() - { - $nextByte = ord($this->_fread(1)); - $val = $nextByte & 0x7F; - - for ($shift=7; ($nextByte & 0x80) != 0; $shift += 7) { - $nextByte = ord($this->_fread(1)); - $val |= ($nextByte & 0x7F) << $shift; - } - return $val; - } - - /** - * Writes a variable-length integer to the end of file. - * - * @param integer $value - */ - public function writeVInt($value) - { - settype($value, 'integer'); - while ($value > 0x7F) { - $this->_fwrite(chr( ($value & 0x7F)|0x80 )); - $value >>= 7; - } - $this->_fwrite(chr($value)); - } - - - /** - * Reads a string from the current position in the file - * and advances the file pointer. - * - * @return string - */ - public function readString() - { - $strlen = $this->readVInt(); - if ($strlen == 0) { - return ''; - } else { - /** - * This implementation supports only Basic Multilingual Plane - * (BMP) characters (from 0x0000 to 0xFFFF) and doesn't support - * "supplementary characters" (characters whose code points are - * greater than 0xFFFF) - * Java 2 represents these characters as a pair of char (16-bit) - * values, the first from the high-surrogates range (0xD800-0xDBFF), - * the second from the low-surrogates range (0xDC00-0xDFFF). Then - * they are encoded as usual UTF-8 characters in six bytes. - * Standard UTF-8 representation uses four bytes for supplementary - * characters. - */ - - $str_val = $this->_fread($strlen); - - for ($count = 0; $count < $strlen; $count++ ) { - if (( ord($str_val[$count]) & 0xC0 ) == 0xC0) { - $addBytes = 1; - if (ord($str_val[$count]) & 0x20 ) { - $addBytes++; - - // Never used. Java2 doesn't encode strings in four bytes - if (ord($str_val[$count]) & 0x10 ) { - $addBytes++; - } - } - $str_val .= $this->_fread($addBytes); - $strlen += $addBytes; - - // Check for null character. Java2 encodes null character - // in two bytes. - if (ord($str_val[$count]) == 0xC0 && - ord($str_val[$count+1]) == 0x80 ) { - $str_val[$count] = 0; - $str_val = substr($str_val,0,$count+1) - . substr($str_val,$count+2); - } - $count += $addBytes; - } - } - - return $str_val; - } - } - - /** - * Writes a string to the end of file. - * - * @param string $str - * @throws Zend_Search_Lucene_Exception - */ - public function writeString($str) - { - /** - * This implementation supports only Basic Multilingual Plane - * (BMP) characters (from 0x0000 to 0xFFFF) and doesn't support - * "supplementary characters" (characters whose code points are - * greater than 0xFFFF) - * Java 2 represents these characters as a pair of char (16-bit) - * values, the first from the high-surrogates range (0xD800-0xDBFF), - * the second from the low-surrogates range (0xDC00-0xDFFF). Then - * they are encoded as usual UTF-8 characters in six bytes. - * Standard UTF-8 representation uses four bytes for supplementary - * characters. - */ - - // convert input to a string before iterating string characters - settype($str, 'string'); - - $chars = $strlen = strlen($str); - $containNullChars = false; - - for ($count = 0; $count < $strlen; $count++ ) { - /** - * String is already in Java 2 representation. - * We should only calculate actual string length and replace - * \x00 by \xC0\x80 - */ - if ((ord($str[$count]) & 0xC0) == 0xC0) { - $addBytes = 1; - if (ord($str[$count]) & 0x20 ) { - $addBytes++; - - // Never used. Java2 doesn't encode strings in four bytes - // and we dont't support non-BMP characters - if (ord($str[$count]) & 0x10 ) { - $addBytes++; - } - } - $chars -= $addBytes; - - if (ord($str[$count]) == 0 ) { - $containNullChars = true; - } - $count += $addBytes; - } - } - - if ($chars < 0) { - #require_once 'Zend/Search/Lucene/Exception.php'; - throw new Zend_Search_Lucene_Exception('Invalid UTF-8 string'); - } - - $this->writeVInt($chars); - if ($containNullChars) { - $this->_fwrite(str_replace($str, "\x00", "\xC0\x80")); - } else { - $this->_fwrite($str); - } - } - - - /** - * Reads binary data from the current position in the file - * and advances the file pointer. - * - * @return string - */ - public function readBinary() - { - return $this->_fread($this->readVInt()); - } -} diff --git a/library/Zend/Search/Lucene/Storage/File/Filesystem.php b/library/Zend/Search/Lucene/Storage/File/Filesystem.php deleted file mode 100644 index 4a21d8cb87..0000000000 --- a/library/Zend/Search/Lucene/Storage/File/Filesystem.php +++ /dev/null @@ -1,231 +0,0 @@ -_fileHandle = @fopen($filename, $mode); - - if ($this->_fileHandle === false) { - ini_set('track_errors', $trackErrors); - #require_once 'Zend/Search/Lucene/Exception.php'; - throw new Zend_Search_Lucene_Exception($php_errormsg); - } - - ini_set('track_errors', $trackErrors); - } - - /** - * Sets the file position indicator and advances the file pointer. - * The new position, measured in bytes from the beginning of the file, - * is obtained by adding offset to the position specified by whence, - * whose values are defined as follows: - * SEEK_SET - Set position equal to offset bytes. - * SEEK_CUR - Set position to current location plus offset. - * SEEK_END - Set position to end-of-file plus offset. (To move to - * a position before the end-of-file, you need to pass a negative value - * in offset.) - * SEEK_CUR is the only supported offset type for compound files - * - * Upon success, returns 0; otherwise, returns -1 - * - * @param integer $offset - * @param integer $whence - * @return integer - */ - public function seek($offset, $whence=SEEK_SET) - { - return fseek($this->_fileHandle, $offset, $whence); - } - - - /** - * Get file position. - * - * @return integer - */ - public function tell() - { - return ftell($this->_fileHandle); - } - - /** - * Flush output. - * - * Returns true on success or false on failure. - * - * @return boolean - */ - public function flush() - { - return fflush($this->_fileHandle); - } - - /** - * Close File object - */ - public function close() - { - if ($this->_fileHandle !== null ) { - @fclose($this->_fileHandle); - $this->_fileHandle = null; - } - } - - /** - * Get the size of the already opened file - * - * @return integer - */ - public function size() - { - $position = ftell($this->_fileHandle); - fseek($this->_fileHandle, 0, SEEK_END); - $size = ftell($this->_fileHandle); - fseek($this->_fileHandle,$position); - - return $size; - } - - /** - * Read a $length bytes from the file and advance the file pointer. - * - * @param integer $length - * @return string - */ - protected function _fread($length=1) - { - if ($length == 0) { - return ''; - } - - if ($length < 1024) { - return fread($this->_fileHandle, $length); - } - - $data = ''; - while ($length > 0 && !feof($this->_fileHandle)) { - $nextBlock = fread($this->_fileHandle, $length); - if ($nextBlock === false) { - #require_once 'Zend/Search/Lucene/Exception.php'; - throw new Zend_Search_Lucene_Exception( "Error occured while file reading." ); - } - - $data .= $nextBlock; - $length -= strlen($nextBlock); - } - if ($length != 0) { - #require_once 'Zend/Search/Lucene/Exception.php'; - throw new Zend_Search_Lucene_Exception( "Error occured while file reading." ); - } - - return $data; - } - - - /** - * Writes $length number of bytes (all, if $length===null) to the end - * of the file. - * - * @param string $data - * @param integer $length - */ - protected function _fwrite($data, $length=null) - { - if ($length === null ) { - fwrite($this->_fileHandle, $data); - } else { - fwrite($this->_fileHandle, $data, $length); - } - } - - /** - * Lock file - * - * Lock type may be a LOCK_SH (shared lock) or a LOCK_EX (exclusive lock) - * - * @param integer $lockType - * @param boolean $nonBlockingLock - * @return boolean - */ - public function lock($lockType, $nonBlockingLock = false) - { - if ($nonBlockingLock) { - return flock($this->_fileHandle, $lockType | LOCK_NB); - } else { - return flock($this->_fileHandle, $lockType); - } - } - - /** - * Unlock file - * - * Returns true on success - * - * @return boolean - */ - public function unlock() - { - if ($this->_fileHandle !== null ) { - return flock($this->_fileHandle, LOCK_UN); - } else { - return true; - } - } -} - diff --git a/library/Zend/Search/Lucene/Storage/File/Memory.php b/library/Zend/Search/Lucene/Storage/File/Memory.php deleted file mode 100644 index ae10627b2e..0000000000 --- a/library/Zend/Search/Lucene/Storage/File/Memory.php +++ /dev/null @@ -1,601 +0,0 @@ -_data = $data; - } - - /** - * Reads $length number of bytes at the current position in the - * file and advances the file pointer. - * - * @param integer $length - * @return string - */ - protected function _fread($length = 1) - { - $returnValue = substr($this->_data, $this->_position, $length); - $this->_position += $length; - return $returnValue; - } - - - /** - * Sets the file position indicator and advances the file pointer. - * The new position, measured in bytes from the beginning of the file, - * is obtained by adding offset to the position specified by whence, - * whose values are defined as follows: - * SEEK_SET - Set position equal to offset bytes. - * SEEK_CUR - Set position to current location plus offset. - * SEEK_END - Set position to end-of-file plus offset. (To move to - * a position before the end-of-file, you need to pass a negative value - * in offset.) - * Upon success, returns 0; otherwise, returns -1 - * - * @param integer $offset - * @param integer $whence - * @return integer - */ - public function seek($offset, $whence=SEEK_SET) - { - switch ($whence) { - case SEEK_SET: - $this->_position = $offset; - break; - - case SEEK_CUR: - $this->_position += $offset; - break; - - case SEEK_END: - $this->_position = strlen($this->_data); - $this->_position += $offset; - break; - - default: - break; - } - } - - /** - * Get file position. - * - * @return integer - */ - public function tell() - { - return $this->_position; - } - - /** - * Flush output. - * - * Returns true on success or false on failure. - * - * @return boolean - */ - public function flush() - { - // Do nothing - - return true; - } - - /** - * Writes $length number of bytes (all, if $length===null) to the end - * of the file. - * - * @param string $data - * @param integer $length - */ - protected function _fwrite($data, $length=null) - { - // We do not need to check if file position points to the end of "file". - // Only append operation is supported now - - if ($length !== null) { - $this->_data .= substr($data, 0, $length); - } else { - $this->_data .= $data; - } - - $this->_position = strlen($this->_data); - } - - /** - * Lock file - * - * Lock type may be a LOCK_SH (shared lock) or a LOCK_EX (exclusive lock) - * - * @param integer $lockType - * @return boolean - */ - public function lock($lockType, $nonBlockinLock = false) - { - // Memory files can't be shared - // do nothing - - return true; - } - - /** - * Unlock file - */ - public function unlock() - { - // Memory files can't be shared - // do nothing - } - - /** - * Reads a byte from the current position in the file - * and advances the file pointer. - * - * @return integer - */ - public function readByte() - { - return ord($this->_data[$this->_position++]); - } - - /** - * Writes a byte to the end of the file. - * - * @param integer $byte - */ - public function writeByte($byte) - { - // We do not need to check if file position points to the end of "file". - // Only append operation is supported now - - $this->_data .= chr($byte); - $this->_position = strlen($this->_data); - - return 1; - } - - /** - * Read num bytes from the current position in the file - * and advances the file pointer. - * - * @param integer $num - * @return string - */ - public function readBytes($num) - { - $returnValue = substr($this->_data, $this->_position, $num); - $this->_position += $num; - - return $returnValue; - } - - /** - * Writes num bytes of data (all, if $num===null) to the end - * of the string. - * - * @param string $data - * @param integer $num - */ - public function writeBytes($data, $num=null) - { - // We do not need to check if file position points to the end of "file". - // Only append operation is supported now - - if ($num !== null) { - $this->_data .= substr($data, 0, $num); - } else { - $this->_data .= $data; - } - - $this->_position = strlen($this->_data); - } - - - /** - * Reads an integer from the current position in the file - * and advances the file pointer. - * - * @return integer - */ - public function readInt() - { - $str = substr($this->_data, $this->_position, 4); - $this->_position += 4; - - return ord($str[0]) << 24 | - ord($str[1]) << 16 | - ord($str[2]) << 8 | - ord($str[3]); - } - - - /** - * Writes an integer to the end of file. - * - * @param integer $value - */ - public function writeInt($value) - { - // We do not need to check if file position points to the end of "file". - // Only append operation is supported now - - settype($value, 'integer'); - $this->_data .= chr($value>>24 & 0xFF) . - chr($value>>16 & 0xFF) . - chr($value>>8 & 0xFF) . - chr($value & 0xFF); - - $this->_position = strlen($this->_data); - } - - - /** - * Returns a long integer from the current position in the file - * and advances the file pointer. - * - * @return integer - * @throws Zend_Search_Lucene_Exception - */ - public function readLong() - { - /** - * Check, that we work in 64-bit mode. - * fseek() uses long for offset. Thus, largest index segment file size in 32bit mode is 2Gb - */ - if (PHP_INT_SIZE > 4) { - $str = substr($this->_data, $this->_position, 8); - $this->_position += 8; - - return ord($str[0]) << 56 | - ord($str[1]) << 48 | - ord($str[2]) << 40 | - ord($str[3]) << 32 | - ord($str[4]) << 24 | - ord($str[5]) << 16 | - ord($str[6]) << 8 | - ord($str[7]); - } else { - return $this->readLong32Bit(); - } - } - - /** - * Writes long integer to the end of file - * - * @param integer $value - * @throws Zend_Search_Lucene_Exception - */ - public function writeLong($value) - { - // We do not need to check if file position points to the end of "file". - // Only append operation is supported now - - /** - * Check, that we work in 64-bit mode. - * fseek() and ftell() use long for offset. Thus, largest index segment file size in 32bit mode is 2Gb - */ - if (PHP_INT_SIZE > 4) { - settype($value, 'integer'); - $this->_data .= chr($value>>56 & 0xFF) . - chr($value>>48 & 0xFF) . - chr($value>>40 & 0xFF) . - chr($value>>32 & 0xFF) . - chr($value>>24 & 0xFF) . - chr($value>>16 & 0xFF) . - chr($value>>8 & 0xFF) . - chr($value & 0xFF); - } else { - $this->writeLong32Bit($value); - } - - $this->_position = strlen($this->_data); - } - - - /** - * Returns a long integer from the current position in the file, - * advances the file pointer and return it as float (for 32-bit platforms). - * - * @return integer|float - * @throws Zend_Search_Lucene_Exception - */ - public function readLong32Bit() - { - $wordHigh = $this->readInt(); - $wordLow = $this->readInt(); - - if ($wordHigh & (int)0x80000000) { - // It's a negative value since the highest bit is set - if ($wordHigh == (int)0xFFFFFFFF && ($wordLow & (int)0x80000000)) { - return $wordLow; - } else { - #require_once 'Zend/Search/Lucene/Exception.php'; - throw new Zend_Search_Lucene_Exception('Long integers lower than -2147483648 (0x80000000) are not supported on 32-bit platforms.'); - } - - } - - if ($wordLow < 0) { - // Value is large than 0x7FFF FFFF. Represent low word as float. - $wordLow &= 0x7FFFFFFF; - $wordLow += (float)0x80000000; - } - - if ($wordHigh == 0) { - // Return value as integer if possible - return $wordLow; - } - - return $wordHigh*(float)0x100000000/* 0x00000001 00000000 */ + $wordLow; - } - - - /** - * Writes long integer to the end of file (32-bit platforms implementation) - * - * @param integer|float $value - * @throws Zend_Search_Lucene_Exception - */ - public function writeLong32Bit($value) - { - if ($value < (int)0x80000000) { - #require_once 'Zend/Search/Lucene/Exception.php'; - throw new Zend_Search_Lucene_Exception('Long integers lower than -2147483648 (0x80000000) are not supported on 32-bit platforms.'); - } - - if ($value < 0) { - $wordHigh = (int)0xFFFFFFFF; - $wordLow = (int)$value; - } else { - $wordHigh = (int)($value/(float)0x100000000/* 0x00000001 00000000 */); - $wordLow = $value - $wordHigh*(float)0x100000000/* 0x00000001 00000000 */; - - if ($wordLow > 0x7FFFFFFF) { - // Highest bit of low word is set. Translate it to the corresponding negative integer value - $wordLow -= 0x80000000; - $wordLow |= 0x80000000; - } - } - - $this->writeInt($wordHigh); - $this->writeInt($wordLow); - } - - /** - * Returns a variable-length integer from the current - * position in the file and advances the file pointer. - * - * @return integer - */ - public function readVInt() - { - $nextByte = ord($this->_data[$this->_position++]); - $val = $nextByte & 0x7F; - - for ($shift=7; ($nextByte & 0x80) != 0; $shift += 7) { - $nextByte = ord($this->_data[$this->_position++]); - $val |= ($nextByte & 0x7F) << $shift; - } - return $val; - } - - /** - * Writes a variable-length integer to the end of file. - * - * @param integer $value - */ - public function writeVInt($value) - { - // We do not need to check if file position points to the end of "file". - // Only append operation is supported now - - settype($value, 'integer'); - while ($value > 0x7F) { - $this->_data .= chr( ($value & 0x7F)|0x80 ); - $value >>= 7; - } - $this->_data .= chr($value); - - $this->_position = strlen($this->_data); - } - - - /** - * Reads a string from the current position in the file - * and advances the file pointer. - * - * @return string - */ - public function readString() - { - $strlen = $this->readVInt(); - if ($strlen == 0) { - return ''; - } else { - /** - * This implementation supports only Basic Multilingual Plane - * (BMP) characters (from 0x0000 to 0xFFFF) and doesn't support - * "supplementary characters" (characters whose code points are - * greater than 0xFFFF) - * Java 2 represents these characters as a pair of char (16-bit) - * values, the first from the high-surrogates range (0xD800-0xDBFF), - * the second from the low-surrogates range (0xDC00-0xDFFF). Then - * they are encoded as usual UTF-8 characters in six bytes. - * Standard UTF-8 representation uses four bytes for supplementary - * characters. - */ - - $str_val = substr($this->_data, $this->_position, $strlen); - $this->_position += $strlen; - - for ($count = 0; $count < $strlen; $count++ ) { - if (( ord($str_val[$count]) & 0xC0 ) == 0xC0) { - $addBytes = 1; - if (ord($str_val[$count]) & 0x20 ) { - $addBytes++; - - // Never used. Java2 doesn't encode strings in four bytes - if (ord($str_val[$count]) & 0x10 ) { - $addBytes++; - } - } - $str_val .= substr($this->_data, $this->_position, $addBytes); - $this->_position += $addBytes; - $strlen += $addBytes; - - // Check for null character. Java2 encodes null character - // in two bytes. - if (ord($str_val[$count]) == 0xC0 && - ord($str_val[$count+1]) == 0x80 ) { - $str_val[$count] = 0; - $str_val = substr($str_val,0,$count+1) - . substr($str_val,$count+2); - } - $count += $addBytes; - } - } - - return $str_val; - } - } - - /** - * Writes a string to the end of file. - * - * @param string $str - * @throws Zend_Search_Lucene_Exception - */ - public function writeString($str) - { - /** - * This implementation supports only Basic Multilingual Plane - * (BMP) characters (from 0x0000 to 0xFFFF) and doesn't support - * "supplementary characters" (characters whose code points are - * greater than 0xFFFF) - * Java 2 represents these characters as a pair of char (16-bit) - * values, the first from the high-surrogates range (0xD800-0xDBFF), - * the second from the low-surrogates range (0xDC00-0xDFFF). Then - * they are encoded as usual UTF-8 characters in six bytes. - * Standard UTF-8 representation uses four bytes for supplementary - * characters. - */ - - // We do not need to check if file position points to the end of "file". - // Only append operation is supported now - - // convert input to a string before iterating string characters - settype($str, 'string'); - - $chars = $strlen = strlen($str); - $containNullChars = false; - - for ($count = 0; $count < $strlen; $count++ ) { - /** - * String is already in Java 2 representation. - * We should only calculate actual string length and replace - * \x00 by \xC0\x80 - */ - if ((ord($str[$count]) & 0xC0) == 0xC0) { - $addBytes = 1; - if (ord($str[$count]) & 0x20 ) { - $addBytes++; - - // Never used. Java2 doesn't encode strings in four bytes - // and we dont't support non-BMP characters - if (ord($str[$count]) & 0x10 ) { - $addBytes++; - } - } - $chars -= $addBytes; - - if (ord($str[$count]) == 0 ) { - $containNullChars = true; - } - $count += $addBytes; - } - } - - if ($chars < 0) { - #require_once 'Zend/Search/Lucene/Exception.php'; - throw new Zend_Search_Lucene_Exception('Invalid UTF-8 string'); - } - - $this->writeVInt($chars); - if ($containNullChars) { - $this->_data .= str_replace($str, "\x00", "\xC0\x80"); - - } else { - $this->_data .= $str; - } - - $this->_position = strlen($this->_data); - } - - - /** - * Reads binary data from the current position in the file - * and advances the file pointer. - * - * @return string - */ - public function readBinary() - { - $length = $this->readVInt(); - $returnValue = substr($this->_data, $this->_position, $length); - $this->_position += $length; - return $returnValue; - } -} - diff --git a/library/Zend/Search/Lucene/TermStreamsPriorityQueue.php b/library/Zend/Search/Lucene/TermStreamsPriorityQueue.php deleted file mode 100644 index 36c404557d..0000000000 --- a/library/Zend/Search/Lucene/TermStreamsPriorityQueue.php +++ /dev/null @@ -1,172 +0,0 @@ -_termStreams = $termStreams; - - $this->resetTermsStream(); - } - - /** - * Reset terms stream. - */ - public function resetTermsStream() - { - /** Zend_Search_Lucene_Index_TermsPriorityQueue */ - #require_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(); - } - - /** - * Skip terms stream up to the specified term preffix. - * - * Prefix contains fully specified field info and portion of searched term - * - * @param Zend_Search_Lucene_Index_Term $prefix - */ - public function skipTo(Zend_Search_Lucene_Index_Term $prefix) - { - $this->_termsStreamQueue = new Zend_Search_Lucene_Index_TermsPriorityQueue(); - - foreach ($this->_termStreams as $termStream) { - $termStream->skipTo($prefix); - - if ($termStream->currentTerm() !== null) { - $this->_termsStreamQueue->put($termStream); - } - } - - return $this->nextTerm(); - } - - /** - * Scans term streams and returns next term - * - * @return Zend_Search_Lucene_Index_Term|null - */ - 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; - } - - /** - * Returns term in current position - * - * @return Zend_Search_Lucene_Index_Term|null - */ - public function currentTerm() - { - return $this->_lastTerm; - } - - /** - * Close terms stream - * - * Should be used for resources clean up if stream is not read up to the end - */ - public function closeTermsStream() - { - while (($termStream = $this->_termsStreamQueue->pop()) !== null) { - $termStream->closeTermsStream(); - } - - $this->_termsStreamQueue = null; - $this->_lastTerm = null; - } -} diff --git a/library/Zend/Serializer.php b/library/Zend/Serializer.php deleted file mode 100644 index b25489b06c..0000000000 --- a/library/Zend/Serializer.php +++ /dev/null @@ -1,188 +0,0 @@ -load($adapterName); - } catch (Exception $e) { - #require_once 'Zend/Serializer/Exception.php'; - throw new Zend_Serializer_Exception('Can\'t load serializer adapter "'.$adapterName.'"', 0, $e); - } - - // ZF-8842: - // check that the loaded class implements Zend_Serializer_Adapter_AdapterInterface without execute code - if (!in_array('Zend_Serializer_Adapter_AdapterInterface', class_implements($adapterClass))) { - #require_once 'Zend/Serializer/Exception.php'; - throw new Zend_Serializer_Exception('The serializer adapter class "'.$adapterClass.'" must implement Zend_Serializer_Adapter_AdapterInterface'); - } - - return new $adapterClass($opts); - } - - /** - * Get the adapter plugin loader. - * - * @return Zend_Loader_PluginLoader - */ - public static function getAdapterLoader() - { - if (self::$_adapterLoader === null) { - self::$_adapterLoader = self::_getDefaultAdapterLoader(); - } - return self::$_adapterLoader; - } - - /** - * Change the adapter plugin load. - * - * @param Zend_Loader_PluginLoader $pluginLoader - * @return void - */ - public static function setAdapterLoader(Zend_Loader_PluginLoader $pluginLoader) - { - self::$_adapterLoader = $pluginLoader; - } - - /** - * Resets the internal adapter plugin loader - * - * @return Zend_Loader_PluginLoader - */ - public static function resetAdapterLoader() - { - self::$_adapterLoader = self::_getDefaultAdapterLoader(); - return self::$_adapterLoader; - } - - /** - * Returns a default adapter plugin loader - * - * @return Zend_Loader_PluginLoader - */ - protected static function _getDefaultAdapterLoader() - { - $loader = new Zend_Loader_PluginLoader(); - $loader->addPrefixPath('Zend_Serializer_Adapter', dirname(__FILE__).'/Serializer/Adapter'); - return $loader; - } - - /** - * Change the default adapter. - * - * @param string|Zend_Serializer_Adapter_AdapterInterface $adapter - * @param array|Zend_Config $options - */ - public static function setDefaultAdapter($adapter, $options = array()) - { - self::$_defaultAdapter = self::factory($adapter, $options); - } - - /** - * Get the default adapter. - * - * @return Zend_Serializer_Adapter_AdapterInterface - */ - public static function getDefaultAdapter() - { - if (!self::$_defaultAdapter instanceof Zend_Serializer_Adapter_AdapterInterface) { - self::setDefaultAdapter(self::$_defaultAdapter); - } - return self::$_defaultAdapter; - } - - /** - * Generates a storable representation of a value using the default adapter. - * - * @param mixed $value - * @param array $options - * @return string - * @throws Zend_Serializer_Exception - */ - public static function serialize($value, array $options = array()) - { - if (isset($options['adapter'])) { - $adapter = self::factory($options['adapter']); - unset($options['adapter']); - } else { - $adapter = self::getDefaultAdapter(); - } - - return $adapter->serialize($value, $options); - } - - /** - * Creates a PHP value from a stored representation using the default adapter. - * - * @param string $serialized - * @param array $options - * @return mixed - * @throws Zend_Serializer_Exception - */ - public static function unserialize($serialized, array $options = array()) - { - if (isset($options['adapter'])) { - $adapter = self::factory($options['adapter']); - unset($options['adapter']); - } else { - $adapter = self::getDefaultAdapter(); - } - - return $adapter->unserialize($serialized, $options); - } -} diff --git a/library/Zend/Serializer/Adapter/AdapterAbstract.php b/library/Zend/Serializer/Adapter/AdapterAbstract.php deleted file mode 100644 index 0d812ecabf..0000000000 --- a/library/Zend/Serializer/Adapter/AdapterAbstract.php +++ /dev/null @@ -1,112 +0,0 @@ -setOptions($opts); - } - - /** - * Set serializer options - * - * @param array|Zend_Config $opts Serializer options - * @return Zend_Serializer_Adapter_AdapterAbstract - */ - public function setOptions($opts) - { - if ($opts instanceof Zend_Config) { - $opts = $opts->toArray(); - } else { - $opts = (array) $opts; - } - - foreach ($opts as $k => $v) { - $this->setOption($k, $v); - } - return $this; - } - - /** - * Set a serializer option - * - * @param string $name Option name - * @param mixed $value Option value - * @return Zend_Serializer_Adapter_AdapterAbstract - */ - public function setOption($name, $value) - { - $this->_options[(string) $name] = $value; - return $this; - } - - /** - * Get serializer options - * - * @return array - */ - public function getOptions() - { - return $this->_options; - } - - /** - * Get a serializer option - * - * @param string $name - * @return mixed - * @throws Zend_Serializer_Exception - */ - public function getOption($name) - { - $name = (string) $name; - if (!array_key_exists($name, $this->_options)) { - #require_once 'Zend/Serializer/Exception.php'; - throw new Zend_Serializer_Exception('Unknown option name "'.$name.'"'); - } - - return $this->_options[$name]; - } -} diff --git a/library/Zend/Serializer/Adapter/AdapterInterface.php b/library/Zend/Serializer/Adapter/AdapterInterface.php deleted file mode 100644 index 970b02519e..0000000000 --- a/library/Zend/Serializer/Adapter/AdapterInterface.php +++ /dev/null @@ -1,92 +0,0 @@ -writeTypeMarker($value); - return $stream->getStream(); - } catch (Exception $e) { - #require_once 'Zend/Serializer/Exception.php'; - throw new Zend_Serializer_Exception('Serialization failed by previous error', 0, $e); - } - } - - /** - * Unserialize an AMF0 value to PHP - * - * @param mixed $value - * @param array $opts - * @return void - * @throws Zend_Serializer_Exception - */ - public function unserialize($value, array $opts = array()) - { - try { - $stream = new Zend_Amf_Parse_InputStream($value); - $deserializer = new Zend_Amf_Parse_Amf0_Deserializer($stream); - return $deserializer->readTypeMarker(); - } catch (Exception $e) { - #require_once 'Zend/Serializer/Exception.php'; - throw new Zend_Serializer_Exception('Unserialization failed by previous error', 0, $e); - } - } - -} diff --git a/library/Zend/Serializer/Adapter/Amf3.php b/library/Zend/Serializer/Adapter/Amf3.php deleted file mode 100644 index 6132b04841..0000000000 --- a/library/Zend/Serializer/Adapter/Amf3.php +++ /dev/null @@ -1,87 +0,0 @@ -writeTypeMarker($value); - return $stream->getStream(); - } catch (Exception $e) { - #require_once 'Zend/Serializer/Exception.php'; - throw new Zend_Serializer_Exception('Serialization failed by previous error', 0, $e); - } - } - - /** - * Deserialize an AMF3 value to PHP - * - * @param mixed $value - * @param array $opts - * @return string - * @throws Zend_Serializer_Exception - */ - public function unserialize($value, array $opts = array()) - { - try { - $stream = new Zend_Amf_Parse_InputStream($value); - $deserializer = new Zend_Amf_Parse_Amf3_Deserializer($stream); - return $deserializer->readTypeMarker(); - } catch (Exception $e) { - #require_once 'Zend/Serializer/Exception.php'; - throw new Zend_Serializer_Exception('Unserialization failed by previous error', 0, $e); - } - } -} diff --git a/library/Zend/Serializer/Adapter/Igbinary.php b/library/Zend/Serializer/Adapter/Igbinary.php deleted file mode 100644 index 69c44a5b56..0000000000 --- a/library/Zend/Serializer/Adapter/Igbinary.php +++ /dev/null @@ -1,98 +0,0 @@ - false, - 'enableJsonExprFinder' => false, - 'objectDecodeType' => Zend_Json::TYPE_ARRAY, - ); - - /** - * Serialize PHP value to JSON - * - * @param mixed $value - * @param array $opts - * @return string - * @throws Zend_Serializer_Exception on JSON encoding exception - */ - public function serialize($value, array $opts = array()) - { - $opts = $opts + $this->_options; - - try { - return Zend_Json::encode($value, $opts['cycleCheck'], $opts); - } catch (Exception $e) { - #require_once 'Zend/Serializer/Exception.php'; - throw new Zend_Serializer_Exception('Serialization failed', 0, $e); - } - } - - /** - * Deserialize JSON to PHP value - * - * @param string $json - * @param array $opts - * @return mixed - */ - public function unserialize($json, array $opts = array()) - { - $opts = $opts + $this->_options; - - try { - $ret = Zend_Json::decode($json, $opts['objectDecodeType']); - } catch (Zend_Json_Exception $e) { - #require_once 'Zend/Serializer/Exception.php'; - throw new Zend_Serializer_Exception('Invalid json data'); - } catch (Exception $e) { - #require_once 'Zend/Serializer/Exception.php'; - throw new Zend_Serializer_Exception('Unserialization failed by previous error', 0, $e); - } - - return $ret; - } -} diff --git a/library/Zend/Serializer/Adapter/PhpCode.php b/library/Zend/Serializer/Adapter/PhpCode.php deleted file mode 100644 index 653893509d..0000000000 --- a/library/Zend/Serializer/Adapter/PhpCode.php +++ /dev/null @@ -1,67 +0,0 @@ - '\\\\', - "\x00" => '\\x00', "\x01" => '\\x01', "\x02" => '\\x02', "\x03" => '\\x03', - "\x04" => '\\x04', "\x05" => '\\x05', "\x06" => '\\x06', "\x07" => '\\x07', - "\x08" => '\\x08', "\x09" => '\\t', "\x0a" => '\\n', "\x0b" => '\\x0b', - "\x0c" => '\\x0c', "\x0d" => '\\r', "\x0e" => '\\x0e', "\x0f" => '\\x0f', - "\x10" => '\\x10', "\x11" => '\\x11', "\x12" => '\\x12', "\x13" => '\\x13', - "\x14" => '\\x14', "\x15" => '\\x15', "\x16" => '\\x16', "\x17" => '\\x17', - "\x18" => '\\x18', "\x19" => '\\x19', "\x1a" => '\\x1a', "\x1b" => '\\x1b', - "\x1c" => '\\x1c', "\x1d" => '\\x1d', "\x1e" => '\\x1e', "\x1f" => '\\x1f', - "\xff" => '\\xff' - ); - - /** - * @var array Default options - */ - protected $_options = array( - 'protocol' => 0, - ); - - // process vars - protected $_protocol = 0; - protected $_binary = false; - protected $_memo = array(); - protected $_pickle = ''; - protected $_pickleLen = 0; - protected $_pos = 0; - protected $_stack = array(); - protected $_marker = null; - - /** - * Constructor - * - * @link Zend_Serializer_Adapter_AdapterAbstract::__construct() - */ - public function __construct($opts=array()) - { - parent::__construct($opts); - - // init - if (self::$_isLittleEndian === null) { - self::$_isLittleEndian = (pack('l', 1) === "\x01\x00\x00\x00"); - } - - $this->_marker = new stdClass(); - } - - /** - * Set an option - * - * @link Zend_Serializer_Adapter_AdapterAbstract::setOption() - * @param string $name - * @param mixed $value - * @return Zend_Serializer_Adapter_PythonPickle - */ - public function setOption($name, $value) - { - switch ($name) { - case 'protocol': - $value = $this->_checkProtocolNumber($value); - break; - } - - return parent::setOption($name, $value); - } - - /** - * Check and normalize pickle protocol number - * - * @param int $number - * @return int - * @throws Zend_Serializer_Exception - */ - protected function _checkProtocolNumber($number) - { - $int = (int) $number; - if ($int < 0 || $int > 3) { - #require_once 'Zend/Serializer/Exception.php'; - throw new Zend_Serializer_Exception('Invalid or unknown protocol version "'.$number.'"'); - } - return $int; - } - - /* serialize */ - - /** - * Serialize PHP to PythonPickle format - * - * @param mixed $value - * @param array $opts - * @return string - */ - public function serialize($value, array $opts = array()) - { - $opts = $opts + $this->_options; - - $this->_protocol = $this->_checkProtocolNumber($opts['protocol']); - $this->_binary = $this->_protocol != 0; - - // clear process vars before serializing - $this->_memo = array(); - $this->_pickle = ''; - - // write - if ($this->_protocol >= 2) { - $this->_writeProto($this->_protocol); - } - $this->_write($value); - $this->_writeStop(); - - // clear process vars after serializing - $this->_memo = array(); - $pickle = $this->_pickle; - $this->_pickle = ''; - - return $pickle; - } - - /** - * Write a value - * - * @param mixed $value - * @return void - * @throws Zend_Serializer_Exception on invalid or unrecognized value type - */ - protected function _write($value) - { - if ($value === null) { - $this->_writeNull(); - } elseif ($value === true) { - $this->_writeTrue(); - } elseif ($value === false) { - $this->_writeFalse(); - } elseif (is_int($value)) { - $this->_writeInt($value); - } elseif (is_float($value)) { - $this->_writeFloat($value); - } elseif (is_string($value)) { - // TODO: write unicode / binary - $this->_writeString($value); - } elseif (is_array($value)) { - if ($this->_isArrayAssoc($value)) { - $this->_writeArrayDict($value); - } else { - $this->_writeArrayList($value); - } - } elseif (is_object($value)) { - $this->_writeObject($value); - } else { - #require_once 'Zend/Serializer/Exception.php'; - throw new Zend_Serializer_Exception( - 'PHP-Type "'.gettype($value).'" isn\'t serializable with '.get_class($this) - ); - } - } - - /** - * Write pickle protocol - * - * @param int $protocol - * @return void - */ - protected function _writeProto($protocol) - { - $this->_pickle .= self::OP_PROTO . $protocol; - } - - /** - * Write a get - * - * @param int $id Id of memo - * @return void - */ - protected function _writeGet($id) - { - if ($this->_binary) { - if ($id <= 0xff) { - // BINGET + chr(i) - $this->_pickle .= self::OP_BINGET . chr($id); - } else { - // LONG_BINGET + pack("_pickle .= self::OP_LONG_BINGET . $bin; - } - } else { - $this->_pickle .= self::OP_GET . $id . "\r\n"; - } - } - - /** - * Write a put - * - * @param int $id Id of memo - * @return void - */ - protected function _writePut($id) - { - if ($this->_binary) { - if ($id <= 0xff) { - // BINPUT + chr(i) - $this->_pickle .= self::OP_BINPUT . chr($id); - } else { - // LONG_BINPUT + pack("_pickle .= self::OP_LONG_BINPUT . $bin; - } - } else { - $this->_pickle .= self::OP_PUT . $id . "\r\n"; - } - } - - /** - * Write a null as None - * - * @return void - */ - protected function _writeNull() - { - $this->_pickle .= self::OP_NONE; - } - - /** - * Write a boolean true - * - * @return void - */ - protected function _writeTrue() - { - if ($this->_protocol >= 2) { - $this->_pickle .= self::OP_NEWTRUE; - } else { - $this->_pickle .= self::OP_INT . "01\r\n"; - } - } - - /** - * Write a boolean false - * - * @return void - */ - protected function _writeFalse() - { - if ($this->_protocol >= 2) { - $this->_pickle .= self::OP_NEWFALSE; - } else { - $this->_pickle .= self::OP_INT . "00\r\n"; - } - } - - /** - * Write an integer value - * - * @param int $value - * @return void - */ - protected function _writeInt($value) - { - if ($this->_binary) { - if ($value >= 0) { - if ($value <= 0xff) { - // self.write(BININT1 + chr(obj)) - $this->_pickle .= self::OP_BININT1 . chr($value); - } elseif ($value <= 0xffff) { - // self.write("%c%c%c" % (BININT2, obj&0xff, obj>>8)) - $this->_pickle .= self::OP_BININT2 . pack('v', $value); - } - return; - } - - // Next check for 4-byte signed ints: - $highBits = $value >> 31; // note that Python shift sign-extends - if ($highBits == 0 || $highBits == -1) { - // All high bits are copies of bit 2**31, so the value - // fits in a 4-byte signed int. - // self.write(BININT + pack("_pickle .= self::OP_BININT . $bin; - return; - } - } - - $this->_pickle .= self::OP_INT . $value . "\r\n"; - } - - /** - * Write a float value - * - * @param float $value - * @return void - */ - protected function _writeFloat($value) - { - if ($this->_binary) { - // self.write(BINFLOAT + pack('>d', obj)) - $bin = pack('d', $value); - if (self::$_isLittleEndian === true) { - $bin = strrev($bin); - } - $this->_pickle .= self::OP_BINFLOAT . $bin; - } else { - $this->_pickle .= self::OP_FLOAT . $value . "\r\n"; - } - } - - /** - * Write a string value - * - * @param string $value - * @return void - */ - protected function _writeString($value) - { - if ( ($id=$this->_searchMomo($value)) !== false ) { - $this->_writeGet($id); - return; - } - - if ($this->_binary) { - $n = strlen($value); - if ($n <= 0xff) { - // self.write(SHORT_BINSTRING + chr(n) + obj) - $this->_pickle .= self::OP_SHORT_BINSTRING . chr($n) . $value; - } else { - // self.write(BINSTRING + pack("_pickle .= self::OP_BINSTRING . $binLen . $value; - } - } else { - $this->_pickle .= self::OP_STRING . $this->_quoteString($value) . "\r\n"; - } - - $this->_momorize($value); - } - - /** - * Write an associative array value as dictionary - * - * @param array $value - * @return void - */ - protected function _writeArrayDict(array $value) - { - if (($id=$this->_searchMomo($value)) !== false) { - $this->_writeGet($id);; - return; - } - - $this->_pickle .= self::OP_MARK . self::OP_DICT; - $this->_momorize($value); - - foreach ($value as $k => $v) { - $this->_pickle .= $this->_write($k) - . $this->_write($v) - . self::OP_SETITEM; - } - } - - /** - * Write a simple array value as list - * - * @param array $value - * @return void - */ - protected function _writeArrayList(array $value) - { - if (($id = $this->_searchMomo($value)) !== false) { - $this->_writeGet($id); - return; - } - - $this->_pickle .= self::OP_MARK . self::OP_LIST; - $this->_momorize($value); - - foreach ($value as $k => $v) { - $this->_pickle .= $this->_write($v) . self::OP_APPEND; - } - } - - /** - * Write an object as an dictionary - * - * @param object $value - * @return void - */ - protected function _writeObject($value) - { - // can't serialize php objects to python objects yet - $this->_writeArrayDict(get_object_vars($value)); - } - - /** - * Write stop - * - * @return void - */ - protected function _writeStop() - { - $this->_pickle .= self::OP_STOP; - } - - /* serialize helper */ - - /** - * Add a value to the memo and write the id - * - * @param mixed $value - * @return void - */ - protected function _momorize($value) - { - $id = count($this->_memo); - $this->_memo[$id] = $value; - $this->_writePut($id); - } - - /** - * Search a value in the meno and return the id - * - * @param mixed $value - * @return int|false The id or false - */ - protected function _searchMomo($value) - { - return array_search($value, $this->_memo, true); - } - - /** - * Is an array associative? - * - * @param array $value - * @return boolean - */ - protected function _isArrayAssoc(array $value) - { - return array_diff_key($value, array_keys(array_keys($value))); - } - - /** - * Quote/Escape a string - * - * @param string $str - * @return string quoted string - */ - protected function _quoteString($str) - { - $quoteArr = self::$_quoteString; - - if (($cntSingleQuote = substr_count($str, "'")) - && ($cntDoubleQuote = substr_count($str, '"')) - && ($cntSingleQuote < $cntDoubleQuote) - ) { - $quoteArr['"'] = '\\"'; - $enclosure = '"'; - } else { - $quoteArr["'"] = "\\'"; - $enclosure = "'"; - } - - return $enclosure . strtr($str, $quoteArr) . $enclosure; - } - - /* unserialize */ - - /** - * Unserialize from Python Pickle format to PHP - * - * @param string $pickle - * @param array $opts - * @return mixed - * @throws Zend_Serializer_Exception on invalid Pickle string - */ - public function unserialize($pickle, array $opts = array()) - { - // init process vars - $this->_pos = 0; - $this->_pickle = $pickle; - $this->_pickleLen = strlen($this->_pickle); - $this->_memo = array(); - $this->_stack = array(); - - // read pickle string - while (($op=$this->_read(1)) !== self::OP_STOP) { - $this->_load($op); - } - - if (!count($this->_stack)) { - #require_once 'Zend/Serializer/Exception.php'; - throw new Zend_Serializer_Exception('No data found'); - } - - $ret = array_pop($this->_stack); - - // clear process vars - $this->_pos = 0; - $this->_pickle = ''; - $this->_pickleLen = 0; - $this->_memo = array(); - $this->_stack = array(); - - return $ret; - } - - /** - * Load a pickle opcode - * - * @param string $op - * @return void - * @throws Zend_Serializer_Exception on invalid opcode - */ - protected function _load($op) - { - switch ($op) { - case self::OP_PUT: - $this->_loadPut(); - break; - case self::OP_BINPUT: - $this->_loadBinPut(); - break; - case self::OP_LONG_BINPUT: - $this->_loadLongBinPut(); - break; - case self::OP_GET: - $this->_loadGet(); - break; - case self::OP_BINGET: - $this->_loadBinGet(); - break; - case self::OP_LONG_BINGET: - $this->_loadLongBinGet(); - break; - case self::OP_NONE: - $this->_loadNone(); - break; - case self::OP_NEWTRUE: - $this->_loadNewTrue(); - break; - case self::OP_NEWFALSE: - $this->_loadNewFalse(); - break; - case self::OP_INT: - $this->_loadInt(); - break; - case self::OP_BININT: - $this->_loadBinInt(); - break; - case self::OP_BININT1: - $this->_loadBinInt1(); - break; - case self::OP_BININT2: - $this->_loadBinInt2(); - break; - case self::OP_LONG: - $this->_loadLong(); - break; - case self::OP_LONG1: - $this->_loadLong1(); - break; - case self::OP_LONG4: - $this->_loadLong4(); - break; - case self::OP_FLOAT: - $this->_loadFloat(); - break; - case self::OP_BINFLOAT: - $this->_loadBinFloat(); - break; - case self::OP_STRING: - $this->_loadString(); - break; - case self::OP_BINSTRING: - $this->_loadBinString(); - break; - case self::OP_SHORT_BINSTRING: - $this->_loadShortBinString(); - break; - case self::OP_BINBYTES: - $this->_loadBinBytes(); - break; - case self::OP_SHORT_BINBYTES: - $this->_loadShortBinBytes(); - break; - case self::OP_UNICODE: - $this->_loadUnicode(); - break; - case self::OP_BINUNICODE: - $this->_loadBinUnicode(); - break; - case self::OP_MARK: - $this->_loadMark(); - break; - case self::OP_LIST: - $this->_loadList(); - break; - case self::OP_EMPTY_LIST: - $this->_loadEmptyList(); - break; - case self::OP_APPEND: - $this->_loadAppend(); - break; - case self::OP_APPENDS: - $this->_loadAppends(); - break; - case self::OP_DICT: - $this->_loadDict(); - break; - case self::OP_EMPTY_DICT: - $this->_loadEmptyDict(); - break; - case self::OP_SETITEM: - $this->_loadSetItem(); - break; - case self::OP_SETITEMS: - $this->_loadSetItems(); - break; - case self::OP_TUPLE: - $this->_loadTuple(); - break; - case self::OP_TUPLE1: - $this->_loadTuple1(); - break; - case self::OP_TUPLE2: - $this->_loadTuple2(); - break; - case self::OP_TUPLE3: - $this->_loadTuple3(); - break; - case self::OP_PROTO: - $this->_loadProto(); - break; - default: - #require_once 'Zend/Serializer/Exception.php'; - throw new Zend_Serializer_Exception('Invalid or unknown opcode "'.$op.'"'); - } - } - - /** - * Load a PUT opcode - * - * @return void - * @throws Zend_Serializer_Exception on missing stack - */ - protected function _loadPut() - { - $id = (int)$this->_readline(); - - $lastStack = count($this->_stack)-1; - if (!isset($this->_stack[$lastStack])) { - #require_once 'Zend/Serializer/Exception.php'; - throw new Zend_Serializer_Exception('No stack exist'); - } - $this->_memo[$id] = & $this->_stack[$lastStack]; - } - - /** - * Load a binary PUT - * - * @return void - * @throws Zend_Serializer_Exception on missing stack - */ - protected function _loadBinPut() - { - $id = ord($this->_read(1)); - - $lastStack = count($this->_stack)-1; - if (!isset($this->_stack[$lastStack])) { - #require_once 'Zend/Serializer/Exception.php'; - throw new Zend_Serializer_Exception('No stack exist'); - } - $this->_memo[$id] = & $this->_stack[$lastStack]; - } - - /** - * Load a long binary PUT - * - * @return void - * @throws Zend_Serializer_Exception on missing stack - */ - protected function _loadLongBinPut() - { - $bin = $this->_read(4); - if (self::$_isLittleEndian === false) { - $bin = strrev($bin); - } - list(, $id) = unpack('l', $bin); - - $lastStack = count($this->_stack)-1; - if (!isset($this->_stack[$lastStack])) { - #require_once 'Zend/Serializer/Exception.php'; - throw new Zend_Serializer_Exception('No stack exist'); - } - $this->_memo[$id] = & $this->_stack[$lastStack]; - } - - /** - * Load a GET operation - * - * @return void - * @throws Zend_Serializer_Exception on missing GET identifier - */ - protected function _loadGet() - { - $id = (int)$this->_readline(); - - if (!array_key_exists($id, $this->_memo)) { - #require_once 'Zend/Serializer/Exception.php'; - throw new Zend_Serializer_Exception('Get id "' . $id . '" not found in momo'); - } - $this->_stack[] = & $this->_memo[$id]; - } - - /** - * Load a binary GET operation - * - * @return void - * @throws Zend_Serializer_Exception on missing GET identifier - */ - protected function _loadBinGet() - { - $id = ord($this->_read(1)); - - if (!array_key_exists($id, $this->_memo)) { - #require_once 'Zend/Serializer/Exception.php'; - throw new Zend_Serializer_Exception('Get id "' . $id . '" not found in momo'); - } - $this->_stack[] = & $this->_memo[$id]; - } - - /** - * Load a long binary GET operation - * - * @return void - * @throws Zend_Serializer_Exception on missing GET identifier - */ - protected function _loadLongBinGet() - { - $bin = $this->_read(4); - if (self::$_isLittleEndian === false) { - $bin = strrev($bin); - } - list(, $id) = unpack('l', $bin); - - if (!array_key_exists($id, $this->_memo)) { - #require_once 'Zend/Serializer/Exception.php'; - throw new Zend_Serializer_Exception('Get id "' . $id . '" not found in momo'); - } - $this->_stack[] = & $this->_memo[$id]; - } - - /** - * Load a NONE operator - * - * @return void - */ - protected function _loadNone() - { - $this->_stack[] = null; - } - - /** - * Load a boolean TRUE operator - * - * @return void - */ - protected function _loadNewTrue() - { - $this->_stack[] = true; - } - - /** - * Load a boolean FALSE operator - * - * @return void - */ - protected function _loadNewFalse() - { - $this->_stack[] = false; - } - - /** - * Load an integer operator - * - * @return void - */ - protected function _loadInt() - { - $line = $this->_readline(); - if ($line === '01') { - $this->_stack[] = true; - } elseif ($line === '00') { - $this->_stack[] = false; - } else { - $this->_stack[] = (int)$line; - } - } - - /** - * Load a binary integer operator - * - * @return void - */ - protected function _loadBinInt() - { - $bin = $this->_read(4); - if (self::$_isLittleEndian === false) { - $bin = strrev($bin); - } - list(, $int) = unpack('l', $bin); - $this->_stack[] = $int; - } - - /** - * Load the first byte of a binary integer - * - * @return void - */ - protected function _loadBinInt1() - { - $this->_stack[] = ord($this->_read(1)); - } - - /** - * Load the second byte of a binary integer - * - * @return void - */ - protected function _loadBinInt2() - { - $bin = $this->_read(2); - list(, $int) = unpack('v', $bin); - $this->_stack[] = $int; - } - - /** - * Load a long (float) operator - * - * @return void - */ - protected function _loadLong() - { - $data = rtrim($this->_readline(), 'L'); - if ($data === '') { - $this->_stack[] = 0; - } else { - $this->_stack[] = $data; - } - } - - /** - * Load a one byte long integer - * - * @return void - */ - protected function _loadLong1() - { - $n = ord($this->_read(1)); - $data = $this->_read($n); - $this->_stack[] = $this->_decodeBinLong($data); - } - - /** - * Load a 4 byte long integer - * - * @return void - */ - protected function _loadLong4() - { - $nBin = $this->_read(4); - if (self::$_isLittleEndian === false) { - $nBin = strrev($$nBin); - } - list(, $n) = unpack('l', $nBin); - $data = $this->_read($n); - - $this->_stack[] = $this->_decodeBinLong($data); - } - - /** - * Load a float value - * - * @return void - */ - protected function _loadFloat() - { - $float = (float)$this->_readline(); - $this->_stack[] = $float; - } - - /** - * Load a binary float value - * - * @return void - */ - protected function _loadBinFloat() - { - $bin = $this->_read(8); - if (self::$_isLittleEndian === true) { - $bin = strrev($bin); - } - list(, $float) = unpack('d', $bin); - $this->_stack[] = $float; - } - - /** - * Load a string - * - * @return void - */ - protected function _loadString() - { - $this->_stack[] = $this->_unquoteString((string)$this->_readline()); - } - - /** - * Load a binary string - * - * @return void - */ - protected function _loadBinString() - { - $bin = $this->_read(4); - if (!self::$_isLittleEndian) { - $bin = strrev($bin); - } - list(, $len) = unpack('l', $bin); - $this->_stack[] = (string)$this->_read($len); - } - - /** - * Load a short binary string - * - * @return void - */ - protected function _loadShortBinString() - { - $len = ord($this->_read(1)); - $this->_stack[] = (string)$this->_read($len); - } - - /** - * Load arbitrary binary bytes - * - * @return void - */ - protected function _loadBinBytes() - { - // read byte length - $nBin = $this->_read(4); - if (self::$_isLittleEndian === false) { - $nBin = strrev($$nBin); - } - list(, $n) = unpack('l', $nBin); - $this->_stack[] = $this->_read($n); - } - - /** - * Load a single binary byte - * - * @return void - */ - protected function _loadShortBinBytes() - { - $n = ord($this->_read(1)); - $this->_stack[] = $this->_read($n); - } - - /** - * Load a unicode string - * - * @return void - */ - protected function _loadUnicode() - { - $data = $this->_readline(); - $pattern = '/\\\\u([a-fA-F0-9]{4})/u'; // \uXXXX - $data = preg_replace_callback($pattern, array($this, '_convertMatchingUnicodeSequence2Utf8'), $data); - - $this->_stack[] = $data; - } - - /** - * Convert a unicode sequence to UTF-8 - * - * @param array $match - * @return string - */ - protected function _convertMatchingUnicodeSequence2Utf8(array $match) - { - return $this->_hex2Utf8($match[1]); - } - - /** - * Convert a hex string to a UTF-8 string - * - * @param string $sequence - * @return string - * @throws Zend_Serializer_Exception on unmatched unicode sequence - */ - protected function _hex2Utf8($hex) - { - $uniCode = hexdec($hex); - - if ($uniCode < 0x80) { // 1Byte - $utf8Char = chr($uniCode); - - } elseif ($uniCode < 0x800) { // 2Byte - $utf8Char = chr(0xC0 | $uniCode >> 6) - . chr(0x80 | $uniCode & 0x3F); - - } elseif ($uniCode < 0x10000) { // 3Byte - $utf8Char = chr(0xE0 | $uniCode >> 12) - . chr(0x80 | $uniCode >> 6 & 0x3F) - . chr(0x80 | $uniCode & 0x3F); - - } elseif ($uniCode < 0x110000) { // 4Byte - $utf8Char = chr(0xF0 | $uniCode >> 18) - . chr(0x80 | $uniCode >> 12 & 0x3F) - . chr(0x80 | $uniCode >> 6 & 0x3F) - . chr(0x80 | $uniCode & 0x3F); - } else { - #require_once 'Zend/Serializer/Exception.php'; - throw new Zend_Serializer_Exception('Unsupported unicode character found "' . dechex($uniCode) . '"'); - } - - return $utf8Char; - } - - /** - * Load binary unicode sequence - * - * @return void - */ - protected function _loadBinUnicode() - { - // read byte length - $n = $this->_read(4); - if (self::$_isLittleEndian === false) { - $n = strrev($n); - } - list(, $n) = unpack('l', $n); - $data = $this->_read($n); - - $this->_stack[] = $data; - } - - /** - * Load a marker sequence - * - * @return void - */ - protected function _loadMark() - { - $this->_stack[] = $this->_marker; - } - - /** - * Load an array (list) - * - * @return void - */ - protected function _loadList() - { - $k = $this->_lastMarker(); - $this->_stack[$k] = array(); - - // remove all elements after marker - $max = count($this->_stack); - for ($i = $k+1, $max; $i < $max; $i++) { - unset($this->_stack[$i]); - } - } - - /** - * Load an append (to list) sequence - * - * @return void - */ - protected function _loadAppend() - { - $value = array_pop($this->_stack); - $list =& $this->_stack[count($this->_stack)-1]; - $list[] = $value; - } - - /** - * Load an empty list sequence - * - * @return void - */ - protected function _loadEmptyList() - { - $this->_stack[] = array(); - } - - /** - * Load multiple append (to list) sequences at once - * - * @return void - */ - protected function _loadAppends() - { - $k = $this->_lastMarker(); - $list =& $this->_stack[$k - 1]; - $max = count($this->_stack); - for ($i = $k + 1; $i < $max; $i++) { - $list[] = $this->_stack[$i]; - unset($this->_stack[$i]); - } - unset($this->_stack[$k]); - } - - /** - * Load an associative array (Python dictionary) - * - * @return void - */ - protected function _loadDict() - { - $k = $this->_lastMarker(); - $this->_stack[$k] = array(); - - // remove all elements after marker - $max = count($this->_stack); - for($i = $k + 1; $i < $max; $i++) { - unset($this->_stack[$i]); - } - } - - /** - * Load an item from a set - * - * @return void - */ - protected function _loadSetItem() - { - $value = array_pop($this->_stack); - $key = array_pop($this->_stack); - $dict =& $this->_stack[count($this->_stack) - 1]; - $dict[$key] = $value; - } - - /** - * Load an empty dictionary - * - * @return void - */ - protected function _loadEmptyDict() - { - $this->_stack[] = array(); - } - - /** - * Load set items - * - * @return void - */ - protected function _loadSetItems() - { - $k = $this->_lastMarker(); - $dict =& $this->_stack[$k - 1]; - $max = count($this->_stack); - for ($i = $k + 1; $i < $max; $i += 2) { - $key = $this->_stack[$i]; - $value = $this->_stack[$i + 1]; - $dict[$key] = $value; - unset($this->_stack[$i], $this->_stack[$i+1]); - } - unset($this->_stack[$k]); - } - - /** - * Load a tuple - * - * @return void - */ - protected function _loadTuple() - { - $k = $this->_lastMarker(); - $this->_stack[$k] = array(); - $tuple =& $this->_stack[$k]; - $max = count($this->_stack); - for($i = $k + 1; $i < $max; $i++) { - $tuple[] = $this->_stack[$i]; - unset($this->_stack[$i]); - } - } - - /** - * Load single item tuple - * - * @return void - */ - protected function _loadTuple1() - { - $value1 = array_pop($this->_stack); - $this->_stack[] = array($value1); - } - - /** - * Load two item tuple - * - * @return void - */ - protected function _loadTuple2() - { - $value2 = array_pop($this->_stack); - $value1 = array_pop($this->_stack); - $this->_stack[] = array($value1, $value2); - } - - /** - * Load three item tuple - * - * @return void - */ - protected function _loadTuple3() { - $value3 = array_pop($this->_stack); - $value2 = array_pop($this->_stack); - $value1 = array_pop($this->_stack); - $this->_stack[] = array($value1, $value2, $value3); - } - - /** - * Load a proto value - * - * @return void - * @throws Zend_Serializer_Exception if Pickle version does not support this feature - */ - protected function _loadProto() - { - $proto = ord($this->_read(1)); - if ($proto < 2 || $proto > 3) { - #require_once 'Zend/Serializer/Exception.php'; - throw new Zend_Serializer_Exception('Invalid protocol version detected'); - } - $this->_protocol = $proto; - } - - /* unserialize helper */ - - /** - * Read a segment of the pickle - * - * @param mixed $len - * @return string - * @throws Zend_Serializer_Exception if position matches end of data - */ - protected function _read($len) - { - if (($this->_pos + $len) > $this->_pickleLen) { - #require_once 'Zend/Serializer/Exception.php'; - throw new Zend_Serializer_Exception('End of data'); - } - - $this->_pos+= $len; - return substr($this->_pickle, ($this->_pos - $len), $len); - } - - /** - * Read a line of the pickle at once - * - * @return string - * @throws Zend_Serializer_Exception if no EOL character found - */ - protected function _readline() - { - $eolLen = 2; - $eolPos = strpos($this->_pickle, "\r\n", $this->_pos); - if ($eolPos === false) { - $eolPos = strpos($this->_pickle, "\n", $this->_pos); - $eolLen = 1; - } - - if ($eolPos === false) { - #require_once 'Zend/Serializer/Exception.php'; - throw new Zend_Serializer_Exception('No new line found'); - } - $ret = substr($this->_pickle, $this->_pos, $eolPos-$this->_pos); - $this->_pos = $eolPos + $eolLen; - - return $ret; - } - - /** - * Unquote/Unescape a quoted string - * - * @param string $str quoted string - * @return string unquoted string - */ - protected function _unquoteString($str) - { - $quoteArr = array_flip(self::$_quoteString); - - if ($str[0] == '"') { - $quoteArr['\\"'] = '"'; - } else { - $quoteArr["\\'"] = "'"; - } - - return strtr(substr(trim($str), 1, -1), $quoteArr); - } - - /** - * Return last marker position in stack - * - * @return int - */ - protected function _lastMarker() - { - for ($k = count($this->_stack)-1; $k >= 0; $k -= 1) { - if ($this->_stack[$k] === $this->_marker) { - break; - } - } - return $k; - } - - /** - * Decode a binary long sequence - * - * @param string $data - * @return int|float|string - */ - protected function _decodeBinLong($data) - { - $nbytes = strlen($data); - - if ($nbytes == 0) { - return 0; - } - - $long = 0; - - if ($nbytes > 7) { - if (!extension_loaded('bcmath')) { - return INF; - } - - for ($i=0; $i<$nbytes; $i++) { - $long = bcadd($long, bcmul(ord($data[$i]), bcpow(256, $i, 0))); - } - if (0x80 <= ord($data[$nbytes-1])) { - $long = bcsub($long, bcpow(2, $nbytes * 8)); - } - - } else { - for ($i=0; $i<$nbytes; $i++) { - $long+= ord($data[$i]) * pow(256, $i); - } - if (0x80 <= ord($data[$nbytes-1])) { - $long-= pow(2, $nbytes * 8); - // $long-= 1 << ($nbytes * 8); - } - } - - return $long; - } -} diff --git a/library/Zend/Serializer/Adapter/Wddx.php b/library/Zend/Serializer/Adapter/Wddx.php deleted file mode 100644 index 84dd4906c7..0000000000 --- a/library/Zend/Serializer/Adapter/Wddx.php +++ /dev/null @@ -1,124 +0,0 @@ - null, - ); - - /** - * Constructor - * - * @param array $opts - * @return void - * @throws Zend_Serializer_Exception if wddx extension not found - */ - public function __construct($opts = array()) - { - if (!extension_loaded('wddx')) { - #require_once 'Zend/Serializer/Exception.php'; - throw new Zend_Serializer_Exception('PHP extension "wddx" is required for this adapter'); - } - - parent::__construct($opts); - } - - /** - * Serialize PHP to WDDX - * - * @param mixed $value - * @param array $opts - * @return string - * @throws Zend_Serializer_Exception on wddx error - */ - public function serialize($value, array $opts = array()) - { - $opts = $opts + $this->_options; - - if (isset($opts['comment']) && $opts['comment']) { - $wddx = wddx_serialize_value($value, (string)$opts['comment']); - } else { - $wddx = wddx_serialize_value($value); - } - - if ($wddx === false) { - $lastErr = error_get_last(); - #require_once 'Zend/Serializer/Exception.php'; - throw new Zend_Serializer_Exception($lastErr['message']); - } - return $wddx; - } - - /** - * Unserialize from WDDX to PHP - * - * @param string $wddx - * @param array $opts - * @return mixed - * @throws Zend_Serializer_Exception on wddx error - */ - public function unserialize($wddx, array $opts = array()) - { - $ret = wddx_deserialize($wddx); - - if ($ret === null) { - // check if the returned NULL is valid - // or based on an invalid wddx string - try { - $simpleXml = Zend_Xml_Security::scan($wddx); - if (isset($simpleXml->data[0]->null[0])) { - return null; // valid null - } - $errMsg = 'Can\'t unserialize wddx string'; - } catch (Zend_Xml_Exception $e) { - $errMsg = $e->getMessage(); - } - - #require_once 'Zend/Serializer/Exception.php'; - throw new Zend_Serializer_Exception($errMsg); - } - - return $ret; - } -} diff --git a/library/Zend/Serializer/Exception.php b/library/Zend/Serializer/Exception.php deleted file mode 100644 index 30e520867e..0000000000 --- a/library/Zend/Serializer/Exception.php +++ /dev/null @@ -1,33 +0,0 @@ -metadata = $metadata; - $this->registerCallback($callback); - } - - /** - * Error handler - * - * Used by registerCallback() when calling is_callable() to capture engine warnings. - * - * @param int $errno - * @param string $errstr - * @return void - */ - public function errorHandler($errno, $errstr) - { - $this->error = true; - } - - /** - * Registers the callback provided in the constructor - * - * If you have pecl/weakref {@see http://pecl.php.net/weakref} installed, - * this method provides additional behavior. - * - * If a callback is a functor, or an array callback composing an object - * instance, this method will pass the object to a WeakRef instance prior - * to registering the callback. - * - * @param Callable $callback - * @return void - */ - protected function registerCallback($callback) - { - set_error_handler(array($this, 'errorHandler'), E_STRICT); - $callable = is_callable($callback); - restore_error_handler(); - if (!$callable || $this->error) { - #require_once 'Zend/Stdlib/Exception/InvalidCallbackException.php'; - throw new Zend_Stdlib_Exception_InvalidCallbackException('Invalid callback provided; not callable'); - } - - // If pecl/weakref is not installed, simply store the callback and return - set_error_handler(array($this, 'errorHandler'), E_WARNING); - $callable = class_exists('WeakRef'); - restore_error_handler(); - if (!$callable || $this->error) { - $this->callback = $callback; - return; - } - - // If WeakRef exists, we want to use it. - - // If we have a non-closure object, pass it to WeakRef, and then - // register it. - if (is_object($callback) && !$callback instanceof Closure) { - $this->callback = new WeakRef($callback); - return; - } - - // If we have a string or closure, register as-is - if (!is_array($callback)) { - $this->callback = $callback; - return; - } - - list($target, $method) = $callback; - - // If we have an array callback, and the first argument is not an - // object, register as-is - if (!is_object($target)) { - $this->callback = $callback; - return; - } - - // We have an array callback with an object as the first argument; - // pass it to WeakRef, and then register the new callback - $target = new WeakRef($target); - $this->callback = array($target, $method); - } - - /** - * Retrieve registered callback - * - * @return Callable - */ - public function getCallback() - { - $callback = $this->callback; - - // String callbacks -- simply return - if (is_string($callback)) { - return $callback; - } - - // WeakRef callbacks -- pull it out of the object and return it - if ($callback instanceof WeakRef) { - return $callback->get(); - } - - // Non-WeakRef object callback -- return it - if (is_object($callback)) { - return $callback; - } - - // Array callback with WeakRef object -- retrieve the object first, and - // then return - list($target, $method) = $callback; - if ($target instanceof WeakRef) { - return array($target->get(), $method); - } - - // Otherwise, return it - return $callback; - } - - /** - * Invoke handler - * - * @param array $args Arguments to pass to callback - * @return mixed - */ - public function call(array $args = array()) - { - $callback = $this->getCallback(); - - $isPhp54 = version_compare(PHP_VERSION, '5.4.0rc1', '>='); - - if ($isPhp54 && is_string($callback)) { - $this->validateStringCallbackFor54($callback); - } - - // Minor performance tweak; use call_user_func() until > 3 arguments - // reached - switch (count($args)) { - case 0: - if ($isPhp54) { - return $callback(); - } - return call_user_func($callback); - case 1: - if ($isPhp54) { - return $callback(array_shift($args)); - } - return call_user_func($callback, array_shift($args)); - case 2: - $arg1 = array_shift($args); - $arg2 = array_shift($args); - if ($isPhp54) { - return $callback($arg1, $arg2); - } - return call_user_func($callback, $arg1, $arg2); - case 3: - $arg1 = array_shift($args); - $arg2 = array_shift($args); - $arg3 = array_shift($args); - if ($isPhp54) { - return $callback($arg1, $arg2, $arg3); - } - return call_user_func($callback, $arg1, $arg2, $arg3); - default: - return call_user_func_array($callback, $args); - } - } - - /** - * Invoke as functor - * - * @return mixed - */ - public function __invoke() - { - return $this->call(func_get_args()); - } - - /** - * Get all callback metadata - * - * @return array - */ - public function getMetadata() - { - return $this->metadata; - } - - /** - * Retrieve a single metadatum - * - * @param string $name - * @return mixed - */ - public function getMetadatum($name) - { - if (array_key_exists($name, $this->metadata)) { - return $this->metadata[$name]; - } - return null; - } - - /** - * Validate a static method call - * - * Validates that a static method call in PHP 5.4 will actually work - * - * @param string $callback - * @return true - * @throws Zend_Stdlib_Exception_InvalidCallbackException if invalid - */ - protected function validateStringCallbackFor54($callback) - { - if (!strstr($callback, '::')) { - return true; - } - - list($class, $method) = explode('::', $callback, 2); - - if (!class_exists($class)) { - #require_once 'Zend/Stdlib/Exception/InvalidCallbackException.php'; - throw new Zend_Stdlib_Exception_InvalidCallbackException(sprintf( - 'Static method call "%s" refers to a class that does not exist', - $callback - )); - } - - $r = new ReflectionClass($class); - if (!$r->hasMethod($method)) { - #require_once 'Zend/Stdlib/Exception/InvalidCallbackException.php'; - throw new Zend_Stdlib_Exception_InvalidCallbackException(sprintf( - 'Static method call "%s" refers to a method that does not exist', - $callback - )); - } - $m = $r->getMethod($method); - if (!$m->isStatic()) { - #require_once 'Zend/Stdlib/Exception/InvalidCallbackException.php'; - throw new Zend_Stdlib_Exception_InvalidCallbackException(sprintf( - 'Static method call "%s" refers to a method that is not static', - $callback - )); - } - - return true; - } -} diff --git a/library/Zend/Stdlib/Exception.php b/library/Zend/Stdlib/Exception.php deleted file mode 100644 index 05cb27533e..0000000000 --- a/library/Zend/Stdlib/Exception.php +++ /dev/null @@ -1,31 +0,0 @@ -items[] = array( - 'data' => $data, - 'priority' => $priority, - ); - $this->getQueue()->insert($data, $priority); - return $this; - } - - /** - * Remove an item from the queue - * - * This is different than {@link extract()}; its purpose is to dequeue an - * item. - * - * This operation is potentially expensive, as it requires - * re-initialization and re-population of the inner queue. - * - * Note: this removes the first item matching the provided item found. If - * the same item has been added multiple times, it will not remove other - * instances. - * - * @param mixed $datum - * @return boolean False if the item was not found, true otherwise. - */ - public function remove($datum) - { - $found = false; - foreach ($this->items as $key => $item) { - if ($item['data'] === $datum) { - $found = true; - break; - } - } - if ($found) { - unset($this->items[$key]); - $this->queue = null; - $queue = $this->getQueue(); - foreach ($this->items as $item) { - $queue->insert($item['data'], $item['priority']); - } - return true; - } - return false; - } - - /** - * Is the queue empty? - * - * @return bool - */ - public function isEmpty() - { - return (0 === $this->count()); - } - - /** - * How many items are in the queue? - * - * @return int - */ - public function count() - { - return count($this->items); - } - - /** - * Peek at the top node in the queue, based on priority. - * - * @return mixed - */ - public function top() - { - return $this->getIterator()->top(); - } - - /** - * Extract a node from the inner queue and sift up - * - * @return mixed - */ - public function extract() - { - return $this->getQueue()->extract(); - } - - /** - * Retrieve the inner iterator - * - * SplPriorityQueue acts as a heap, which typically implies that as items - * are iterated, they are also removed. This does not work for situations - * where the queue may be iterated multiple times. As such, this class - * aggregates the values, and also injects an SplPriorityQueue. This method - * retrieves the inner queue object, and clones it for purposes of - * iteration. - * - * @return SplPriorityQueue - */ - public function getIterator() - { - $queue = $this->getQueue(); - return clone $queue; - } - - /** - * Serialize the data structure - * - * @return string - */ - public function serialize() - { - return serialize($this->items); - } - - /** - * Unserialize a string into a Zend_Stdlib_PriorityQueue object - * - * Serialization format is compatible with {@link Zend_Stdlib_SplPriorityQueue} - * - * @param string $data - * @return void - */ - public function unserialize($data) - { - foreach (unserialize($data) as $item) { - $this->insert($item['data'], $item['priority']); - } - } - - /** - * Serialize to an array - * - * By default, returns only the item data, and in the order registered (not - * sorted). You may provide one of the EXTR_* flags as an argument, allowing - * the ability to return priorities or both data and priority. - * - * @param int $flag - * @return array - */ - public function toArray($flag = self::EXTR_DATA) - { - switch ($flag) { - case self::EXTR_BOTH: - return $this->items; - case self::EXTR_PRIORITY: - return array_map(array($this, 'returnPriority'), $this->items); - case self::EXTR_DATA: - default: - return array_map(array($this, 'returnData'), $this->items); - } - } - - /** - * Specify the internal queue class - * - * Please see {@link getIterator()} for details on the necessity of an - * internal queue class. The class provided should extend SplPriorityQueue. - * - * @param string $class - * @return Zend_Stdlib_PriorityQueue - */ - public function setInternalQueueClass($class) - { - $this->queueClass = (string) $class; - return $this; - } - - /** - * Does the queue contain the given datum? - * - * @param mixed $datum - * @return bool - */ - public function contains($datum) - { - foreach ($this->items as $item) { - if ($item['data'] === $datum) { - return true; - } - } - return false; - } - - /** - * Does the queue have an item with the given priority? - * - * @param int $priority - * @return bool - */ - public function hasPriority($priority) - { - foreach ($this->items as $item) { - if ($item['priority'] === $priority) { - return true; - } - } - return false; - } - - /** - * Get the inner priority queue instance - * - * @return Zend_Stdlib_SplPriorityQueue - */ - protected function getQueue() - { - if (null === $this->queue) { - $this->queue = new $this->queueClass(); - if (!$this->queue instanceof SplPriorityQueue) { - throw new DomainException(sprintf( - 'Zend_Stdlib_PriorityQueue expects an internal queue of type SplPriorityQueue; received "%s"', - get_class($this->queue) - )); - } - } - return $this->queue; - } - - /** - * Return priority from an internal item - * - * Used as a lambda in toArray(). - * - * @param array $item - * @return mixed - */ - public function returnPriority($item) - { - return $item['priority']; - } - - /** - * Return data from an internal item - * - * Used as a lambda in toArray(). - * - * @param array $item - * @return mixed - */ - public function returnData($item) - { - return $item['data']; - } -} diff --git a/library/Zend/Stdlib/SplPriorityQueue.php b/library/Zend/Stdlib/SplPriorityQueue.php deleted file mode 100644 index bf19cc7aae..0000000000 --- a/library/Zend/Stdlib/SplPriorityQueue.php +++ /dev/null @@ -1,499 +0,0 @@ - $value, 'priority' => $priority) - */ - const EXTR_BOTH = 0x00000003; - - /** - * Count of items in the queue - * @var int - */ - protected $count = 0; - - /** - * Flag indicating what should be returned when iterating or extracting - * @var int - */ - protected $extractFlags = self::EXTR_DATA; - - /** - * @var bool|array - */ - protected $preparedQueue = false; - - /** - * All items in the queue - * @var array - */ - protected $queue = array(); - - /** - * Constructor - * - * Creates a new, empty queue - * - * @return void - */ - public function __construct() - { - } - - /** - * Compare two priorities - * - * Returns positive integer if $priority1 is greater than $priority2, 0 - * if equal, negative otherwise. - * - * Unused internally, and only included in order to retain the same - * interface as PHP's SplPriorityQueue. - * - * @param mixed $priority1 - * @param mixed $priority2 - * @return int - */ - public function compare($priority1, $priority2) - { - if ($priority1 > $priority2) { - return 1; - } - if ($priority1 == $priority2) { - return 0; - } - - return -1; - } - - /** - * Countable: return number of items composed in the queue - * - * @return int - */ - public function count() - { - return $this->count; - } - - /** - * Iterator: return current item - * - * @return mixed - */ - public function current() - { - if (!$this->preparedQueue) { - $this->rewind(); - } - if (!$this->count) { - throw new OutOfBoundsException('Cannot iterate SplPriorityQueue; no elements present'); - } - -if (!is_array($this->preparedQueue)) { - throw new DomainException(sprintf( - "Queue was prepared, but is empty?\n PreparedQueue: %s\n Internal Queue: %s\n", - var_export($this->preparedQueue, 1), - var_export($this->queue, 1) - )); -} - - $return = array_shift($this->preparedQueue); - $priority = $return['priority']; - $priorityKey = $return['priorityKey']; - $key = $return['key']; - unset($return['key']); - unset($return['priorityKey']); - unset($this->queue[$priorityKey][$key]); - - switch ($this->extractFlags) { - case self::EXTR_DATA: - return $return['data']; - case self::EXTR_PRIORITY: - return $return['priority']; - case self::EXTR_BOTH: - default: - return $return; - }; - } - - /** - * Extract a node from top of the heap and sift up - * - * Returns either the value, the priority, or both, depending on the extract flag. - * - * @return mixed; - */ - public function extract() - { - if (!$this->count) { - return null; - } - - if (!$this->preparedQueue) { - $this->prepareQueue(); - } - - if (empty($this->preparedQueue)) { - return null; - } - - $return = array_shift($this->preparedQueue); - $priority = $return['priority']; - $priorityKey = $return['priorityKey']; - $key = $return['key']; - unset($return['key']); - unset($return['priorityKey']); - unset($this->queue[$priorityKey][$key]); - $this->count--; - - switch ($this->extractFlags) { - case self::EXTR_DATA: - return $return['data']; - case self::EXTR_PRIORITY: - return $return['priority']; - case self::EXTR_BOTH: - default: - return $return; - }; - } - - /** - * Insert a value into the heap, at the specified priority - * - * @param mixed $value - * @param mixed $priority - * @return void - */ - public function insert($value, $priority) - { - if (!is_scalar($priority)) { - $priority = serialize($priority); - } - if (!isset($this->queue[$priority])) { - $this->queue[$priority] = array(); - } - $this->queue[$priority][] = $value; - $this->count++; - $this->preparedQueue = false; - } - - /** - * Is the queue currently empty? - * - * @return bool - */ - public function isEmpty() - { - return (0 == $this->count); - } - - /** - * Iterator: return current key - * - * @return mixed Usually an int or string - */ - public function key() - { - return $this->count; - } - - /** - * Iterator: Move pointer forward - * - * @return void - */ - public function next() - { - $this->count--; - } - - /** - * Recover from corrupted state and allow further actions on the queue - * - * Unimplemented, and only included in order to retain the same interface as PHP's - * SplPriorityQueue. - * - * @return void - */ - public function recoverFromCorruption() - { - } - - /** - * Iterator: Move pointer to first item - * - * @return void - */ - public function rewind() - { - if (!$this->preparedQueue) { - $this->prepareQueue(); - } - } - - /** - * Set the extract flags - * - * Defines what is extracted by SplPriorityQueue::current(), - * SplPriorityQueue::top() and SplPriorityQueue::extract(). - * - * - SplPriorityQueue::EXTR_DATA (0x00000001): Extract the data - * - SplPriorityQueue::EXTR_PRIORITY (0x00000002): Extract the priority - * - SplPriorityQueue::EXTR_BOTH (0x00000003): Extract an array containing both - * - * The default mode is SplPriorityQueue::EXTR_DATA. - * - * @param int $flags - * @return void - */ - public function setExtractFlags($flags) - { - $expected = array( - self::EXTR_DATA => true, - self::EXTR_PRIORITY => true, - self::EXTR_BOTH => true, - ); - if (!isset($expected[$flags])) { - throw new InvalidArgumentException(sprintf('Expected an EXTR_* flag; received %s', $flags)); - } - $this->extractFlags = $flags; - } - - /** - * Return the value or priority (or both) of the top node, depending on - * the extract flag - * - * @return mixed - */ - public function top() - { - $this->sort(); - $keys = array_keys($this->queue); - $key = array_shift($keys); - if (preg_match('/^(a|O):/', $key)) { - $key = unserialize($key); - } - - if ($this->extractFlags == self::EXTR_PRIORITY) { - return $key; - } - - if ($this->extractFlags == self::EXTR_DATA) { - return $this->queue[$key][0]; - } - - return array( - 'data' => $this->queue[$key][0], - 'priority' => $key, - ); - } - - /** - * Iterator: is the current position valid for the queue - * - * @return bool - */ - public function valid() - { - return (bool) $this->count; - } - - /** - * Sort the queue - * - * @return void - */ - protected function sort() - { - krsort($this->queue); - } - - /** - * Prepare the queue for iteration and/or extraction - * - * @return void - */ - protected function prepareQueue() - { - $this->sort(); - $count = $this->count; - $queue = array(); - foreach ($this->queue as $priority => $values) { - $priorityKey = $priority; - if (preg_match('/^(a|O):/', $priority)) { - $priority = unserialize($priority); - } - foreach ($values as $key => $value) { - $queue[$count] = array( - 'data' => $value, - 'priority' => $priority, - 'priorityKey' => $priorityKey, - 'key' => $key, - ); - $count--; - } - } - $this->preparedQueue = $queue; - } - } -} - -/** - * Serializable version of SplPriorityQueue - * - * Also, provides predictable heap order for datums added with the same priority - * (i.e., they will be emitted in the same order they are enqueued). - * - * @category Zend - * @package Zend_Stdlib - * @copyright Copyright (c) 2005-2015 Zend Technologies USA Inc. (http://www.zend.com) - * @license http://framework.zend.com/license/new-bsd New BSD License - */ -class Zend_Stdlib_SplPriorityQueue extends SplPriorityQueue implements Serializable -{ - /** - * @var int Seed used to ensure queue order for items of the same priority - */ - protected $serial = PHP_INT_MAX; - - /** - * @var bool - */ - protected $isPhp53; - - /** - * Constructor - * - * @return void - */ - public function __construct() - { - $this->isPhp53 = version_compare(PHP_VERSION, '5.3', '>='); - } - - /** - * Insert a value with a given priority - * - * Utilizes {@var $serial} to ensure that values of equal priority are - * emitted in the same order in which they are inserted. - * - * @param mixed $datum - * @param mixed $priority - * @return void - */ - public function insert($datum, $priority) - { - // If using the native PHP SplPriorityQueue implementation, we need to - // hack around it to ensure that items registered at the same priority - // return in the order registered. In the userland version, this is not - // necessary. - if ($this->isPhp53) { - if (!is_array($priority)) { - $priority = array($priority, $this->serial--); - } - } - parent::insert($datum, $priority); - } - - /** - * Serialize to an array - * - * Array will be priority => data pairs - * - * @return array - */ - public function toArray() - { - $this->setExtractFlags(self::EXTR_BOTH); - $array = array(); - while ($this->valid()) { - $array[] = $this->current(); - $this->next(); - } - $this->setExtractFlags(self::EXTR_DATA); - - // Iterating through a priority queue removes items - foreach ($array as $item) { - $this->insert($item['data'], $item['priority']); - } - - // Return only the data - $return = array(); - foreach ($array as $item) { - $return[] = $item['data']; - } - - return $return; - } - - /** - * Serialize - * - * @return string - */ - public function serialize() - { - $data = array(); - $this->setExtractFlags(self::EXTR_BOTH); - while ($this->valid()) { - $data[] = $this->current(); - $this->next(); - } - $this->setExtractFlags(self::EXTR_DATA); - - // Iterating through a priority queue removes items - foreach ($data as $item) { - $this->insert($item['data'], $item['priority']); - } - - return serialize($data); - } - - /** - * Deserialize - * - * @param string $data - * @return void - */ - public function unserialize($data) - { - foreach (unserialize($data) as $item) { - $this->insert($item['data'], $item['priority']); - } - } -} diff --git a/library/Zend/Tag/Cloud.php b/library/Zend/Tag/Cloud.php deleted file mode 100644 index c765eba59d..0000000000 --- a/library/Zend/Tag/Cloud.php +++ /dev/null @@ -1,410 +0,0 @@ -setConfig($options); - } - - if (is_array($options)) { - $this->setOptions($options); - } - } - - /** - * Set options from Zend_Config - * - * @param Zend_Config $config - * @return Zend_Tag_Cloud - */ - public function setConfig(Zend_Config $config) - { - $this->setOptions($config->toArray()); - - return $this; - } - - /** - * Set options from array - * - * @param array $options Configuration for Zend_Tag_Cloud - * @return Zend_Tag_Cloud - */ - public function setOptions(array $options) - { - if (isset($options['prefixPath'])) { - $this->addPrefixPaths($options['prefixPath']); - unset($options['prefixPath']); - } - - foreach ($options as $key => $value) { - if (in_array(strtolower($key), $this->_skipOptions)) { - continue; - } - - $method = 'set' . ucfirst($key); - if (method_exists($this, $method)) { - $this->$method($value); - } - } - - return $this; - } - - /** - * Set the tags for the tag cloud. - * - * $tags should be an array containing single tags as array. Each tag - * array should at least contain the keys 'title' and 'weight'. Optionally - * you may supply the key 'url', to which the tag links to. Any additional - * parameter in the array is silently ignored and can be used by custom - * decorators. - * - * @param array $tags - * @return Zend_Tag_Cloud - */ - public function setTags(array $tags) - { - // Validate and cleanup the tags - $itemList = $this->getItemList(); - - foreach ($tags as $tag) { - if ($tag instanceof Zend_Tag_Taggable) { - $itemList[] = $tag; - } else if (is_array($tag)) { - $itemList[] = new Zend_Tag_Item($tag); - } else { - #require_once 'Zend/Tag/Cloud/Exception.php'; - throw new Zend_Tag_Cloud_Exception('Tag must be an instance of Zend_Tag_Taggable or an array'); - } - } - - return $this; - } - - /** - * Append a single tag to the cloud - * - * @param Zend_Tag_Taggable|array $tag - * @return Zend_Tag_Cloud - */ - public function appendTag($tag) - { - $tags = $this->getItemList(); - if ($tag instanceof Zend_Tag_Taggable) { - $tags[] = $tag; - } else if (is_array($tag)) { - $tags[] = new Zend_Tag_Item($tag); - } else { - #require_once 'Zend/Tag/Cloud/Exception.php'; - throw new Zend_Tag_Cloud_Exception('Tag must be an instance of Zend_Tag_Taggable or an array'); - } - - return $this; - } - - /** - * Set the item list - * - * @param Zend_Tag_ItemList $itemList - * @return Zend_Tag_Cloud - */ - public function setItemList(Zend_Tag_ItemList $itemList) - { - $this->_tags = $itemList; - return $this; - } - - /** - * Retrieve the item list - * - * If item list is undefined, creates one. - * - * @return Zend_Tag_ItemList - */ - public function getItemList() - { - if (null === $this->_tags) { - #require_once 'Zend/Tag/ItemList.php'; - $this->setItemList(new Zend_Tag_ItemList()); - } - return $this->_tags; - } - - /** - * Set the decorator for the cloud - * - * @param mixed $decorator - * @return Zend_Tag_Cloud - */ - public function setCloudDecorator($decorator) - { - $options = null; - - if (is_array($decorator)) { - if (isset($decorator['options'])) { - $options = $decorator['options']; - } - - if (isset($decorator['decorator'])) { - $decorator = $decorator['decorator']; - } - } - - if (is_string($decorator)) { - $classname = $this->getPluginLoader()->load($decorator); - $decorator = new $classname($options); - } - - if (!($decorator instanceof Zend_Tag_Cloud_Decorator_Cloud)) { - #require_once 'Zend/Tag/Cloud/Exception.php'; - throw new Zend_Tag_Cloud_Exception('Decorator is no instance of Zend_Tag_Cloud_Decorator_Cloud'); - } - - $this->_cloudDecorator = $decorator; - - return $this; - } - - /** - * Get the decorator for the cloud - * - * @return Zend_Tag_Cloud_Decorator_Cloud - */ - public function getCloudDecorator() - { - if (null === $this->_cloudDecorator) { - $this->setCloudDecorator('htmlCloud'); - } - return $this->_cloudDecorator; - } - - /** - * Set the decorator for the tags - * - * @param mixed $decorator - * @return Zend_Tag_Cloud - */ - public function setTagDecorator($decorator) - { - $options = null; - - if (is_array($decorator)) { - if (isset($decorator['options'])) { - $options = $decorator['options']; - } - - if (isset($decorator['decorator'])) { - $decorator = $decorator['decorator']; - } - } - - if (is_string($decorator)) { - $classname = $this->getPluginLoader()->load($decorator); - $decorator = new $classname($options); - } - - if (!($decorator instanceof Zend_Tag_Cloud_Decorator_Tag)) { - #require_once 'Zend/Tag/Cloud/Exception.php'; - throw new Zend_Tag_Cloud_Exception('Decorator is no instance of Zend_Tag_Cloud_Decorator_Tag'); - } - - $this->_tagDecorator = $decorator; - - return $this; - } - - /** - * Get the decorator for the tags - * - * @return Zend_Tag_Cloud_Decorator_Tag - */ - public function getTagDecorator() - { - if (null === $this->_tagDecorator) { - $this->setTagDecorator('htmlTag'); - } - return $this->_tagDecorator; - } - - /** - * Set plugin loaders for use with decorators - * - * @param Zend_Loader_PluginLoader_Interface $loader - * @return Zend_Tag_Cloud - */ - public function setPluginLoader(Zend_Loader_PluginLoader_Interface $loader) - { - $this->_pluginLoader = $loader; - return $this; - } - - /** - * Get the plugin loader for decorators - * - * @return Zend_Loader_PluginLoader - */ - public function getPluginLoader() - { - if ($this->_pluginLoader === null) { - $prefix = 'Zend_Tag_Cloud_Decorator_'; - $pathPrefix = 'Zend/Tag/Cloud/Decorator/'; - - #require_once 'Zend/Loader/PluginLoader.php'; - $this->_pluginLoader = new Zend_Loader_PluginLoader(array($prefix => $pathPrefix)); - } - - return $this->_pluginLoader; - } - - /** - * Add many prefix paths at once - * - * @param array $paths - * @return Zend_Tag_Cloud - */ - public function addPrefixPaths(array $paths) - { - if (isset($paths['prefix']) && isset($paths['path'])) { - return $this->addPrefixPath($paths['prefix'], $paths['path']); - } - - foreach ($paths as $path) { - if (!isset($path['prefix']) || !isset($path['path'])) { - continue; - } - - $this->addPrefixPath($path['prefix'], $path['path']); - } - - return $this; - } - - /** - * Add prefix path for plugin loader - * - * @param string $prefix - * @param string $path - * @return Zend_Tag_Cloud - */ - public function addPrefixPath($prefix, $path) - { - $loader = $this->getPluginLoader(); - $loader->addPrefixPath($prefix, $path); - - return $this; - } - - /** - * Render the tag cloud - * - * @return string - */ - public function render() - { - $tags = $this->getItemList(); - - if (count($tags) === 0) { - return ''; - } - - $tagsResult = $this->getTagDecorator()->render($tags); - $cloudResult = $this->getCloudDecorator()->render($tagsResult); - - return $cloudResult; - } - - /** - * Render the tag cloud - * - * @return string - */ - public function __toString() - { - try { - $result = $this->render(); - return $result; - } catch (Exception $e) { - $message = "Exception caught by tag cloud: " . $e->getMessage() - . "\nStack Trace:\n" . $e->getTraceAsString(); - trigger_error($message, E_USER_WARNING); - return ''; - } - } -} diff --git a/library/Zend/Tag/Cloud/Decorator/Cloud.php b/library/Zend/Tag/Cloud/Decorator/Cloud.php deleted file mode 100644 index e649d54f2b..0000000000 --- a/library/Zend/Tag/Cloud/Decorator/Cloud.php +++ /dev/null @@ -1,88 +0,0 @@ -toArray(); - } - - if (is_array($options)) { - $this->setOptions($options); - } - } - - /** - * Set options from array - * - * @param array $options Configuration for the decorator - * @return Zend_Tag_Cloud - */ - public function setOptions(array $options) - { - foreach ($options as $key => $value) { - if (in_array(strtolower($key), $this->_skipOptions)) { - continue; - } - - $method = 'set' . $key; - if (method_exists($this, $method)) { - $this->$method($value); - } - } - - return $this; - } - - /** - * Render a list of formatted tags - * - * @param array $tags - * @return string - */ - abstract public function render(array $tags); -} diff --git a/library/Zend/Tag/Cloud/Decorator/Exception.php b/library/Zend/Tag/Cloud/Decorator/Exception.php deleted file mode 100644 index 216dcde9de..0000000000 --- a/library/Zend/Tag/Cloud/Decorator/Exception.php +++ /dev/null @@ -1,39 +0,0 @@ - array('class' => 'Zend_Tag_Cloud') - ); - - /** - * Separator for the single tags - * - * @var string - */ - protected $_separator = ' '; - - /** - * Get encoding - * - * @return string - */ - public function getEncoding() - { - return $this->_encoding; - } - - /** - * Set encoding - * - * @param string - * @return Zend_Tag_Cloud_Decorator_HtmlCloud - */ - public function setEncoding($value) - { - $this->_encoding = (string) $value; - return $this; - } - - /** - * Set the HTML tags surrounding all tags - * - * @param array $htmlTags - * @return Zend_Tag_Cloud_Decorator_HtmlCloud - */ - public function setHtmlTags(array $htmlTags) - { - $this->_htmlTags = $htmlTags; - return $this; - } - - /** - * Retrieve HTML tag map - * - * @return array - */ - public function getHtmlTags() - { - return $this->_htmlTags; - } - - /** - * Set the separator between the single tags - * - * @param string - * @return Zend_Tag_Cloud_Decorator_HtmlCloud - */ - public function setSeparator($separator) - { - $this->_separator = $separator; - return $this; - } - - /** - * Get tag separator - * - * @return string - */ - public function getSeparator() - { - return $this->_separator; - } - - /** - * Defined by Zend_Tag_Cloud_Decorator_Cloud - * - * @param array $tags - * @return string - */ - public function render(array $tags) - { - $cloudHtml = implode($this->getSeparator(), $tags); - - $enc = $this->getEncoding(); - foreach ($this->getHtmlTags() as $key => $data) { - if (is_array($data)) { - $htmlTag = $key; - $attributes = ''; - - foreach ($data as $param => $value) { - $attributes .= ' ' . $param . '="' . htmlspecialchars($value, ENT_COMPAT, $enc) . '"'; - } - } else { - $htmlTag = $data; - $attributes = ''; - } - - $cloudHtml = sprintf('<%1$s%3$s>%2$s', $htmlTag, $cloudHtml, $attributes); - } - - return $cloudHtml; - } -} diff --git a/library/Zend/Tag/Cloud/Decorator/HtmlTag.php b/library/Zend/Tag/Cloud/Decorator/HtmlTag.php deleted file mode 100644 index c36a9a558a..0000000000 --- a/library/Zend/Tag/Cloud/Decorator/HtmlTag.php +++ /dev/null @@ -1,306 +0,0 @@ -_classList = $classList; - return $this; - } - - /** - * Get class list - * - * @return array - */ - public function getClassList() - { - return $this->_classList; - } - - /** - * Get encoding - * - * @return string - */ - public function getEncoding() - { - return $this->_encoding; - } - - /** - * Set encoding - * - * @param string $value - * @return Zend_Tag_Cloud_Decorator_HtmlTag - */ - public function setEncoding($value) - { - $this->_encoding = (string) $value; - return $this; - } - - /** - * Set the font size unit - * - * Possible values are: em, ex, px, in, cm, mm, pt, pc and % - * - * @param string $fontSizeUnit - * @throws Zend_Tag_Cloud_Decorator_Exception When an invalid fontsize unit is specified - * @return Zend_Tag_Cloud_Decorator_HtmlTag - */ - public function setFontSizeUnit($fontSizeUnit) - { - if (!in_array($fontSizeUnit, $this->_alloweFontSizeUnits)) { - #require_once 'Zend/Tag/Cloud/Decorator/Exception.php'; - throw new Zend_Tag_Cloud_Decorator_Exception('Invalid fontsize unit specified'); - } - - $this->_fontSizeUnit = (string) $fontSizeUnit; - $this->setClassList(null); - return $this; - } - - /** - * Retrieve font size unit - * - * @return string - */ - public function getFontSizeUnit() - { - return $this->_fontSizeUnit; - } - /** - * Set the HTML tags surrounding the element - * - * @param array $htmlTags - * @return Zend_Tag_Cloud_Decorator_HtmlTag - */ - public function setHtmlTags(array $htmlTags) - { - $this->_htmlTags = $htmlTags; - return $this; - } - - /** - * Get HTML tags map - * - * @return array - */ - public function getHtmlTags() - { - return $this->_htmlTags; - } - - /** - * Set maximum font size - * - * @param integer $maxFontSize - * @throws Zend_Tag_Cloud_Decorator_Exception When fontsize is not numeric - * @return Zend_Tag_Cloud_Decorator_HtmlTag - */ - public function setMaxFontSize($maxFontSize) - { - if (!is_numeric($maxFontSize)) { - #require_once 'Zend/Tag/Cloud/Decorator/Exception.php'; - throw new Zend_Tag_Cloud_Decorator_Exception('Fontsize must be numeric'); - } - - $this->_maxFontSize = (int) $maxFontSize; - $this->setClassList(null); - return $this; - } - - /** - * Retrieve maximum font size - * - * @return int - */ - public function getMaxFontSize() - { - return $this->_maxFontSize; - } - - /** - * Set minimum font size - * - * @param int $minFontSize - * @throws Zend_Tag_Cloud_Decorator_Exception When fontsize is not numeric - * @return Zend_Tag_Cloud_Decorator_HtmlTag - */ - public function setMinFontSize($minFontSize) - { - if (!is_numeric($minFontSize)) { - #require_once 'Zend/Tag/Cloud/Decorator/Exception.php'; - throw new Zend_Tag_Cloud_Decorator_Exception('Fontsize must be numeric'); - } - - $this->_minFontSize = (int) $minFontSize; - $this->setClassList(null); - return $this; - } - - /** - * Retrieve minimum font size - * - * @return int - */ - public function getMinFontSize() - { - return $this->_minFontSize; - } - - /** - * Defined by Zend_Tag_Cloud_Decorator_Tag - * - * @param Zend_Tag_ItemList $tags - * @return array - */ - public function render(Zend_Tag_ItemList $tags) - { - if (null === ($weightValues = $this->getClassList())) { - $weightValues = range($this->getMinFontSize(), $this->getMaxFontSize()); - } - - $tags->spreadWeightValues($weightValues); - - $result = array(); - - $enc = $this->getEncoding(); - foreach ($tags as $tag) { - if (null === ($classList = $this->getClassList())) { - $attribute = sprintf('style="font-size: %d%s;"', $tag->getParam('weightValue'), $this->getFontSizeUnit()); - } else { - $attribute = sprintf('class="%s"', htmlspecialchars($tag->getParam('weightValue'), ENT_COMPAT, $enc)); - } - - $tagHtml = sprintf('%s', htmlSpecialChars($tag->getParam('url'), ENT_COMPAT, $enc), $attribute, $tag->getTitle()); - - foreach ($this->getHtmlTags() as $key => $data) { - if (is_array($data)) { - $htmlTag = $key; - $attributes = ''; - - foreach ($data as $param => $value) { - $attributes .= ' ' . $param . '="' . htmlspecialchars($value, ENT_COMPAT, $enc) . '"'; - } - } else { - $htmlTag = $data; - $attributes = ''; - } - - $tagHtml = sprintf('<%1$s%3$s>%2$s', $htmlTag, $tagHtml, $attributes); - } - - $result[] = $tagHtml; - } - - return $result; - } -} diff --git a/library/Zend/Tag/Cloud/Decorator/Tag.php b/library/Zend/Tag/Cloud/Decorator/Tag.php deleted file mode 100644 index b236956913..0000000000 --- a/library/Zend/Tag/Cloud/Decorator/Tag.php +++ /dev/null @@ -1,88 +0,0 @@ -toArray(); - } - - if (is_array($options)) { - $this->setOptions($options); - } - } - - /** - * Set options from array - * - * @param array $options Configuration for the decorator - * @return Zend_Tag_Cloud - */ - public function setOptions(array $options) - { - foreach ($options as $key => $value) { - if (in_array(strtolower($key), $this->_skipOptions)) { - continue; - } - - $method = 'set' . $key; - if (method_exists($this, $method)) { - $this->$method($value); - } - } - - return $this; - } - - /** - * Render a list of tags - * - * @param Zend_Tag_ItemList $tags - * @return array - */ - abstract public function render(Zend_Tag_ItemList $tags); -} diff --git a/library/Zend/Tag/Cloud/Exception.php b/library/Zend/Tag/Cloud/Exception.php deleted file mode 100644 index e7f4b694f7..0000000000 --- a/library/Zend/Tag/Cloud/Exception.php +++ /dev/null @@ -1,38 +0,0 @@ -toArray(); - } - - if (!is_array($options)) { - #require_once 'Zend/Tag/Exception.php'; - throw new Zend_Tag_Exception('Invalid options provided to constructor'); - } - - $this->setOptions($options); - - if ($this->_title === null) { - #require_once 'Zend/Tag/Exception.php'; - throw new Zend_Tag_Exception('Title was not set'); - } - - if ($this->_weight === null) { - #require_once 'Zend/Tag/Exception.php'; - throw new Zend_Tag_Exception('Weight was not set'); - } - } - - /** - * Set options of the tag - * - * @param array $options - * @return Zend_Tag_Item - */ - public function setOptions(array $options) - { - foreach ($options as $key => $value) { - if (in_array(strtolower($key), $this->_skipOptions)) { - continue; - } - - $method = 'set' . $key; - if (method_exists($this, $method)) { - $this->$method($value); - } - } - - return $this; - } - - /** - * Defined by Zend_Tag_Taggable - * - * @return string - */ - public function getTitle() - { - return $this->_title; - } - - /** - * Set the title - * - * @param string $title - * @throws Zend_Tag_Exception When title is no string - * @return Zend_Tag_Item - */ - public function setTitle($title) - { - if (!is_string($title)) { - #require_once 'Zend/Tag/Exception.php'; - throw new Zend_Tag_Exception('Title must be a string'); - } - - $this->_title = (string) $title; - return $this; - } - - /** - * Defined by Zend_Tag_Taggable - * - * @return float - */ - public function getWeight() - { - return $this->_weight; - } - - /** - * Set the weight - * - * @param float $weight - * @throws Zend_Tag_Exception When weight is not numeric - * @return Zend_Tag_Item - */ - public function setWeight($weight) - { - if (!is_numeric($weight)) { - #require_once 'Zend/Tag/Exception.php'; - throw new Zend_Tag_Exception('Weight must be numeric'); - } - - $this->_weight = (float) $weight; - return $this; - } - - /** - * Set multiple params at once - * - * @param array $params - * @return Zend_Tag_Item - */ - public function setParams(array $params) - { - foreach ($params as $name => $value) { - $this->setParam($name, $value); - } - - return $this; - } - - /** - * Defined by Zend_Tag_Taggable - * - * @param string $name - * @param mixed $value - * @return Zend_Tag_Item - */ - public function setParam($name, $value) - { - $this->_params[$name] = $value; - return $this; - } - - /** - * Defined by Zend_Tag_Taggable - * - * @param string $name - * @return mixed - */ - public function getParam($name) - { - if (isset($this->_params[$name])) { - return $this->_params[$name]; - } - return null; - } -} diff --git a/library/Zend/Tag/ItemList.php b/library/Zend/Tag/ItemList.php deleted file mode 100644 index 9887c71527..0000000000 --- a/library/Zend/Tag/ItemList.php +++ /dev/null @@ -1,238 +0,0 @@ -_items); - } - - /** - * Spread values in the items relative to their weight - * - * @param array $values - * @throws Zend_Tag_Exception When value list is empty - * @return void - */ - public function spreadWeightValues(array $values) - { - // Don't allow an empty value list - if (count($values) === 0) { - #require_once 'Zend/Tag/Exception.php'; - throw new Zend_Tag_Exception('Value list may not be empty'); - } - - // Re-index the array - $values = array_values($values); - - // If just a single value is supplied simply assign it to to all tags - if (count($values) === 1) { - foreach ($this->_items as $item) { - $item->setParam('weightValue', $values[0]); - } - } else { - // Calculate min- and max-weight - $minWeight = null; - $maxWeight = null; - - foreach ($this->_items as $item) { - if ($minWeight === null && $maxWeight === null) { - $minWeight = $item->getWeight(); - $maxWeight = $item->getWeight(); - } else { - $minWeight = min($minWeight, $item->getWeight()); - $maxWeight = max($maxWeight, $item->getWeight()); - } - } - - // Calculate the thresholds - $steps = count($values); - $delta = ($maxWeight - $minWeight) / ($steps - 1); - $thresholds = array(); - - for ($i = 0; $i < $steps; $i++) { - $thresholds[$i] = floor(100 * log(($minWeight + $i * $delta) + 2)); - } - - // Then assign the weight values - foreach ($this->_items as $item) { - $threshold = floor(100 * log($item->getWeight() + 2)); - - for ($i = 0; $i < $steps; $i++) { - if ($threshold <= $thresholds[$i]) { - $item->setParam('weightValue', $values[$i]); - break; - } - } - } - } - } - - /** - * Seek to an absolute positio - * - * @param integer $index - * @throws OutOfBoundsException When the seek position is invalid - * @return void - */ - public function seek($index) - { - $this->rewind(); - $position = 0; - - while ($position < $index && $this->valid()) { - $this->next(); - $position++; - } - - if (!$this->valid()) { - throw new OutOfBoundsException('Invalid seek position'); - } - } - - /** - * Return the current element - * - * @return mixed - */ - public function current() - { - return current($this->_items); - } - - /** - * Move forward to next element - * - * @return mixed - */ - public function next() - { - return next($this->_items); - } - - /** - * Return the key of the current element - * - * @return mixed - */ - public function key() - { - return key($this->_items); - } - - /** - * Check if there is a current element after calls to rewind() or next() - * - * @return boolean - */ - public function valid() - { - return ($this->current() !== false); - } - - /** - * Rewind the Iterator to the first element - * - * @return void - */ - public function rewind() - { - reset($this->_items); - } - - /** - * Check if an offset exists - * - * @param mixed $offset - * @return boolean - */ - public function offsetExists($offset) { - return array_key_exists($offset, $this->_items); - } - - /** - * Get the value of an offset - * - * @param mixed $offset - * @return Zend_Tag_Taggable - */ - public function offsetGet($offset) { - return $this->_items[$offset]; - } - - /** - * Append a new item - * - * @param mixed $offset - * @param Zend_Tag_Taggable $item - * @throws OutOfBoundsException When item does not implement Zend_Tag_Taggable - * @return void - */ - public function offsetSet($offset, $item) { - // We need to make that check here, as the method signature must be - // compatible with ArrayAccess::offsetSet() - if (!($item instanceof Zend_Tag_Taggable)) { - #require_once 'Zend/Tag/Exception.php'; - throw new Zend_Tag_Exception('Item must implement Zend_Tag_Taggable'); - } - - if ($offset === null) { - $this->_items[] = $item; - } else { - $this->_items[$offset] = $item; - } - } - - /** - * Unset an item - * - * @param mixed $offset - * @return void - */ - public function offsetUnset($offset) { - unset($this->_items[$offset]); - } -} diff --git a/library/Zend/Tag/Taggable.php b/library/Zend/Tag/Taggable.php deleted file mode 100644 index 767b8e5b0c..0000000000 --- a/library/Zend/Tag/Taggable.php +++ /dev/null @@ -1,60 +0,0 @@ -setEnabled(true); - $this->setProfiler($profiler); - } - - /** - * Append a new Statement to the SQL Result Stack. - * - * @param Zend_Test_DbStatement $stmt - * @return Zend_Test_DbAdapter - */ - public function appendStatementToStack(Zend_Test_DbStatement $stmt) - { - array_push($this->_statementStack, $stmt); - return $this; - } - - /** - * Append a new Insert Id to the {@see lastInsertId}. - * - * @param int|string $id - * @return Zend_Test_DbAdapter - */ - public function appendLastInsertIdToStack($id) - { - array_push($this->_lastInsertIdStack, $id); - return $this; - } - - /** - * @var string - */ - public function setQuoteIdentifierSymbol($symbol) - { - $this->_quoteIdentifierSymbol = $symbol; - } - - /** - * Returns the symbol the adapter uses for delimited identifiers. - * - * @return string - */ - public function getQuoteIdentifierSymbol() - { - return $this->_quoteIdentifierSymbol; - } - - /** - * Set the result from {@see listTables()}. - * - * @param array $listTables - */ - public function setListTables(array $listTables) - { - $this->_listTables = $listTables; - } - - /** - * Returns a list of the tables in the database. - * - * @return array - */ - public function listTables() - { - return $this->_listTables; - } - - /** - * - * @param string $table - * @param array $tableInfo - * @return Zend_Test_DbAdapter - */ - public function setDescribeTable($table, $tableInfo) - { - $this->_describeTables[$table] = $tableInfo; - return $this; - } - - /** - * Returns the column descriptions for a table. - * - * The return value is an associative array keyed by the column name, - * as returned by the RDBMS. - * - * The value of each array element is an associative array - * with the following keys: - * - * SCHEMA_NAME => string; name of database or schema - * TABLE_NAME => string; - * COLUMN_NAME => string; column name - * COLUMN_POSITION => number; ordinal position of column in table - * DATA_TYPE => string; SQL datatype name of column - * DEFAULT => string; default expression of column, null if none - * NULLABLE => boolean; true if column can have nulls - * LENGTH => number; length of CHAR/VARCHAR - * SCALE => number; scale of NUMERIC/DECIMAL - * PRECISION => number; precision of NUMERIC/DECIMAL - * UNSIGNED => boolean; unsigned property of an integer type - * PRIMARY => boolean; true if column is part of the primary key - * PRIMARY_POSITION => integer; position of column in primary key - * - * @param string $tableName - * @param string $schemaName OPTIONAL - * @return array - */ - public function describeTable($tableName, $schemaName = null) - { - if(isset($this->_describeTables[$tableName])) { - return $this->_describeTables[$tableName]; - } else { - return array(); - } - } - - /** - * Creates a connection to the database. - * - * @return void - */ - protected function _connect() - { - $this->_connected = true; - } - - /** - * Test if a connection is active - * - * @return boolean - */ - public function isConnected() - { - return $this->_connected; - } - - /** - * Force the connection to close. - * - * @return void - */ - public function closeConnection() - { - $this->_connected = false; - } - - /** - * Prepare a statement and return a PDOStatement-like object. - * - * @param string|Zend_Db_Select $sql SQL query - * @return Zend_Db_Statment|PDOStatement - */ - public function prepare($sql) - { - $queryId = $this->getProfiler()->queryStart($sql); - - if(count($this->_statementStack)) { - $stmt = array_pop($this->_statementStack); - } else { - $stmt = new Zend_Test_DbStatement(); - } - - if($this->getProfiler()->getEnabled() == true) { - $qp = $this->getProfiler()->getQueryProfile($queryId); - $stmt->setQueryProfile($qp); - } - - return $stmt; - } - - /** - * Gets the last ID generated automatically by an IDENTITY/AUTOINCREMENT column. - * - * As a convention, on RDBMS brands that support sequences - * (e.g. Oracle, PostgreSQL, DB2), this method forms the name of a sequence - * from the arguments and returns the last id generated by that sequence. - * On RDBMS brands that support IDENTITY/AUTOINCREMENT columns, this method - * returns the last value generated for such a column, and the table name - * argument is disregarded. - * - * @param string $tableName OPTIONAL Name of table. - * @param string $primaryKey OPTIONAL Name of primary key column. - * @return string - */ - public function lastInsertId($tableName = null, $primaryKey = null) - { - if(count($this->_lastInsertIdStack)) { - return array_pop($this->_lastInsertIdStack); - } else { - return false; - } - } - - /** - * Begin a transaction. - */ - protected function _beginTransaction() - { - return; - } - - /** - * Commit a transaction. - */ - protected function _commit() - { - return; - } - - /** - * Roll-back a transaction. - */ - protected function _rollBack() - { - - } - - /** - * Set the fetch mode. - * - * @param integer $mode - * @return void - * @throws Zend_Db_Adapter_Exception - */ - public function setFetchMode($mode) - { - return; - } - - /** - * Adds an adapter-specific LIMIT clause to the SELECT statement. - * - * @param mixed $sql - * @param integer $count - * @param integer $offset - * @return string - */ - public function limit($sql, $count, $offset = 0) - { - return sprintf('%s LIMIT %d,%d', $sql, $offset, $count); - } - - /** - * Check if the adapter supports real SQL parameters. - * - * @param string $type 'positional' or 'named' - * @return bool - */ - public function supportsParameters($type) - { - return true; - } - - /** - * Retrieve server version in PHP style - * - * @return string - */ - function getServerVersion() - { - return "1.0.0"; - } -} diff --git a/library/Zend/Test/DbStatement.php b/library/Zend/Test/DbStatement.php deleted file mode 100644 index 739c51e74e..0000000000 --- a/library/Zend/Test/DbStatement.php +++ /dev/null @@ -1,404 +0,0 @@ -append($row); - } - return $stmt; - } - - /** - * Create an Insert Statement - * - * @param int $affectedRows - * @return Zend_Test_DbStatement - */ - static public function createInsertStatement($affectedRows=0) - { - return self::_createRowCountStatement($affectedRows); - } - - /** - * Create an Delete Statement - * - * @param int $affectedRows - * @return Zend_Test_DbStatement - */ - static public function createDeleteStatement($affectedRows=0) - { - return self::_createRowCountStatement($affectedRows); - } - - /** - * Create an Update Statement - * - * @param int $affectedRows - * @return Zend_Test_DbStatement - */ - static public function createUpdateStatement($affectedRows=0) - { - return self::_createRowCountStatement($affectedRows); - } - - /** - * Create a Row Count Statement - * - * @param int $affectedRows - * @return Zend_Test_DbStatement - */ - static protected function _createRowCountStatement($affectedRows) - { - $stmt = new Zend_Test_DbStatement(); - $stmt->setRowCount($affectedRows); - return $stmt; - } - - /** - * @param Zend_Db_Profiler_Query $qp - */ - public function setQueryProfile(Zend_Db_Profiler_Query $qp) - { - $this->_queryProfile = $qp; - } - - /** - * @param int $rowCount - */ - public function setRowCount($rowCount) - { - $this->_rowCount = $rowCount; - } - - /** - * Append a new row to the fetch stack. - * - * @param array $row - */ - public function append($row) - { - $this->_columnCount = count($row); - $this->_fetchStack[] = $row; - } - - /** - * Bind a column of the statement result set to a PHP variable. - * - * @param string $column Name the column in the result set, either by - * position or by name. - * @param mixed $param Reference to the PHP variable containing the value. - * @param mixed $type OPTIONAL - * @return bool - * @throws Zend_Db_Statement_Exception - */ - public function bindColumn($column, &$param, $type = null) - { - return true; - } - - /** - * Binds a parameter to the specified variable name. - * - * @param mixed $parameter Name the parameter, either integer or string. - * @param mixed $variable Reference to PHP variable containing the value. - * @param mixed $type OPTIONAL Datatype of SQL parameter. - * @param mixed $length OPTIONAL Length of SQL parameter. - * @param mixed $options OPTIONAL Other options. - * @return bool - * @throws Zend_Db_Statement_Exception - */ - public function bindParam($parameter, &$variable, $type = null, $length = null, $options = null) - { - if($this->_queryProfile !== null) { - $this->_queryProfile->bindParam($parameter, $variable); - } - return true; - } - - /** - * Binds a value to a parameter. - * - * @param mixed $parameter Name the parameter, either integer or string. - * @param mixed $value Scalar value to bind to the parameter. - * @param mixed $type OPTIONAL Datatype of the parameter. - * @return bool - * @throws Zend_Db_Statement_Exception - */ - public function bindValue($parameter, $value, $type = null) - { - return true; - } - - /** - * Closes the cursor, allowing the statement to be executed again. - * - * @return bool - * @throws Zend_Db_Statement_Exception - */ - public function closeCursor() - { - return true; - } - - /** - * Returns the number of columns in the result set. - * Returns null if the statement has no result set metadata. - * - * @return int The number of columns. - * @throws Zend_Db_Statement_Exception - */ - public function columnCount() - { - return $this->_columnCount; - } - - /** - * Retrieves the error code, if any, associated with the last operation on - * the statement handle. - * - * @return string error code. - * @throws Zend_Db_Statement_Exception - */ - public function errorCode() - { - return false; - } - - /** - * Retrieves an array of error information, if any, associated with the - * last operation on the statement handle. - * - * @return array - * @throws Zend_Db_Statement_Exception - */ - public function errorInfo() - { - return false; - } - - /** - * Executes a prepared statement. - * - * @param array $params OPTIONAL Values to bind to parameter placeholders. - * @return bool - * @throws Zend_Db_Statement_Exception - */ - public function execute(array $params = array()) - { - if($this->_queryProfile !== null) { - $this->_queryProfile->bindParams($params); - $this->_queryProfile->end(); - } - return true; - } - - /** - * Fetches a row from the result set. - * - * @param int $style OPTIONAL Fetch mode for this fetch operation. - * @param int $cursor OPTIONAL Absolute, relative, or other. - * @param int $offset OPTIONAL Number for absolute or relative cursors. - * @return mixed Array, object, or scalar depending on fetch mode. - * @throws Zend_Db_Statement_Exception - */ - public function fetch($style = null, $cursor = null, $offset = null) - { - if(count($this->_fetchStack)) { - $row = array_shift($this->_fetchStack); - return $row; - } else { - return false; - } - } - - /** - * Returns an array containing all of the result set rows. - * - * @param int $style OPTIONAL Fetch mode. - * @param int $col OPTIONAL Column number, if fetch mode is by column. - * @return array Collection of rows, each in a format by the fetch mode. - * @throws Zend_Db_Statement_Exception - */ - public function fetchAll($style = null, $col = null) - { - $rows = $this->_fetchStack; - $this->_fetchStack = array(); - - return $rows; - } - - /** - * Returns a single column from the next row of a result set. - * - * @param int $col OPTIONAL Position of the column to fetch. - * @return string - * @throws Zend_Db_Statement_Exception - */ - public function fetchColumn($col = 0) - { - $row = $this->fetch(); - - if($row == false) { - return false; - } else { - if(count($row) < $col) { - #require_once "Zend/Db/Statement/Exception.php"; - throw new Zend_Db_Statement_Exception( - "Column Position '".$col."' is out of bounds." - ); - } - - $keys = array_keys($row); - return $row[$keys[$col]]; - } - } - - /** - * Fetches the next row and returns it as an object. - * - * @param string $class OPTIONAL Name of the class to create. - * @param array $config OPTIONAL Constructor arguments for the class. - * @return mixed One object instance of the specified class. - * @throws Zend_Db_Statement_Exception - */ - public function fetchObject($class = 'stdClass', array $config = array()) - { - if(!class_exists($class)) { - throw new Zend_Db_Statement_Exception("Class '".$class."' does not exist!"); - } - - $object = new $class(); - $row = $this->fetch(); - foreach($row AS $k => $v) { - $object->$k = $v; - } - - return $object; - } - - /** - * Retrieve a statement attribute. - * - * @param string $key Attribute name. - * @return mixed Attribute value. - * @throws Zend_Db_Statement_Exception - */ - public function getAttribute($key) - { - return false; - } - - /** - * Retrieves the next rowset (result set) for a SQL statement that has - * multiple result sets. An example is a stored procedure that returns - * the results of multiple queries. - * - * @return bool - * @throws Zend_Db_Statement_Exception - */ - public function nextRowset() - { - return false; - } - - /** - * Returns the number of rows affected by the execution of the - * last INSERT, DELETE, or UPDATE statement executed by this - * statement object. - * - * @return int The number of rows affected. - * @throws Zend_Db_Statement_Exception - */ - public function rowCount() - { - return $this->_rowCount; - } - - /** - * Set a statement attribute. - * - * @param string $key Attribute name. - * @param mixed $val Attribute value. - * @return bool - * @throws Zend_Db_Statement_Exception - */ - public function setAttribute($key, $val) - { - return true; - } - - /** - * Set the default fetch mode for this statement. - * - * @param int $mode The fetch mode. - * @return bool - * @throws Zend_Db_Statement_Exception - */ - public function setFetchMode($mode) - { - return true; - } -} diff --git a/library/Zend/Test/PHPUnit/Constraint/DomQuery.php b/library/Zend/Test/PHPUnit/Constraint/DomQuery.php deleted file mode 100644 index 2aa52794b5..0000000000 --- a/library/Zend/Test/PHPUnit/Constraint/DomQuery.php +++ /dev/null @@ -1,38 +0,0 @@ -=')) { - include(dirname(__FILE__) . DIRECTORY_SEPARATOR . 'DomQuery41.php'); - - class Zend_Test_PHPUnit_Constraint_DomQuery extends Zend_Test_PHPUnit_Constraint_DomQuery41 - {} -} elseif (version_compare(PHPUnit_Runner_Version::id(), '3.5', '>=')) { - include(dirname(__FILE__) . DIRECTORY_SEPARATOR . 'DomQuery37.php'); - - class Zend_Test_PHPUnit_Constraint_DomQuery extends Zend_Test_PHPUnit_Constraint_DomQuery37 - {} -} else { - include(dirname(__FILE__) . DIRECTORY_SEPARATOR . 'DomQuery34.php'); - - class Zend_Test_PHPUnit_Constraint_DomQuery extends Zend_Test_PHPUnit_Constraint_DomQuery34 - {} -} diff --git a/library/Zend/Test/PHPUnit/Constraint/DomQuery34.php b/library/Zend/Test/PHPUnit/Constraint/DomQuery34.php deleted file mode 100644 index b200ff7b0f..0000000000 --- a/library/Zend/Test/PHPUnit/Constraint/DomQuery34.php +++ /dev/null @@ -1,422 +0,0 @@ -_path = $path; - } - - /** - * Indicate negative match - * - * @param bool $flag - * @return void - */ - public function setNegate($flag = true) - { - $this->_negate = $flag; - } - - /** - * Whether or not path is a straight XPath expression - * - * @param bool $flag - * @return Zend_Test_PHPUnit_Constraint_DomQuery - */ - public function setUseXpath($flag = true) - { - $this->_useXpath = (bool) $flag; - return $this; - } - - /** - * Evaluate an object to see if it fits the constraints - * - * @param string $other String to examine - * @param null|string Assertion type - * @return bool - */ - public function evaluate($other, $assertType = null) - { - if (strstr($assertType, 'Not')) { - $this->setNegate(true); - $assertType = str_replace('Not', '', $assertType); - } - - if (strstr($assertType, 'Xpath')) { - $this->setUseXpath(true); - $assertType = str_replace('Xpath', 'Query', $assertType); - } - - if (!in_array($assertType, $this->_assertTypes)) { - #require_once 'Zend/Test/PHPUnit/Constraint/Exception.php'; - throw new Zend_Test_PHPUnit_Constraint_Exception(sprintf('Invalid assertion type "%s" provided to %s constraint', $assertType, __CLASS__)); - } - - $this->_assertType = $assertType; - - $method = $this->_useXpath ? 'queryXpath' : 'query'; - $domQuery = new Zend_Dom_Query($other); - $domQuery->registerXpathNamespaces($this->_xpathNamespaces); - $result = $domQuery->$method($this->_path); - $argv = func_get_args(); - $argc = func_num_args(); - - switch ($assertType) { - case self::ASSERT_CONTENT_CONTAINS: - if (3 > $argc) { - #require_once 'Zend/Test/PHPUnit/Constraint/Exception.php'; - throw new Zend_Test_PHPUnit_Constraint_Exception('No content provided against which to match'); - } - $this->_content = $content = $argv[2]; - return ($this->_negate) - ? $this->_notMatchContent($result, $content) - : $this->_matchContent($result, $content); - case self::ASSERT_CONTENT_REGEX: - if (3 > $argc) { - #require_once 'Zend/Test/PHPUnit/Constraint/Exception.php'; - throw new Zend_Test_PHPUnit_Constraint_Exception('No pattern provided against which to match'); - } - $this->_content = $content = $argv[2]; - return ($this->_negate) - ? $this->_notRegexContent($result, $content) - : $this->_regexContent($result, $content); - case self::ASSERT_CONTENT_COUNT: - case self::ASSERT_CONTENT_COUNT_MIN: - case self::ASSERT_CONTENT_COUNT_MAX: - if (3 > $argc) { - #require_once 'Zend/Test/PHPUnit/Constraint/Exception.php'; - throw new Zend_Test_PHPUnit_Constraint_Exception('No count provided against which to compare'); - } - $this->_content = $content = $argv[2]; - return $this->_countContent($result, $content, $assertType); - case self::ASSERT_QUERY: - default: - if ($this->_negate) { - return (0 == count($result)); - } else { - return (0 != count($result)); - } - } - } - - /** - * Report Failure - * - * @see PHPUnit_Framework_Constraint for implementation details - * @param mixed $other CSS selector path - * @param string $description - * @param bool $not - * @return void - * @throws PHPUnit_Framework_ExpectationFailedException - */ - public function fail($other, $description, $not = false) - { - #require_once 'Zend/Test/PHPUnit/Constraint/Exception.php'; - switch ($this->_assertType) { - case self::ASSERT_CONTENT_CONTAINS: - $failure = 'Failed asserting node denoted by %s CONTAINS content "%s"'; - if ($this->_negate) { - $failure = 'Failed asserting node DENOTED BY %s DOES NOT CONTAIN content "%s"'; - } - $failure = sprintf($failure, $other, $this->_content); - break; - case self::ASSERT_CONTENT_REGEX: - $failure = 'Failed asserting node denoted by %s CONTAINS content MATCHING "%s"'; - if ($this->_negate) { - $failure = 'Failed asserting node DENOTED BY %s DOES NOT CONTAIN content MATCHING "%s"'; - } - $failure = sprintf($failure, $other, $this->_content); - break; - case self::ASSERT_CONTENT_COUNT: - $failure = 'Failed asserting node DENOTED BY %s OCCURS EXACTLY %d times'; - if ($this->_negate) { - $failure = 'Failed asserting node DENOTED BY %s DOES NOT OCCUR EXACTLY %d times'; - } - $failure = sprintf($failure, $other, $this->_content); - break; - case self::ASSERT_CONTENT_COUNT_MIN: - $failure = 'Failed asserting node DENOTED BY %s OCCURS AT LEAST %d times'; - $failure = sprintf($failure, $other, $this->_content); - break; - case self::ASSERT_CONTENT_COUNT_MAX: - $failure = 'Failed asserting node DENOTED BY %s OCCURS AT MOST %d times'; - $failure = sprintf($failure, $other, $this->_content); - break; - case self::ASSERT_QUERY: - default: - $failure = 'Failed asserting node DENOTED BY %s EXISTS'; - if ($this->_negate) { - $failure = 'Failed asserting node DENOTED BY %s DOES NOT EXIST'; - } - $failure = sprintf($failure, $other); - break; - } - - if (!empty($description)) { - $failure = $description . "\n" . $failure; - } - - throw new Zend_Test_PHPUnit_Constraint_Exception($failure); - } - - /** - * Complete implementation - * - * @return string - */ - public function toString() - { - return ''; - } - - /** - * Register XPath namespaces - * - * @param array $xpathNamespaces - * @return void - */ - public function registerXpathNamespaces($xpathNamespaces) - { - $this->_xpathNamespaces = $xpathNamespaces; - } - - /** - * Check to see if content is matched in selected nodes - * - * @param Zend_Dom_Query_Result $result - * @param string $match Content to match - * @return bool - */ - protected function _matchContent($result, $match) - { - $match = (string) $match; - - if (0 == count($result)) { - return false; - } - - foreach ($result as $node) { - $content = $this->_getNodeContent($node); - if (strstr($content, $match)) { - return true; - } - } - - return false; - } - - /** - * Check to see if content is NOT matched in selected nodes - * - * @param Zend_Dom_Query_Result $result - * @param string $match - * @return bool - */ - protected function _notMatchContent($result, $match) - { - if (0 == count($result)) { - return true; - } - - foreach ($result as $node) { - $content = $this->_getNodeContent($node); - if (strstr($content, $match)) { - return false; - } - } - - return true; - } - - /** - * Check to see if content is matched by regex in selected nodes - * - * @param Zend_Dom_Query_Result $result - * @param string $pattern - * @return bool - */ - protected function _regexContent($result, $pattern) - { - if (0 == count($result)) { - return false; - } - - foreach ($result as $node) { - $content = $this->_getNodeContent($node); - if (preg_match($pattern, $content)) { - return true; - } - } - - return false; - } - - /** - * Check to see if content is NOT matched by regex in selected nodes - * - * @param Zend_Dom_Query_Result $result - * @param string $pattern - * @return bool - */ - protected function _notRegexContent($result, $pattern) - { - if (0 == count($result)) { - return true; - } - - foreach ($result as $node) { - $content = $this->_getNodeContent($node); - if (preg_match($pattern, $content)) { - return false; - } - } - - return true; - } - - /** - * Determine if content count matches criteria - * - * @param Zend_Dom_Query_Result $result - * @param int $test Value against which to test - * @param string $type assertion type - * @return boolean - */ - protected function _countContent($result, $test, $type) - { - $count = count($result); - - switch ($type) { - case self::ASSERT_CONTENT_COUNT: - return ($this->_negate) - ? ($test != $count) - : ($test == $count); - case self::ASSERT_CONTENT_COUNT_MIN: - return ($count >= $test); - case self::ASSERT_CONTENT_COUNT_MAX: - return ($count <= $test); - default: - return false; - } - } - - /** - * Get node content, minus node markup tags - * - * @param DOMNode $node - * @return string - */ - protected function _getNodeContent(DOMNode $node) - { - if ($node instanceof DOMAttr) { - return $node->value; - } else { - $doc = $node->ownerDocument; - $content = $doc->saveXML($node); - $tag = $node->nodeName; - $regex = '|]*>|'; - return preg_replace($regex, '', $content); - } - } -} diff --git a/library/Zend/Test/PHPUnit/Constraint/DomQuery37.php b/library/Zend/Test/PHPUnit/Constraint/DomQuery37.php deleted file mode 100644 index 2d07f09ded..0000000000 --- a/library/Zend/Test/PHPUnit/Constraint/DomQuery37.php +++ /dev/null @@ -1,434 +0,0 @@ -_path = $path; - } - - /** - * Indicate negative match - * - * @param bool $flag - * @return void - */ - public function setNegate($flag = true) - { - $this->_negate = $flag; - } - - /** - * Whether or not path is a straight XPath expression - * - * @param bool $flag - * @return Zend_Test_PHPUnit_Constraint_DomQuery - */ - public function setUseXpath($flag = true) - { - $this->_useXpath = (bool) $flag; - return $this; - } - - /** - * Evaluate an object to see if it fits the constraints - * - * @param string Response content to be matched against (haystack) - * @param null|string Assertion type - * @param string (optional) String to match (needle), may be required depending on assertion type - * @return bool - * - * NOTE: - * Drastic changes up to PHPUnit 3.5.15 this was: - * public function evaluate($other, $assertType = null) - * In PHPUnit 3.6.0 they changed the interface into this: - * public function evaluate($other, $description = '', $returnResult = FALSE) - * We use the new interface for PHP-strict checking, but emulate the old one - */ - public function evaluate($content, $assertType = '', $match = FALSE) - { - if (strstr($assertType, 'Not')) { - $this->setNegate(true); - $assertType = str_replace('Not', '', $assertType); - } - - if (strstr($assertType, 'Xpath')) { - $this->setUseXpath(true); - $assertType = str_replace('Xpath', 'Query', $assertType); - } - - if (!in_array($assertType, $this->_assertTypes)) { - #require_once 'Zend/Test/PHPUnit/Constraint/Exception.php'; - throw new Zend_Test_PHPUnit_Constraint_Exception(sprintf('Invalid assertion type "%s" provided to %s constraint', $assertType, __CLASS__)); - } - - $this->_assertType = $assertType; - - $method = $this->_useXpath ? 'queryXpath' : 'query'; - $domQuery = new Zend_Dom_Query($content); - $domQuery->registerXpathNamespaces($this->_xpathNamespaces); - $result = $domQuery->$method($this->_path); - - switch ($assertType) { - case self::ASSERT_CONTENT_CONTAINS: - if (!$match) { - #require_once 'Zend/Test/PHPUnit/Constraint/Exception.php'; - throw new Zend_Test_PHPUnit_Constraint_Exception('No content provided against which to match'); - } - $this->_content = $match; - return ($this->_negate) - ? $this->_notMatchContent($result, $match) - : $this->_matchContent($result, $match); - case self::ASSERT_CONTENT_REGEX: - if (!$match) { - #require_once 'Zend/Test/PHPUnit/Constraint/Exception.php'; - throw new Zend_Test_PHPUnit_Constraint_Exception('No pattern provided against which to match'); - } - $this->_content = $match; - return ($this->_negate) - ? $this->_notRegexContent($result, $match) - : $this->_regexContent($result, $match); - case self::ASSERT_CONTENT_COUNT: - case self::ASSERT_CONTENT_COUNT_MIN: - case self::ASSERT_CONTENT_COUNT_MAX: - if ($match === false) { - #require_once 'Zend/Test/PHPUnit/Constraint/Exception.php'; - throw new Zend_Test_PHPUnit_Constraint_Exception('No count provided against which to compare'); - } - $this->_content = $match; - return $this->_countContent($result, $match, $assertType); - case self::ASSERT_QUERY: - default: - if ($this->_negate) { - return (0 == count($result)); - } else { - return (0 != count($result)); - } - } - } - - /** - * Report Failure - * - * @see PHPUnit_Framework_Constraint for implementation details - * @param mixed CSS selector path - * @param string Failure description - * @param object Cannot be used, null - * @return void - * @throws PHPUnit_Framework_ExpectationFailedException - * NOTE: - * Drastic changes up to PHPUnit 3.5.15 this was: - * public function fail($other, $description, $not = false) - * In PHPUnit 3.6.0 they changed the interface into this: - * protected function fail($other, $description, PHPUnit_Framework_ComparisonFailure $comparisonFailure = NULL) - * We use the new interface for PHP-strict checking - */ - public function fail($other, $description, PHPUnit_Framework_ComparisonFailure $cannot_be_used = NULL) - { - #require_once 'Zend/Test/PHPUnit/Constraint/Exception.php'; - switch ($this->_assertType) { - case self::ASSERT_CONTENT_CONTAINS: - $failure = 'Failed asserting node denoted by %s CONTAINS content "%s"'; - if ($this->_negate) { - $failure = 'Failed asserting node DENOTED BY %s DOES NOT CONTAIN content "%s"'; - } - $failure = sprintf($failure, $other, $this->_content); - break; - case self::ASSERT_CONTENT_REGEX: - $failure = 'Failed asserting node denoted by %s CONTAINS content MATCHING "%s"'; - if ($this->_negate) { - $failure = 'Failed asserting node DENOTED BY %s DOES NOT CONTAIN content MATCHING "%s"'; - } - $failure = sprintf($failure, $other, $this->_content); - break; - case self::ASSERT_CONTENT_COUNT: - $failure = 'Failed asserting node DENOTED BY %s OCCURS EXACTLY %d times'; - if ($this->_negate) { - $failure = 'Failed asserting node DENOTED BY %s DOES NOT OCCUR EXACTLY %d times'; - } - $failure = sprintf($failure, $other, $this->_content); - break; - case self::ASSERT_CONTENT_COUNT_MIN: - $failure = 'Failed asserting node DENOTED BY %s OCCURS AT LEAST %d times'; - $failure = sprintf($failure, $other, $this->_content); - break; - case self::ASSERT_CONTENT_COUNT_MAX: - $failure = 'Failed asserting node DENOTED BY %s OCCURS AT MOST %d times'; - $failure = sprintf($failure, $other, $this->_content); - break; - case self::ASSERT_QUERY: - default: - $failure = 'Failed asserting node DENOTED BY %s EXISTS'; - if ($this->_negate) { - $failure = 'Failed asserting node DENOTED BY %s DOES NOT EXIST'; - } - $failure = sprintf($failure, $other); - break; - } - - if (!empty($description)) { - $failure = $description . "\n" . $failure; - } - - throw new Zend_Test_PHPUnit_Constraint_Exception($failure); - } - - /** - * Complete implementation - * - * @return string - */ - public function toString() - { - return ''; - } - - /** - * Register XPath namespaces - * - * @param array $xpathNamespaces - * @return void - */ - public function registerXpathNamespaces($xpathNamespaces) - { - $this->_xpathNamespaces = $xpathNamespaces; - } - - /** - * Check to see if content is matched in selected nodes - * - * @param Zend_Dom_Query_Result $result - * @param string $match Content to match - * @return bool - */ - protected function _matchContent($result, $match) - { - $match = (string) $match; - - if (0 == count($result)) { - return false; - } - - foreach ($result as $node) { - $content = $this->_getNodeContent($node); - if (strstr($content, $match)) { - return true; - } - } - - return false; - } - - /** - * Check to see if content is NOT matched in selected nodes - * - * @param Zend_Dom_Query_Result $result - * @param string $match - * @return bool - */ - protected function _notMatchContent($result, $match) - { - if (0 == count($result)) { - return true; - } - - foreach ($result as $node) { - $content = $this->_getNodeContent($node); - if (strstr($content, $match)) { - return false; - } - } - - return true; - } - - /** - * Check to see if content is matched by regex in selected nodes - * - * @param Zend_Dom_Query_Result $result - * @param string $pattern - * @return bool - */ - protected function _regexContent($result, $pattern) - { - if (0 == count($result)) { - return false; - } - - foreach ($result as $node) { - $content = $this->_getNodeContent($node); - if (preg_match($pattern, $content)) { - return true; - } - } - - return false; - } - - /** - * Check to see if content is NOT matched by regex in selected nodes - * - * @param Zend_Dom_Query_Result $result - * @param string $pattern - * @return bool - */ - protected function _notRegexContent($result, $pattern) - { - if (0 == count($result)) { - return true; - } - - foreach ($result as $node) { - $content = $this->_getNodeContent($node); - if (preg_match($pattern, $content)) { - return false; - } - } - - return true; - } - - /** - * Determine if content count matches criteria - * - * @param Zend_Dom_Query_Result $result - * @param int $test Value against which to test - * @param string $type assertion type - * @return boolean - */ - protected function _countContent($result, $test, $type) - { - $count = count($result); - - switch ($type) { - case self::ASSERT_CONTENT_COUNT: - return ($this->_negate) - ? ($test != $count) - : ($test == $count); - case self::ASSERT_CONTENT_COUNT_MIN: - return ($count >= $test); - case self::ASSERT_CONTENT_COUNT_MAX: - return ($count <= $test); - default: - return false; - } - } - - /** - * Get node content, minus node markup tags - * - * @param DOMNode $node - * @return string - */ - protected function _getNodeContent(DOMNode $node) - { - if ($node instanceof DOMAttr) { - return $node->value; - } else { - $doc = $node->ownerDocument; - $content = $doc->saveXML($node); - $tag = $node->nodeName; - $regex = '|]*>|'; - return preg_replace($regex, '', $content); - } - } -} diff --git a/library/Zend/Test/PHPUnit/Constraint/DomQuery41.php b/library/Zend/Test/PHPUnit/Constraint/DomQuery41.php deleted file mode 100644 index 631d5587a7..0000000000 --- a/library/Zend/Test/PHPUnit/Constraint/DomQuery41.php +++ /dev/null @@ -1,436 +0,0 @@ -_path = $path; - } - - /** - * Indicate negative match - * - * @param bool $flag - * @return void - */ - public function setNegate($flag = true) - { - $this->_negate = $flag; - } - - /** - * Whether or not path is a straight XPath expression - * - * @param bool $flag - * @return Zend_Test_PHPUnit_Constraint_DomQuery - */ - public function setUseXpath($flag = true) - { - $this->_useXpath = (bool) $flag; - return $this; - } - - /** - * Evaluate an object to see if it fits the constraints - * - * @param string Response content to be matched against (haystack) - * @param null|string Assertion type - * @param string (optional) String to match (needle), may be required depending on assertion type - * @return bool - * - * NOTE: - * Drastic changes up to PHPUnit 3.5.15 this was: - * public function evaluate($other, $assertType = null) - * In PHPUnit 3.6.0 they changed the interface into this: - * public function evaluate($other, $description = '', $returnResult = FALSE) - * We use the new interface for PHP-strict checking, but emulate the old one - */ - public function evaluate($content, $assertType = '', $match = FALSE) - { - if (strstr($assertType, 'Not')) { - $this->setNegate(true); - $assertType = str_replace('Not', '', $assertType); - } - - if (strstr($assertType, 'Xpath')) { - $this->setUseXpath(true); - $assertType = str_replace('Xpath', 'Query', $assertType); - } - - if (!in_array($assertType, $this->_assertTypes)) { - #require_once 'Zend/Test/PHPUnit/Constraint/Exception.php'; - throw new Zend_Test_PHPUnit_Constraint_Exception(sprintf('Invalid assertion type "%s" provided to %s constraint', $assertType, __CLASS__)); - } - - $this->_assertType = $assertType; - - $method = $this->_useXpath ? 'queryXpath' : 'query'; - $domQuery = new Zend_Dom_Query($content); - $domQuery->registerXpathNamespaces($this->_xpathNamespaces); - $result = $domQuery->$method($this->_path); - - switch ($assertType) { - case self::ASSERT_CONTENT_CONTAINS: - if (!$match) { - #require_once 'Zend/Test/PHPUnit/Constraint/Exception.php'; - throw new Zend_Test_PHPUnit_Constraint_Exception('No content provided against which to match'); - } - $this->_content = $match; - return ($this->_negate) - ? $this->_notMatchContent($result, $match) - : $this->_matchContent($result, $match); - case self::ASSERT_CONTENT_REGEX: - if (!$match) { - #require_once 'Zend/Test/PHPUnit/Constraint/Exception.php'; - throw new Zend_Test_PHPUnit_Constraint_Exception('No pattern provided against which to match'); - } - $this->_content = $match; - return ($this->_negate) - ? $this->_notRegexContent($result, $match) - : $this->_regexContent($result, $match); - case self::ASSERT_CONTENT_COUNT: - case self::ASSERT_CONTENT_COUNT_MIN: - case self::ASSERT_CONTENT_COUNT_MAX: - if ($match === false) { - #require_once 'Zend/Test/PHPUnit/Constraint/Exception.php'; - throw new Zend_Test_PHPUnit_Constraint_Exception('No count provided against which to compare'); - } - $this->_content = $match; - return $this->_countContent($result, $match, $assertType); - case self::ASSERT_QUERY: - default: - if ($this->_negate) { - return (0 == count($result)); - } else { - return (0 != count($result)); - } - } - } - - /** - * Report Failure - * - * @see PHPUnit_Framework_Constraint for implementation details - * @param mixed CSS selector path - * @param string Failure description - * @param object Cannot be used, null - * @return void - * @throws PHPUnit_Framework_ExpectationFailedException - * NOTE: - * Drastic changes up to PHPUnit 3.5.15 this was: - * public function fail($other, $description, $not = false) - * In PHPUnit 3.6.0 they changed the interface into this: - * protected function fail($other, $description, PHPUnit_Framework_ComparisonFailure $comparisonFailure = NULL) - * We use the new interface for PHP-strict checking - * NOTE 2: - * Interface changed again in PHPUnit 4.1.0 because of refactoring to SebastianBergmann\Comparator - */ - public function fail($other, $description, \SebastianBergmann\Comparator\ComparisonFailure $cannot_be_used = NULL) - { - #require_once 'Zend/Test/PHPUnit/Constraint/Exception.php'; - switch ($this->_assertType) { - case self::ASSERT_CONTENT_CONTAINS: - $failure = 'Failed asserting node denoted by %s CONTAINS content "%s"'; - if ($this->_negate) { - $failure = 'Failed asserting node DENOTED BY %s DOES NOT CONTAIN content "%s"'; - } - $failure = sprintf($failure, $other, $this->_content); - break; - case self::ASSERT_CONTENT_REGEX: - $failure = 'Failed asserting node denoted by %s CONTAINS content MATCHING "%s"'; - if ($this->_negate) { - $failure = 'Failed asserting node DENOTED BY %s DOES NOT CONTAIN content MATCHING "%s"'; - } - $failure = sprintf($failure, $other, $this->_content); - break; - case self::ASSERT_CONTENT_COUNT: - $failure = 'Failed asserting node DENOTED BY %s OCCURS EXACTLY %d times'; - if ($this->_negate) { - $failure = 'Failed asserting node DENOTED BY %s DOES NOT OCCUR EXACTLY %d times'; - } - $failure = sprintf($failure, $other, $this->_content); - break; - case self::ASSERT_CONTENT_COUNT_MIN: - $failure = 'Failed asserting node DENOTED BY %s OCCURS AT LEAST %d times'; - $failure = sprintf($failure, $other, $this->_content); - break; - case self::ASSERT_CONTENT_COUNT_MAX: - $failure = 'Failed asserting node DENOTED BY %s OCCURS AT MOST %d times'; - $failure = sprintf($failure, $other, $this->_content); - break; - case self::ASSERT_QUERY: - default: - $failure = 'Failed asserting node DENOTED BY %s EXISTS'; - if ($this->_negate) { - $failure = 'Failed asserting node DENOTED BY %s DOES NOT EXIST'; - } - $failure = sprintf($failure, $other); - break; - } - - if (!empty($description)) { - $failure = $description . "\n" . $failure; - } - - throw new Zend_Test_PHPUnit_Constraint_Exception($failure); - } - - /** - * Complete implementation - * - * @return string - */ - public function toString() - { - return ''; - } - - /** - * Register XPath namespaces - * - * @param array $xpathNamespaces - * @return void - */ - public function registerXpathNamespaces($xpathNamespaces) - { - $this->_xpathNamespaces = $xpathNamespaces; - } - - /** - * Check to see if content is matched in selected nodes - * - * @param Zend_Dom_Query_Result $result - * @param string $match Content to match - * @return bool - */ - protected function _matchContent($result, $match) - { - $match = (string) $match; - - if (0 == count($result)) { - return false; - } - - foreach ($result as $node) { - $content = $this->_getNodeContent($node); - if (strstr($content, $match)) { - return true; - } - } - - return false; - } - - /** - * Check to see if content is NOT matched in selected nodes - * - * @param Zend_Dom_Query_Result $result - * @param string $match - * @return bool - */ - protected function _notMatchContent($result, $match) - { - if (0 == count($result)) { - return true; - } - - foreach ($result as $node) { - $content = $this->_getNodeContent($node); - if (strstr($content, $match)) { - return false; - } - } - - return true; - } - - /** - * Check to see if content is matched by regex in selected nodes - * - * @param Zend_Dom_Query_Result $result - * @param string $pattern - * @return bool - */ - protected function _regexContent($result, $pattern) - { - if (0 == count($result)) { - return false; - } - - foreach ($result as $node) { - $content = $this->_getNodeContent($node); - if (preg_match($pattern, $content)) { - return true; - } - } - - return false; - } - - /** - * Check to see if content is NOT matched by regex in selected nodes - * - * @param Zend_Dom_Query_Result $result - * @param string $pattern - * @return bool - */ - protected function _notRegexContent($result, $pattern) - { - if (0 == count($result)) { - return true; - } - - foreach ($result as $node) { - $content = $this->_getNodeContent($node); - if (preg_match($pattern, $content)) { - return false; - } - } - - return true; - } - - /** - * Determine if content count matches criteria - * - * @param Zend_Dom_Query_Result $result - * @param int $test Value against which to test - * @param string $type assertion type - * @return boolean - */ - protected function _countContent($result, $test, $type) - { - $count = count($result); - - switch ($type) { - case self::ASSERT_CONTENT_COUNT: - return ($this->_negate) - ? ($test != $count) - : ($test == $count); - case self::ASSERT_CONTENT_COUNT_MIN: - return ($count >= $test); - case self::ASSERT_CONTENT_COUNT_MAX: - return ($count <= $test); - default: - return false; - } - } - - /** - * Get node content, minus node markup tags - * - * @param DOMNode $node - * @return string - */ - protected function _getNodeContent(DOMNode $node) - { - if ($node instanceof DOMAttr) { - return $node->value; - } else { - $doc = $node->ownerDocument; - $content = $doc->saveXML($node); - $tag = $node->nodeName; - $regex = '|]*>|'; - return preg_replace($regex, '', $content); - } - } -} diff --git a/library/Zend/Test/PHPUnit/Constraint/Exception.php b/library/Zend/Test/PHPUnit/Constraint/Exception.php deleted file mode 100644 index 2286fef076..0000000000 --- a/library/Zend/Test/PHPUnit/Constraint/Exception.php +++ /dev/null @@ -1,35 +0,0 @@ -=')) { - include(dirname(__FILE__) . DIRECTORY_SEPARATOR . 'Redirect41.php'); - - class Zend_Test_PHPUnit_Constraint_Redirect extends Zend_Test_PHPUnit_Constraint_Redirect41 - {} -} elseif (version_compare(PHPUnit_Runner_Version::id(), '3.5', '>=')) { - include(dirname(__FILE__) . DIRECTORY_SEPARATOR . 'Redirect37.php'); - - class Zend_Test_PHPUnit_Constraint_Redirect extends Zend_Test_PHPUnit_Constraint_Redirect37 - {} -} else { - include(dirname(__FILE__) . DIRECTORY_SEPARATOR . 'Redirect34.php'); - - class Zend_Test_PHPUnit_Constraint_Redirect extends Zend_Test_PHPUnit_Constraint_Redirect34 - {} -} diff --git a/library/Zend/Test/PHPUnit/Constraint/Redirect34.php b/library/Zend/Test/PHPUnit/Constraint/Redirect34.php deleted file mode 100644 index 8f350189bb..0000000000 --- a/library/Zend/Test/PHPUnit/Constraint/Redirect34.php +++ /dev/null @@ -1,303 +0,0 @@ -_negate = $flag; - } - - /** - * Evaluate an object to see if it fits the constraints - * - * @param string $other String to examine - * @param null|string Assertion type - * @return bool - */ - public function evaluate($other, $assertType = null) - { - if (!$other instanceof Zend_Controller_Response_Abstract) { - #require_once 'Zend/Test/PHPUnit/Constraint/Exception.php'; - throw new Zend_Test_PHPUnit_Constraint_Exception('Redirect constraint assertions require a response object'); - } - - if (strstr($assertType, 'Not')) { - $this->setNegate(true); - $assertType = str_replace('Not', '', $assertType); - } - - if (!in_array($assertType, $this->_assertTypes)) { - #require_once 'Zend/Test/PHPUnit/Constraint/Exception.php'; - throw new Zend_Test_PHPUnit_Constraint_Exception(sprintf('Invalid assertion type "%s" provided to %s constraint', $assertType, __CLASS__)); - } - - $this->_assertType = $assertType; - - $response = $other; - $argv = func_get_args(); - $argc = func_num_args(); - - switch ($assertType) { - case self::ASSERT_REDIRECT_TO: - if (3 > $argc) { - #require_once 'Zend/Test/PHPUnit/Constraint/Exception.php'; - throw new Zend_Test_PHPUnit_Constraint_Exception('No redirect URL provided against which to match'); - } - $this->_match = $match = $argv[2]; - return ($this->_negate) - ? $this->_notMatch($response, $match) - : $this->_match($response, $match); - case self::ASSERT_REDIRECT_REGEX: - if (3 > $argc) { - #require_once 'Zend/Test/PHPUnit/Constraint/Exception.php'; - throw new Zend_Test_PHPUnit_Constraint_Exception('No pattern provided against which to match redirect'); - } - $this->_match = $match = $argv[2]; - return ($this->_negate) - ? $this->_notRegex($response, $match) - : $this->_regex($response, $match); - case self::ASSERT_REDIRECT: - default: - $headers = $response->sendHeaders(); - if (isset($headers['location'])) { - $redirect = $headers['location']; - $redirect = str_replace('Location: ', '', $redirect); - $this->_actual = $redirect; - } - return ($this->_negate) ? !$response->isRedirect() : $response->isRedirect(); - } - } - - /** - * Report Failure - * - * @see PHPUnit_Framework_Constraint for implementation details - * @param mixed $other - * @param string $description Additional message to display - * @param bool $not - * @return void - * @throws PHPUnit_Framework_ExpectationFailedException - */ - public function fail($other, $description, $not = false) - { - #require_once 'Zend/Test/PHPUnit/Constraint/Exception.php'; - switch ($this->_assertType) { - case self::ASSERT_REDIRECT_TO: - $failure = 'Failed asserting response redirects to "%s"'; - if ($this->_negate) { - $failure = 'Failed asserting response DOES NOT redirect to "%s"'; - } - $failure = sprintf($failure, $this->_match); - if (!$this->_negate && $this->_actual) { - $failure .= sprintf(PHP_EOL . 'It redirects to "%s".', $this->_actual); - } - break; - case self::ASSERT_REDIRECT_REGEX: - $failure = 'Failed asserting response redirects to URL MATCHING "%s"'; - if ($this->_negate) { - $failure = 'Failed asserting response DOES NOT redirect to URL MATCHING "%s"'; - } - $failure = sprintf($failure, $this->_match); - if ($this->_actual) { - $failure .= sprintf(PHP_EOL . 'It redirects to "%s".', $this->_actual); - } - break; - case self::ASSERT_REDIRECT: - default: - $failure = 'Failed asserting response is a redirect'; - if ($this->_negate) { - $failure = 'Failed asserting response is NOT a redirect'; - if ($this->_actual) { - $failure .= sprintf(PHP_EOL . 'It redirects to "%s"', $this->_actual); - } - } - break; - } - - if (!empty($description)) { - $failure = $description . "\n" . $failure; - } - - throw new Zend_Test_PHPUnit_Constraint_Exception($failure); - } - - /** - * Complete implementation - * - * @return string - */ - public function toString() - { - return ''; - } - - /** - * Check to see if content is matched in selected nodes - * - * @param Zend_Controller_Response_HttpTestCase $response - * @param string $match Content to match - * @return bool - */ - protected function _match($response, $match) - { - if (!$response->isRedirect()) { - return false; - } - - $headers = $response->sendHeaders(); - $redirect = $headers['location']; - $redirect = str_replace('Location: ', '', $redirect); - $this->_actual = $redirect; - - return ($redirect == $match); - } - - /** - * Check to see if content is NOT matched in selected nodes - * - * @param Zend_Controller_Response_HttpTestCase $response - * @param string $match - * @return bool - */ - protected function _notMatch($response, $match) - { - if (!$response->isRedirect()) { - return true; - } - - $headers = $response->sendHeaders(); - $redirect = $headers['location']; - $redirect = str_replace('Location: ', '', $redirect); - $this->_actual = $redirect; - - return ($redirect != $match); - } - - /** - * Check to see if content is matched by regex in selected nodes - * - * @param Zend_Controller_Response_HttpTestCase $response - * @param string $pattern - * @return bool - */ - protected function _regex($response, $pattern) - { - if (!$response->isRedirect()) { - return false; - } - - $headers = $response->sendHeaders(); - $redirect = $headers['location']; - $redirect = str_replace('Location: ', '', $redirect); - $this->_actual = $redirect; - - return preg_match($pattern, $redirect); - } - - /** - * Check to see if content is NOT matched by regex in selected nodes - * - * @param Zend_Controller_Response_HttpTestCase $response - * @param string $pattern - * @return bool - */ - protected function _notRegex($response, $pattern) - { - if (!$response->isRedirect()) { - return true; - } - - $headers = $response->sendHeaders(); - $redirect = $headers['location']; - $redirect = str_replace('Location: ', '', $redirect); - $this->_actual = $redirect; - - return !preg_match($pattern, $redirect); - } -} diff --git a/library/Zend/Test/PHPUnit/Constraint/Redirect37.php b/library/Zend/Test/PHPUnit/Constraint/Redirect37.php deleted file mode 100644 index f47c491eee..0000000000 --- a/library/Zend/Test/PHPUnit/Constraint/Redirect37.php +++ /dev/null @@ -1,315 +0,0 @@ -_negate = $flag; - } - - /** - * Evaluate an object to see if it fits the constraints - * - * @param string $other String to examine - * @param null|string Assertion type - * @return bool - * NOTE: - * Drastic changes up to PHPUnit 3.5.15 this was: - * public function evaluate($other, $assertType = null) - * In PHPUnit 3.6.0 they changed the interface into this: - * public function evaluate($other, $description = '', $returnResult = FALSE) - * We use the new interface for PHP-strict checking, but emulate the old one - */ - public function evaluate($other, $assertType = null, $variable = FALSE) - { - if (!$other instanceof Zend_Controller_Response_Abstract) { - #require_once 'Zend/Test/PHPUnit/Constraint/Exception.php'; - throw new Zend_Test_PHPUnit_Constraint_Exception('Redirect constraint assertions require a response object'); - } - - if (strstr($assertType, 'Not')) { - $this->setNegate(true); - $assertType = str_replace('Not', '', $assertType); - } - - if (!in_array($assertType, $this->_assertTypes)) { - #require_once 'Zend/Test/PHPUnit/Constraint/Exception.php'; - throw new Zend_Test_PHPUnit_Constraint_Exception(sprintf('Invalid assertion type "%s" provided to %s constraint', $assertType, __CLASS__)); - } - - $this->_assertType = $assertType; - - $response = $other; - $argv = func_get_args(); - $argc = func_num_args(); - - switch ($assertType) { - case self::ASSERT_REDIRECT_TO: - if (3 > $argc) { - #require_once 'Zend/Test/PHPUnit/Constraint/Exception.php'; - throw new Zend_Test_PHPUnit_Constraint_Exception('No redirect URL provided against which to match'); - } - $this->_match = $match = $argv[2]; - return ($this->_negate) - ? $this->_notMatch($response, $match) - : $this->_match($response, $match); - case self::ASSERT_REDIRECT_REGEX: - if (3 > $argc) { - #require_once 'Zend/Test/PHPUnit/Constraint/Exception.php'; - throw new Zend_Test_PHPUnit_Constraint_Exception('No pattern provided against which to match redirect'); - } - $this->_match = $match = $argv[2]; - return ($this->_negate) - ? $this->_notRegex($response, $match) - : $this->_regex($response, $match); - case self::ASSERT_REDIRECT: - default: - $headers = $response->sendHeaders(); - if (isset($headers['location'])) { - $redirect = $headers['location']; - $redirect = str_replace('Location: ', '', $redirect); - $this->_actual = $redirect; - } - return ($this->_negate) ? !$response->isRedirect() : $response->isRedirect(); - } - } - - /** - * Report Failure - * - * @see PHPUnit_Framework_Constraint for implementation details - * @param mixed $other - * @param string $description Additional message to display - * @param bool $not - * @return void - * @throws PHPUnit_Framework_ExpectationFailedException - * NOTE: - * Drastic changes up to PHPUnit 3.5.15 this was: - * public function fail($other, $description, $not = false) - * In PHPUnit 3.6.0 they changed the interface into this: - * protected function fail($other, $description, PHPUnit_Framework_ComparisonFailure $comparisonFailure = NULL) - * We use the new interface for PHP-strict checking - */ - public function fail($other, $description, PHPUnit_Framework_ComparisonFailure $cannot_be_used = NULL) - { - #require_once 'Zend/Test/PHPUnit/Constraint/Exception.php'; - switch ($this->_assertType) { - case self::ASSERT_REDIRECT_TO: - $failure = 'Failed asserting response redirects to "%s"'; - if ($this->_negate) { - $failure = 'Failed asserting response DOES NOT redirect to "%s"'; - } - $failure = sprintf($failure, $this->_match); - if (!$this->_negate && $this->_actual) { - $failure .= sprintf(PHP_EOL . 'It redirects to "%s".', $this->_actual); - } - break; - case self::ASSERT_REDIRECT_REGEX: - $failure = 'Failed asserting response redirects to URL MATCHING "%s"'; - if ($this->_negate) { - $failure = 'Failed asserting response DOES NOT redirect to URL MATCHING "%s"'; - } - $failure = sprintf($failure, $this->_match); - if ($this->_actual) { - $failure .= sprintf(PHP_EOL . 'It redirects to "%s".', $this->_actual); - } - break; - case self::ASSERT_REDIRECT: - default: - $failure = 'Failed asserting response is a redirect'; - if ($this->_negate) { - $failure = 'Failed asserting response is NOT a redirect'; - if ($this->_actual) { - $failure .= sprintf(PHP_EOL . 'It redirects to "%s"', $this->_actual); - } - } - break; - } - - if (!empty($description)) { - $failure = $description . "\n" . $failure; - } - - throw new Zend_Test_PHPUnit_Constraint_Exception($failure); - } - - /** - * Complete implementation - * - * @return string - */ - public function toString() - { - return ''; - } - - /** - * Check to see if content is matched in selected nodes - * - * @param Zend_Controller_Response_HttpTestCase $response - * @param string $match Content to match - * @return bool - */ - protected function _match($response, $match) - { - if (!$response->isRedirect()) { - return false; - } - - $headers = $response->sendHeaders(); - $redirect = $headers['location']; - $redirect = str_replace('Location: ', '', $redirect); - $this->_actual = $redirect; - - return ($redirect == $match); - } - - /** - * Check to see if content is NOT matched in selected nodes - * - * @param Zend_Controller_Response_HttpTestCase $response - * @param string $match - * @return bool - */ - protected function _notMatch($response, $match) - { - if (!$response->isRedirect()) { - return true; - } - - $headers = $response->sendHeaders(); - $redirect = $headers['location']; - $redirect = str_replace('Location: ', '', $redirect); - $this->_actual = $redirect; - - return ($redirect != $match); - } - - /** - * Check to see if content is matched by regex in selected nodes - * - * @param Zend_Controller_Response_HttpTestCase $response - * @param string $pattern - * @return bool - */ - protected function _regex($response, $pattern) - { - if (!$response->isRedirect()) { - return false; - } - - $headers = $response->sendHeaders(); - $redirect = $headers['location']; - $redirect = str_replace('Location: ', '', $redirect); - $this->_actual = $redirect; - - return preg_match($pattern, $redirect); - } - - /** - * Check to see if content is NOT matched by regex in selected nodes - * - * @param Zend_Controller_Response_HttpTestCase $response - * @param string $pattern - * @return bool - */ - protected function _notRegex($response, $pattern) - { - if (!$response->isRedirect()) { - return true; - } - - $headers = $response->sendHeaders(); - $redirect = $headers['location']; - $redirect = str_replace('Location: ', '', $redirect); - $this->_actual = $redirect; - - return !preg_match($pattern, $redirect); - } -} diff --git a/library/Zend/Test/PHPUnit/Constraint/Redirect41.php b/library/Zend/Test/PHPUnit/Constraint/Redirect41.php deleted file mode 100644 index 35423a6a58..0000000000 --- a/library/Zend/Test/PHPUnit/Constraint/Redirect41.php +++ /dev/null @@ -1,317 +0,0 @@ -_negate = $flag; - } - - /** - * Evaluate an object to see if it fits the constraints - * - * @param string $other String to examine - * @param null|string Assertion type - * @return bool - * NOTE: - * Drastic changes up to PHPUnit 3.5.15 this was: - * public function evaluate($other, $assertType = null) - * In PHPUnit 3.6.0 they changed the interface into this: - * public function evaluate($other, $description = '', $returnResult = FALSE) - * We use the new interface for PHP-strict checking, but emulate the old one - */ - public function evaluate($other, $assertType = null, $variable = FALSE) - { - if (!$other instanceof Zend_Controller_Response_Abstract) { - #require_once 'Zend/Test/PHPUnit/Constraint/Exception.php'; - throw new Zend_Test_PHPUnit_Constraint_Exception('Redirect constraint assertions require a response object'); - } - - if (strstr($assertType, 'Not')) { - $this->setNegate(true); - $assertType = str_replace('Not', '', $assertType); - } - - if (!in_array($assertType, $this->_assertTypes)) { - #require_once 'Zend/Test/PHPUnit/Constraint/Exception.php'; - throw new Zend_Test_PHPUnit_Constraint_Exception(sprintf('Invalid assertion type "%s" provided to %s constraint', $assertType, __CLASS__)); - } - - $this->_assertType = $assertType; - - $response = $other; - $argv = func_get_args(); - $argc = func_num_args(); - - switch ($assertType) { - case self::ASSERT_REDIRECT_TO: - if (3 > $argc) { - #require_once 'Zend/Test/PHPUnit/Constraint/Exception.php'; - throw new Zend_Test_PHPUnit_Constraint_Exception('No redirect URL provided against which to match'); - } - $this->_match = $match = $argv[2]; - return ($this->_negate) - ? $this->_notMatch($response, $match) - : $this->_match($response, $match); - case self::ASSERT_REDIRECT_REGEX: - if (3 > $argc) { - #require_once 'Zend/Test/PHPUnit/Constraint/Exception.php'; - throw new Zend_Test_PHPUnit_Constraint_Exception('No pattern provided against which to match redirect'); - } - $this->_match = $match = $argv[2]; - return ($this->_negate) - ? $this->_notRegex($response, $match) - : $this->_regex($response, $match); - case self::ASSERT_REDIRECT: - default: - $headers = $response->sendHeaders(); - if (isset($headers['location'])) { - $redirect = $headers['location']; - $redirect = str_replace('Location: ', '', $redirect); - $this->_actual = $redirect; - } - return ($this->_negate) ? !$response->isRedirect() : $response->isRedirect(); - } - } - - /** - * Report Failure - * - * @see PHPUnit_Framework_Constraint for implementation details - * @param mixed $other - * @param string $description Additional message to display - * @param bool $not - * @return void - * @throws PHPUnit_Framework_ExpectationFailedException - * NOTE: - * Drastic changes up to PHPUnit 3.5.15 this was: - * public function fail($other, $description, $not = false) - * In PHPUnit 3.6.0 they changed the interface into this: - * protected function fail($other, $description, PHPUnit_Framework_ComparisonFailure $comparisonFailure = NULL) - * We use the new interface for PHP-strict checking - * NOTE 2: - * Interface changed again in PHPUnit 4.1.0 because of refactoring to SebastianBergmann\Comparator - */ - public function fail($other, $description, \SebastianBergmann\Comparator\ComparisonFailure $cannot_be_used = NULL) - { - #require_once 'Zend/Test/PHPUnit/Constraint/Exception.php'; - switch ($this->_assertType) { - case self::ASSERT_REDIRECT_TO: - $failure = 'Failed asserting response redirects to "%s"'; - if ($this->_negate) { - $failure = 'Failed asserting response DOES NOT redirect to "%s"'; - } - $failure = sprintf($failure, $this->_match); - if (!$this->_negate && $this->_actual) { - $failure .= sprintf(PHP_EOL . 'It redirects to "%s".', $this->_actual); - } - break; - case self::ASSERT_REDIRECT_REGEX: - $failure = 'Failed asserting response redirects to URL MATCHING "%s"'; - if ($this->_negate) { - $failure = 'Failed asserting response DOES NOT redirect to URL MATCHING "%s"'; - } - $failure = sprintf($failure, $this->_match); - if ($this->_actual) { - $failure .= sprintf(PHP_EOL . 'It redirects to "%s".', $this->_actual); - } - break; - case self::ASSERT_REDIRECT: - default: - $failure = 'Failed asserting response is a redirect'; - if ($this->_negate) { - $failure = 'Failed asserting response is NOT a redirect'; - if ($this->_actual) { - $failure .= sprintf(PHP_EOL . 'It redirects to "%s"', $this->_actual); - } - } - break; - } - - if (!empty($description)) { - $failure = $description . "\n" . $failure; - } - - throw new Zend_Test_PHPUnit_Constraint_Exception($failure); - } - - /** - * Complete implementation - * - * @return string - */ - public function toString() - { - return ''; - } - - /** - * Check to see if content is matched in selected nodes - * - * @param Zend_Controller_Response_HttpTestCase $response - * @param string $match Content to match - * @return bool - */ - protected function _match($response, $match) - { - if (!$response->isRedirect()) { - return false; - } - - $headers = $response->sendHeaders(); - $redirect = $headers['location']; - $redirect = str_replace('Location: ', '', $redirect); - $this->_actual = $redirect; - - return ($redirect == $match); - } - - /** - * Check to see if content is NOT matched in selected nodes - * - * @param Zend_Controller_Response_HttpTestCase $response - * @param string $match - * @return bool - */ - protected function _notMatch($response, $match) - { - if (!$response->isRedirect()) { - return true; - } - - $headers = $response->sendHeaders(); - $redirect = $headers['location']; - $redirect = str_replace('Location: ', '', $redirect); - $this->_actual = $redirect; - - return ($redirect != $match); - } - - /** - * Check to see if content is matched by regex in selected nodes - * - * @param Zend_Controller_Response_HttpTestCase $response - * @param string $pattern - * @return bool - */ - protected function _regex($response, $pattern) - { - if (!$response->isRedirect()) { - return false; - } - - $headers = $response->sendHeaders(); - $redirect = $headers['location']; - $redirect = str_replace('Location: ', '', $redirect); - $this->_actual = $redirect; - - return preg_match($pattern, $redirect); - } - - /** - * Check to see if content is NOT matched by regex in selected nodes - * - * @param Zend_Controller_Response_HttpTestCase $response - * @param string $pattern - * @return bool - */ - protected function _notRegex($response, $pattern) - { - if (!$response->isRedirect()) { - return true; - } - - $headers = $response->sendHeaders(); - $redirect = $headers['location']; - $redirect = str_replace('Location: ', '', $redirect); - $this->_actual = $redirect; - - return !preg_match($pattern, $redirect); - } -} diff --git a/library/Zend/Test/PHPUnit/Constraint/ResponseHeader.php b/library/Zend/Test/PHPUnit/Constraint/ResponseHeader.php deleted file mode 100644 index 178de05051..0000000000 --- a/library/Zend/Test/PHPUnit/Constraint/ResponseHeader.php +++ /dev/null @@ -1,38 +0,0 @@ -=')) { - include(dirname(__FILE__) . DIRECTORY_SEPARATOR . 'ResponseHeader41.php'); - - class Zend_Test_PHPUnit_Constraint_ResponseHeader extends Zend_Test_PHPUnit_Constraint_ResponseHeader41 - {} -} elseif (version_compare(PHPUnit_Runner_Version::id(), '3.5', '>=')) { - include(dirname(__FILE__) . DIRECTORY_SEPARATOR . 'ResponseHeader37.php'); - - class Zend_Test_PHPUnit_Constraint_ResponseHeader extends Zend_Test_PHPUnit_Constraint_ResponseHeader37 - {} -} else { - include(dirname(__FILE__) . DIRECTORY_SEPARATOR . 'ResponseHeader34.php'); - - class Zend_Test_PHPUnit_Constraint_ResponseHeader extends Zend_Test_PHPUnit_Constraint_ResponseHeader34 - {} -} diff --git a/library/Zend/Test/PHPUnit/Constraint/ResponseHeader34.php b/library/Zend/Test/PHPUnit/Constraint/ResponseHeader34.php deleted file mode 100644 index e866af3888..0000000000 --- a/library/Zend/Test/PHPUnit/Constraint/ResponseHeader34.php +++ /dev/null @@ -1,406 +0,0 @@ -_negate = $flag; - } - - /** - * Evaluate an object to see if it fits the constraints - * - * @param Zend_Controller_Response_Abstract $other String to examine - * @param null|string Assertion type - * @return bool - */ - public function evaluate($other, $assertType = null) - { - if (!$other instanceof Zend_Controller_Response_Abstract) { - #require_once 'Zend/Test/PHPUnit/Constraint/Exception.php'; - throw new Zend_Test_PHPUnit_Constraint_Exception('Header constraint assertions require a response object'); - } - - if (strstr($assertType, 'Not')) { - $this->setNegate(true); - $assertType = str_replace('Not', '', $assertType); - } - - if (!in_array($assertType, $this->_assertTypes)) { - #require_once 'Zend/Test/PHPUnit/Constraint/Exception.php'; - throw new Zend_Test_PHPUnit_Constraint_Exception(sprintf('Invalid assertion type "%s" provided to %s constraint', $assertType, __CLASS__)); - } - - $this->_assertType = $assertType; - - $response = $other; - $argv = func_get_args(); - $argc = func_num_args(); - - switch ($assertType) { - case self::ASSERT_RESPONSE_CODE: - if (3 > $argc) { - #require_once 'Zend/Test/PHPUnit/Constraint/Exception.php'; - throw new Zend_Test_PHPUnit_Constraint_Exception('No response code provided against which to match'); - } - $this->_code = $code = $argv[2]; - return ($this->_negate) - ? $this->_notCode($response, $code) - : $this->_code($response, $code); - case self::ASSERT_HEADER: - if (3 > $argc) { - #require_once 'Zend/Test/PHPUnit/Constraint/Exception.php'; - throw new Zend_Test_PHPUnit_Constraint_Exception('No header provided against which to match'); - } - $this->_header = $header = $argv[2]; - return ($this->_negate) - ? $this->_notHeader($response, $header) - : $this->_header($response, $header); - case self::ASSERT_HEADER_CONTAINS: - if (4 > $argc) { - #require_once 'Zend/Test/PHPUnit/Constraint/Exception.php'; - throw new Zend_Test_PHPUnit_Constraint_Exception('Both a header name and content to match are required for ' . __FUNCTION__); - } - $this->_header = $header = $argv[2]; - $this->_match = $match = $argv[3]; - return ($this->_negate) - ? $this->_notHeaderContains($response, $header, $match) - : $this->_headerContains($response, $header, $match); - case self::ASSERT_HEADER_REGEX: - if (4 > $argc) { - #require_once 'Zend/Test/PHPUnit/Constraint/Exception.php'; - throw new Zend_Test_PHPUnit_Constraint_Exception('Both a header name and content to match are required for ' . __FUNCTION__); - } - $this->_header = $header = $argv[2]; - $this->_match = $match = $argv[3]; - return ($this->_negate) - ? $this->_notHeaderRegex($response, $header, $match) - : $this->_headerRegex($response, $header, $match); - default: - #require_once 'Zend/Test/PHPUnit/Constraint/Exception.php'; - throw new Zend_Test_PHPUnit_Constraint_Exception('Invalid assertion type ' . __FUNCTION__); - } - } - - /** - * Report Failure - * - * @see PHPUnit_Framework_Constraint for implementation details - * @param mixed $other - * @param string $description Additional message to display - * @param bool $not - * @return void - * @throws PHPUnit_Framework_ExpectationFailedException - */ - public function fail($other, $description, $not = false) - { - #require_once 'Zend/Test/PHPUnit/Constraint/Exception.php'; - switch ($this->_assertType) { - case self::ASSERT_RESPONSE_CODE: - $failure = 'Failed asserting response code "%s"'; - if ($this->_negate) { - $failure = 'Failed asserting response code IS NOT "%s"'; - } - $failure = sprintf($failure, $this->_code); - if (!$this->_negate && $this->_actualCode) { - $failure .= sprintf(PHP_EOL . 'Was "%s"', $this->_actualCode); - } - break; - case self::ASSERT_HEADER: - $failure = 'Failed asserting response header "%s" found'; - if ($this->_negate) { - $failure = 'Failed asserting response response header "%s" WAS NOT found'; - } - $failure = sprintf($failure, $this->_header); - break; - case self::ASSERT_HEADER_CONTAINS: - $failure = 'Failed asserting response header "%s" exists and contains "%s"'; - if ($this->_negate) { - $failure = 'Failed asserting response header "%s" DOES NOT CONTAIN "%s"'; - } - $failure = sprintf($failure, $this->_header, $this->_match); - break; - case self::ASSERT_HEADER_REGEX: - $failure = 'Failed asserting response header "%s" exists and matches regex "%s"'; - if ($this->_negate) { - $failure = 'Failed asserting response header "%s" DOES NOT MATCH regex "%s"'; - } - $failure = sprintf($failure, $this->_header, $this->_match); - break; - default: - throw new Zend_Test_PHPUnit_Constraint_Exception('Invalid assertion type ' . __FUNCTION__); - } - - if (!empty($description)) { - $failure = $description . "\n" . $failure; - } - - throw new Zend_Test_PHPUnit_Constraint_Exception($failure); - } - - /** - * Complete implementation - * - * @return string - */ - public function toString() - { - return ''; - } - - /** - * Compare response code for positive match - * - * @param Zend_Controller_Response_Abstract $response - * @param int $code - * @return bool - */ - protected function _code(Zend_Controller_Response_Abstract $response, $code) - { - $test = $this->_getCode($response); - $this->_actualCode = $test; - return ($test == $code); - } - - /** - * Compare response code for negative match - * - * @param Zend_Controller_Response_Abstract $response - * @param int $code - * @return bool - */ - protected function _notCode(Zend_Controller_Response_Abstract $response, $code) - { - $test = $this->_getCode($response); - return ($test != $code); - } - - /** - * Retrieve response code - * - * @param Zend_Controller_Response_Abstract $response - * @return int - */ - protected function _getCode(Zend_Controller_Response_Abstract $response) - { - $test = $response->getHttpResponseCode(); - if (null === $test) { - $test = 200; - } - return $test; - } - - /** - * Positive check for response header presence - * - * @param Zend_Controller_Response_Abstract $response - * @param string $header - * @return bool - */ - protected function _header(Zend_Controller_Response_Abstract $response, $header) - { - return (null !== $this->_getHeader($response, $header)); - } - - /** - * Negative check for response header presence - * - * @param Zend_Controller_Response_Abstract $response - * @param string $header - * @return bool - */ - protected function _notHeader(Zend_Controller_Response_Abstract $response, $header) - { - return (null === $this->_getHeader($response, $header)); - } - - /** - * Retrieve response header - * - * @param Zend_Controller_Response_Abstract $response - * @param string $header - * @return string|null - */ - protected function _getHeader(Zend_Controller_Response_Abstract $response, $header) - { - $headers = $response->sendHeaders(); - $header = strtolower($header); - if (array_key_exists($header, $headers)) { - return $headers[$header]; - } - return null; - } - - /** - * Positive check for header contents matching pattern - * - * @param Zend_Controller_Response_Abstract $response - * @param string $header - * @param string $match - * @return bool - */ - protected function _headerContains(Zend_Controller_Response_Abstract $response, $header, $match) - { - if (null === ($fullHeader = $this->_getHeader($response, $header))) { - return false; - } - - $contents = str_replace($header . ': ', '', $fullHeader); - - return (strstr($contents, $match) !== false); - } - - /** - * Negative check for header contents matching pattern - * - * @param Zend_Controller_Response_Abstract $response - * @param string $header - * @param string $match - * @return bool - */ - protected function _notHeaderContains(Zend_Controller_Response_Abstract $response, $header, $match) - { - if (null === ($fullHeader = $this->_getHeader($response, $header))) { - return true; - } - - $contents = str_replace($header . ': ', '', $fullHeader); - - return (strstr($contents, $match) === false); - } - - /** - * Positive check for header contents matching regex - * - * @param Zend_Controller_Response_Abstract $response - * @param string $header - * @param string $pattern - * @return bool - */ - protected function _headerRegex(Zend_Controller_Response_Abstract $response, $header, $pattern) - { - if (null === ($fullHeader = $this->_getHeader($response, $header))) { - return false; - } - - $contents = str_replace($header . ': ', '', $fullHeader); - - return preg_match($pattern, $contents); - } - - /** - * Negative check for header contents matching regex - * - * @param Zend_Controller_Response_Abstract $response - * @param string $header - * @param string $pattern - * @return bool - */ - protected function _notHeaderRegex(Zend_Controller_Response_Abstract $response, $header, $pattern) - { - if (null === ($fullHeader = $this->_getHeader($response, $header))) { - return true; - } - - $contents = str_replace($header . ': ', '', $fullHeader); - - return !preg_match($pattern, $contents); - } -} diff --git a/library/Zend/Test/PHPUnit/Constraint/ResponseHeader37.php b/library/Zend/Test/PHPUnit/Constraint/ResponseHeader37.php deleted file mode 100644 index aea80339d4..0000000000 --- a/library/Zend/Test/PHPUnit/Constraint/ResponseHeader37.php +++ /dev/null @@ -1,419 +0,0 @@ -_negate = $flag; - } - - /** - * Evaluate an object to see if it fits the constraints - * - * @param object of Zend_Controller_Response_Abstract to be evaluated - * @param null|string Assertion type - * @param int|string HTTP response code to evaluate against | header string (haystack) - * @param string (optional) match (needle), may be required depending on assertion type - * @return bool - * NOTE: - * Drastic changes up to PHPUnit 3.5.15 this was: - * public function evaluate($other, $assertType = null) - * In PHPUnit 3.6.0 they changed the interface into this: - * public function evaluate($other, $description = '', $returnResult = FALSE) - * We use the new interface for PHP-strict checking, but emulate the old one - */ - public function evaluate($response, $assertType = '', $variable = FALSE) - { - if (!$response instanceof Zend_Controller_Response_Abstract) { - #require_once 'Zend/Test/PHPUnit/Constraint/Exception.php'; - throw new Zend_Test_PHPUnit_Constraint_Exception('Header constraint assertions require a response object'); - } - - if (strstr($assertType, 'Not')) { - $this->setNegate(true); - $assertType = str_replace('Not', '', $assertType); - } - - if (!in_array($assertType, $this->_assertTypes)) { - #require_once 'Zend/Test/PHPUnit/Constraint/Exception.php'; - throw new Zend_Test_PHPUnit_Constraint_Exception(sprintf('Invalid assertion type "%s" provided to %s constraint', $assertType, __CLASS__)); - } - - $this->_assertType = $assertType; - - $argv = func_get_args(); - $argc = func_num_args(); - - switch ($assertType) { - case self::ASSERT_RESPONSE_CODE: - if (3 > $argc) { - #require_once 'Zend/Test/PHPUnit/Constraint/Exception.php'; - throw new Zend_Test_PHPUnit_Constraint_Exception('No response code provided against which to match'); - } - $this->_code = $code = $argv[2]; - return ($this->_negate) - ? $this->_notCode($response, $code) - : $this->_code($response, $code); - case self::ASSERT_HEADER: - if (3 > $argc) { - #require_once 'Zend/Test/PHPUnit/Constraint/Exception.php'; - throw new Zend_Test_PHPUnit_Constraint_Exception('No header provided against which to match'); - } - $this->_header = $header = $argv[2]; - return ($this->_negate) - ? $this->_notHeader($response, $header) - : $this->_header($response, $header); - case self::ASSERT_HEADER_CONTAINS: - if (4 > $argc) { - #require_once 'Zend/Test/PHPUnit/Constraint/Exception.php'; - throw new Zend_Test_PHPUnit_Constraint_Exception('Both a header name and content to match are required for ' . $assertType); - } - $this->_header = $header = $argv[2]; - $this->_match = $match = $argv[3]; - return ($this->_negate) - ? $this->_notHeaderContains($response, $header, $match) - : $this->_headerContains($response, $header, $match); - case self::ASSERT_HEADER_REGEX: - if (4 > $argc) { - #require_once 'Zend/Test/PHPUnit/Constraint/Exception.php'; - throw new Zend_Test_PHPUnit_Constraint_Exception('Both a header name and content to match are required for ' . $assertType); - } - $this->_header = $header = $argv[2]; - $this->_match = $match = $argv[3]; - return ($this->_negate) - ? $this->_notHeaderRegex($response, $header, $match) - : $this->_headerRegex($response, $header, $match); - default: - #require_once 'Zend/Test/PHPUnit/Constraint/Exception.php'; - throw new Zend_Test_PHPUnit_Constraint_Exception('Invalid assertion type ' . $assertType); - } - } - - /** - * Report Failure - * - * @see PHPUnit_Framework_Constraint for implementation details - * @param mixed CSS selector path - * @param string Failure description - * @param object Cannot be used, null - * @return void - * @throws PHPUnit_Framework_ExpectationFailedException - * NOTE: - * Drastic changes up to PHPUnit 3.5.15 this was: - * public function fail($other, $description, $not = false) - * In PHPUnit 3.6.0 they changed the interface into this: - * protected function fail($other, $description, PHPUnit_Framework_ComparisonFailure $comparisonFailure = NULL) - * We use the new interface for PHP-strict checking - */ - public function fail($other, $description, PHPUnit_Framework_ComparisonFailure $cannot_be_used = NULL) - { - #require_once 'Zend/Test/PHPUnit/Constraint/Exception.php'; - switch ($this->_assertType) { - case self::ASSERT_RESPONSE_CODE: - $failure = 'Failed asserting response code "%s"'; - if ($this->_negate) { - $failure = 'Failed asserting response code IS NOT "%s"'; - } - $failure = sprintf($failure, $this->_code); - if (!$this->_negate && $this->_actualCode) { - $failure .= sprintf(PHP_EOL . 'Was "%s"', $this->_actualCode); - } - break; - case self::ASSERT_HEADER: - $failure = 'Failed asserting response header "%s" found'; - if ($this->_negate) { - $failure = 'Failed asserting response response header "%s" WAS NOT found'; - } - $failure = sprintf($failure, $this->_header); - break; - case self::ASSERT_HEADER_CONTAINS: - $failure = 'Failed asserting response header "%s" exists and contains "%s"'; - if ($this->_negate) { - $failure = 'Failed asserting response header "%s" DOES NOT CONTAIN "%s"'; - } - $failure = sprintf($failure, $this->_header, $this->_match); - break; - case self::ASSERT_HEADER_REGEX: - $failure = 'Failed asserting response header "%s" exists and matches regex "%s"'; - if ($this->_negate) { - $failure = 'Failed asserting response header "%s" DOES NOT MATCH regex "%s"'; - } - $failure = sprintf($failure, $this->_header, $this->_match); - break; - default: - throw new Zend_Test_PHPUnit_Constraint_Exception('Invalid assertion type ' . __FUNCTION__); - } - - if (!empty($description)) { - $failure = $description . "\n" . $failure; - } - - throw new Zend_Test_PHPUnit_Constraint_Exception($failure); - } - - /** - * Complete implementation - * - * @return string - */ - public function toString() - { - return ''; - } - - /** - * Compare response code for positive match - * - * @param Zend_Controller_Response_Abstract $response - * @param int $code - * @return bool - */ - protected function _code(Zend_Controller_Response_Abstract $response, $code) - { - $test = $this->_getCode($response); - $this->_actualCode = $test; - return ($test == $code); - } - - /** - * Compare response code for negative match - * - * @param Zend_Controller_Response_Abstract $response - * @param int $code - * @return bool - */ - protected function _notCode(Zend_Controller_Response_Abstract $response, $code) - { - $test = $this->_getCode($response); - return ($test != $code); - } - - /** - * Retrieve response code - * - * @param Zend_Controller_Response_Abstract $response - * @return int - */ - protected function _getCode(Zend_Controller_Response_Abstract $response) - { - $test = $response->getHttpResponseCode(); - if (null === $test) { - $test = 200; - } - return $test; - } - - /** - * Positive check for response header presence - * - * @param Zend_Controller_Response_Abstract $response - * @param string $header - * @return bool - */ - protected function _header(Zend_Controller_Response_Abstract $response, $header) - { - return (null !== $this->_getHeader($response, $header)); - } - - /** - * Negative check for response header presence - * - * @param Zend_Controller_Response_Abstract $response - * @param string $header - * @return bool - */ - protected function _notHeader(Zend_Controller_Response_Abstract $response, $header) - { - return (null === $this->_getHeader($response, $header)); - } - - /** - * Retrieve response header - * - * @param Zend_Controller_Response_Abstract $response - * @param string $header - * @return string|null - */ - protected function _getHeader(Zend_Controller_Response_Abstract $response, $header) - { - $headers = $response->sendHeaders(); - $header = strtolower($header); - if (array_key_exists($header, $headers)) { - return $headers[$header]; - } - return null; - } - - /** - * Positive check for header contents matching pattern - * - * @param Zend_Controller_Response_Abstract $response - * @param string $header - * @param string $match - * @return bool - */ - protected function _headerContains(Zend_Controller_Response_Abstract $response, $header, $match) - { - if (null === ($fullHeader = $this->_getHeader($response, $header))) { - return false; - } - - $contents = str_replace($header . ': ', '', $fullHeader); - - return (strstr($contents, $match) !== false); - } - - /** - * Negative check for header contents matching pattern - * - * @param Zend_Controller_Response_Abstract $response - * @param string $header - * @param string $match - * @return bool - */ - protected function _notHeaderContains(Zend_Controller_Response_Abstract $response, $header, $match) - { - if (null === ($fullHeader = $this->_getHeader($response, $header))) { - return true; - } - - $contents = str_replace($header . ': ', '', $fullHeader); - - return (strstr($contents, $match) === false); - } - - /** - * Positive check for header contents matching regex - * - * @param Zend_Controller_Response_Abstract $response - * @param string $header - * @param string $pattern - * @return bool - */ - protected function _headerRegex(Zend_Controller_Response_Abstract $response, $header, $pattern) - { - if (null === ($fullHeader = $this->_getHeader($response, $header))) { - return false; - } - - $contents = str_replace($header . ': ', '', $fullHeader); - - return preg_match($pattern, $contents); - } - - /** - * Negative check for header contents matching regex - * - * @param Zend_Controller_Response_Abstract $response - * @param string $header - * @param string $pattern - * @return bool - */ - protected function _notHeaderRegex(Zend_Controller_Response_Abstract $response, $header, $pattern) - { - if (null === ($fullHeader = $this->_getHeader($response, $header))) { - return true; - } - - $contents = str_replace($header . ': ', '', $fullHeader); - - return !preg_match($pattern, $contents); - } -} diff --git a/library/Zend/Test/PHPUnit/Constraint/ResponseHeader41.php b/library/Zend/Test/PHPUnit/Constraint/ResponseHeader41.php deleted file mode 100644 index e5da1f965f..0000000000 --- a/library/Zend/Test/PHPUnit/Constraint/ResponseHeader41.php +++ /dev/null @@ -1,421 +0,0 @@ -_negate = $flag; - } - - /** - * Evaluate an object to see if it fits the constraints - * - * @param object of Zend_Controller_Response_Abstract to be evaluated - * @param null|string Assertion type - * @param int|string HTTP response code to evaluate against | header string (haystack) - * @param string (optional) match (needle), may be required depending on assertion type - * @return bool - * NOTE: - * Drastic changes up to PHPUnit 3.5.15 this was: - * public function evaluate($other, $assertType = null) - * In PHPUnit 3.6.0 they changed the interface into this: - * public function evaluate($other, $description = '', $returnResult = FALSE) - * We use the new interface for PHP-strict checking, but emulate the old one - */ - public function evaluate($response, $assertType = '', $variable = FALSE) - { - if (!$response instanceof Zend_Controller_Response_Abstract) { - #require_once 'Zend/Test/PHPUnit/Constraint/Exception.php'; - throw new Zend_Test_PHPUnit_Constraint_Exception('Header constraint assertions require a response object'); - } - - if (strstr($assertType, 'Not')) { - $this->setNegate(true); - $assertType = str_replace('Not', '', $assertType); - } - - if (!in_array($assertType, $this->_assertTypes)) { - #require_once 'Zend/Test/PHPUnit/Constraint/Exception.php'; - throw new Zend_Test_PHPUnit_Constraint_Exception(sprintf('Invalid assertion type "%s" provided to %s constraint', $assertType, __CLASS__)); - } - - $this->_assertType = $assertType; - - $argv = func_get_args(); - $argc = func_num_args(); - - switch ($assertType) { - case self::ASSERT_RESPONSE_CODE: - if (3 > $argc) { - #require_once 'Zend/Test/PHPUnit/Constraint/Exception.php'; - throw new Zend_Test_PHPUnit_Constraint_Exception('No response code provided against which to match'); - } - $this->_code = $code = $argv[2]; - return ($this->_negate) - ? $this->_notCode($response, $code) - : $this->_code($response, $code); - case self::ASSERT_HEADER: - if (3 > $argc) { - #require_once 'Zend/Test/PHPUnit/Constraint/Exception.php'; - throw new Zend_Test_PHPUnit_Constraint_Exception('No header provided against which to match'); - } - $this->_header = $header = $argv[2]; - return ($this->_negate) - ? $this->_notHeader($response, $header) - : $this->_header($response, $header); - case self::ASSERT_HEADER_CONTAINS: - if (4 > $argc) { - #require_once 'Zend/Test/PHPUnit/Constraint/Exception.php'; - throw new Zend_Test_PHPUnit_Constraint_Exception('Both a header name and content to match are required for ' . $assertType); - } - $this->_header = $header = $argv[2]; - $this->_match = $match = $argv[3]; - return ($this->_negate) - ? $this->_notHeaderContains($response, $header, $match) - : $this->_headerContains($response, $header, $match); - case self::ASSERT_HEADER_REGEX: - if (4 > $argc) { - #require_once 'Zend/Test/PHPUnit/Constraint/Exception.php'; - throw new Zend_Test_PHPUnit_Constraint_Exception('Both a header name and content to match are required for ' . $assertType); - } - $this->_header = $header = $argv[2]; - $this->_match = $match = $argv[3]; - return ($this->_negate) - ? $this->_notHeaderRegex($response, $header, $match) - : $this->_headerRegex($response, $header, $match); - default: - #require_once 'Zend/Test/PHPUnit/Constraint/Exception.php'; - throw new Zend_Test_PHPUnit_Constraint_Exception('Invalid assertion type ' . $assertType); - } - } - - /** - * Report Failure - * - * @see PHPUnit_Framework_Constraint for implementation details - * @param mixed CSS selector path - * @param string Failure description - * @param object Cannot be used, null - * @return void - * @throws PHPUnit_Framework_ExpectationFailedException - * NOTE: - * Drastic changes up to PHPUnit 3.5.15 this was: - * public function fail($other, $description, $not = false) - * In PHPUnit 3.6.0 they changed the interface into this: - * protected function fail($other, $description, PHPUnit_Framework_ComparisonFailure $comparisonFailure = NULL) - * We use the new interface for PHP-strict checking - * NOTE 2: - * Interface changed again in PHPUnit 4.1.0 because of refactoring to SebastianBergmann\Comparator - */ - public function fail($other, $description, \SebastianBergmann\Comparator\ComparisonFailure $cannot_be_used = NULL) - { - #require_once 'Zend/Test/PHPUnit/Constraint/Exception.php'; - switch ($this->_assertType) { - case self::ASSERT_RESPONSE_CODE: - $failure = 'Failed asserting response code "%s"'; - if ($this->_negate) { - $failure = 'Failed asserting response code IS NOT "%s"'; - } - $failure = sprintf($failure, $this->_code); - if (!$this->_negate && $this->_actualCode) { - $failure .= sprintf(PHP_EOL . 'Was "%s"', $this->_actualCode); - } - break; - case self::ASSERT_HEADER: - $failure = 'Failed asserting response header "%s" found'; - if ($this->_negate) { - $failure = 'Failed asserting response response header "%s" WAS NOT found'; - } - $failure = sprintf($failure, $this->_header); - break; - case self::ASSERT_HEADER_CONTAINS: - $failure = 'Failed asserting response header "%s" exists and contains "%s"'; - if ($this->_negate) { - $failure = 'Failed asserting response header "%s" DOES NOT CONTAIN "%s"'; - } - $failure = sprintf($failure, $this->_header, $this->_match); - break; - case self::ASSERT_HEADER_REGEX: - $failure = 'Failed asserting response header "%s" exists and matches regex "%s"'; - if ($this->_negate) { - $failure = 'Failed asserting response header "%s" DOES NOT MATCH regex "%s"'; - } - $failure = sprintf($failure, $this->_header, $this->_match); - break; - default: - throw new Zend_Test_PHPUnit_Constraint_Exception('Invalid assertion type ' . __FUNCTION__); - } - - if (!empty($description)) { - $failure = $description . "\n" . $failure; - } - - throw new Zend_Test_PHPUnit_Constraint_Exception($failure); - } - - /** - * Complete implementation - * - * @return string - */ - public function toString() - { - return ''; - } - - /** - * Compare response code for positive match - * - * @param Zend_Controller_Response_Abstract $response - * @param int $code - * @return bool - */ - protected function _code(Zend_Controller_Response_Abstract $response, $code) - { - $test = $this->_getCode($response); - $this->_actualCode = $test; - return ($test == $code); - } - - /** - * Compare response code for negative match - * - * @param Zend_Controller_Response_Abstract $response - * @param int $code - * @return bool - */ - protected function _notCode(Zend_Controller_Response_Abstract $response, $code) - { - $test = $this->_getCode($response); - return ($test != $code); - } - - /** - * Retrieve response code - * - * @param Zend_Controller_Response_Abstract $response - * @return int - */ - protected function _getCode(Zend_Controller_Response_Abstract $response) - { - $test = $response->getHttpResponseCode(); - if (null === $test) { - $test = 200; - } - return $test; - } - - /** - * Positive check for response header presence - * - * @param Zend_Controller_Response_Abstract $response - * @param string $header - * @return bool - */ - protected function _header(Zend_Controller_Response_Abstract $response, $header) - { - return (null !== $this->_getHeader($response, $header)); - } - - /** - * Negative check for response header presence - * - * @param Zend_Controller_Response_Abstract $response - * @param string $header - * @return bool - */ - protected function _notHeader(Zend_Controller_Response_Abstract $response, $header) - { - return (null === $this->_getHeader($response, $header)); - } - - /** - * Retrieve response header - * - * @param Zend_Controller_Response_Abstract $response - * @param string $header - * @return string|null - */ - protected function _getHeader(Zend_Controller_Response_Abstract $response, $header) - { - $headers = $response->sendHeaders(); - $header = strtolower($header); - if (array_key_exists($header, $headers)) { - return $headers[$header]; - } - return null; - } - - /** - * Positive check for header contents matching pattern - * - * @param Zend_Controller_Response_Abstract $response - * @param string $header - * @param string $match - * @return bool - */ - protected function _headerContains(Zend_Controller_Response_Abstract $response, $header, $match) - { - if (null === ($fullHeader = $this->_getHeader($response, $header))) { - return false; - } - - $contents = str_replace($header . ': ', '', $fullHeader); - - return (strstr($contents, $match) !== false); - } - - /** - * Negative check for header contents matching pattern - * - * @param Zend_Controller_Response_Abstract $response - * @param string $header - * @param string $match - * @return bool - */ - protected function _notHeaderContains(Zend_Controller_Response_Abstract $response, $header, $match) - { - if (null === ($fullHeader = $this->_getHeader($response, $header))) { - return true; - } - - $contents = str_replace($header . ': ', '', $fullHeader); - - return (strstr($contents, $match) === false); - } - - /** - * Positive check for header contents matching regex - * - * @param Zend_Controller_Response_Abstract $response - * @param string $header - * @param string $pattern - * @return bool - */ - protected function _headerRegex(Zend_Controller_Response_Abstract $response, $header, $pattern) - { - if (null === ($fullHeader = $this->_getHeader($response, $header))) { - return false; - } - - $contents = str_replace($header . ': ', '', $fullHeader); - - return preg_match($pattern, $contents); - } - - /** - * Negative check for header contents matching regex - * - * @param Zend_Controller_Response_Abstract $response - * @param string $header - * @param string $pattern - * @return bool - */ - protected function _notHeaderRegex(Zend_Controller_Response_Abstract $response, $header, $pattern) - { - if (null === ($fullHeader = $this->_getHeader($response, $header))) { - return true; - } - - $contents = str_replace($header . ': ', '', $fullHeader); - - return !preg_match($pattern, $contents); - } -} diff --git a/library/Zend/Test/PHPUnit/ControllerTestCase.php b/library/Zend/Test/PHPUnit/ControllerTestCase.php deleted file mode 100644 index 8b9972937d..0000000000 --- a/library/Zend/Test/PHPUnit/ControllerTestCase.php +++ /dev/null @@ -1,1165 +0,0 @@ -$name = $value; - } - - /** - * Overloading for common properties - * - * Provides overloading for request, response, and frontController objects. - * - * @param mixed $name - * @return null|Zend_Controller_Front|Zend_Controller_Request_HttpTestCase|Zend_Controller_Response_HttpTestCase - */ - public function __get($name) - { - switch ($name) { - case 'request': - return $this->getRequest(); - case 'response': - return $this->getResponse(); - case 'frontController': - return $this->getFrontController(); - } - - return null; - } - - /** - * Set up MVC app - * - * Calls {@link bootstrap()} by default - */ - protected function setUp() - { - $this->bootstrap(); - } - - /** - * Bootstrap the front controller - * - * Resets the front controller, and then bootstraps it. - * - * If {@link $bootstrap} is a callback, executes it; if it is a file, it include's - * it. When done, sets the test case request and response objects into the - * front controller. - */ - final public function bootstrap() - { - $this->reset(); - if (null !== $this->bootstrap) { - if ($this->bootstrap instanceof Zend_Application) { - $this->bootstrap->bootstrap(); - $this->_frontController = $this->bootstrap->getBootstrap()->getResource('frontcontroller'); - } elseif (is_callable($this->bootstrap)) { - call_user_func($this->bootstrap); - } elseif (is_string($this->bootstrap)) { - #require_once 'Zend/Loader.php'; - if (Zend_Loader::isReadable($this->bootstrap)) { - include $this->bootstrap; - } - } - } - $this->frontController - ->setRequest($this->getRequest()) - ->setResponse($this->getResponse()); - } - - /** - * Dispatch the MVC - * - * If a URL is provided, sets it as the request URI in the request object. - * Then sets test case request and response objects in front controller, - * disables throwing exceptions, and disables returning the response. - * Finally, dispatches the front controller. - * - * @param string|null $url - */ - public function dispatch($url = null) - { - // redirector should not exit - $redirector = Zend_Controller_Action_HelperBroker::getStaticHelper('redirector'); - $redirector->setExit(false); - - // json helper should not exit - $json = Zend_Controller_Action_HelperBroker::getStaticHelper('json'); - $json->suppressExit = true; - - $request = $this->getRequest(); - if (null !== $url) { - $request->setRequestUri($url); - } - $request->setPathInfo(null); - - $controller = $this->getFrontController(); - $this->frontController - ->setRequest($request) - ->setResponse($this->getResponse()) - ->throwExceptions(false) - ->returnResponse(false); - - if ($this->bootstrap instanceof Zend_Application) { - $this->bootstrap->run(); - } else { - $this->frontController->dispatch(); - } - } - - /** - * Reset MVC state - * - * Creates new request/response objects, resets the front controller - * instance, and resets the action helper broker. - * - * @todo Need to update Zend_Layout to add a resetInstance() method - */ - public function reset() - { - $_SESSION = array(); - $_GET = array(); - $_POST = array(); - $_COOKIE = array(); - $this->resetRequest(); - $this->resetResponse(); - Zend_Layout::resetMvcInstance(); - Zend_Controller_Action_HelperBroker::resetHelpers(); - $this->frontController->resetInstance(); - Zend_Session::$_unitTestEnabled = true; - } - - /** - * Rest all view placeholders - */ - protected function _resetPlaceholders() - { - $registry = Zend_Registry::getInstance(); - $remove = array(); - foreach ($registry as $key => $value) { - if (strstr($key, '_View_')) { - $remove[] = $key; - } - } - - foreach ($remove as $key) { - unset($registry[$key]); - } - } - - /** - * Reset the request object - * - * Useful for test cases that need to test multiple trips to the server. - * - * @return Zend_Test_PHPUnit_ControllerTestCase - */ - public function resetRequest() - { - if ($this->_request instanceof Zend_Controller_Request_HttpTestCase) { - $this->_request->clearQuery() - ->clearPost(); - } - $this->_request = null; - return $this; - } - - /** - * Reset the response object - * - * Useful for test cases that need to test multiple trips to the server. - * - * @return Zend_Test_PHPUnit_ControllerTestCase - */ - public function resetResponse() - { - $this->_response = null; - $this->_resetPlaceholders(); - return $this; - } - - /** - * Assert against DOM selection - * - * @param string $path CSS selector path - * @param string $message - */ - public function assertQuery($path, $message = '') - { - $this->_incrementAssertionCount(); - #require_once 'Zend/Test/PHPUnit/Constraint/DomQuery.php'; - $constraint = new Zend_Test_PHPUnit_Constraint_DomQuery($path); - $content = $this->response->outputBody(); - if (!$constraint->evaluate($content, __FUNCTION__)) { - $constraint->fail($path, $message); - } - } - - /** - * Assert against DOM selection - * - * @param string $path CSS selector path - * @param string $message - */ - public function assertNotQuery($path, $message = '') - { - $this->_incrementAssertionCount(); - #require_once 'Zend/Test/PHPUnit/Constraint/DomQuery.php'; - $constraint = new Zend_Test_PHPUnit_Constraint_DomQuery($path); - $content = $this->response->outputBody(); - if (!$constraint->evaluate($content, __FUNCTION__)) { - $constraint->fail($path, $message); - } - } - - /** - * Assert against DOM selection; node should contain content - * - * @param string $path CSS selector path - * @param string $match content that should be contained in matched nodes - * @param string $message - */ - public function assertQueryContentContains($path, $match, $message = '') - { - $this->_incrementAssertionCount(); - #require_once 'Zend/Test/PHPUnit/Constraint/DomQuery.php'; - $constraint = new Zend_Test_PHPUnit_Constraint_DomQuery($path); - $content = $this->response->outputBody(); - if (!$constraint->evaluate($content, __FUNCTION__, $match)) { - $constraint->fail($path, $message); - } - } - - /** - * Assert against DOM selection; node should NOT contain content - * - * @param string $path CSS selector path - * @param string $match content that should NOT be contained in matched nodes - * @param string $message - */ - public function assertNotQueryContentContains($path, $match, $message = '') - { - $this->_incrementAssertionCount(); - #require_once 'Zend/Test/PHPUnit/Constraint/DomQuery.php'; - $constraint = new Zend_Test_PHPUnit_Constraint_DomQuery($path); - $content = $this->response->outputBody(); - if (!$constraint->evaluate($content, __FUNCTION__, $match)) { - $constraint->fail($path, $message); - } - } - - /** - * Assert against DOM selection; node should match content - * - * @param string $path CSS selector path - * @param string $pattern Pattern that should be contained in matched nodes - * @param string $message - */ - public function assertQueryContentRegex($path, $pattern, $message = '') - { - $this->_incrementAssertionCount(); - #require_once 'Zend/Test/PHPUnit/Constraint/DomQuery.php'; - $constraint = new Zend_Test_PHPUnit_Constraint_DomQuery($path); - $content = $this->response->outputBody(); - if (!$constraint->evaluate($content, __FUNCTION__, $pattern)) { - $constraint->fail($path, $message); - } - } - - /** - * Assert against DOM selection; node should NOT match content - * - * @param string $path CSS selector path - * @param string $pattern pattern that should NOT be contained in matched nodes - * @param string $message - */ - public function assertNotQueryContentRegex($path, $pattern, $message = '') - { - $this->_incrementAssertionCount(); - #require_once 'Zend/Test/PHPUnit/Constraint/DomQuery.php'; - $constraint = new Zend_Test_PHPUnit_Constraint_DomQuery($path); - $content = $this->response->outputBody(); - if (!$constraint->evaluate($content, __FUNCTION__, $pattern)) { - $constraint->fail($path, $message); - } - } - - /** - * Assert against DOM selection; should contain exact number of nodes - * - * @param string $path CSS selector path - * @param string $count Number of nodes that should match - * @param string $message - */ - public function assertQueryCount($path, $count, $message = '') - { - $this->_incrementAssertionCount(); - #require_once 'Zend/Test/PHPUnit/Constraint/DomQuery.php'; - $constraint = new Zend_Test_PHPUnit_Constraint_DomQuery($path); - $content = $this->response->outputBody(); - if (!$constraint->evaluate($content, __FUNCTION__, $count)) { - $constraint->fail($path, $message); - } - } - - /** - * Assert against DOM selection; should NOT contain exact number of nodes - * - * @param string $path CSS selector path - * @param string $count Number of nodes that should NOT match - * @param string $message - */ - public function assertNotQueryCount($path, $count, $message = '') - { - $this->_incrementAssertionCount(); - #require_once 'Zend/Test/PHPUnit/Constraint/DomQuery.php'; - $constraint = new Zend_Test_PHPUnit_Constraint_DomQuery($path); - $content = $this->response->outputBody(); - if (!$constraint->evaluate($content, __FUNCTION__, $count)) { - $constraint->fail($path, $message); - } - } - - /** - * Assert against DOM selection; should contain at least this number of nodes - * - * @param string $path CSS selector path - * @param string $count Minimum number of nodes that should match - * @param string $message - */ - public function assertQueryCountMin($path, $count, $message = '') - { - $this->_incrementAssertionCount(); - #require_once 'Zend/Test/PHPUnit/Constraint/DomQuery.php'; - $constraint = new Zend_Test_PHPUnit_Constraint_DomQuery($path); - $content = $this->response->outputBody(); - if (!$constraint->evaluate($content, __FUNCTION__, $count)) { - $constraint->fail($path, $message); - } - } - - /** - * Assert against DOM selection; should contain no more than this number of nodes - * - * @param string $path CSS selector path - * @param string $count Maximum number of nodes that should match - * @param string $message - */ - public function assertQueryCountMax($path, $count, $message = '') - { - $this->_incrementAssertionCount(); - #require_once 'Zend/Test/PHPUnit/Constraint/DomQuery.php'; - $constraint = new Zend_Test_PHPUnit_Constraint_DomQuery($path); - $content = $this->response->outputBody(); - if (!$constraint->evaluate($content, __FUNCTION__, $count)) { - $constraint->fail($path, $message); - } - } - - /** - * Register XPath namespaces - * - * @param array $xpathNamespaces - */ - public function registerXpathNamespaces($xpathNamespaces) - { - $this->_xpathNamespaces = $xpathNamespaces; - } - - /** - * Assert against XPath selection - * - * @param string $path XPath path - * @param string $message - */ - public function assertXpath($path, $message = '') - { - $this->_incrementAssertionCount(); - #require_once 'Zend/Test/PHPUnit/Constraint/DomQuery.php'; - $constraint = new Zend_Test_PHPUnit_Constraint_DomQuery($path); - $constraint->registerXpathNamespaces($this->_xpathNamespaces); - $content = $this->response->outputBody(); - if (!$constraint->evaluate($content, __FUNCTION__)) { - $constraint->fail($path, $message); - } - } - - /** - * Assert against XPath selection - * - * @param string $path XPath path - * @param string $message - */ - public function assertNotXpath($path, $message = '') - { - $this->_incrementAssertionCount(); - #require_once 'Zend/Test/PHPUnit/Constraint/DomQuery.php'; - $constraint = new Zend_Test_PHPUnit_Constraint_DomQuery($path); - $constraint->registerXpathNamespaces($this->_xpathNamespaces); - $content = $this->response->outputBody(); - if (!$constraint->evaluate($content, __FUNCTION__)) { - $constraint->fail($path, $message); - } - } - - /** - * Assert against XPath selection; node should contain content - * - * @param string $path XPath path - * @param string $match content that should be contained in matched nodes - * @param string $message - */ - public function assertXpathContentContains($path, $match, $message = '') - { - $this->_incrementAssertionCount(); - #require_once 'Zend/Test/PHPUnit/Constraint/DomQuery.php'; - $constraint = new Zend_Test_PHPUnit_Constraint_DomQuery($path); - $constraint->registerXpathNamespaces($this->_xpathNamespaces); - $content = $this->response->outputBody(); - if (!$constraint->evaluate($content, __FUNCTION__, $match)) { - $constraint->fail($path, $message); - } - } - - /** - * Assert against XPath selection; node should NOT contain content - * - * @param string $path XPath path - * @param string $match content that should NOT be contained in matched nodes - * @param string $message - */ - public function assertNotXpathContentContains($path, $match, $message = '') - { - $this->_incrementAssertionCount(); - #require_once 'Zend/Test/PHPUnit/Constraint/DomQuery.php'; - $constraint = new Zend_Test_PHPUnit_Constraint_DomQuery($path); - $constraint->registerXpathNamespaces($this->_xpathNamespaces); - $content = $this->response->outputBody(); - if (!$constraint->evaluate($content, __FUNCTION__, $match)) { - $constraint->fail($path, $message); - } - } - - /** - * Assert against XPath selection; node should match content - * - * @param string $path XPath path - * @param string $pattern Pattern that should be contained in matched nodes - * @param string $message - */ - public function assertXpathContentRegex($path, $pattern, $message = '') - { - $this->_incrementAssertionCount(); - #require_once 'Zend/Test/PHPUnit/Constraint/DomQuery.php'; - $constraint = new Zend_Test_PHPUnit_Constraint_DomQuery($path); - $constraint->registerXpathNamespaces($this->_xpathNamespaces); - $content = $this->response->outputBody(); - if (!$constraint->evaluate($content, __FUNCTION__, $pattern)) { - $constraint->fail($path, $message); - } - } - - /** - * Assert against XPath selection; node should NOT match content - * - * @param string $path XPath path - * @param string $pattern pattern that should NOT be contained in matched nodes - * @param string $message - */ - public function assertNotXpathContentRegex($path, $pattern, $message = '') - { - $this->_incrementAssertionCount(); - #require_once 'Zend/Test/PHPUnit/Constraint/DomQuery.php'; - $constraint = new Zend_Test_PHPUnit_Constraint_DomQuery($path); - $constraint->registerXpathNamespaces($this->_xpathNamespaces); - $content = $this->response->outputBody(); - if (!$constraint->evaluate($content, __FUNCTION__, $pattern)) { - $constraint->fail($path, $message); - } - } - - /** - * Assert against XPath selection; should contain exact number of nodes - * - * @param string $path XPath path - * @param string $count Number of nodes that should match - * @param string $message - */ - public function assertXpathCount($path, $count, $message = '') - { - $this->_incrementAssertionCount(); - #require_once 'Zend/Test/PHPUnit/Constraint/DomQuery.php'; - $constraint = new Zend_Test_PHPUnit_Constraint_DomQuery($path); - $constraint->registerXpathNamespaces($this->_xpathNamespaces); - $content = $this->response->outputBody(); - if (!$constraint->evaluate($content, __FUNCTION__, $count)) { - $constraint->fail($path, $message); - } - } - - /** - * Assert against XPath selection; should NOT contain exact number of nodes - * - * @param string $path XPath path - * @param string $count Number of nodes that should NOT match - * @param string $message - */ - public function assertNotXpathCount($path, $count, $message = '') - { - $this->_incrementAssertionCount(); - #require_once 'Zend/Test/PHPUnit/Constraint/DomQuery.php'; - $constraint = new Zend_Test_PHPUnit_Constraint_DomQuery($path); - $constraint->registerXpathNamespaces($this->_xpathNamespaces); - $content = $this->response->outputBody(); - if (!$constraint->evaluate($content, __FUNCTION__, $count)) { - $constraint->fail($path, $message); - } - } - - /** - * Assert against XPath selection; should contain at least this number of nodes - * - * @param string $path XPath path - * @param string $count Minimum number of nodes that should match - * @param string $message - */ - public function assertXpathCountMin($path, $count, $message = '') - { - $this->_incrementAssertionCount(); - #require_once 'Zend/Test/PHPUnit/Constraint/DomQuery.php'; - $constraint = new Zend_Test_PHPUnit_Constraint_DomQuery($path); - $constraint->registerXpathNamespaces($this->_xpathNamespaces); - $content = $this->response->outputBody(); - if (!$constraint->evaluate($content, __FUNCTION__, $count)) { - $constraint->fail($path, $message); - } - } - - /** - * Assert against XPath selection; should contain no more than this number of nodes - * - * @param string $path XPath path - * @param string $count Maximum number of nodes that should match - * @param string $message - */ - public function assertXpathCountMax($path, $count, $message = '') - { - $this->_incrementAssertionCount(); - #require_once 'Zend/Test/PHPUnit/Constraint/DomQuery.php'; - $constraint = new Zend_Test_PHPUnit_Constraint_DomQuery($path); - $constraint->registerXpathNamespaces($this->_xpathNamespaces); - $content = $this->response->outputBody(); - if (!$constraint->evaluate($content, __FUNCTION__, $count)) { - $constraint->fail($path, $message); - } - } - - /** - * Assert that response is a redirect - * - * @param string $message - */ - public function assertRedirect($message = '') - { - $this->_incrementAssertionCount(); - #require_once 'Zend/Test/PHPUnit/Constraint/Redirect.php'; - $constraint = new Zend_Test_PHPUnit_Constraint_Redirect(); - $response = $this->response; - if (!$constraint->evaluate($response, __FUNCTION__)) { - $constraint->fail($response, $message); - } - } - - /** - * Assert that response is NOT a redirect - * - * @param string $message - */ - public function assertNotRedirect($message = '') - { - $this->_incrementAssertionCount(); - #require_once 'Zend/Test/PHPUnit/Constraint/Redirect.php'; - $constraint = new Zend_Test_PHPUnit_Constraint_Redirect(); - $response = $this->response; - if (!$constraint->evaluate($response, __FUNCTION__)) { - $constraint->fail($response, $message); - } - } - - /** - * Assert that response redirects to given URL - * - * @param string $url - * @param string $message - */ - public function assertRedirectTo($url, $message = '') - { - $this->_incrementAssertionCount(); - #require_once 'Zend/Test/PHPUnit/Constraint/Redirect.php'; - $constraint = new Zend_Test_PHPUnit_Constraint_Redirect(); - $response = $this->response; - if (!$constraint->evaluate($response, __FUNCTION__, $url)) { - $constraint->fail($response, $message); - } - } - - /** - * Assert that response does not redirect to given URL - * - * @param string $url - * @param string $message - */ - public function assertNotRedirectTo($url, $message = '') - { - $this->_incrementAssertionCount(); - #require_once 'Zend/Test/PHPUnit/Constraint/Redirect.php'; - $constraint = new Zend_Test_PHPUnit_Constraint_Redirect(); - $response = $this->response; - if (!$constraint->evaluate($response, __FUNCTION__, $url)) { - $constraint->fail($response, $message); - } - } - - /** - * Assert that redirect location matches pattern - * - * @param string $pattern - * @param string $message - */ - public function assertRedirectRegex($pattern, $message = '') - { - $this->_incrementAssertionCount(); - #require_once 'Zend/Test/PHPUnit/Constraint/Redirect.php'; - $constraint = new Zend_Test_PHPUnit_Constraint_Redirect(); - $response = $this->response; - if (!$constraint->evaluate($response, __FUNCTION__, $pattern)) { - $constraint->fail($response, $message); - } - } - - /** - * Assert that redirect location does not match pattern - * - * @param string $pattern - * @param string $message - */ - public function assertNotRedirectRegex($pattern, $message = '') - { - $this->_incrementAssertionCount(); - #require_once 'Zend/Test/PHPUnit/Constraint/Redirect.php'; - $constraint = new Zend_Test_PHPUnit_Constraint_Redirect(); - $response = $this->response; - if (!$constraint->evaluate($response, __FUNCTION__, $pattern)) { - $constraint->fail($response, $message); - } - } - - /** - * Assert response code - * - * @param int $code - * @param string $message - */ - public function assertResponseCode($code, $message = '') - { - $this->_incrementAssertionCount(); - #require_once 'Zend/Test/PHPUnit/Constraint/ResponseHeader.php'; - $constraint = new Zend_Test_PHPUnit_Constraint_ResponseHeader(); - $response = $this->response; - if (!$constraint->evaluate($response, __FUNCTION__, $code)) { - $constraint->fail($response, $message); - } - } - - /** - * Assert response code - * - * @param int $code - * @param string $message - */ - public function assertNotResponseCode($code, $message = '') - { - $this->_incrementAssertionCount(); - #require_once 'Zend/Test/PHPUnit/Constraint/ResponseHeader.php'; - $constraint = new Zend_Test_PHPUnit_Constraint_ResponseHeader(); - $constraint->setNegate(true); - $response = $this->response; - if (!$constraint->evaluate($response, __FUNCTION__, $code)) { - $constraint->fail($response, $message); - } - } - - /** - * Assert response header exists - * - * @param string $header - * @param string $message - */ - public function assertHeader($header, $message = '') - { - $this->_incrementAssertionCount(); - #require_once 'Zend/Test/PHPUnit/Constraint/ResponseHeader.php'; - $constraint = new Zend_Test_PHPUnit_Constraint_ResponseHeader(); - $response = $this->response; - if (!$constraint->evaluate($response, __FUNCTION__, $header)) { - $constraint->fail($response, $message); - } - } - - /** - * Assert response header does not exist - * - * @param string $header - * @param string $message - */ - public function assertNotHeader($header, $message = '') - { - $this->_incrementAssertionCount(); - #require_once 'Zend/Test/PHPUnit/Constraint/ResponseHeader.php'; - $constraint = new Zend_Test_PHPUnit_Constraint_ResponseHeader(); - $constraint->setNegate(true); - $response = $this->response; - if (!$constraint->evaluate($response, __FUNCTION__, $header)) { - $constraint->fail($response, $message); - } - } - - /** - * Assert response header exists and contains the given string - * - * @param string $header - * @param string $match - * @param string $message - */ - public function assertHeaderContains($header, $match, $message = '') - { - $this->_incrementAssertionCount(); - #require_once 'Zend/Test/PHPUnit/Constraint/ResponseHeader.php'; - $constraint = new Zend_Test_PHPUnit_Constraint_ResponseHeader(); - $response = $this->response; - if (!$constraint->evaluate($response, __FUNCTION__, $header, $match)) { - $constraint->fail($response, $message); - } - } - - /** - * Assert response header does not exist and/or does not contain the given string - * - * @param string $header - * @param string $match - * @param string $message - */ - public function assertNotHeaderContains($header, $match, $message = '') - { - $this->_incrementAssertionCount(); - #require_once 'Zend/Test/PHPUnit/Constraint/ResponseHeader.php'; - $constraint = new Zend_Test_PHPUnit_Constraint_ResponseHeader(); - $constraint->setNegate(true); - $response = $this->response; - if (!$constraint->evaluate($response, __FUNCTION__, $header, $match)) { - $constraint->fail($response, $message); - } - } - - /** - * Assert response header exists and matches the given pattern - * - * @param string $header - * @param string $pattern - * @param string $message - */ - public function assertHeaderRegex($header, $pattern, $message = '') - { - $this->_incrementAssertionCount(); - #require_once 'Zend/Test/PHPUnit/Constraint/ResponseHeader.php'; - $constraint = new Zend_Test_PHPUnit_Constraint_ResponseHeader(); - $response = $this->response; - if (!$constraint->evaluate($response, __FUNCTION__, $header, $pattern)) { - $constraint->fail($response, $message); - } - } - - /** - * Assert response header does not exist and/or does not match the given regex - * - * @param string $header - * @param string $pattern - * @param string $message - */ - public function assertNotHeaderRegex($header, $pattern, $message = '') - { - $this->_incrementAssertionCount(); - #require_once 'Zend/Test/PHPUnit/Constraint/ResponseHeader.php'; - $constraint = new Zend_Test_PHPUnit_Constraint_ResponseHeader(); - $constraint->setNegate(true); - $response = $this->response; - if (!$constraint->evaluate($response, __FUNCTION__, $header, $pattern)) { - $constraint->fail($response, $message); - } - } - - /** - * Assert that the last handled request used the given module - * - * @param string $module - * @param string $message - */ - public function assertModule($module, $message = '') - { - $this->_incrementAssertionCount(); - if ($module != $this->request->getModuleName()) { - $msg = sprintf('Failed asserting last module used <"%s"> was "%s"', - $this->request->getModuleName(), - $module - ); - if (!empty($message)) { - $msg = $message . "\n" . $msg; - } - $this->fail($msg); - } - } - - /** - * Assert that the last handled request did NOT use the given module - * - * @param string $module - * @param string $message - */ - public function assertNotModule($module, $message = '') - { - $this->_incrementAssertionCount(); - if ($module == $this->request->getModuleName()) { - $msg = sprintf('Failed asserting last module used was NOT "%s"', $module); - if (!empty($message)) { - $msg = $message . "\n" . $msg; - } - $this->fail($msg); - } - } - - /** - * Assert that the last handled request used the given controller - * - * @param string $controller - * @param string $message - */ - public function assertController($controller, $message = '') - { - $this->_incrementAssertionCount(); - if ($controller != $this->request->getControllerName()) { - $msg = sprintf('Failed asserting last controller used <"%s"> was "%s"', - $this->request->getControllerName(), - $controller - ); - if (!empty($message)) { - $msg = $message . "\n" . $msg; - } - $this->fail($msg); - } - } - - /** - * Assert that the last handled request did NOT use the given controller - * - * @param string $controller - * @param string $message - */ - public function assertNotController($controller, $message = '') - { - $this->_incrementAssertionCount(); - if ($controller == $this->request->getControllerName()) { - $msg = sprintf('Failed asserting last controller used <"%s"> was NOT "%s"', - $this->request->getControllerName(), - $controller - ); - if (!empty($message)) { - $msg = $message . "\n" . $msg; - } - $this->fail($msg); - } - } - - /** - * Assert that the last handled request used the given action - * - * @param string $action - * @param string $message - */ - public function assertAction($action, $message = '') - { - $this->_incrementAssertionCount(); - if ($action != $this->request->getActionName()) { - $msg = sprintf('Failed asserting last action used <"%s"> was "%s"', $this->request->getActionName(), $action); - if (!empty($message)) { - $msg = $message . "\n" . $msg; - } - $this->fail($msg); - } - } - - /** - * Assert that the last handled request did NOT use the given action - * - * @param string $action - * @param string $message - */ - public function assertNotAction($action, $message = '') - { - $this->_incrementAssertionCount(); - if ($action == $this->request->getActionName()) { - $msg = sprintf('Failed asserting last action used <"%s"> was NOT "%s"', $this->request->getActionName(), $action); - if (!empty($message)) { - $msg = $message . "\n" . $msg; - } - $this->fail($msg); - } - } - - /** - * Assert that the specified route was used - * - * @param string $route - * @param string $message - */ - public function assertRoute($route, $message = '') - { - $this->_incrementAssertionCount(); - $router = $this->frontController->getRouter(); - if ($route != $router->getCurrentRouteName()) { - $msg = sprintf('Failed asserting matched route was "%s", actual route is %s', - $route, - $router->getCurrentRouteName() - ); - if (!empty($message)) { - $msg = $message . "\n" . $msg; - } - $this->fail($msg); - } - } - - /** - * Assert that the route matched is NOT as specified - * - * @param string $route - * @param string $message - */ - public function assertNotRoute($route, $message = '') - { - $this->_incrementAssertionCount(); - $router = $this->frontController->getRouter(); - if ($route == $router->getCurrentRouteName()) { - $msg = sprintf('Failed asserting route matched was NOT "%s"', $route); - if (!empty($message)) { - $msg = $message . "\n" . $msg; - } - $this->fail($msg); - } - } - - /** - * Retrieve front controller instance - * - * @return Zend_Controller_Front - */ - public function getFrontController() - { - if (null === $this->_frontController) { - $this->_frontController = Zend_Controller_Front::getInstance(); - } - return $this->_frontController; - } - - /** - * Retrieve test case request object - * - * @return Zend_Controller_Request_HttpTestCase - */ - public function getRequest() - { - if (null === $this->_request) { - #require_once 'Zend/Controller/Request/HttpTestCase.php'; - $this->_request = new Zend_Controller_Request_HttpTestCase; - } - return $this->_request; - } - - /** - * Retrieve test case response object - * - * @return Zend_Controller_Response_HttpTestCase - */ - public function getResponse() - { - if (null === $this->_response) { - #require_once 'Zend/Controller/Response/HttpTestCase.php'; - $this->_response = new Zend_Controller_Response_HttpTestCase; - } - return $this->_response; - } - - /** - * Retrieve DOM query object - * - * @return Zend_Dom_Query - */ - public function getQuery() - { - if (null === $this->_query) { - #require_once 'Zend/Dom/Query.php'; - $this->_query = new Zend_Dom_Query; - } - return $this->_query; - } - - /** - * URL Helper - * - * @param array $urlOptions - * @param string $name - * @param bool $reset - * @param bool $encode - * @throws Exception - * @throws Zend_Controller_Router_Exception - * @return string - */ - public function url($urlOptions = array(), $name = null, $reset = false, $encode = true) - { - $frontController = $this->getFrontController(); - $router = $frontController->getRouter(); - if (!$router instanceof Zend_Controller_Router_Rewrite) { - throw new Exception('This url helper utility function only works when the router is of type Zend_Controller_Router_Rewrite'); - } - if (count($router->getRoutes()) == 0) { - $router->addDefaultRoutes(); - } - return $router->assemble($urlOptions, $name, $reset, $encode); - } - - /** - * Urlize options - * - * @param array $urlOptions - * @param bool $actionControllerModuleOnly - * @return mixed - */ - public function urlizeOptions($urlOptions, $actionControllerModuleOnly = true) - { - $ccToDash = new Zend_Filter_Word_CamelCaseToDash(); - foreach ($urlOptions as $n => $v) { - if (in_array($n, array('action', 'controller', 'module'))) { - $urlOptions[$n] = $ccToDash->filter($v); - } - } - return $urlOptions; - } - - /** - * Increment assertion count - */ - protected function _incrementAssertionCount() - { - $stack = debug_backtrace(); - foreach ($stack as $step) { - if (isset($step['object']) - && $step['object'] instanceof PHPUnit_Framework_TestCase - ) { - if (version_compare(PHPUnit_Runner_Version::id(), '3.3.0', 'lt')) { - break; - } elseif (version_compare(PHPUnit_Runner_Version::id(), '3.3.3', 'lt')) { - $step['object']->incrementAssertionCounter(); - } else { - $step['object']->addToAssertionCount(1); - } - break; - } - } - } -} diff --git a/library/Zend/Test/PHPUnit/DatabaseTestCase.php b/library/Zend/Test/PHPUnit/DatabaseTestCase.php deleted file mode 100644 index 79b563ca0e..0000000000 --- a/library/Zend/Test/PHPUnit/DatabaseTestCase.php +++ /dev/null @@ -1,146 +0,0 @@ -getConnection()->getConnection(); - } - - /** - * Returns the database operation executed in test setup. - * - * @return PHPUnit_Extensions_Database_Operation_DatabaseOperation - */ - protected function getSetUpOperation() - { - return new PHPUnit_Extensions_Database_Operation_Composite(array( - new Zend_Test_PHPUnit_Db_Operation_Truncate(), - new Zend_Test_PHPUnit_Db_Operation_Insert(), - )); - } - - /** - * Returns the database operation executed in test cleanup. - * - * @return PHPUnit_Extensions_Database_Operation_DatabaseOperation - */ - protected function getTearDownOperation() - { - return PHPUnit_Extensions_Database_Operation_Factory::NONE(); - } - - /** - * Create a dataset based on multiple Zend_Db_Table instances - * - * @param array $tables - * @return Zend_Test_PHPUnit_Db_DataSet_DbTableDataSet - */ - protected function createDbTableDataSet(array $tables=array()) - { - $dataSet = new Zend_Test_PHPUnit_Db_DataSet_DbTableDataSet(); - foreach($tables AS $table) { - $dataSet->addTable($table); - } - return $dataSet; - } - - /** - * Create a table based on one Zend_Db_Table instance - * - * @param Zend_Db_Table_Abstract $table - * @param string $where - * @param string $order - * @param string $count - * @param string $offset - * @return Zend_Test_PHPUnit_Db_DataSet_DbTable - */ - protected function createDbTable(Zend_Db_Table_Abstract $table, $where=null, $order=null, $count=null, $offset=null) - { - return new Zend_Test_PHPUnit_Db_DataSet_DbTable($table, $where, $order, $count, $offset); - } - - /** - * Create a data table based on a Zend_Db_Table_Rowset instance - * - * @param Zend_Db_Table_Rowset_Abstract $rowset - * @param string - * @return Zend_Test_PHPUnit_Db_DataSet_DbRowset - */ - protected function createDbRowset(Zend_Db_Table_Rowset_Abstract $rowset, $tableName = null) - { - return new Zend_Test_PHPUnit_Db_DataSet_DbRowset($rowset, $tableName); - } -} diff --git a/library/Zend/Test/PHPUnit/Db/Connection.php b/library/Zend/Test/PHPUnit/Db/Connection.php deleted file mode 100644 index 95552b9c4d..0000000000 --- a/library/Zend/Test/PHPUnit/Db/Connection.php +++ /dev/null @@ -1,144 +0,0 @@ -_connection = $db; - $this->_schema = $schema; - } - - /** - * Close this connection. - * - * @return void - */ - public function close() - { - $this->_connection->closeConnection(); - } - - /** - * Creates a table with the result of the specified SQL statement. - * - * @param string $resultName - * @param string $sql - * @return PHPUnit_Extensions_Database_DataSet_ITable - */ - public function createQueryTable($resultName, $sql) - { - return new Zend_Test_PHPUnit_Db_DataSet_QueryTable($resultName, $sql, $this); - } - - /** - * Returns a Zend_Db Connection - * - * @return Zend_Db_Adapter_Abstract - */ - public function getConnection() - { - return $this->_connection; - } - - /** - * Returns a database metadata object that can be used to retrieve table - * meta data from the database. - * - * @return PHPUnit_Extensions_Database_DB_IMetaData - */ - public function getMetaData() - { - if($this->_metaData === null) { - $this->_metaData = new Zend_Test_PHPUnit_Db_Metadata_Generic($this->getConnection(), $this->getSchema()); - } - return $this->_metaData; - } - - /** - * Returns the schema for the connection. - * - * @return string - */ - public function getSchema() - { - return $this->_schema; - } - - /** - * Returns the command used to truncate a table. - * - * @return string - */ - public function getTruncateCommand() - { - return "DELETE"; - } -} diff --git a/library/Zend/Test/PHPUnit/Db/DataSet/DbRowset.php b/library/Zend/Test/PHPUnit/Db/DataSet/DbRowset.php deleted file mode 100644 index d89e0d4db6..0000000000 --- a/library/Zend/Test/PHPUnit/Db/DataSet/DbRowset.php +++ /dev/null @@ -1,73 +0,0 @@ -getTable(); - if($table !== null) { - $tableName = $table->info('name'); - } else { - #require_once "Zend/Test/PHPUnit/Db/Exception.php"; - throw new Zend_Test_PHPUnit_Db_Exception( - 'No table name was given to Rowset Table and table name cannot be infered from the table, '. - 'because the rowset is disconnected from database.' - ); - } - } - - $this->data = $rowset->toArray(); - - $columns = array(); - if(isset($this->data[0]) > 0) { - $columns = array_keys($this->data[0]); - } else if($rowset->getTable() != null) { - $columns = $rowset->getTable()->info('cols'); - } - - $this->tableName = $tableName; - $this->tableMetaData = new PHPUnit_Extensions_Database_DataSet_DefaultTableMetaData($this->tableName, $columns); - } -} diff --git a/library/Zend/Test/PHPUnit/Db/DataSet/DbTable.php b/library/Zend/Test/PHPUnit/Db/DataSet/DbTable.php deleted file mode 100644 index ad37642906..0000000000 --- a/library/Zend/Test/PHPUnit/Db/DataSet/DbTable.php +++ /dev/null @@ -1,120 +0,0 @@ -tableName = $table->info('name'); - $this->_columns = $table->info('cols'); - - $this->_table = $table; - $this->_where = $where; - $this->_order = $order; - $this->_count = $count; - $this->_offset = $offset; - } - - /** - * Lazy load data via table fetchAll() method. - * - * @return void - */ - protected function loadData() - { - if ($this->data === null) { - $this->data = $this->_table->fetchAll( - $this->_where, $this->_order, $this->_count, $this->_offset - ); - if($this->data instanceof Zend_Db_Table_Rowset_Abstract) { - $this->data = $this->data->toArray(); - } - } - } - - /** - * Create Table Metadata object - */ - protected function createTableMetaData() - { - if ($this->tableMetaData === NULL) { - $this->loadData(); - $this->tableMetaData = new PHPUnit_Extensions_Database_DataSet_DefaultTableMetaData($this->tableName, $this->_columns); - } - } -} diff --git a/library/Zend/Test/PHPUnit/Db/DataSet/DbTableDataSet.php b/library/Zend/Test/PHPUnit/Db/DataSet/DbTableDataSet.php deleted file mode 100644 index 52cf43e5c5..0000000000 --- a/library/Zend/Test/PHPUnit/Db/DataSet/DbTableDataSet.php +++ /dev/null @@ -1,98 +0,0 @@ -info('name'); - $this->tables[$tableName] = new Zend_Test_PHPUnit_Db_DataSet_DbTable($table, $where, $order, $count, $offset); - } - - /** - * Creates an iterator over the tables in the data set. If $reverse is - * true a reverse iterator will be returned. - * - * @param bool $reverse - * @return PHPUnit_Extensions_Database_DB_TableIterator - */ - protected function createIterator($reverse = FALSE) - { - return new PHPUnit_Extensions_Database_DataSet_DefaultTableIterator($this->tables, $reverse); - } - - /** - * Returns a table object for the given table. - * - * @param string $tableName - * @return PHPUnit_Extensions_Database_DB_Table - */ - public function getTable($tableName) - { - if (!isset($this->tables[$tableName])) { - throw new InvalidArgumentException("$tableName is not a table in the current database."); - } - - return $this->tables[$tableName]; - } - - /** - * Returns a list of table names for the database - * - * @return Array - */ - public function getTableNames() - { - return array_keys($this->tables); - } -} diff --git a/library/Zend/Test/PHPUnit/Db/DataSet/QueryDataSet.php b/library/Zend/Test/PHPUnit/Db/DataSet/QueryDataSet.php deleted file mode 100644 index 3e3251c3e4..0000000000 --- a/library/Zend/Test/PHPUnit/Db/DataSet/QueryDataSet.php +++ /dev/null @@ -1,80 +0,0 @@ -databaseConnection = $databaseConnection; - } - - /** - * Add a Table dataset representation by specifiying an arbitrary select query. - * - * By default a select * will be done on the given tablename. - * - * @param string $tableName - * @param string|Zend_Db_Select $query - */ - public function addTable($tableName, $query = NULL) - { - if ($query === NULL) { - $query = $this->databaseConnection->getConnection()->select(); - $query->from($tableName, Zend_Db_Select::SQL_WILDCARD); - } - - if($query instanceof Zend_Db_Select) { - $query = $query->__toString(); - } - - $this->tables[$tableName] = new Zend_Test_PHPUnit_Db_DataSet_QueryTable($tableName, $query, $this->databaseConnection); - } -} diff --git a/library/Zend/Test/PHPUnit/Db/DataSet/QueryTable.php b/library/Zend/Test/PHPUnit/Db/DataSet/QueryTable.php deleted file mode 100644 index cfa5e600c7..0000000000 --- a/library/Zend/Test/PHPUnit/Db/DataSet/QueryTable.php +++ /dev/null @@ -1,82 +0,0 @@ -data === null) { - $stmt = $this->databaseConnection->getConnection()->query($this->query); - $this->data = $stmt->fetchAll(Zend_Db::FETCH_ASSOC); - } - } - - /** - * Create Table Metadata - */ - protected function createTableMetaData() - { - if ($this->tableMetaData === NULL) - { - $this->loadData(); - $keys = array(); - if(count($this->data) > 0) { - $keys = array_keys($this->data[0]); - } - $this->tableMetaData = new PHPUnit_Extensions_Database_DataSet_DefaultTableMetaData( - $this->tableName, $keys - ); - } - } -} diff --git a/library/Zend/Test/PHPUnit/Db/Exception.php b/library/Zend/Test/PHPUnit/Db/Exception.php deleted file mode 100644 index 818fc04ed3..0000000000 --- a/library/Zend/Test/PHPUnit/Db/Exception.php +++ /dev/null @@ -1,40 +0,0 @@ -_connection = $db; - $this->_schema = $schema; - } - - /** - * List Tables - * - * @return array - */ - public function getTableNames() - { - return $this->_connection->listTables(); - } - - /** - * Get Table information - * - * @param string $tableName - * @return array - */ - protected function getTableDescription($tableName) - { - if(!isset($this->_tableMetadata[$tableName])) { - $this->_tableMetadata[$tableName] = $this->_connection->describeTable($tableName); - } - return $this->_tableMetadata[$tableName]; - } - - /** - * Returns an array containing the names of all the columns in the - * $tableName table, - * - * @param string $tableName - * @return array - */ - public function getTableColumns($tableName) - { - $tableMeta = $this->getTableDescription($tableName); - $columns = array_keys($tableMeta); - return $columns; - } - - /** - * Returns an array containing the names of all the primary key columns in - * the $tableName table. - * - * @param string $tableName - * @return array - */ - public function getTablePrimaryKeys($tableName) - { - $tableMeta = $this->getTableDescription($tableName); - - $primaryColumnNames = array(); - foreach($tableMeta AS $column) { - if($column['PRIMARY'] == true) { - $primaryColumnNames[] = $column['COLUMN_NAME']; - } - } - return $primaryColumnNames; - } - - /** - * Returns the name of the default schema. - * - * @return string - */ - public function getSchema() - { - return $this->_schema; - } - - /** - * Returns a quoted schema object. (table name, column name, etc) - * - * @param string $object - * @return string - */ - public function quoteSchemaObject($object) - { - return $this->_connection->quoteIdentifier($object); - } - - /** - * Returns true if the rdbms allows cascading - * - * @return bool - */ - public function allowsCascading() - { - return false; - } - - /** - * Disables primary keys if rdbms does not allow setting them otherwise - * - * @param string $tableName - */ - public function disablePrimaryKeys($tableName) - { - // Implemented only to match new DBUnit interface - } - - /** - * Reenables primary keys after they have been disabled - * - * @param string $tableName - */ - public function enablePrimaryKeys($tableName) - { - // Implemented only to match new DBUnit interface - } -} diff --git a/library/Zend/Test/PHPUnit/Db/Operation/DeleteAll.php b/library/Zend/Test/PHPUnit/Db/Operation/DeleteAll.php deleted file mode 100644 index 9a42c03037..0000000000 --- a/library/Zend/Test/PHPUnit/Db/Operation/DeleteAll.php +++ /dev/null @@ -1,60 +0,0 @@ -getTableMetaData()->getTableName(); - $connection->getConnection()->delete($tableName); - } catch (Exception $e) { - throw new PHPUnit_Extensions_Database_Operation_Exception('DELETEALL', 'DELETE FROM '.$tableName.'', array(), $table, $e->getMessage()); - } - } - } -} diff --git a/library/Zend/Test/PHPUnit/Db/Operation/Insert.php b/library/Zend/Test/PHPUnit/Db/Operation/Insert.php deleted file mode 100644 index a6f22b3701..0000000000 --- a/library/Zend/Test/PHPUnit/Db/Operation/Insert.php +++ /dev/null @@ -1,84 +0,0 @@ -createDataSet(); - - $dsIterator = $dataSet->getIterator(); - - foreach($dsIterator as $table) { - $tableName = $table->getTableMetaData()->getTableName(); - - $db = $connection->getConnection(); - for($i = 0; $i < $table->getRowCount(); $i++) { - $values = $this->buildInsertValues($table, $i); - try { - $db->insert($tableName, $values); - } catch (Exception $e) { - throw new PHPUnit_Extensions_Database_Operation_Exception("INSERT", "INSERT INTO ".$tableName." [..]", $values, $table, $e->getMessage()); - } - } - } - } - - /** - * - * @param PHPUnit_Extensions_Database_DataSet_ITable $table - * @param int $rowNum - * @return array - */ - protected function buildInsertValues(PHPUnit_Extensions_Database_DataSet_ITable $table, $rowNum) - { - $values = array(); - foreach($table->getTableMetaData()->getColumns() as $columnName) { - $values[$columnName] = $table->getValue($rowNum, $columnName); - } - return $values; - } -} diff --git a/library/Zend/Test/PHPUnit/Db/Operation/Truncate.php b/library/Zend/Test/PHPUnit/Db/Operation/Truncate.php deleted file mode 100644 index c44e9fb31c..0000000000 --- a/library/Zend/Test/PHPUnit/Db/Operation/Truncate.php +++ /dev/null @@ -1,110 +0,0 @@ -getReverseIterator() AS $table) { - try { - $tableName = $table->getTableMetaData()->getTableName(); - $this->_truncate($connection->getConnection(), $tableName); - } catch (Exception $e) { - throw new PHPUnit_Extensions_Database_Operation_Exception('TRUNCATE', 'TRUNCATE '.$tableName.'', array(), $table, $e->getMessage()); - } - } - } - - /** - * Truncate a given table. - * - * @param Zend_Db_Adapter_Abstract $db - * @param string $tableName - * @return void - */ - protected function _truncate(Zend_Db_Adapter_Abstract $db, $tableName) - { - $tableName = $db->quoteIdentifier($tableName, true); - if($db instanceof Zend_Db_Adapter_Pdo_Sqlite) { - $db->query('DELETE FROM '.$tableName); - } else if($db instanceof Zend_Db_Adapter_Db2) { - /*if(strstr(PHP_OS, "WIN")) { - $file = tempnam(sys_get_temp_dir(), "zendtestdbibm_"); - file_put_contents($file, ""); - $db->query('IMPORT FROM '.$file.' OF DEL REPLACE INTO '.$tableName); - unlink($file); - } else { - $db->query('IMPORT FROM /dev/null OF DEL REPLACE INTO '.$tableName); - }*/ - #require_once "Zend/Exception.php"; - throw Zend_Exception("IBM Db2 TRUNCATE not supported."); - } else if($this->_isMssqlOrOracle($db)) { - $db->query('TRUNCATE TABLE '.$tableName); - } else if($db instanceof Zend_Db_Adapter_Pdo_Pgsql) { - $db->query('TRUNCATE '.$tableName.' CASCADE'); - } else { - $db->query('TRUNCATE '.$tableName); - } - } - - /** - * Detect if an adapter is for Mssql or Oracle Databases. - * - * @param Zend_Db_Adapter_Abstract $db - * @return bool - */ - private function _isMssqlOrOracle($db) - { - return ( - $db instanceof Zend_Db_Adapter_Pdo_Mssql || - $db instanceof Zend_Db_Adapter_Sqlsrv || - $db instanceof Zend_Db_Adapter_Pdo_Oci || - $db instanceof Zend_Db_Adapter_Oracle - ); - } -} diff --git a/library/Zend/Test/PHPUnit/Db/SimpleTester.php b/library/Zend/Test/PHPUnit/Db/SimpleTester.php deleted file mode 100644 index da9676a759..0000000000 --- a/library/Zend/Test/PHPUnit/Db/SimpleTester.php +++ /dev/null @@ -1,75 +0,0 @@ -connection = $connection; - $this->setUpOperation = new PHPUnit_Extensions_Database_Operation_Composite(array( - new Zend_Test_PHPUnit_Db_Operation_Truncate(), - new Zend_Test_PHPUnit_Db_Operation_Insert(), - )); - $this->tearDownOperation = PHPUnit_Extensions_Database_Operation_Factory::NONE(); - } - - /** - * Set Up the database using the given Dataset and the SetUp strategy "Truncate, then Insert" - * - * @param PHPUnit_Extensions_Database_DataSet_IDataSet $dataSet - */ - public function setUpDatabase(PHPUnit_Extensions_Database_DataSet_IDataSet $dataSet) - { - $this->setDataSet($dataSet); - $this->onSetUp(); - } -} diff --git a/library/Zend/Tool/Framework/Action/Base.php b/library/Zend/Tool/Framework/Action/Base.php deleted file mode 100644 index 593d93204a..0000000000 --- a/library/Zend/Tool/Framework/Action/Base.php +++ /dev/null @@ -1,95 +0,0 @@ -setName($options); - } - // implement $options here in the future if this is needed - } - } - - /** - * setName() - * - * @param string $name - * @return Zend_Tool_Framework_Action_Base - */ - public function setName($name) - { - $this->_name = $name; - return $this; - } - - /** - * getName() - * - * @return string - */ - public function getName() - { - if ($this->_name == null) { - $this->_name = $this->_parseName(); - } - return $this->_name; - } - - /** - * _parseName - internal method to determine the name of an action when one is not explicity provided. - * - * @param Zend_Tool_Framework_Action_Interface $action - * @return string - */ - protected function _parseName() - { - $className = get_class($this); - $actionName = substr($className, strrpos($className, '_')+1); - return $actionName; - } - -} diff --git a/library/Zend/Tool/Framework/Action/Exception.php b/library/Zend/Tool/Framework/Action/Exception.php deleted file mode 100644 index 63231e9ba6..0000000000 --- a/library/Zend/Tool/Framework/Action/Exception.php +++ /dev/null @@ -1,37 +0,0 @@ -_registry = $registry; - } - - /** - * addAction() - * - * @param Zend_Tool_Framework_Action_Interface $action - * @return Zend_Tool_Framework_Action_Repository - */ - public function addAction(Zend_Tool_Framework_Action_Interface $action, $overrideExistingAction = false) - { - $actionName = $action->getName(); - - if ($actionName == '' || $actionName == 'Base') { - #require_once 'Zend/Tool/Framework/Action/Exception.php'; - throw new Zend_Tool_Framework_Action_Exception('An action name for the provided action could not be determined.'); - } - - if (!$overrideExistingAction && array_key_exists(strtolower($actionName), $this->_actions)) { - #require_once 'Zend/Tool/Framework/Action/Exception.php'; - throw new Zend_Tool_Framework_Action_Exception('An action by the name ' . $actionName - . ' is already registered and $overrideExistingAction is set to false.'); - } - - $this->_actions[strtolower($actionName)] = $action; - return $this; - } - - /** - * process() - this is called when the client is done constructing (after init()) - * - * @return unknown - */ - public function process() - { - return null; - } - - /** - * getActions() - get all actions in the repository - * - * @return array - */ - public function getActions() - { - return $this->_actions; - } - - /** - * getAction() - get an action by a specific name - * - * @param string $actionName - * @return Zend_Tool_Framework_Action_Interface - */ - public function getAction($actionName) - { - if (!array_key_exists(strtolower($actionName), $this->_actions)) { - return null; - } - - return $this->_actions[strtolower($actionName)]; - } - - /** - * count() required by the Countable interface - * - * @return int - */ - public function count() - { - return count($this->_actions); - } - - /** - * getIterator() - get all actions, this supports the IteratorAggregate interface - * - * @return array - */ - public function getIterator() - { - return new ArrayIterator($this->_actions); - } - -} diff --git a/library/Zend/Tool/Framework/Client/Abstract.php b/library/Zend/Tool/Framework/Client/Abstract.php deleted file mode 100644 index 8bb8d36a3c..0000000000 --- a/library/Zend/Tool/Framework/Client/Abstract.php +++ /dev/null @@ -1,333 +0,0 @@ -setClient($this); - - // NOTE: at this moment, $this->_registry should contain the registry object - - if ($options) { - $this->setOptions($options); - } - } - - public function setOptions(Array $options) - { - foreach ($options as $optionName => $optionValue) { - $setMethodName = 'set' . $optionName; - if (method_exists($this, $setMethodName)) { - $this->{$setMethodName}($optionValue); - } - } - } - - /** - * getName() - Return the client name which can be used to - * query the manifest if need be. - * - * @return string The client name - */ - abstract public function getName(); - - /** - * initialized() - This will initialize the client for use - * - */ - public function initialize() - { - // if its already initialized, no need to initialize again - if ($this->_isInitialized) { - return; - } - - // run any preInit - $this->_preInit(); - - $manifest = $this->_registry->getManifestRepository(); - $manifest->addManifest(new Zend_Tool_Framework_Client_Manifest()); - - // setup the debug log - if (!$this->_debugLogger instanceof Zend_Log) { - #require_once 'Zend/Log.php'; - #require_once 'Zend/Log/Writer/Null.php'; - $this->_debugLogger = new Zend_Log(new Zend_Log_Writer_Null()); - } - - // let the loader load, then the repositories process whats been loaded - $this->_registry->getLoader()->load(); - - // process the action repository - $this->_registry->getActionRepository()->process(); - - // process the provider repository - $this->_registry->getProviderRepository()->process(); - - // process the manifest repository - $this->_registry->getManifestRepository()->process(); - - if ($this instanceof Zend_Tool_Framework_Client_Interactive_InputInterface) { - #require_once 'Zend/Tool/Framework/Client/Interactive/InputHandler.php'; - } - - if ($this instanceof Zend_Tool_Framework_Client_Interactive_OutputInterface) { - $this->_registry->getResponse()->setContentCallback(array($this, 'handleInteractiveOutput')); - } - - } - - - /** - * This method should be implemented by the client implementation to - * construct and set custom inflectors, request and response objects. - */ - protected function _preInit() - { - } - - /** - * This method *must* be implemented by the client implementation to - * parse out and setup the request objects action, provider and parameter - * information. - */ - abstract protected function _preDispatch(); - - /** - * This method should be implemented by the client implementation to - * take the output of the response object and return it (in an client - * specific way) back to the Tooling Client. - */ - protected function _postDispatch() - { - } - - /** - * setRegistry() - Required by the Zend_Tool_Framework_Registry_EnabledInterface - * interface which ensures proper registry dependency resolution - * - * @param Zend_Tool_Framework_Registry_Interface $registry - * @return Zend_Tool_Framework_Client_Abstract - */ - public function setRegistry(Zend_Tool_Framework_Registry_Interface $registry) - { - $this->_registry = $registry; - return $this; - } - - /** - * getRegistry(); - * - * @return Zend_Tool_Framework_Registry_Interface - */ - public function getRegistry() - { - return $this->_registry; - } - - /** - * hasInteractiveInput() - Convienence method for determining if this - * client can handle interactive input, and thus be able to run the - * promptInteractiveInput - * - * @return bool - */ - public function hasInteractiveInput() - { - return ($this instanceof Zend_Tool_Framework_Client_Interactive_InputInterface); - } - - public function promptInteractiveInput($inputRequest) - { - if (!$this->hasInteractiveInput()) { - #require_once 'Zend/Tool/Framework/Client/Exception.php'; - throw new Zend_Tool_Framework_Client_Exception('promptInteractive() cannot be called on a non-interactive client.'); - } - - $inputHandler = new Zend_Tool_Framework_Client_Interactive_InputHandler(); - $inputHandler->setClient($this); - $inputHandler->setInputRequest($inputRequest); - return $inputHandler->handle(); - - } - - /** - * This method should be called in order to "handle" a Tooling Client - * request that has come to the client that has been implemented. - */ - public function dispatch() - { - $this->initialize(); - - try { - - $this->_preDispatch(); - - if ($this->_registry->getRequest()->isDispatchable()) { - - if ($this->_registry->getRequest()->getActionName() == null) { - #require_once 'Zend/Tool/Framework/Client/Exception.php'; - throw new Zend_Tool_Framework_Client_Exception('Client failed to setup the action name.'); - } - - if ($this->_registry->getRequest()->getProviderName() == null) { - #require_once 'Zend/Tool/Framework/Client/Exception.php'; - throw new Zend_Tool_Framework_Client_Exception('Client failed to setup the provider name.'); - } - - $this->_handleDispatch(); - - } - - } catch (Exception $exception) { - $this->_registry->getResponse()->setException($exception); - } - - $this->_postDispatch(); - } - - public function convertToClientNaming($string) - { - return $string; - } - - public function convertFromClientNaming($string) - { - return $string; - } - - protected function _handleDispatch() - { - // get the provider repository - $providerRepository = $this->_registry->getProviderRepository(); - - $request = $this->_registry->getRequest(); - - // get the dispatchable provider signature - $providerSignature = $providerRepository->getProviderSignature($request->getProviderName()); - - // get the actual provider - $provider = $providerSignature->getProvider(); - - // ensure that we can pretend if this is a pretend request - if ($request->isPretend() && (!$provider instanceof Zend_Tool_Framework_Provider_Pretendable)) { - #require_once 'Zend/Tool/Framework/Client/Exception.php'; - throw new Zend_Tool_Framework_Client_Exception('Dispatcher error - provider does not support pretend'); - } - - // get the action name - $actionName = $this->_registry->getRequest()->getActionName(); - $specialtyName = $this->_registry->getRequest()->getSpecialtyName(); - - if (!$actionableMethod = $providerSignature->getActionableMethodByActionName($actionName, $specialtyName)) { - #require_once 'Zend/Tool/Framework/Client/Exception.php'; - throw new Zend_Tool_Framework_Client_Exception('Dispatcher error - actionable method not found'); - } - - // get the actual method and param information - $methodName = $actionableMethod['methodName']; - $methodParameters = $actionableMethod['parameterInfo']; - - // get the provider params - $requestParameters = $this->_registry->getRequest()->getProviderParameters(); - - // @todo This seems hackish, determine if there is a better way - $callParameters = array(); - foreach ($methodParameters as $methodParameterName => $methodParameterValue) { - if (!array_key_exists($methodParameterName, $requestParameters) && $methodParameterValue['optional'] == false) { - if ($this instanceof Zend_Tool_Framework_Client_Interactive_InputInterface) { - $promptSting = $this->getMissingParameterPromptString($provider, $actionableMethod['action'], $methodParameterValue['name']); - $parameterPromptValue = $this->promptInteractiveInput($promptSting)->getContent(); - if ($parameterPromptValue == null) { - #require_once 'Zend/Tool/Framework/Client/Exception.php'; - throw new Zend_Tool_Framework_Client_Exception('Value supplied for required parameter "' . $methodParameterValue['name'] . '" is empty'); - } - $callParameters[] = $parameterPromptValue; - } else { - #require_once 'Zend/Tool/Framework/Client/Exception.php'; - throw new Zend_Tool_Framework_Client_Exception('A required parameter "' . $methodParameterValue['name'] . '" was not supplied.'); - } - } else { - $callParameters[] = (array_key_exists($methodParameterName, $requestParameters)) ? $requestParameters[$methodParameterName] : $methodParameterValue['default']; - } - } - - $this->_handleDispatchExecution($provider, $methodName, $callParameters); - } - - protected function _handleDispatchExecution($class, $methodName, $callParameters) - { - if (method_exists($class, $methodName)) { - call_user_func_array(array($class, $methodName), $callParameters); - } elseif (method_exists($class, $methodName . 'Action')) { - call_user_func_array(array($class, $methodName . 'Action'), $callParameters); - } else { - #require_once 'Zend/Tool/Framework/Client/Exception.php'; - throw new Zend_Tool_Framework_Client_Exception('Not a supported method.'); - } - } - -} diff --git a/library/Zend/Tool/Framework/Client/Config.php b/library/Zend/Tool/Framework/Client/Config.php deleted file mode 100644 index 740710377b..0000000000 --- a/library/Zend/Tool/Framework/Client/Config.php +++ /dev/null @@ -1,244 +0,0 @@ -setOptions($options); - } - } - - /** - * @param array $options - */ - public function setOptions(Array $options) - { - foreach ($options as $optionName => $optionValue) { - $setMethodName = 'set' . $optionName; - if (method_exists($this, $setMethodName)) { - $this->{$setMethodName}($optionValue); - } - } - } - - /** - * @param string $configFilepath - * @return Zend_Tool_Framework_Client_Config - */ - public function setConfigFilepath($configFilepath) - { - if (!file_exists($configFilepath)) { - #require_once 'Zend/Tool/Framework/Client/Exception.php'; - throw new Zend_Tool_Framework_Client_Exception('Provided path to config ' . $configFilepath . ' does not exist'); - } - - $this->_configFilepath = $configFilepath; - $this->loadConfig($configFilepath); - - return $this; - } - - /** - * Load the configuration from the given path. - * - * @param string $configFilepath - */ - protected function loadConfig($configFilepath) - { - $suffix = substr($configFilepath, -4); - - switch ($suffix) { - case '.ini': - #require_once 'Zend/Config/Ini.php'; - $this->_config = new Zend_Config_Ini($configFilepath, null, array('allowModifications' => true)); - break; - case '.xml': - #require_once 'Zend/Config/Xml.php'; - $this->_config = new Zend_Config_Xml($configFilepath, null, array('allowModifications' => true)); - break; - case '.php': - #require_once 'Zend/Config.php'; - $this->_config = new Zend_Config(include $configFilepath, true); - break; - default: - #require_once 'Zend/Tool/Framework/Client/Exception.php'; - throw new Zend_Tool_Framework_Client_Exception('Unknown config file type ' - . $suffix . ' at location ' . $configFilepath - ); - } - } - - /** - * Return the filepath of the configuration. - * - * @return string - */ - public function getConfigFilepath() - { - return $this->_configFilepath; - } - - /** - * Get a configuration value. - * - * @param string $name - * @param string $defaultValue - * @return mixed - */ - public function get($name, $defaultValue=null) - { - return $this->getConfigInstance()->get($name, $defaultValue); - } - - /** - * Get a configuration value - * - * @param string $name - * @return mixed - */ - public function __get($name) - { - return $this->getConfigInstance()->{$name}; - } - - /** - * Check if a configuration value isset. - * - * @param string $name - * @return boolean - */ - public function __isset($name) - { - if($this->exists() == false) { - return false; - } - return isset($this->getConfigInstance()->{$name}); - } - - /** - * @param string $name - */ - public function __unset($name) - { - unset($this->getConfigInstance()->$name); - } - - /** - * @param string $name - * @param mixed $value - */ - public function __set($name, $value) - { - return $this->getConfigInstance()->$name = $value; - } - - /** - * Check if the User profile has a configuration. - * - * @return bool - */ - public function exists() - { - return ($this->_config!==null); - } - - /** - * @throws Zend_Tool_Framework_Client_Exception - * @return Zend_Config - */ - public function getConfigInstance() - { - if(!$this->exists()) { - #require_once "Zend/Tool/Framework/Client/Exception.php"; - throw new Zend_Tool_Framework_Client_Exception("Client has no persistent configuration."); - } - - return $this->_config; - } - - /** - * Save changes to the configuration into persistence. - * - * @return bool - */ - public function save() - { - if($this->exists()) { - $writer = $this->getConfigWriter(); - $writer->write($this->getConfigFilepath(), $this->getConfigInstance(), true); - $this->loadConfig($this->getConfigFilepath()); - - return true; - } - return false; - } - - /** - * Get the config writer that corresponds to the current config file type. - * - * @return Zend_Config_Writer_FileAbstract - */ - protected function getConfigWriter() - { - $suffix = substr($this->getConfigFilepath(), -4); - switch($suffix) { - case '.ini': - #require_once "Zend/Config/Writer/Ini.php"; - $writer = new Zend_Config_Writer_Ini(); - $writer->setRenderWithoutSections(); - break; - case '.xml': - #require_once "Zend/Config/Writer/Xml.php"; - $writer = new Zend_Config_Writer_Xml(); - break; - case '.php': - #require_once "Zend/Config/Writer/Array.php"; - $writer = new Zend_Config_Writer_Array(); - break; - default: - #require_once 'Zend/Tool/Framework/Client/Exception.php'; - throw new Zend_Tool_Framework_Client_Exception('Unknown config file type ' - . $suffix . ' at location ' . $this->getConfigFilepath() - ); - } - return $writer; - } -} diff --git a/library/Zend/Tool/Framework/Client/Console.php b/library/Zend/Tool/Framework/Client/Console.php deleted file mode 100644 index 221d44f8b3..0000000000 --- a/library/Zend/Tool/Framework/Client/Console.php +++ /dev/null @@ -1,312 +0,0 @@ -dispatch(); - } - - /** - * getName() - return the name of the client, in this case 'console' - * - * @return string - */ - public function getName() - { - return 'console'; - } - - /** - * setConfigOptions() - * - * @param array $configOptions - */ - public function setConfigOptions($configOptions) - { - $this->_configOptions = $configOptions; - return $this; - } - - /** - * setStorageOptions() - * - * @param array $storageOptions - */ - public function setStorageOptions($storageOptions) - { - $this->_storageOptions = $storageOptions; - return $this; - } - - /** - * @param array $classesToLoad - */ - public function setClassesToLoad($classesToLoad) - { - $this->_classesToLoad = $classesToLoad; - return $this; - } - - /** - * _init() - Tasks processed before the constructor, generally setting up objects to use - * - */ - protected function _preInit() - { - $config = $this->_registry->getConfig(); - - if ($this->_configOptions != null) { - $config->setOptions($this->_configOptions); - } - - $storage = $this->_registry->getStorage(); - - if ($this->_storageOptions != null && isset($this->_storageOptions['directory'])) { - $storage->setAdapter( - new Zend_Tool_Framework_Client_Storage_Directory($this->_storageOptions['directory']) - ); - } - - // which classes are essential to initializing Zend_Tool_Framework_Client_Console - $classesToLoad = array( - 'Zend_Tool_Framework_Client_Console_Manifest', - 'Zend_Tool_Framework_System_Manifest' - ); - - if ($this->_classesToLoad) { - if (is_string($this->_classesToLoad)) { - $classesToLoad[] = $this->_classesToLoad; - } elseif (is_array($this->_classesToLoad)) { - $classesToLoad = array_merge($classesToLoad, $this->_classesToLoad); - } - } - - // add classes to the basic loader from the config file basicloader.classes.1 .. - if (isset($config->basicloader) && isset($config->basicloader->classes)) { - foreach ($config->basicloader->classes as $classKey => $className) { - array_push($classesToLoad, $className); - } - } - - $this->_registry->setLoader( - new Zend_Tool_Framework_Loader_BasicLoader(array('classesToLoad' => $classesToLoad)) - ); - - return; - } - - /** - * _preDispatch() - Tasks handed after initialization but before dispatching - * - */ - protected function _preDispatch() - { - $response = $this->_registry->getResponse(); - - $response->addContentDecorator(new Zend_Tool_Framework_Client_Console_ResponseDecorator_AlignCenter()); - $response->addContentDecorator(new Zend_Tool_Framework_Client_Console_ResponseDecorator_Indention()); - $response->addContentDecorator(new Zend_Tool_Framework_Client_Console_ResponseDecorator_Blockize()); - - if (function_exists('posix_isatty')) { - $response->addContentDecorator(new Zend_Tool_Framework_Client_Console_ResponseDecorator_Colorizer()); - } - - $response->addContentDecorator(new Zend_Tool_Framework_Client_Response_ContentDecorator_Separator()) - ->setDefaultDecoratorOptions(array('separator' => true)); - - $optParser = new Zend_Tool_Framework_Client_Console_ArgumentParser(); - $optParser->setArguments($_SERVER['argv']) - ->setRegistry($this->_registry) - ->parse(); - - return; - } - - /** - * _postDispatch() - Tasks handled after dispatching - * - */ - protected function _postDispatch() - { - $request = $this->_registry->getRequest(); - $response = $this->_registry->getResponse(); - - if ($response->isException()) { - $helpSystem = new Zend_Tool_Framework_Client_Console_HelpSystem(); - $helpSystem->setRegistry($this->_registry) - ->respondWithErrorMessage($response->getException()->getMessage(), $response->getException()) - ->respondWithSpecialtyAndParamHelp( - $request->getProviderName(), - $request->getActionName() - ); - } - - echo PHP_EOL; - return; - } - - /** - * handleInteractiveInputRequest() is required by the Interactive InputInterface - * - * - * @param Zend_Tool_Framework_Client_Interactive_InputRequest $inputRequest - * @return string - */ - public function handleInteractiveInputRequest(Zend_Tool_Framework_Client_Interactive_InputRequest $inputRequest) - { - fwrite(STDOUT, $inputRequest->getContent() . PHP_EOL . 'zf> '); - $inputContent = fgets(STDIN); - return rtrim($inputContent); // remove the return from the end of the string - } - - /** - * handleInteractiveOutput() is required by the Interactive OutputInterface - * - * This allows us to display output immediately from providers, rather - * than displaying it after the provider is done. - * - * @param string $output - */ - public function handleInteractiveOutput($output) - { - echo $output; - } - - /** - * getMissingParameterPromptString() - * - * @param Zend_Tool_Framework_Provider_Interface $provider - * @param Zend_Tool_Framework_Action_Interface $actionInterface - * @param string $missingParameterName - * @return string - */ - public function getMissingParameterPromptString(Zend_Tool_Framework_Provider_Interface $provider, Zend_Tool_Framework_Action_Interface $actionInterface, $missingParameterName) - { - return 'Please provide a value for $' . $missingParameterName; - } - - - /** - * convertToClientNaming() - * - * Convert words to client specific naming, in this case is lower, dash separated - * - * Filters are lazy-loaded. - * - * @param string $string - * @return string - */ - public function convertToClientNaming($string) - { - if (!$this->_filterToClientNaming) { - $filter = new Zend_Filter(); - $filter->addFilter(new Zend_Filter_Word_CamelCaseToDash()); - $filter->addFilter(new Zend_Filter_StringToLower()); - - $this->_filterToClientNaming = $filter; - } - - return $this->_filterToClientNaming->filter($string); - } - - /** - * convertFromClientNaming() - * - * Convert words from client specific naming to code naming - camelcased - * - * Filters are lazy-loaded. - * - * @param string $string - * @return string - */ - public function convertFromClientNaming($string) - { - if (!$this->_filterFromClientNaming) { - $this->_filterFromClientNaming = new Zend_Filter_Word_DashToCamelCase(); - } - - return $this->_filterFromClientNaming->filter($string); - } - -} diff --git a/library/Zend/Tool/Framework/Client/Console/ArgumentParser.php b/library/Zend/Tool/Framework/Client/Console/ArgumentParser.php deleted file mode 100644 index 6b8d40ca96..0000000000 --- a/library/Zend/Tool/Framework/Client/Console/ArgumentParser.php +++ /dev/null @@ -1,539 +0,0 @@ -_argumentsOriginal = $this->_argumentsWorking = $arguments; - return $this; - } - - /** - * setRegistry() - * - * @param Zend_Tool_Framework_Registry_Interface $registry - * @return Zend_Tool_Framework_Client_Console_ArgumentParser - */ - public function setRegistry(Zend_Tool_Framework_Registry_Interface $registry) - { - // get the client registry - $this->_registry = $registry; - - // set manifest repository, request, response for easy access - $this->_manifestRepository = $this->_registry->getManifestRepository(); - $this->_request = $this->_registry->getRequest(); - $this->_response = $this->_registry->getResponse(); - return $this; - } - - /** - * Parse() - This method does the work of parsing the arguments into the enpooint request, - * this will also (during help operations) fill the response in with information as needed - * - * @return null - */ - public function parse() - { - - if ($this->_request == null || $this->_response == null) { - #require_once 'Zend/Tool/Framework/Client/Exception.php'; - throw new Zend_Tool_Framework_Client_Exception('The client registry must have both a request and response registered.'); - } - - // setup the help options - $helpResponseOptions = array(); - - // check to see if the first cli arg is the script name - if ($this->_argumentsWorking[0] == $_SERVER['SCRIPT_NAME' ]) { - array_shift($this->_argumentsWorking); - } - - // process global options - try { - $this->_parseGlobalPart(); - } catch (Zend_Tool_Framework_Client_Exception $exception) { - $this->_createHelpResponse(array('error' => $exception->getMessage())); - return; - } - - // ensure there are arguments left - if (count($this->_argumentsWorking) == 0) { - $this->_request->setDispatchable(false); // at this point request is not dispatchable - - // check to see if this was a help request - if ($this->_help) { - $this->_createHelpResponse(); - } else { - $this->_createHelpResponse(array('error' => 'An action and provider is required.')); - } - return; - } - - // process the action part of the command line - try { - $this->_parseActionPart(); - } catch (Zend_Tool_Framework_Client_Exception $exception) { - $this->_request->setDispatchable(false); - $this->_createHelpResponse(array('error' => $exception->getMessage())); - return; - } - - if ($this->_helpKnownAction) { - $helpResponseOptions = array_merge( - $helpResponseOptions, - array('actionName' => $this->_request->getActionName()) - ); - } - - /* @TODO Action Parameter Requirements */ - - // make sure there are more "words" on the command line - if (count($this->_argumentsWorking) == 0) { - $this->_request->setDispatchable(false); // at this point request is not dispatchable - - // check to see if this is a help request - if ($this->_help) { - $this->_createHelpResponse($helpResponseOptions); - } else { - $this->_createHelpResponse(array_merge($helpResponseOptions, array('error' => 'A provider is required.'))); - } - return; - } - - - // process the provider part of the command line - try { - $this->_parseProviderPart(); - } catch (Zend_Tool_Framework_Client_Exception $exception) { - $this->_request->setDispatchable(false); - $this->_createHelpResponse(array('error' => $exception->getMessage())); - return; - } - - if ($this->_helpKnownProvider) { - $helpResponseOptions = array_merge( - $helpResponseOptions, - array('providerName' => $this->_request->getProviderName()) - ); - } - - if ($this->_helpKnownSpecialty) { - $helpResponseOptions = array_merge( - $helpResponseOptions, - array('specialtyName' => $this->_request->getSpecialtyName()) - ); - } - - // if there are arguments on the command line, lets process them as provider options - if (count($this->_argumentsWorking) != 0) { - $this->_parseProviderOptionsPart(); - } - - // if there is still arguments lingering around, we can assume something is wrong - if (count($this->_argumentsWorking) != 0) { - $this->_request->setDispatchable(false); // at this point request is not dispatchable - if ($this->_help) { - $this->_createHelpResponse($helpResponseOptions); - } else { - $this->_createHelpResponse(array_merge( - $helpResponseOptions, - array('error' => 'Unknown arguments left on the command line: ' . implode(' ', $this->_argumentsWorking)) - )); - } - return; - } - - // everything was processed and this is a request for help information - if ($this->_help) { - $this->_request->setDispatchable(false); // at this point request is not dispatchable - $this->_createHelpResponse($helpResponseOptions); - } - - return; - } - - /** - * Internal routine for parsing global options from the command line - * - * @return null - */ - protected function _parseGlobalPart() - { - $getoptOptions = array(); - $getoptOptions['help|h'] = 'HELP'; - $getoptOptions['verbose|v'] = 'VERBOSE'; - $getoptOptions['pretend|p'] = 'PRETEND'; - $getoptOptions['debug|d'] = 'DEBUG'; - $getoptParser = new Zend_Console_Getopt($getoptOptions, $this->_argumentsWorking, array('parseAll' => false)); - - // @todo catch any exceptions here - $getoptParser->parse(); - - foreach ($getoptParser->getOptions() as $option) { - if ($option == 'pretend') { - $this->_request->setPretend(true); - } elseif ($option == 'debug') { - $this->_request->setDebug(true); - } elseif ($option == 'verbose') { - $this->_request->setVerbose(true); - } else { - $property = '_'.$option; - $this->{$property} = true; - } - } - - $this->_argumentsWorking = $getoptParser->getRemainingArgs(); - - return; - } - - /** - * Internal routine for parsing the action name from the arguments - * - * @return null - */ - protected function _parseActionPart() - { - // the next "word" should be the action name - $consoleActionName = array_shift($this->_argumentsWorking); - - if ($consoleActionName == '?') { - $this->_help = true; - return; - } - - $actionSearchCriteria = array( - 'type' => 'Tool', - 'name' => 'actionName', - 'value' => $consoleActionName, - 'clientName' => 'console' - ); - - // is the action name valid? - $actionMetadata = $this->_manifestRepository->getMetadata($actionSearchCriteria); - - // check for normalized names as well (all lower, no separators) - if (!$actionMetadata) { - $actionSearchCriteria['name'] = 'normalizedActionName'; - $actionSearchCriteria['value'] = strtolower(str_replace(array('-', '_'), '', $consoleActionName)); - $actionSearchCriteria['clientName'] = 'all'; - $actionMetadata = $this->_manifestRepository->getMetadata($actionSearchCriteria); - } - - // if no action, handle error - if (!$actionMetadata) { - #require_once 'Zend/Tool/Framework/Client/Exception.php'; - throw new Zend_Tool_Framework_Client_Exception('Action \'' . $consoleActionName . '\' is not a valid action.'); - } - - // prepare action request name - $this->_helpKnownAction = true; - $this->_request->setActionName($actionMetadata->getActionName()); - return; - } - - /** - * Internal routine for parsing the provider part of the command line arguments - * - * @return null - */ - protected function _parseProviderPart() - { - // get the cli "word" as the provider name from command line - $consoleProviderFull = array_shift($this->_argumentsWorking); - $consoleSpecialtyName = '_global'; - - // if there is notation for specialties? If so, break them up - if (strstr($consoleProviderFull, '.')) { - list($consoleProviderName, $consoleSpecialtyName) = explode('.', $consoleProviderFull); - } else { - $consoleProviderName = $consoleProviderFull; - } - - if ($consoleProviderName == '?') { - $this->_help = true; - return; - } - - $providerSearchCriteria = array( - 'type' => 'Tool', - 'name' => 'providerName', - 'value' => $consoleProviderName, - 'clientName' => 'console' - ); - - // get the cli provider names from the manifest - $providerMetadata = $this->_manifestRepository->getMetadata($providerSearchCriteria); - - // check for normalized names as well (all lower, no separators) - if (!$providerMetadata) { - $providerSearchCriteria['name'] = 'normalizedProviderName'; - $providerSearchCriteria['value'] = strtolower(str_replace(array('-', '_'), '', $consoleProviderName)); - $providerSearchCriteria['clientName'] = 'all'; - $providerMetadata = $this->_manifestRepository->getMetadata($providerSearchCriteria); - } - - if (!$providerMetadata) { - #require_once 'Zend/Tool/Framework/Client/Exception.php'; - throw new Zend_Tool_Framework_Client_Exception( - 'Provider \'' . $consoleProviderFull . '\' is not a valid provider.' - ); - } - - $this->_helpKnownProvider = true; - $this->_request->setProviderName($providerMetadata->getProviderName()); - - if ($consoleSpecialtyName == '?') { - $this->_help = true; - return; - } - - $providerSpecialtySearchCriteria = array( - 'type' => 'Tool', - 'name' => 'specialtyName', - 'value' => $consoleSpecialtyName, - 'providerName' => $providerMetadata->getProviderName(), - 'clientName' => 'console' - ); - - $providerSpecialtyMetadata = $this->_manifestRepository->getMetadata($providerSpecialtySearchCriteria); - - if (!$providerSpecialtyMetadata) { - $providerSpecialtySearchCriteria['name'] = 'normalizedSpecialtyName'; - $providerSpecialtySearchCriteria['value'] = strtolower(str_replace(array('-', '_'), '', $consoleSpecialtyName)); - $providerSpecialtySearchCriteria['clientName'] = 'all'; - $providerSpecialtyMetadata = $this->_manifestRepository->getMetadata($providerSpecialtySearchCriteria); - } - - if (!$providerSpecialtyMetadata) { - #require_once 'Zend/Tool/Framework/Client/Exception.php'; - throw new Zend_Tool_Framework_Client_Exception( - 'Provider \'' . $consoleSpecialtyName . '\' is not a valid specialty.' - ); - } - - $this->_helpKnownSpecialty = true; - $this->_request->setSpecialtyName($providerSpecialtyMetadata->getSpecialtyName()); - return; - } - - /** - * Internal routine for parsing the provider options from the command line - * - * @return null - */ - protected function _parseProviderOptionsPart() - { - if (current($this->_argumentsWorking) == '?') { - $this->_help = true; - return; - } - - $searchParams = array( - 'type' => 'Tool', - 'providerName' => $this->_request->getProviderName(), - 'actionName' => $this->_request->getActionName(), - 'specialtyName' => $this->_request->getSpecialtyName(), - 'clientName' => 'console' - ); - - $actionableMethodLongParamsMetadata = $this->_manifestRepository->getMetadata( - array_merge($searchParams, array('name' => 'actionableMethodLongParams')) - ); - - $actionableMethodShortParamsMetadata = $this->_manifestRepository->getMetadata( - array_merge($searchParams, array('name' => 'actionableMethodShortParams')) - ); - - $paramNameShortValues = $actionableMethodShortParamsMetadata->getValue(); - - $getoptOptions = array(); - $wordArguments = array(); - $longParamCanonicalNames = array(); - - $actionableMethodLongParamsMetadataReference = $actionableMethodLongParamsMetadata->getReference(); - foreach ($actionableMethodLongParamsMetadata->getValue() as $parameterNameLong => $consoleParameterNameLong) { - $optionConfig = $consoleParameterNameLong . '|'; - - $parameterInfo = $actionableMethodLongParamsMetadataReference['parameterInfo'][$parameterNameLong]; - - // process ParameterInfo into array for command line option matching - if ($parameterInfo['type'] == 'string' || $parameterInfo['type'] == 'bool') { - $optionConfig .= $paramNameShortValues[$parameterNameLong] - . (($parameterInfo['optional']) ? '-' : '=') . 's'; - } elseif (in_array($parameterInfo['type'], array('int', 'integer', 'float'))) { - $optionConfig .= $paramNameShortValues[$parameterNameLong] - . (($parameterInfo['optional']) ? '-' : '=') . 'i'; - } else { - $optionConfig .= $paramNameShortValues[$parameterNameLong] . '-s'; - } - - $getoptOptions[$optionConfig] = ($parameterInfo['description'] != '') ? $parameterInfo['description'] : 'No description available.'; - - - // process ParameterInfo into array for command line WORD (argument) matching - $wordArguments[$parameterInfo['position']]['parameterName'] = $parameterInfo['name']; - $wordArguments[$parameterInfo['position']]['optional'] = $parameterInfo['optional']; - $wordArguments[$parameterInfo['position']]['type'] = $parameterInfo['type']; - - // keep a translation of console to canonical names - $longParamCanonicalNames[$consoleParameterNameLong] = $parameterNameLong; - } - - - if (!$getoptOptions) { - // no options to parse here, return - return; - } - - // if non-option arguments exist, attempt to process them before processing options - $wordStack = array(); - while (($wordOnTop = array_shift($this->_argumentsWorking))) { - if (substr($wordOnTop, 0, 1) != '-') { - array_push($wordStack, $wordOnTop); - } else { - // put word back on stack and move on - array_unshift($this->_argumentsWorking, $wordOnTop); - break; - } - - if (count($wordStack) == count($wordArguments)) { - // when we get at most the number of arguments we are expecting - // then break out. - break; - } - - } - - if ($wordStack && $wordArguments) { - for ($wordIndex = 1; $wordIndex <= count($wordArguments); $wordIndex++) { - if (!array_key_exists($wordIndex-1, $wordStack) || !array_key_exists($wordIndex, $wordArguments)) { - break; - } - $this->_request->setProviderParameter($wordArguments[$wordIndex]['parameterName'], $wordStack[$wordIndex-1]); - unset($wordStack[$wordIndex-1]); - } - } - - $getoptParser = new Zend_Console_Getopt($getoptOptions, $this->_argumentsWorking, array('parseAll' => false)); - $getoptParser->parse(); - foreach ($getoptParser->getOptions() as $option) { - $value = $getoptParser->getOption($option); - $providerParamOption = $longParamCanonicalNames[$option]; - $this->_request->setProviderParameter($providerParamOption, $value); - } - - $this->_argumentsWorking = $getoptParser->getRemainingArgs(); - - return; - } - - /** - * _createHelpResponse - * - * @param unknown_type $options - */ - protected function _createHelpResponse($options = array()) - { - #require_once 'Zend/Tool/Framework/Client/Console/HelpSystem.php'; - $helpSystem = new Zend_Tool_Framework_Client_Console_HelpSystem(); - $helpSystem->setRegistry($this->_registry); - - if (isset($options['error'])) { - $helpSystem->respondWithErrorMessage($options['error']); - } - - if (isset($options['actionName']) && isset($options['providerName'])) { - $helpSystem->respondWithSpecialtyAndParamHelp($options['providerName'], $options['actionName']); - } elseif (isset($options['actionName'])) { - $helpSystem->respondWithActionHelp($options['actionName']); - } elseif (isset($options['providerName'])) { - $helpSystem->respondWithProviderHelp($options['providerName']); - } else { - $helpSystem->respondWithGeneralHelp(); - } - - } - -} diff --git a/library/Zend/Tool/Framework/Client/Console/HelpSystem.php b/library/Zend/Tool/Framework/Client/Console/HelpSystem.php deleted file mode 100644 index b2c9727102..0000000000 --- a/library/Zend/Tool/Framework/Client/Console/HelpSystem.php +++ /dev/null @@ -1,378 +0,0 @@ -_registry = $registry; - $this->_response = $registry->getResponse(); - return $this; - } - - /** - * respondWithErrorMessage() - * - * @param string $errorMessage - * @param Exception $exception - */ - public function respondWithErrorMessage($errorMessage, Exception $exception = null) - { - // break apart the message into wrapped chunks - $errorMessages = explode(PHP_EOL, wordwrap($errorMessage, 70, PHP_EOL, false)); - - $text = 'An Error Has Occurred'; - $this->_response->appendContent($text, array('color' => array('hiWhite', 'bgRed'), 'aligncenter' => true)); - $this->_response->appendContent($errorMessage, array('indention' => 1, 'blockize' => 72, 'color' => array('white', 'bgRed'))); - - if ($exception && $this->_registry->getRequest()->isDebug()) { - $this->_response->appendContent($exception->getTraceAsString()); - } - - $this->_response->appendContent(null, array('separator' => true)); - return $this; - } - - /** - * respondWithGeneralHelp() - * - * @return Zend_Tool_Framework_Client_Console_HelpSystem - */ - public function respondWithGeneralHelp() - { - $this->_respondWithHeader(); - - $noSeparator = array('separator' => false); - - $this->_response->appendContent('Usage:', array('color' => 'green')) - ->appendContent(' ', $noSeparator) - ->appendContent('zf', array_merge(array('color' => 'cyan'), $noSeparator)) - ->appendContent(' [--global-opts]', $noSeparator) - ->appendContent(' action-name', array_merge(array('color' => 'cyan'), $noSeparator)) - ->appendContent(' [--action-opts]', $noSeparator) - ->appendContent(' provider-name', array_merge(array('color' => 'cyan'), $noSeparator)) - ->appendContent(' [--provider-opts]', $noSeparator) - ->appendContent(' [provider parameters ...]') - ->appendContent(' Note: You may use "?" in any place of the above usage string to ask for more specific help information.', array('color'=>'yellow')) - ->appendContent(' Example: "zf ? version" will list all available actions for the version provider.', array('color'=>'yellow', 'separator' => 2)) - ->appendContent('Providers and their actions:', array('color' => 'green')); - - $this->_respondWithSystemInformation(); - return $this; - } - - /** - * respondWithActionHelp() - * - * @param string $actionName - * @return Zend_Tool_Framework_Client_Console_HelpSystem - */ - public function respondWithActionHelp($actionName) - { - $this->_respondWithHeader(); - $this->_response->appendContent('Providers that support the action "' . $actionName . '"', array('color' => 'green')); - $this->_respondWithSystemInformation(null, $actionName); - return $this; - } - - /** - * respondWithSpecialtyAndParamHelp() - * - * @param string $providerName - * @param string $actionName - * @return Zend_Tool_Framework_Client_Console_HelpSystem - */ - public function respondWithSpecialtyAndParamHelp($providerName, $actionName) - { - $this->_respondWithHeader(); - $this->_response->appendContent( - 'Details for action "' . $actionName . '" and provider "' . $providerName . '"', - array('color' => 'green') - ); - $this->_respondWithSystemInformation($providerName, $actionName, true); - return $this; - } - - /** - * respondWithProviderHelp() - * - * @param string $providerName - * @return Zend_Tool_Framework_Client_Console_HelpSystem - */ - public function respondWithProviderHelp($providerName) - { - $this->_respondWithHeader(); - $this->_response->appendContent('Actions supported by provider "' . $providerName . '"', array('color' => 'green')); - $this->_respondWithSystemInformation($providerName); - return $this; - } - - /** - * _respondWithHeader() - * - * @return Zend_Tool_Framework_Client_Console_HelpSystem - */ - protected function _respondWithHeader() - { - /** - * @see Zend_Version - */ - #require_once 'Zend/Version.php'; - $this->_response->appendContent('Zend Framework', array('color' => array('hiWhite'), 'separator' => false)); - $this->_response->appendContent(' Command Line Console Tool v' . Zend_Version::VERSION . ''); - return $this; - } - - /** - * _respondWithSystemInformation() - * - * @param string $providerNameFilter - * @param string $actionNameFilter - * @param bool $includeAllSpecialties - * @return Zend_Tool_Framework_Client_Console_HelpSystem - */ - protected function _respondWithSystemInformation($providerNameFilter = null, $actionNameFilter = null, $includeAllSpecialties = false) - { - $manifest = $this->_registry->getManifestRepository(); - - $providerMetadatasSearch = array( - 'type' => 'Tool', - 'name' => 'providerName', - 'clientName' => 'console' - ); - - if (is_string($providerNameFilter)) { - $providerMetadatasSearch = array_merge($providerMetadatasSearch, array('providerName' => $providerNameFilter)); - } - - $actionMetadatasSearch = array( - 'type' => 'Tool', - 'name' => 'actionName', - 'clientName' => 'console' - ); - - if (is_string($actionNameFilter)) { - $actionMetadatasSearch = array_merge($actionMetadatasSearch, array('actionName' => $actionNameFilter)); - } - - // get the metadata's for the things to display - $displayProviderMetadatas = $manifest->getMetadatas($providerMetadatasSearch); - $displayActionMetadatas = $manifest->getMetadatas($actionMetadatasSearch); - - // create index of actionNames - for ($i = 0; $i < count($displayActionMetadatas); $i++) { - $displayActionNames[] = $displayActionMetadatas[$i]->getActionName(); - } - - foreach ($displayProviderMetadatas as $providerMetadata) { - - $providerNameDisplayed = false; - - $providerName = $providerMetadata->getProviderName(); - $providerSignature = $providerMetadata->getReference(); - - foreach ($providerSignature->getActions() as $actionInfo) { - - $actionName = $actionInfo->getName(); - - // check to see if this action name is valid - if (($foundActionIndex = array_search($actionName, $displayActionNames)) === false) { - continue; - } else { - $actionMetadata = $displayActionMetadatas[$foundActionIndex]; - } - - $specialtyMetadata = $manifest->getMetadata(array( - 'type' => 'Tool', - 'name' => 'specialtyName', - 'providerName' => $providerName, - 'specialtyName' => '_Global', - 'clientName' => 'console' - )); - - // lets do the main _Global action first - $actionableGlobalLongParamMetadata = $manifest->getMetadata(array( - 'type' => 'Tool', - 'name' => 'actionableMethodLongParams', - 'providerName' => $providerName, - 'specialtyName' => '_Global', - 'actionName' => $actionName, - 'clientName' => 'console' - )); - - $actionableGlobalMetadatas = $manifest->getMetadatas(array( - 'type' => 'Tool', - 'name' => 'actionableMethodLongParams', - 'providerName' => $providerName, - 'actionName' => $actionName, - 'clientName' => 'console' - )); - - if ($actionableGlobalLongParamMetadata) { - - if (!$providerNameDisplayed) { - $this->_respondWithProviderName($providerMetadata); - $providerNameDisplayed = true; - } - - $this->_respondWithCommand($providerMetadata, $actionMetadata, $specialtyMetadata, $actionableGlobalLongParamMetadata); - - $actionIsGlobal = true; - } else { - $actionIsGlobal = false; - } - - // check for providers without a _Global action - $isSingleSpecialProviderAction = false; - if (!$actionIsGlobal && count($actionableGlobalMetadatas) == 1) { - $isSingleSpecialProviderAction = true; - $this->_respondWithProviderName($providerMetadata); - $providerNameDisplayed = true; - } - - if ($includeAllSpecialties || $isSingleSpecialProviderAction) { - - foreach ($providerSignature->getSpecialties() as $specialtyName) { - - if ($specialtyName == '_Global') { - continue; - } - - $specialtyMetadata = $manifest->getMetadata(array( - 'type' => 'Tool', - 'name' => 'specialtyName', - 'providerName' => $providerMetadata->getProviderName(), - 'specialtyName' => $specialtyName, - 'clientName' => 'console' - )); - - $actionableSpecialtyLongMetadata = $manifest->getMetadata(array( - 'type' => 'Tool', - 'name' => 'actionableMethodLongParams', - 'providerName' => $providerMetadata->getProviderName(), - 'specialtyName' => $specialtyName, - 'actionName' => $actionName, - 'clientName' => 'console' - )); - - if($actionableSpecialtyLongMetadata) { - $this->_respondWithCommand($providerMetadata, $actionMetadata, $specialtyMetadata, $actionableSpecialtyLongMetadata); - } - - } - } - - // reset the special flag for single provider action with specialty - $isSingleSpecialProviderAction = false; - - if (!$includeAllSpecialties && count($actionableGlobalMetadatas) > 1) { - $this->_response->appendContent(' Note: There are specialties, use ', array('color' => 'yellow', 'separator' => false)); - $this->_response->appendContent( - 'zf ' . $actionMetadata->getValue() . ' ' . $providerMetadata->getValue() . '.?', - array('color' => 'cyan', 'separator' => false) - ); - $this->_response->appendContent(' to get specific help on them.', array('color' => 'yellow')); - } - - } - - if ($providerNameDisplayed) { - $this->_response->appendContent(null, array('separator' => true)); - } - } - return $this; - } - - /** - * _respondWithProviderName() - * - * @param Zend_Tool_Framework_Metadata_Tool $providerMetadata - * @return Zend_Tool_Framework_Client_Console_HelpSystem - */ - protected function _respondWithProviderName(Zend_Tool_Framework_Metadata_Tool $providerMetadata) - { - $this->_response->appendContent(' ' . $providerMetadata->getProviderName()); - return $this; - } - - /** - * _respondWithCommand() - * - * @param Zend_Tool_Framework_Metadata_Tool $providerMetadata - * @param Zend_Tool_Framework_Metadata_Tool $actionMetadata - * @param Zend_Tool_Framework_Metadata_Tool $specialtyMetadata - * @param Zend_Tool_Framework_Metadata_Tool $parameterLongMetadata - * @return Zend_Tool_Framework_Client_Console_HelpSystem - */ - protected function _respondWithCommand( - Zend_Tool_Framework_Metadata_Tool $providerMetadata, - Zend_Tool_Framework_Metadata_Tool $actionMetadata, - Zend_Tool_Framework_Metadata_Tool $specialtyMetadata, - Zend_Tool_Framework_Metadata_Tool $parameterLongMetadata)//, - //Zend_Tool_Framework_Metadata_Tool $parameterShortMetadata) - { - $this->_response->appendContent( - ' zf ' . $actionMetadata->getValue() . ' ' . $providerMetadata->getValue(), - array('color' => 'cyan', 'separator' => false) - ); - - if ($specialtyMetadata->getSpecialtyName() != '_Global') { - $this->_response->appendContent('.' . $specialtyMetadata->getValue(), array('color' => 'cyan', 'separator' => false)); - } - - foreach ($parameterLongMetadata->getValue() as $paramName => $consoleParamName) { - $methodInfo = $parameterLongMetadata->getReference(); - $paramString = ' ' . $consoleParamName; - if ( ($defaultValue = $methodInfo['parameterInfo'][$paramName]['default']) != null) { - $paramString .= '[=' . $defaultValue . ']'; - } - $this->_response->appendContent($paramString . '', array('separator' => false)); - } - - $this->_response->appendContent(null, array('separator' => true)); - return $this; - } - -} diff --git a/library/Zend/Tool/Framework/Client/Console/Manifest.php b/library/Zend/Tool/Framework/Client/Console/Manifest.php deleted file mode 100644 index 82554b99a0..0000000000 --- a/library/Zend/Tool/Framework/Client/Console/Manifest.php +++ /dev/null @@ -1,209 +0,0 @@ -_registry = $registry; - return $this; - } - - /** - * getMetadata() is required by the Manifest Interface. - * - * These are the following metadatas that will be setup: - * - * actionName - * - metadata for actions - * - value will be a dashed name for the action named in 'actionName' - * providerName - * - metadata for providers - * - value will be a dashed-name for the provider named in 'providerName' - * providerSpecialtyNames - * - metadata for providers - * actionableMethodLongParameters - * - metadata for providers - * actionableMethodShortParameters - * - metadata for providers - * - * @return array Array of Metadatas - */ - public function getMetadata() - { - $metadatas = array(); - - // setup the camelCase to dashed filter to use since cli expects dashed named - $ccToDashedFilter = new Zend_Filter(); - $ccToDashedFilter - ->addFilter(new Zend_Filter_Word_CamelCaseToDash()) - ->addFilter(new Zend_Filter_StringToLower()); - - // get the registry to get the action and provider repository - $actionRepository = $this->_registry->getActionRepository(); - $providerRepository = $this->_registry->getProviderRepository(); - - // loop through all actions and create a metadata for each - foreach ($actionRepository->getActions() as $action) { - // each action metadata will be called - $metadatas[] = new Zend_Tool_Framework_Metadata_Tool(array( - 'name' => 'actionName', - 'value' => $ccToDashedFilter->filter($action->getName()), - 'reference' => $action, - 'actionName' => $action->getName(), - 'clientName' => 'console', - 'clientReference' => $this->_registry->getClient() - )); - } - - foreach ($providerRepository->getProviderSignatures() as $providerSignature) { - - // create the metadata for the provider's cliProviderName - $metadatas[] = new Zend_Tool_Framework_Metadata_Tool(array( - 'name' => 'providerName', - 'value' => $ccToDashedFilter->filter($providerSignature->getName()), - 'reference' => $providerSignature, - 'clientName' => 'console', - 'providerName' => $providerSignature->getName(), - 'clientReference' => $this->_registry->getClient() - )); - - // create the metadatas for the per provider specialites in providerSpecaltyNames - foreach ($providerSignature->getSpecialties() as $specialty) { - - $metadatas[] = new Zend_Tool_Framework_Metadata_Tool(array( - 'name' => 'specialtyName', - 'value' => $ccToDashedFilter->filter($specialty), - 'reference' => $providerSignature, - 'clientName' => 'console', - 'providerName' => $providerSignature->getName(), - 'specialtyName' => $specialty, - 'clientReference' => $this->_registry->getClient() - )); - - } - - // $actionableMethod is keyed by the methodName (but not used) - foreach ($providerSignature->getActionableMethods() as $actionableMethodData) { - - $methodLongParams = array(); - $methodShortParams = array(); - - // $actionableMethodData get both the long and short names - foreach ($actionableMethodData['parameterInfo'] as $parameterInfoData) { - - // filter to dashed - $methodLongParams[$parameterInfoData['name']] = $ccToDashedFilter->filter($parameterInfoData['name']); - - // simply lower the character, (its only 1 char after all) - $methodShortParams[$parameterInfoData['name']] = strtolower($parameterInfoData['name'][0]); - - } - - // create metadata for the long name cliActionableMethodLongParameters - $metadatas[] = new Zend_Tool_Framework_Metadata_Tool(array( - 'name' => 'actionableMethodLongParams', - 'value' => $methodLongParams, - 'clientName' => 'console', - 'providerName' => $providerSignature->getName(), - 'specialtyName' => $actionableMethodData['specialty'], - 'actionName' => $actionableMethodData['actionName'], - 'reference' => &$actionableMethodData, - 'clientReference' => $this->_registry->getClient() - )); - - // create metadata for the short name cliActionableMethodShortParameters - $metadatas[] = new Zend_Tool_Framework_Metadata_Tool(array( - 'name' => 'actionableMethodShortParams', - 'value' => $methodShortParams, - 'clientName' => 'console', - 'providerName' => $providerSignature->getName(), - 'specialtyName' => $actionableMethodData['specialty'], - 'actionName' => $actionableMethodData['actionName'], - 'reference' => &$actionableMethodData, - 'clientReference' => $this->_registry->getClient() - )); - - } - - } - - return $metadatas; - } - - public function getIndex() - { - return 10000; - } - -} diff --git a/library/Zend/Tool/Framework/Client/Console/ResponseDecorator/AlignCenter.php b/library/Zend/Tool/Framework/Client/Console/ResponseDecorator/AlignCenter.php deleted file mode 100644 index 6f3eafb5ec..0000000000 --- a/library/Zend/Tool/Framework/Client/Console/ResponseDecorator/AlignCenter.php +++ /dev/null @@ -1,66 +0,0 @@ - '30m', - 'hiBlack' => '1;30m', - 'bgBlack' => '40m', - // reds - 'red' => '31m', - 'hiRed' => '1;31m', - 'bgRed' => '41m', - // greens - 'green' => '32m', - 'hiGreen' => '1;32m', - 'bgGreen' => '42m', - // yellows - 'yellow' => '33m', - 'hiYellow' => '1;33m', - 'bgYellow' => '43m', - // blues - 'blue' => '34m', - 'hiBlue' => '1;34m', - 'bgBlue' => '44m', - // magentas - 'magenta' => '35m', - 'hiMagenta' => '1;35m', - 'bgMagenta' => '45m', - // cyans - 'cyan' => '36m', - 'hiCyan' => '1;36m', - 'bgCyan' => '46m', - // whites - 'white' => '37m', - 'hiWhite' => '1;37m', - 'bgWhite' => '47m' - ); - - public function getName() - { - return 'color'; - } - - public function decorate($content, $color) - { - if (is_string($color)) { - $color = array($color); - } - - $newContent = ''; - - foreach ($color as $c) { - if (array_key_exists($c, $this->_colorOptions)) { - $newContent .= "\033[" . $this->_colorOptions[$c]; - } - } - - $newContent .= $content . "\033[m"; - - return $newContent; - } - - -} diff --git a/library/Zend/Tool/Framework/Client/Console/ResponseDecorator/Indention.php b/library/Zend/Tool/Framework/Client/Console/ResponseDecorator/Indention.php deleted file mode 100644 index 5e9b3ab0aa..0000000000 --- a/library/Zend/Tool/Framework/Client/Console/ResponseDecorator/Indention.php +++ /dev/null @@ -1,56 +0,0 @@ -_client = $client; - return $this; - } - - public function setInputRequest($inputRequest) - { - if (is_string($inputRequest)) { - #require_once 'Zend/Tool/Framework/Client/Interactive/InputRequest.php'; - $inputRequest = new Zend_Tool_Framework_Client_Interactive_InputRequest($inputRequest); - } elseif (!$inputRequest instanceof Zend_Tool_Framework_Client_Interactive_InputRequest) { - #require_once 'Zend/Tool/Framework/Client/Exception.php'; - throw new Zend_Tool_Framework_Client_Exception('promptInteractive() requires either a string or an instance of Zend_Tool_Framework_Client_Interactive_InputRequest.'); - } - - $this->_inputRequest = $inputRequest; - return $this; - } - - public function handle() - { - $inputResponse = $this->_client->handleInteractiveInputRequest($this->_inputRequest); - - if (is_string($inputResponse)) { - #require_once 'Zend/Tool/Framework/Client/Interactive/InputResponse.php'; - $inputResponse = new Zend_Tool_Framework_Client_Interactive_InputResponse($inputResponse); - } elseif (!$inputResponse instanceof Zend_Tool_Framework_Client_Interactive_InputResponse) { - #require_once 'Zend/Tool/Framework/Client/Exception.php'; - throw new Zend_Tool_Framework_Client_Exception('The registered $_interactiveCallback for the client must either return a string or an instance of Zend_Tool_Framework_Client_Interactive_InputResponse.'); - } - - return $inputResponse; - } - - -} diff --git a/library/Zend/Tool/Framework/Client/Interactive/InputInterface.php b/library/Zend/Tool/Framework/Client/Interactive/InputInterface.php deleted file mode 100644 index a12a833b54..0000000000 --- a/library/Zend/Tool/Framework/Client/Interactive/InputInterface.php +++ /dev/null @@ -1,41 +0,0 @@ -setContent($content); - } - } - - public function setContent($content) - { - $this->_content = $content; - return $this; - } - - public function getContent() - { - return $this->_content; - } - - public function __toString() - { - return $this->_content; - } -} diff --git a/library/Zend/Tool/Framework/Client/Interactive/InputResponse.php b/library/Zend/Tool/Framework/Client/Interactive/InputResponse.php deleted file mode 100644 index 5a68043855..0000000000 --- a/library/Zend/Tool/Framework/Client/Interactive/InputResponse.php +++ /dev/null @@ -1,52 +0,0 @@ -setContent($content); - } - } - - public function setContent($content) - { - $this->_content = $content; - return $this; - } - - public function getContent() - { - return $this->_content; - } - - -} diff --git a/library/Zend/Tool/Framework/Client/Interactive/OutputInterface.php b/library/Zend/Tool/Framework/Client/Interactive/OutputInterface.php deleted file mode 100644 index 03ecfcc48d..0000000000 --- a/library/Zend/Tool/Framework/Client/Interactive/OutputInterface.php +++ /dev/null @@ -1,33 +0,0 @@ -_registry = $registry; - return $this; - } - - /** - * getMetadata() is required by the Manifest Interface. - * - * These are the following metadatas that will be setup: - * - * normalizedActionName - * - metadata for actions - * - value will be a dashed name for the action named in 'actionName' - * normalizedProviderName - * - metadata for providers - * - value will be a dashed-name for the provider named in 'providerName' - * normalizedProviderSpecialtyNames - * - metadata for providers - * normalizedActionableMethodLongParameters - * - metadata for providers - * normalizedActionableMethodShortParameters - * - metadata for providers - * - * @return array Array of Metadatas - */ - public function getMetadata() - { - $metadatas = array(); - - // setup the camelCase to dashed filter to use since cli expects dashed named - $lowerFilter = new Zend_Filter(); - $lowerFilter->addFilter(new Zend_Filter_StringToLower()); - - // get the registry to get the action and provider repository - $actionRepository = $this->_registry->getActionRepository(); - $providerRepository = $this->_registry->getProviderRepository(); - - // loop through all actions and create a metadata for each - foreach ($actionRepository->getActions() as $action) { - // each action metadata will be called - $metadatas[] = new Zend_Tool_Framework_Metadata_Tool(array( - 'name' => 'normalizedActionName', - 'value' => $lowerFilter->filter($action->getName()), - 'reference' => $action, - 'actionName' => $action->getName(), - 'clientName' => 'all' - )); - } - - foreach ($providerRepository->getProviderSignatures() as $providerSignature) { - - // create the metadata for the provider's cliProviderName - $metadatas[] = new Zend_Tool_Framework_Metadata_Tool(array( - 'name' => 'normalizedProviderName', - 'value' => $lowerFilter->filter($providerSignature->getName()), - 'reference' => $providerSignature, - 'clientName' => 'all', - 'providerName' => $providerSignature->getName() - )); - - // create the metadatas for the per provider specialites in providerSpecaltyNames - foreach ($providerSignature->getSpecialties() as $specialty) { - - if ($specialty == '_Global') { - continue; - } - - $metadatas[] = new Zend_Tool_Framework_Metadata_Tool(array( - 'name' => 'normalizedSpecialtyName', - 'value' => $lowerFilter->filter($specialty), - 'reference' => $providerSignature, - 'clientName' => 'all', - 'providerName' => $providerSignature->getName(), - 'specialtyName' => $specialty - )); - - } - - // $actionableMethod is keyed by the methodName (but not used) - foreach ($providerSignature->getActionableMethods() as $actionableMethodData) { - - $methodLongParams = array(); - $methodShortParams = array(); - - // $actionableMethodData get both the long and short names - foreach ($actionableMethodData['parameterInfo'] as $parameterInfoData) { - - // filter to dashed - $methodLongParams[$parameterInfoData['name']] = $lowerFilter->filter($parameterInfoData['name']); - - // simply lower the character, (its only 1 char after all) - $methodShortParams[$parameterInfoData['name']] = strtolower($parameterInfoData['name'][0]); - - } - - // create metadata for the long name cliActionableMethodLongParameters - $metadatas[] = new Zend_Tool_Framework_Metadata_Tool(array( - 'name' => 'normalizedActionableMethodLongParams', - 'value' => $methodLongParams, - 'clientName' => 'console', - 'providerName' => $providerSignature->getName(), - 'specialtyName' => $actionableMethodData['specialty'], - 'actionName' => $actionableMethodData['actionName'], - 'reference' => &$actionableMethodData - )); - - // create metadata for the short name cliActionableMethodShortParameters - $metadatas[] = new Zend_Tool_Framework_Metadata_Tool(array( - 'name' => 'normalizedActionableMethodShortParams', - 'value' => $methodShortParams, - 'clientName' => 'console', - 'providerName' => $providerSignature->getName(), - 'specialtyName' => $actionableMethodData['specialty'], - 'actionName' => $actionableMethodData['actionName'], - 'reference' => &$actionableMethodData - )); - - } - - } - - return $metadatas; - } - - public function getIndex() - { - return 100000; - } - -} diff --git a/library/Zend/Tool/Framework/Client/Request.php b/library/Zend/Tool/Framework/Client/Request.php deleted file mode 100644 index c3896c680d..0000000000 --- a/library/Zend/Tool/Framework/Client/Request.php +++ /dev/null @@ -1,299 +0,0 @@ -_providerName = $providerName; - return $this; - } - - /** - * getProviderName() - * - * @return string - */ - public function getProviderName() - { - return $this->_providerName; - } - - /** - * setSpecialtyName() - * - * @param string $specialtyName - * @return Zend_Tool_Framework_Client_Request - */ - public function setSpecialtyName($specialtyName) - { - $this->_specialtyName = $specialtyName; - return $this; - } - - /** - * getSpecialtyName() - * - * @return string - */ - public function getSpecialtyName() - { - return $this->_specialtyName; - } - - /** - * setActionName() - * - * @param string $actionName - * @return Zend_Tool_Framework_Client_Request - */ - public function setActionName($actionName) - { - $this->_actionName = $actionName; - return $this; - } - - /** - * getActionName() - * - * @return string - */ - public function getActionName() - { - return $this->_actionName; - } - - /** - * setActionParameter() - * - * @param string $parameterName - * @param string $parameterValue - * @return Zend_Tool_Framework_Client_Request - */ - public function setActionParameter($parameterName, $parameterValue) - { - $this->_actionParameters[$parameterName] = $parameterValue; - return $this; - } - - /** - * getActionParameters() - * - * @return array - */ - public function getActionParameters() - { - return $this->_actionParameters; - } - - /** - * getActionParameter() - * - * @param string $parameterName - * @return string - */ - public function getActionParameter($parameterName) - { - return (isset($this->_actionParameters[$parameterName])) ? $this->_actionParameters[$parameterName] : null; - } - - /** - * setProviderParameter() - * - * @param string $parameterName - * @param string $parameterValue - * @return Zend_Tool_Framework_Client_Request - */ - public function setProviderParameter($parameterName, $parameterValue) - { - $this->_providerParameters[$parameterName] = $parameterValue; - return $this; - } - - /** - * getProviderParameters() - * - * @return array - */ - public function getProviderParameters() - { - return $this->_providerParameters; - } - - /** - * getProviderParameter() - * - * @param string $parameterName - * @return string - */ - public function getProviderParameter($parameterName) - { - return (isset($this->_providerParameters[$parameterName])) ? $this->_providerParameters[$parameterName] : null; - } - - /** - * setPretend() - * - * @param bool $pretend - * @return Zend_Tool_Framework_Client_Request - */ - public function setPretend($pretend) - { - $this->_isPretend = (bool) $pretend; - return $this; - } - - /** - * isPretend() - Whether or not this is a pretend request - * - * @return bool - */ - public function isPretend() - { - return $this->_isPretend; - } - - /** - * setDebug() - * - * @param bool $pretend - * @return Zend_Tool_Framework_Client_Request - */ - public function setDebug($debug) - { - $this->_isDebug = (bool) $debug; - return $this; - } - - /** - * isDebug() - Whether or not this is a debug enabled request - * - * @return bool - */ - public function isDebug() - { - return $this->_isDebug; - } - - /** - * setVerbose() - * - * @param bool $verbose - * @return Zend_Tool_Framework_Client_Request - */ - public function setVerbose($verbose) - { - $this->_isVerbose = (bool) $verbose; - return $this; - } - - /** - * isVerbose() - Whether or not this is a verbose enabled request - * - * @return bool - */ - public function isVerbose() - { - return $this->_isVerbose; - } - - /** - * setDispatchable() - * - * @param bool $dispatchable - * @return Zend_Tool_Framework_Client_Request - */ - public function setDispatchable($dispatchable) - { - $this->_isDispatchable = (bool) $dispatchable; - return $this; - } - - /** - * isDispatchable() Is this request Dispatchable? - * - * @return bool - */ - public function isDispatchable() - { - return $this->_isDispatchable; - } - -} diff --git a/library/Zend/Tool/Framework/Client/Response.php b/library/Zend/Tool/Framework/Client/Response.php deleted file mode 100644 index c71afb81fa..0000000000 --- a/library/Zend/Tool/Framework/Client/Response.php +++ /dev/null @@ -1,223 +0,0 @@ -_callback = $callback; - return $this; - } - - /** - * setContent() - * - * @param string $content - * @return Zend_Tool_Framework_Client_Response - */ - public function setContent($content, Array $decoratorOptions = array()) - { - $content = $this->_applyDecorators($content, $decoratorOptions); - - $this->_content = array(); - $this->appendContent($content); - return $this; - } - - /** - * appendCallback - * - * @param string $content - * @return Zend_Tool_Framework_Client_Response - */ - public function appendContent($content, Array $decoratorOptions = array()) - { - $content = $this->_applyDecorators($content, $decoratorOptions); - - if ($this->_callback !== null) { - call_user_func($this->_callback, $content); - } - - $this->_content[] = $content; - - return $this; - } - - /** - * setDefaultDecoratorOptions() - * - * @param array $decoratorOptions - * @param bool $mergeIntoExisting - * @return Zend_Tool_Framework_Client_Response - */ - public function setDefaultDecoratorOptions(Array $decoratorOptions, $mergeIntoExisting = false) - { - if ($mergeIntoExisting == false) { - $this->_defaultDecoratorOptions = array(); - } - - $this->_defaultDecoratorOptions = array_merge($this->_defaultDecoratorOptions, $decoratorOptions); - return $this; - } - - /** - * getContent() - * - * @return string - */ - public function getContent() - { - return implode('', $this->_content); - } - - /** - * isException() - * - * @return bool - */ - public function isException() - { - return isset($this->_exception); - } - - /** - * setException() - * - * @param Exception $exception - * @return Zend_Tool_Framework_Client_Response - */ - public function setException(Exception $exception) - { - $this->_exception = $exception; - return $this; - } - - /** - * getException() - * - * @return Exception - */ - public function getException() - { - return $this->_exception; - } - - /** - * Add Content Decorator - * - * @param Zend_Tool_Framework_Client_Response_ContentDecorator_Interface $contentDecorator - * @return unknown - */ - public function addContentDecorator(Zend_Tool_Framework_Client_Response_ContentDecorator_Interface $contentDecorator) - { - $decoratorName = strtolower($contentDecorator->getName()); - $this->_decorators[$decoratorName] = $contentDecorator; - return $this; - } - - /** - * getContentDecorators() - * - * @return array - */ - public function getContentDecorators() - { - return $this->_decorators; - } - - /** - * __toString() to cast to a string - * - * @return string - */ - public function __toString() - { - return (string) implode('', $this->_content); - } - - /** - * _applyDecorators() apply a group of decorators - * - * @param string $content - * @param array $decoratorOptions - * @return string - */ - protected function _applyDecorators($content, Array $decoratorOptions) - { - $options = array_merge($this->_defaultDecoratorOptions, $decoratorOptions); - - $options = array_change_key_case($options, CASE_LOWER); - - if ($options) { - foreach ($this->_decorators as $decoratorName => $decorator) { - if (array_key_exists($decoratorName, $options)) { - $content = $decorator->decorate($content, $options[$decoratorName]); - } - } - } - - return $content; - - } - -} diff --git a/library/Zend/Tool/Framework/Client/Response/ContentDecorator/Interface.php b/library/Zend/Tool/Framework/Client/Response/ContentDecorator/Interface.php deleted file mode 100644 index ec29803daf..0000000000 --- a/library/Zend/Tool/Framework/Client/Response/ContentDecorator/Interface.php +++ /dev/null @@ -1,35 +0,0 @@ -_separator = $separator; - return $this; - } - - /** - * getSeparator() - * - * @return string - */ - public function getSeparator() - { - return $this->_separator; - } - - public function decorate($content, $decoratorValue) - { - $run = 1; - if (is_bool($decoratorValue) && $decoratorValue === false) { - return $content; - } - - if (is_int($decoratorValue)) { - $run = $decoratorValue; - } - - for ($i = 0; $i < $run; $i++) { - $content .= $this->_separator; - } - - return $content; - } - -} diff --git a/library/Zend/Tool/Framework/Client/Storage.php b/library/Zend/Tool/Framework/Client/Storage.php deleted file mode 100644 index 63da6a0733..0000000000 --- a/library/Zend/Tool/Framework/Client/Storage.php +++ /dev/null @@ -1,117 +0,0 @@ -setAdapter($options['adapter']); - } - } - - public function setAdapter($adapter) - { - if (is_string($adapter)) { - $storageAdapterClass = 'Zend_Tool_Framework_Client_Storage_' . ucfirst($adapter); - Zend_Loader::loadClass($storageAdapterClass); - $adapter = new $storageAdapterClass(); - } - $this->_adapter = $adapter; - } - - public function isEnabled() - { - return ($this->_adapter instanceof Zend_Tool_Framework_Client_Storage_AdapterInterface); - } - - public function put($name, $value) - { - if (!$this->_adapter) { - return false; - } - - $this->_adapter->put($name, $value); - - return $this; - } - - public function get($name, $defaultValue = false) - { - if (!$this->_adapter) { - return false; - } - - if ($this->_adapter->has($name)) { - return $this->_adapter->get($name); - } else { - return $defaultValue; - } - - } - - public function has($name) - { - if (!$this->_adapter) { - return false; - } - - return $this->_adapter->has($name); - } - - public function remove($name) - { - if (!$this->_adapter) { - return false; - } - - $this->_adapter->remove($name); - - return $this; - } - - public function getStreamUri($name) - { - if (!$this->_adapter) { - return false; - } - - return $this->_adapter->getStreamUri($name); - } -} diff --git a/library/Zend/Tool/Framework/Client/Storage/AdapterInterface.php b/library/Zend/Tool/Framework/Client/Storage/AdapterInterface.php deleted file mode 100644 index e3e717ab91..0000000000 --- a/library/Zend/Tool/Framework/Client/Storage/AdapterInterface.php +++ /dev/null @@ -1,42 +0,0 @@ -_directoryPath = $directoryPath; - } - - public function put($name, $value) - { - return file_put_contents($this->_directoryPath . DIRECTORY_SEPARATOR . $name, $value); - } - - public function get($name) - { - return file_get_contents($this->_directoryPath . DIRECTORY_SEPARATOR . $name); - } - - public function has($name) - { - return file_exists($this->_directoryPath . DIRECTORY_SEPARATOR . $name); - } - - public function remove($name) - { - return unlink($this->_directoryPath . DIRECTORY_SEPARATOR . $name); - } - - public function getStreamUri($name) - { - return $this->_directoryPath . DIRECTORY_SEPARATOR . $name; - } - -} diff --git a/library/Zend/Tool/Framework/Exception.php b/library/Zend/Tool/Framework/Exception.php deleted file mode 100644 index fe2efeae1a..0000000000 --- a/library/Zend/Tool/Framework/Exception.php +++ /dev/null @@ -1,36 +0,0 @@ -_registry = $registry; - return $this; - } - - /** - * load() - called by the client initialize routine to load files - * - */ - public function load() - { - $this->_retrievedFiles = $this->getRetrievedFiles(); - $this->_loadedClasses = array(); - - $manifestRepository = $this->_registry->getManifestRepository(); - $providerRepository = $this->_registry->getProviderRepository(); - - $loadedClasses = array(); - - // loop through files and find the classes declared by loading the file - foreach ($this->_retrievedFiles as $file) { - if(is_dir($file)) { - continue; - } - - $classesLoadedBefore = get_declared_classes(); - $oldLevel = error_reporting(E_ALL | ~E_STRICT); // remove strict so that other packages wont throw warnings - // should we lint the files here? i think so - include_once $file; - error_reporting($oldLevel); // restore old error level - $classesLoadedAfter = get_declared_classes(); - $loadedClasses = array_merge($loadedClasses, array_diff($classesLoadedAfter, $classesLoadedBefore)); - } - - // loop through the loaded classes and ensure that - foreach ($loadedClasses as $loadedClass) { - - // reflect class to see if its something we want to load - $reflectionClass = new ReflectionClass($loadedClass); - if ($reflectionClass->implementsInterface('Zend_Tool_Framework_Manifest_Interface') - && !$reflectionClass->isAbstract()) - { - $manifestRepository->addManifest($reflectionClass->newInstance()); - $this->_loadedClasses[] = $loadedClass; - } - - if ($reflectionClass->implementsInterface('Zend_Tool_Framework_Provider_Interface') - && !$reflectionClass->isAbstract() - && !$providerRepository->hasProvider($reflectionClass->getName(), false)) - { - $providerRepository->addProvider($reflectionClass->newInstance()); - $this->_loadedClasses[] = $loadedClass; - } - - } - - return $this->_loadedClasses; - } - - /** - * getRetrievedFiles() - * - * @return array Array of Files Retrieved - */ - public function getRetrievedFiles() - { - if ($this->_retrievedFiles == null) { - $this->_retrievedFiles = $this->_getFiles(); - } - - return $this->_retrievedFiles; - } - - /** - * getLoadedClasses() - * - * @return array Array of Loaded Classes - */ - public function getLoadedClasses() - { - return $this->_loadedClasses; - } - - -} diff --git a/library/Zend/Tool/Framework/Loader/BasicLoader.php b/library/Zend/Tool/Framework/Loader/BasicLoader.php deleted file mode 100644 index 0fe3143b16..0000000000 --- a/library/Zend/Tool/Framework/Loader/BasicLoader.php +++ /dev/null @@ -1,157 +0,0 @@ -setOptions($options); - } - } - - public function setOptions(Array $options) - { - foreach ($options as $optionName => $optionValue) { - $setMethod = 'set' . $optionName; - if (method_exists($this, $setMethod)) { - $this->{$setMethod}($optionValue); - } - } - } - - /** - * setRegistry() - required by the enabled interface to get an instance of - * the registry - * - * @param Zend_Tool_Framework_Registry_Interface $registry - * @return Zend_Tool_Framework_Loader_Abstract - */ - public function setRegistry(Zend_Tool_Framework_Registry_Interface $registry) - { - $this->_registry = $registry; - return $this; - } - - /** - * @param array $classesToLoad - * @return Zend_Tool_Framework_Loader_Abstract - */ - public function setClassesToLoad(array $classesToLoad) - { - $this->_classesToLoad = $classesToLoad; - return $this; - } - - public function load() - { - $manifestRegistry = $this->_registry->getManifestRepository(); - $providerRegistry = $this->_registry->getProviderRepository(); - - $loadedClasses = array(); - - // loop through the loaded classes and ensure that - foreach ($this->_classesToLoad as $class) { - - if (!class_exists($class)) { - Zend_Loader::loadClass($class); - } - - // reflect class to see if its something we want to load - $reflectionClass = new ReflectionClass($class); - if ($this->_isManifestImplementation($reflectionClass)) { - $manifestRegistry->addManifest($reflectionClass->newInstance()); - $loadedClasses[] = $class; - } - - if ($this->_isProviderImplementation($reflectionClass)) { - $providerRegistry->addProvider($reflectionClass->newInstance()); - $loadedClasses[] = $class; - } - - } - - return $loadedClasses; - } - - /** - * @param ReflectionClass $reflectionClass - * @return bool - */ - private function _isManifestImplementation($reflectionClass) - { - return ( - $reflectionClass->implementsInterface('Zend_Tool_Framework_Manifest_Interface') - && !$reflectionClass->isAbstract() - ); - } - - /** - * @param ReflectionClass $reflectionClass - * @return bool - */ - private function _isProviderImplementation($reflectionClass) - { - $providerRegistry = $this->_registry->getProviderRepository(); - - return ( - $reflectionClass->implementsInterface('Zend_Tool_Framework_Provider_Interface') - && !$reflectionClass->isAbstract() - && !$providerRegistry->hasProvider($reflectionClass->getName(), false) - ); - } - -} diff --git a/library/Zend/Tool/Framework/Loader/IncludePathLoader.php b/library/Zend/Tool/Framework/Loader/IncludePathLoader.php deleted file mode 100644 index 53bdb77220..0000000000 --- a/library/Zend/Tool/Framework/Loader/IncludePathLoader.php +++ /dev/null @@ -1,139 +0,0 @@ -_fileIsBlacklisted($file)) { - continue; - } - - // ensure that the same named file from separate include_paths is not loaded - $relativeItem = preg_replace('#^' . preg_quote($realIncludePath . DIRECTORY_SEPARATOR, '#') . '#', '', $item->getRealPath()); - - // no links allowed here for now - if ($item->isLink()) { - continue; - } - - // no items that are relavitely the same are allowed - if (in_array($relativeItem, $relativeItems)) { - continue; - } - - $relativeItems[] = $relativeItem; - $files[] = $item->getRealPath(); - } - } - - return $files; - } - - /** - * - * @param string $file - * @return bool - */ - protected function _fileIsBlacklisted($file) - { - $blacklist = array( - "PHPUnit".DIRECTORY_SEPARATOR."Framework", - "Zend".DIRECTORY_SEPARATOR."OpenId".DIRECTORY_SEPARATOR."Provider" - ); - - foreach($blacklist AS $blacklitedPattern) { - if(strpos($file, $blacklitedPattern) !== false) { - return true; - } - } - return false; - } -} diff --git a/library/Zend/Tool/Framework/Loader/IncludePathLoader/RecursiveFilterIterator.php b/library/Zend/Tool/Framework/Loader/IncludePathLoader/RecursiveFilterIterator.php deleted file mode 100644 index 50c9c74095..0000000000 --- a/library/Zend/Tool/Framework/Loader/IncludePathLoader/RecursiveFilterIterator.php +++ /dev/null @@ -1,91 +0,0 @@ -_denyDirectoryPattern = $denyDirectoryPattern; - $this->_acceptFilePattern = $acceptFilePattern; - parent::__construct($iterator); - } - - /** - * accept() - Which iterable items to accept or deny, required by FilterInterface - * - * @return unknown - */ - public function accept() - { - $currentNode = $this->current(); - $currentNodeRealPath = $currentNode->getRealPath(); - - // if the current node is a directory AND doesn't match the denyDirectory pattern, accept - if ($currentNode->isDir() - && !preg_match('#' . $this->_denyDirectoryPattern . '#', $currentNodeRealPath)) { - return true; - } - - // if the file matches the accept file pattern, accept - $acceptable = (preg_match('#' . $this->_acceptFilePattern . '#', $currentNodeRealPath)) ? true : false; - return $acceptable; - } - - /** - * getChildren() - overridden from RecursiveFilterIterator to allow the persistence of - * the $_denyDirectoryPattern and the $_acceptFilePattern when sub iterators of this filter - * are needed to be created. - * - * @return Zend_Tool_Framework_Loader_IncludePathLoader_RecursiveFilterIterator - */ - public function getChildren() - { - if (empty($this->ref)) { - $this->ref = new ReflectionClass($this); - } - - return $this->ref->newInstance( - $this->getInnerIterator()->getChildren(), - $this->_denyDirectoryPattern, - $this->_acceptFilePattern - ); - } - -} - diff --git a/library/Zend/Tool/Framework/Loader/Interface.php b/library/Zend/Tool/Framework/Loader/Interface.php deleted file mode 100644 index f734a7cc1d..0000000000 --- a/library/Zend/Tool/Framework/Loader/Interface.php +++ /dev/null @@ -1,42 +0,0 @@ -_registry = $registry; - return $this; - } - - /** - * addManifest() - Add a manifest for later processing - * - * @param Zend_Tool_Framework_Manifest_Interface $manifest - * @return Zend_Tool_Framework_Manifest_Repository - */ - public function addManifest(Zend_Tool_Framework_Manifest_Interface $manifest) - { - // we need to get an index number so that manifests with - // higher indexes have priority over others - $index = count($this->_manifests); - - if ($manifest instanceof Zend_Tool_Framework_Registry_EnabledInterface) { - $manifest->setRegistry($this->_registry); - } - - // if the manifest supplies a getIndex() method, use it - if ($manifest instanceof Zend_Tool_Framework_Manifest_Indexable) { - $index = $manifest->getIndex(); - } - - // get the required objects from the framework registry - $actionRepository = $this->_registry->getActionRepository(); - $providerRepository = $this->_registry->getProviderRepository(); - - // load providers if interface supports that method - if ($manifest instanceof Zend_Tool_Framework_Manifest_ProviderManifestable) { - $providers = $manifest->getProviders(); - if (!is_array($providers)) { - $providers = array($providers); - } - - foreach ($providers as $provider) { - - // if provider is a string, try and load it as an object - if (is_string($provider)) { - $provider = new $provider(); - } - - if (!$provider instanceof Zend_Tool_Framework_Provider_Interface) { - #require_once 'Zend/Tool/Framework/Manifest/Exception.php'; - throw new Zend_Tool_Framework_Manifest_Exception( - 'A provider provided by the ' . get_class($manifest) - . ' does not implement Zend_Tool_Framework_Provider_Interface' - ); - } - if (!$providerRepository->hasProvider($provider, false)) { - $providerRepository->addProvider($provider); - } - } - - } - - // load actions if interface supports that method - if ($manifest instanceof Zend_Tool_Framework_Manifest_ActionManifestable) { - $actions = $manifest->getActions(); - if (!is_array($actions)) { - $actions = array($actions); - } - - foreach ($actions as $action) { - if (is_string($action)) { - $action = new Zend_Tool_Framework_Action_Base($action); - } - $actionRepository->addAction($action); - } - } - - // should we detect collisions here? does it even matter? - $this->_manifests[$index] = $manifest; - ksort($this->_manifests); - - return $this; - } - - /** - * getManifests() - * - * @return Zend_Tool_Framework_Manifest_Interface[] - */ - public function getManifests() - { - return $this->_manifests; - } - - /** - * addMetadata() - add a metadata peice by peice - * - * @param Zend_Tool_Framework_Manifest_Metadata $metadata - * @return Zend_Tool_Framework_Manifest_Repository - */ - public function addMetadata(Zend_Tool_Framework_Metadata_Interface $metadata) - { - $this->_metadatas[] = $metadata; - return $this; - } - - /** - * process() - Process is expected to be called at the end of client construction time. - * By this time, the loader has run and loaded any found manifests into the repository - * for loading - * - * @return Zend_Tool_Framework_Manifest_Repository - */ - public function process() - { - - foreach ($this->_manifests as $manifest) { - if ($manifest instanceof Zend_Tool_Framework_Manifest_MetadataManifestable) { - $metadatas = $manifest->getMetadata(); - if (!is_array($metadatas)) { - $metadatas = array($metadatas); - } - - foreach ($metadatas as $metadata) { - if (is_array($metadata)) { - if (!class_exists('Zend_Tool_Framework_Metadata_Dynamic')) { - #require_once 'Zend/Tool/Framework/Metadata/Dynamic.php'; - } - $metadata = new Zend_Tool_Framework_Metadata_Dynamic($metadata); - } - - if (!$metadata instanceof Zend_Tool_Framework_Metadata_Interface) { - #require_once 'Zend/Tool/Framework/Manifest/Exception.php'; - throw new Zend_Tool_Framework_Manifest_Exception( - 'A Zend_Tool_Framework_Metadata_Interface object was not found in manifest ' . get_class($manifest) - ); - } - - $this->addMetadata($metadata); - } - - } - } - - return $this; - } - - /** - * getMetadatas() - This is the main search function for the repository. - * - * example: This will retrieve all metadata that matches the following criteria - * $manifestRepo->getMetadatas(array( - * 'providerName' => 'Version', - * 'actionName' => 'show' - * )); - * - * @param array $searchProperties - * @param bool $includeNonExistentProperties - * @return Zend_Tool_Framework_Manifest_Metadata[] - */ - public function getMetadatas(Array $searchProperties = array(), $includeNonExistentProperties = true) - { - - $returnMetadatas = array(); - - // loop through the metadatas so that we can search each individual one - foreach ($this->_metadatas as $metadata) { - - // each value will be retrieved from the metadata, each metadata should - // implement a getter method to retrieve the value - foreach ($searchProperties as $searchPropertyName => $searchPropertyValue) { - if (method_exists($metadata, 'get' . $searchPropertyName)) { - if ($metadata->{'get' . $searchPropertyName}() != $searchPropertyValue) { - // if the metadata supports a specific property but the value does not - // match, move on - continue 2; - } - } elseif (!$includeNonExistentProperties) { - // if the option $includeNonExitentProperties is false, then move on as - // we dont want to include this metadata if non existent - // search properties are not inside the target (current) metadata - continue 2; - } - } - - // all searching has been accounted for, if we reach this point, then the metadata - // is good and we can return it - $returnMetadatas[] = $metadata; - - } - - return $returnMetadatas; - } - - /** - * getMetadata() - This will proxy to getMetadatas(), but will only return a single metadata. This method - * should be used in situations where the search criteria is known to only find a single metadata object - * - * @param array $searchProperties - * @param bool $includeNonExistentProperties - * @return Zend_Tool_Framework_Manifest_Metadata - */ - public function getMetadata(Array $searchProperties = array(), $includeNonExistentProperties = true) - { - $metadatas = $this->getMetadatas($searchProperties, $includeNonExistentProperties); - return array_shift($metadatas); - } - - /** - * __toString() - cast to string - * - * @return string - */ - public function __toString() - { - $metadatasByType = array(); - - foreach ($this->_metadatas as $metadata) { - if (!array_key_exists($metadata->getType(), $metadatasByType)) { - $metadatasByType[$metadata->getType()] = array(); - } - $metadatasByType[$metadata->getType()][] = $metadata; - } - - $string = ''; - foreach ($metadatasByType as $type => $metadatas) { - $string .= $type . PHP_EOL; - foreach ($metadatas as $metadata) { - $metadataString = ' ' . $metadata->__toString() . PHP_EOL; - //$metadataString = str_replace(PHP_EOL, PHP_EOL . ' ', $metadataString); - $string .= $metadataString; - } - } - - return $string; - } - - /** - * count() - required by the Countable Interface - * - * @return int - */ - public function count() - { - return count($this->_metadatas); - } - - /** - * getIterator() - required by the IteratorAggregate interface - * - * @return ArrayIterator - */ - public function getIterator() - { - return new ArrayIterator($this->_metadatas); - } - -} diff --git a/library/Zend/Tool/Framework/Metadata/Attributable.php b/library/Zend/Tool/Framework/Metadata/Attributable.php deleted file mode 100644 index 869f5d5e29..0000000000 --- a/library/Zend/Tool/Framework/Metadata/Attributable.php +++ /dev/null @@ -1,33 +0,0 @@ -setOptions($options); - } - } - - /** - * setOptions() - standard issue implementation, this will set any - * options that are supported via a set method. - * - * @param array $options - * @return Zend_Tool_Framework_Metadata_Basic - */ - public function setOptions(Array $options) - { - foreach ($options as $optionName => $optionValue) { - $setMethod = 'set' . $optionName; - if (method_exists($this, $setMethod)) { - $this->{$setMethod}($optionValue); - } - } - - return $this; - } - - /** - * getType() - * - * @return string - */ - public function getType() - { - return $this->_type; - } - - /** - * setType() - * - * @param string $type - * @return Zend_Tool_Framework_Metadata_Basic - */ - public function setType($type) - { - $this->_type = $type; - return $this; - } - - /** - * getName() - * - * @return string - */ - public function getName() - { - return $this->_name; - } - - /** - * setName() - * - * @param string $name - * @return Zend_Tool_Framework_Metadata_Basic - */ - public function setName($name) - { - $this->_name = $name; - return $this; - } - - /** - * getValue() - * - * @return mixed - */ - public function getValue() - { - return $this->_value; - } - - /** - * setValue() - * - * @param unknown_type $Value - * @return Zend_Tool_Framework_Metadata_Basic - */ - public function setValue($value) - { - $this->_value = $value; - return $this; - } - - /** - * setReference() - * - * @param mixed $reference - * @return Zend_Tool_Framework_Metadata_Basic - */ - public function setReference($reference) - { - $this->_reference = $reference; - return $this; - } - - /** - * getReference() - * - * @return mixed - */ - public function getReference() - { - return $this->_reference; - } - - /** - * getAttributes() - this will retrieve any attributes of this object that exist as properties - * This is most useful for printing metadata. - * - * @param const $type - * @return array - */ - public function getAttributes($type = self::ATTRIBUTES_ALL, $stringRepresentationOfNonScalars = false) - { - $thisReflection = new ReflectionObject($this); - - $metadataPairValues = array(); - - foreach (get_object_vars($this) as $varName => $varValue) { - if ($type == self::ATTRIBUTES_NO_PARENT && ($thisReflection->getProperty($varName)->getDeclaringClass()->getName() == 'Zend_Tool_Framework_Metadata_Basic')) { - continue; - } - - if ($stringRepresentationOfNonScalars) { - - if (is_object($varValue)) { - $varValue = '(object)'; - } - - if ($varValue === null) { - $varValue = '(null)'; - } - - } - - $metadataPairValues[ltrim($varName, '_')] = $varValue; - } - - return $metadataPairValues; - } - - /** - * __toString() - string representation of this object - * - * @return string - */ - public function __toString() - { - return 'Type: ' . $this->_type . ', Name: ' . $this->_name . ', Value: ' . (is_array($this->_value) ? http_build_query($this->_value) : (string) $this->_value); - } -} diff --git a/library/Zend/Tool/Framework/Metadata/Dynamic.php b/library/Zend/Tool/Framework/Metadata/Dynamic.php deleted file mode 100644 index 9c8791b6fa..0000000000 --- a/library/Zend/Tool/Framework/Metadata/Dynamic.php +++ /dev/null @@ -1,219 +0,0 @@ -setOptions($options); - } - } - - public function setOptions(Array $options = array()) - { - foreach ($options as $optName => $optValue) { - $methodName = 'set' . $optName; - $this->{$methodName}($optValue); - } - } - - /** - * setType() - * - * @param string $type - * @return Zend_Tool_Framework_Metadata_Dynamic - */ - public function setType($type) - { - $this->_type = $type; - return $this; - } - - /** - * getType() - * - * The type of metadata this describes - * - * @return string - */ - public function getType() - { - return $this->_type; - } - - /** - * setName() - * - * @param string $name - * @return Zend_Tool_Framework_Metadata_Dynamic - */ - public function setName($name) - { - $this->_name = $name; - return $this; - } - - /** - * getName() - * - * Metadata name - * - * @return string - */ - public function getName() - { - return $this->_name; - } - - /** - * setValue() - * - * @param mixed $value - * @return Zend_Tool_Framework_Metadata_Dynamic - */ - public function setValue($value) - { - $this->_value = $value; - return $this; - } - - /** - * getValue() - * - * Metadata Value - * - * @return string - */ - public function getValue() - { - return $this->_value; - } - - public function getAttributes() - { - return $this->_dynamicAttributes; - } - - /** - * __isset() - * - * Check if an attrbute is set - * - * @param string $name - * @return bool - */ - public function __isset($name) - { - return isset($this->_dynamicAttributes[$name]); - } - - /** - * __unset() - * - * @param string $name - * @return null - */ - public function __unset($name) - { - unset($this->_dynamicAttributes[$name]); - return; - } - - /** - * __get() - Get a property via property call $metadata->foo - * - * @param string $name - * @return mixed - */ - public function __get($name) - { - if (method_exists($this, 'get' . $name)) { - return $this->{'get' . $name}(); - } elseif (array_key_exists($name, $this->_dynamicAttributes)) { - return $this->_dynamicAttributes[$name]; - } else { - #require_once 'Zend/Tool/Framework/Registry/Exception.php'; - throw new Zend_Tool_Framework_Registry_Exception('Property ' . $name . ' was not located in this metadata.'); - } - } - - /** - * __set() - Set a property via the magic set $metadata->foo = 'foo' - * - * @param string $name - * @param mixed $value - */ - public function __set($name, $value) - { - if (method_exists($this, 'set' . $name)) { - $this->{'set' . $name}($value); - return $this; - } else { - $this->_dynamicAttributes[$name] = $value; - return $this; - } -// { -// #require_once 'Zend/Tool/Framework/Registry/Exception.php'; -// throw new Zend_Tool_Framework_Registry_Exception('Property ' . $name . ' was not located in this registry.'); -// } - } - -} diff --git a/library/Zend/Tool/Framework/Metadata/Interface.php b/library/Zend/Tool/Framework/Metadata/Interface.php deleted file mode 100644 index d7e327bf34..0000000000 --- a/library/Zend/Tool/Framework/Metadata/Interface.php +++ /dev/null @@ -1,52 +0,0 @@ -_clientName = $clientName; - return $this; - } - - public function getClientName() - { - return $this->_clientName; - } - - /** - * setActionName() - * - * @param string $actionName - * @return Zend_Tool_Framework_Metadata_Tool - */ - public function setActionName($actionName) - { - $this->_actionName = $actionName; - return $this; - } - - /** - * getActionName() - * - * @return string - */ - public function getActionName() - { - return $this->_actionName; - } - - /** - * setProviderName() - * - * @param string $providerName - * @return Zend_Tool_Framework_Metadata_Tool - */ - public function setProviderName($providerName) - { - $this->_providerName = $providerName; - return $this; - } - - /** - * getProviderName() - * - * @return string - */ - public function getProviderName() - { - return $this->_providerName; - } - - /** - * setSpecialtyName() - * - * @param string $specialtyName - * @return Zend_Tool_Framework_Metadata_Tool - */ - public function setSpecialtyName($specialtyName) - { - $this->_specialtyName = $specialtyName; - return $this; - } - - /** - * getSpecialtyName() - * - * @return string - */ - public function getSpecialtyName() - { - return $this->_specialtyName; - } - - /** - * setClientReference() - * - * @param Zend_Tool_Framework_Client_Abstract $client - * @return Zend_Tool_Framework_Metadata_Tool - */ - public function setClientReference(Zend_Tool_Framework_Client_Abstract $client) - { - $this->_clientReference = $client; - return $this; - } - - /** - * getClientReference() - * - * @return Zend_Tool_Framework_Client_Abstract - */ - public function getClientReference() - { - return $this->_clientReference; - } - - /** - * setActionReference() - * - * @param Zend_Tool_Framework_Action_Interface $action - * @return Zend_Tool_Framework_Metadata_Tool - */ - public function setActionReference(Zend_Tool_Framework_Action_Interface $action) - { - $this->_actionReference = $action; - return $this; - } - - /** - * getActionReference() - * - * @return Zend_Tool_Framework_Action_Interface - */ - public function getActionReference() - { - return $this->_actionReference; - } - - /** - * setProviderReference() - * - * @param Zend_Tool_Framework_Provider_Interface $provider - * @return Zend_Tool_Framework_Metadata_Tool - */ - public function setProviderReference(Zend_Tool_Framework_Provider_Interface $provider) - { - $this->_providerReference = $provider; - return $this; - } - - /** - * getProviderReference() - * - * @return Zend_Tool_Framework_Provider_Interface - */ - public function getProviderReference() - { - return $this->_providerReference; - } - - /** - * __toString() cast to string - * - * @return string - */ - public function __toString() - { - $string = parent::__toString(); - $string .= ' (ProviderName: ' . $this->_providerName - . ', ActionName: ' . $this->_actionName - . ', SpecialtyName: ' . $this->_specialtyName - . ')'; - - return $string; - } - -} diff --git a/library/Zend/Tool/Framework/Provider/Abstract.php b/library/Zend/Tool/Framework/Provider/Abstract.php deleted file mode 100644 index 0fc0709c55..0000000000 --- a/library/Zend/Tool/Framework/Provider/Abstract.php +++ /dev/null @@ -1,68 +0,0 @@ -_registry = $registry; - return $this; - } - - -} diff --git a/library/Zend/Tool/Framework/Provider/DocblockManifestable.php b/library/Zend/Tool/Framework/Provider/DocblockManifestable.php deleted file mode 100644 index 19bd7d6d79..0000000000 --- a/library/Zend/Tool/Framework/Provider/DocblockManifestable.php +++ /dev/null @@ -1,30 +0,0 @@ -_registry = $registry; - return $this; - } - - /** - * Set the ProcessOnAdd flag - * - * @param unknown_type $processOnAdd - * @return unknown - */ - public function setProcessOnAdd($processOnAdd = true) - { - $this->_processOnAdd = (bool) $processOnAdd; - return $this; - } - - /** - * Add a provider to the repository for processing - * - * @param Zend_Tool_Framework_Provider_Interface $provider - * @return Zend_Tool_Framework_Provider_Repository - */ - public function addProvider(Zend_Tool_Framework_Provider_Interface $provider, $overwriteExistingProvider = false) - { - if ($provider instanceof Zend_Tool_Framework_Registry_EnabledInterface) { - $provider->setRegistry($this->_registry); - } - - if (method_exists($provider, 'getName')) { - $providerName = $provider->getName(); - } else { - $providerName = $this->_parseName($provider); - } - - // if a provider by the given name already exist, and its not set as overwritable, throw exception - if (!$overwriteExistingProvider && - (array_key_exists($providerName, $this->_unprocessedProviders) - || array_key_exists($providerName, $this->_providers))) - { - #require_once 'Zend/Tool/Framework/Provider/Exception.php'; - throw new Zend_Tool_Framework_Provider_Exception('A provider by the name ' . $providerName - . ' is already registered and $overrideExistingProvider is set to false.'); - } - - $this->_unprocessedProviders[$providerName] = $provider; - - // if process has already been called, process immediately. - if ($this->_processOnAdd) { - $this->process(); - } - - return $this; - } - - public function hasProvider($providerOrClassName, $processedOnly = true) - { - if ($providerOrClassName instanceof Zend_Tool_Framework_Provider_Interface) { - $targetProviderClassName = get_class($providerOrClassName); - } else { - $targetProviderClassName = (string) $providerOrClassName; - } - - if (!$processedOnly) { - foreach ($this->_unprocessedProviders as $unprocessedProvider) { - if (get_class($unprocessedProvider) == $targetProviderClassName) { - return true; - } - } - } - - foreach ($this->_providers as $processedProvider) { - if (get_class($processedProvider) == $targetProviderClassName) { - return true; - } - } - - return false; - } - - /** - * Process all of the unprocessed providers - * - */ - public function process() - { - - // process all providers in the unprocessedProviders array - //foreach ($this->_unprocessedProviders as $providerName => $provider) { - reset($this->_unprocessedProviders); - while ($this->_unprocessedProviders) { - - $providerName = key($this->_unprocessedProviders); - $provider = array_shift($this->_unprocessedProviders); - - // create a signature for the provided provider - $providerSignature = new Zend_Tool_Framework_Provider_Signature($provider); - - if ($providerSignature instanceof Zend_Tool_Framework_Registry_EnabledInterface) { - $providerSignature->setRegistry($this->_registry); - } - - $providerSignature->process(); - - // ensure the name is lowercased for easier searching - $providerName = strtolower($providerName); - - // add to the appropraite place - $this->_providerSignatures[$providerName] = $providerSignature; - $this->_providers[$providerName] = $providerSignature->getProvider(); - - if ($provider instanceof Zend_Tool_Framework_Provider_Initializable) { - $provider->initialize(); - } - - } - - } - - /** - * getProviders() Get all the providers in the repository - * - * @return array - */ - public function getProviders() - { - return $this->_providers; - } - - /** - * getProviderSignatures() Get all the provider signatures - * - * @return array - */ - public function getProviderSignatures() - { - return $this->_providerSignatures; - } - - /** - * getProvider() - * - * @param string $providerName - * @return Zend_Tool_Framework_Provider_Interface - */ - public function getProvider($providerName) - { - return $this->_providers[strtolower($providerName)]; - } - - /** - * getProviderSignature() - * - * @param string $providerName - * @return Zend_Tool_Framework_Provider_Signature - */ - public function getProviderSignature($providerName) - { - return $this->_providerSignatures[strtolower($providerName)]; - } - - /** - * count() - return the number of providers - * - * @return int - */ - public function count() - { - return count($this->_providers); - } - - /** - * getIterator() - Required by the IteratorAggregate Interface - * - * @return ArrayIterator - */ - public function getIterator() - { - return new ArrayIterator($this->getProviders()); - } - - /** - * _parseName - internal method to determine the name of an action when one is not explicity provided. - * - * @param Zend_Tool_Framework_Action_Interface $action - * @return string - */ - protected function _parseName(Zend_Tool_Framework_Provider_Interface $provider) - { - $className = get_class($provider); - $providerName = $className; - if (strpos($providerName, '_') !== false) { - $providerName = substr($providerName, strrpos($providerName, '_')+1); - } - if (substr($providerName, -8) == 'Provider') { - $providerName = substr($providerName, 0, strlen($providerName)-8); - } - return $providerName; - } - -} diff --git a/library/Zend/Tool/Framework/Provider/Signature.php b/library/Zend/Tool/Framework/Provider/Signature.php deleted file mode 100644 index 6cb3ff3143..0000000000 --- a/library/Zend/Tool/Framework/Provider/Signature.php +++ /dev/null @@ -1,394 +0,0 @@ -_provider = $provider; - $this->_providerReflection = new Zend_Reflection_Class($provider); - } - - /** - * setRegistry() - * - * @param Zend_Tool_Framework_Registry_Interface $registry - * @return Zend_Tool_Framework_Provider_Signature - */ - public function setRegistry(Zend_Tool_Framework_Registry_Interface $registry) - { - $this->_registry = $registry; - return $this; - } - - public function process() - { - if ($this->_isProcessed) { - return; - } - - $this->_process(); - } - - /** - * getName() of the provider - * - * @return unknown - */ - public function getName() - { - return $this->_name; - } - - /** - * Get the provider for this signature - * - * @return Zend_Tool_Framework_Provider_Interface - */ - public function getProvider() - { - return $this->_provider; - } - - /** - * getProviderReflection() - * - * @return Zend_Reflection_Class - */ - public function getProviderReflection() - { - return $this->_providerReflection; - } - - /** - * getSpecialities() - * - * @return array - */ - public function getSpecialties() - { - return $this->_specialties; - } - - /** - * getActions() - * - * @return array Array of Actions - */ - public function getActions() - { - return $this->_actions; - } - - /** - * getActionableMethods() - * - * @return array - */ - public function getActionableMethods() - { - return $this->_actionableMethods; - } - - /** - * getActionableMethod() - Get an actionable method by name, this will return an array of - * useful information about what can be exectued on this provider - * - * @param string $methodName - * @return array - */ - public function getActionableMethod($methodName) - { - if (isset($this->_actionableMethods[$methodName])) { - return $this->_actionableMethods[$methodName]; - } - - return false; - } - - /** - * getActionableMethodByActionName() - Get an actionable method by its action name, this - * will return an array of useful information about what can be exectued on this provider - * - * @param string $actionName - * @return array - */ - public function getActionableMethodByActionName($actionName, $specialtyName = '_Global') - { - foreach ($this->_actionableMethods as $actionableMethod) { - if ($actionName == $actionableMethod['actionName'] - && $specialtyName == $actionableMethod['specialty']) { - return $actionableMethod; - } - } - - return false; - } - - /** - * _process() is called at construction time and is what will build the signature information - * for determining what is actionable - * - */ - protected function _process() - { - $this->_isProcessed = true; - $this->_processName(); - $this->_processSpecialties(); - $this->_processActionableMethods(); - } - - /** - * _processName(); - * - */ - protected function _processName() - { - if (method_exists($this->_provider, 'getName')) { - $this->_name = $this->_provider->getName(); - } - - if ($this->_name == null) { - $className = get_class($this->_provider); - $name = $className; - if (strpos($name, '_')) { - $name = substr($name, strrpos($name, '_')+1); - } - $name = preg_replace('#(Provider|Manifest)$#', '', $name); - $this->_name = $name; - } - } - - /** - * _processSpecialties() - Break out the specialty names for this provider - * - */ - protected function _processSpecialties() - { - $specialties = array(); - - if ($this->_providerReflection->hasMethod('getSpecialties')) { - $specialties = $this->_provider->getSpecialties(); - if (!is_array($specialties)) { - #require_once 'Zend/Tool/Framework/Provider/Exception.php'; - throw new Zend_Tool_Framework_Provider_Exception( - 'Provider ' . get_class($this->_provider) . ' must return an array for method getSpecialties().' - ); - } - } else { - $defaultProperties = $this->_providerReflection->getDefaultProperties(); - $specialties = (isset($defaultProperties['_specialties'])) ? $defaultProperties['_specialties'] : array(); - if (!is_array($specialties)) { - #require_once 'Zend/Tool/Framework/Provider/Exception.php'; - throw new Zend_Tool_Framework_Provider_Exception( - 'Provider ' . get_class($this->_provider) . '\'s property $_specialties must be an array.' - ); - } - } - - $this->_specialties = array_merge(array('_Global'), $specialties); - - } - - /** - * _processActionableMethods() - process all methods that can be called on this provider. - * - */ - protected function _processActionableMethods() - { - - $specialtyRegex = '#(.*)(' . implode('|', $this->_specialties) . ')$#i'; - - - $methods = $this->_providerReflection->getMethods(); - - $actionableMethods = array(); - foreach ($methods as $method) { - - $methodName = $method->getName(); - - /** - * the following will determine what methods are actually actionable - * public, non-static, non-underscore prefixed, classes that dont - * contain the name " - */ - if (!$method->getDeclaringClass()->isInstantiable() - || !$method->isPublic() - || $methodName[0] == '_' - || $method->isStatic() - || in_array($methodName, array('getContextClasses', 'getName')) // other protected public methods will nee to go here - ) { - continue; - } - - /** - * check to see if the method was a required method by a Zend_Tool_* interface - */ - foreach ($method->getDeclaringClass()->getInterfaces() as $methodDeclaringClassInterface) { - if (strpos($methodDeclaringClassInterface->getName(), 'Zend_Tool_') === 0 - && $methodDeclaringClassInterface->hasMethod($methodName)) { - continue 2; - } - } - - $actionableName = ucfirst($methodName); - - if (substr($actionableName, -6) == 'Action') { - $actionableName = substr($actionableName, 0, -6); - } - - $actionableMethods[$methodName]['methodName'] = $methodName; - - $matches = null; - if (preg_match($specialtyRegex, $actionableName, $matches)) { - $actionableMethods[$methodName]['actionName'] = $matches[1]; - $actionableMethods[$methodName]['specialty'] = $matches[2]; - } else { - $actionableMethods[$methodName]['actionName'] = $actionableName; - $actionableMethods[$methodName]['specialty'] = '_Global'; - } - - // get the action, and create non-existent actions when they dont exist (the true part below) - $action = $this->_registry->getActionRepository()->getAction($actionableMethods[$methodName]['actionName']); - if ($action == null) { - $action = new Zend_Tool_Framework_Action_Base($actionableMethods[$methodName]['actionName']); - $this->_registry->getActionRepository()->addAction($action); - } - $actionableMethods[$methodName]['action'] = $action; - - if (!in_array($actionableMethods[$methodName]['action'], $this->_actions)) { - $this->_actions[] = $actionableMethods[$methodName]['action']; - } - - $parameterInfo = array(); - $position = 1; - foreach ($method->getParameters() as $parameter) { - $currentParam = $parameter->getName(); - $parameterInfo[$currentParam]['position'] = $position++; - $parameterInfo[$currentParam]['optional'] = $parameter->isOptional(); - $parameterInfo[$currentParam]['default'] = ($parameter->isOptional()) ? $parameter->getDefaultValue() : null; - $parameterInfo[$currentParam]['name'] = $currentParam; - $parameterInfo[$currentParam]['type'] = 'string'; - $parameterInfo[$currentParam]['description'] = null; - } - - $matches = null; - if (($docComment = $method->getDocComment()) != '' && - (preg_match_all('/@param\s+(\w+)+\s+(\$\S+)\s+(.*?)(?=(?:\*\s*@)|(?:\*\/))/s', $docComment, $matches))) - { - for ($i=0; $i <= count($matches[0])-1; $i++) { - $currentParam = ltrim($matches[2][$i], '$'); - - if ($currentParam != '' && isset($parameterInfo[$currentParam])) { - - $parameterInfo[$currentParam]['type'] = $matches[1][$i]; - - $descriptionSource = $matches[3][$i]; - - if ($descriptionSource != '') { - $parameterInfo[$currentParam]['description'] = trim($descriptionSource); - } - - } - - } - - } - - $actionableMethods[$methodName]['parameterInfo'] = $parameterInfo; - - } - - $this->_actionableMethods = $actionableMethods; - } - -} diff --git a/library/Zend/Tool/Framework/Registry.php b/library/Zend/Tool/Framework/Registry.php deleted file mode 100644 index 12bba90bba..0000000000 --- a/library/Zend/Tool/Framework/Registry.php +++ /dev/null @@ -1,419 +0,0 @@ -_client); - unset($this->_loader); - unset($this->_actionRepository); - unset($this->_providerRepository); - unset($this->_request); - unset($this->_response); - } - -// public function __construct() -// { -// // no instantiation from outside -// } - - /** - * Enter description here... - * - * @param Zend_Tool_Framework_Client_Abstract $client - * @return Zend_Tool_Framework_Registry - */ - public function setClient(Zend_Tool_Framework_Client_Abstract $client) - { - $this->_client = $client; - if ($this->isObjectRegistryEnablable($this->_client)) { - $this->enableRegistryOnObject($this->_client); - } - return $this; - } - - /** - * getClient() return the client in the registry - * - * @return Zend_Tool_Framework_Client_Abstract - */ - public function getClient() - { - return $this->_client; - } - - /** - * setConfig() - * - * @param Zend_Tool_Framework_Client_Config $config - * @return Zend_Tool_Framework_Registry - */ - public function setConfig(Zend_Tool_Framework_Client_Config $config) - { - $this->_config = $config; - return $this; - } - - /** - * getConfig() - * - * @return Zend_Tool_Framework_Client_Config - */ - public function getConfig() - { - if ($this->_config === null) { - #require_once 'Zend/Tool/Framework/Client/Config.php'; - $this->setConfig(new Zend_Tool_Framework_Client_Config()); - } - - return $this->_config; - } - - /** - * setStorage() - * - * @param Zend_Tool_Framework_Client_Storage $storage - * @return Zend_Tool_Framework_Registry - */ - public function setStorage(Zend_Tool_Framework_Client_Storage $storage) - { - $this->_storage = $storage; - return $this; - } - - /** - * getConfig() - * - * @return Zend_Tool_Framework_Client_Storage - */ - public function getStorage() - { - if ($this->_storage === null) { - #require_once 'Zend/Tool/Framework/Client/Storage.php'; - $this->setStorage(new Zend_Tool_Framework_Client_Storage()); - } - - return $this->_storage; - } - - /** - * setLoader() - * - * @param Zend_Tool_Framework_Loader_Interface $loader - * @return Zend_Tool_Framework_Registry - */ - public function setLoader(Zend_Tool_Framework_Loader_Interface $loader) - { - $this->_loader = $loader; - if ($this->isObjectRegistryEnablable($this->_loader)) { - $this->enableRegistryOnObject($this->_loader); - } - return $this; - } - - /** - * getLoader() - * - * @return Zend_Tool_Framework_Loader_Abstract - */ - public function getLoader() - { - if ($this->_loader === null) { - #require_once 'Zend/Tool/Framework/Loader/IncludePathLoader.php'; - $this->setLoader(new Zend_Tool_Framework_Loader_IncludePathLoader()); - } - - return $this->_loader; - } - - /** - * setActionRepository() - * - * @param Zend_Tool_Framework_Action_Repository $actionRepository - * @return Zend_Tool_Framework_Registry - */ - public function setActionRepository(Zend_Tool_Framework_Action_Repository $actionRepository) - { - $this->_actionRepository = $actionRepository; - if ($this->isObjectRegistryEnablable($this->_actionRepository)) { - $this->enableRegistryOnObject($this->_actionRepository); - } - return $this; - } - - /** - * getActionRepository() - * - * @return Zend_Tool_Framework_Action_Repository - */ - public function getActionRepository() - { - if ($this->_actionRepository == null) { - #require_once 'Zend/Tool/Framework/Action/Repository.php'; - $this->setActionRepository(new Zend_Tool_Framework_Action_Repository()); - } - - return $this->_actionRepository; - } - - /** - * setProviderRepository() - * - * @param Zend_Tool_Framework_Provider_Repository $providerRepository - * @return Zend_Tool_Framework_Registry - */ - public function setProviderRepository(Zend_Tool_Framework_Provider_Repository $providerRepository) - { - $this->_providerRepository = $providerRepository; - if ($this->isObjectRegistryEnablable($this->_providerRepository)) { - $this->enableRegistryOnObject($this->_providerRepository); - } - return $this; - } - - /** - * getProviderRepository() - * - * @return Zend_Tool_Framework_Provider_Repository - */ - public function getProviderRepository() - { - if ($this->_providerRepository == null) { - #require_once 'Zend/Tool/Framework/Provider/Repository.php'; - $this->setProviderRepository(new Zend_Tool_Framework_Provider_Repository()); - } - - return $this->_providerRepository; - } - - /** - * setManifestRepository() - * - * @param Zend_Tool_Framework_Manifest_Repository $manifestRepository - * @return Zend_Tool_Framework_Registry - */ - public function setManifestRepository(Zend_Tool_Framework_Manifest_Repository $manifestRepository) - { - $this->_manifestRepository = $manifestRepository; - if ($this->isObjectRegistryEnablable($this->_manifestRepository)) { - $this->enableRegistryOnObject($this->_manifestRepository); - } - return $this; - } - - /** - * getManifestRepository() - * - * @return Zend_Tool_Framework_Manifest_Repository - */ - public function getManifestRepository() - { - if ($this->_manifestRepository == null) { - #require_once 'Zend/Tool/Framework/Manifest/Repository.php'; - $this->setManifestRepository(new Zend_Tool_Framework_Manifest_Repository()); - } - - return $this->_manifestRepository; - } - - /** - * setRequest() - * - * @param Zend_Tool_Framework_Client_Request $request - * @return Zend_Tool_Framework_Registry - */ - public function setRequest(Zend_Tool_Framework_Client_Request $request) - { - $this->_request = $request; - return $this; - } - - /** - * getRequest() - * - * @return Zend_Tool_Framework_Client_Request - */ - public function getRequest() - { - if ($this->_request == null) { - #require_once 'Zend/Tool/Framework/Client/Request.php'; - $this->setRequest(new Zend_Tool_Framework_Client_Request()); - } - - return $this->_request; - } - - /** - * setResponse() - * - * @param Zend_Tool_Framework_Client_Response $response - * @return Zend_Tool_Framework_Registry - */ - public function setResponse(Zend_Tool_Framework_Client_Response $response) - { - $this->_response = $response; - return $this; - } - - /** - * getResponse() - * - * @return Zend_Tool_Framework_Client_Response - */ - public function getResponse() - { - if ($this->_response == null) { - #require_once 'Zend/Tool/Framework/Client/Response.php'; - $this->setResponse(new Zend_Tool_Framework_Client_Response()); - } - - return $this->_response; - } - - /** - * __get() - Get a property via property call $registry->foo - * - * @param string $name - * @return mixed - */ - public function __get($name) - { - if (method_exists($this, 'get' . $name)) { - return $this->{'get' . $name}(); - } else { - #require_once 'Zend/Tool/Framework/Registry/Exception.php'; - throw new Zend_Tool_Framework_Registry_Exception('Property ' . $name . ' was not located in this registry.'); - } - } - - /** - * __set() - Set a property via the magic set $registry->foo = 'foo' - * - * @param string $name - * @param mixed $value - */ - public function __set($name, $value) - { - if (method_exists($this, 'set' . $name)) { - $this->{'set' . $name}($value); - return; - } else { - #require_once 'Zend/Tool/Framework/Registry/Exception.php'; - throw new Zend_Tool_Framework_Registry_Exception('Property ' . $name . ' was not located in this registry.'); - } - } - - /** - * isObjectRegistryEnablable() - Check whether an object is registry enablable - * - * @param object $object - * @return bool - */ - public function isObjectRegistryEnablable($object) - { - if (!is_object($object)) { - #require_once 'Zend/Tool/Framework/Registry/Exception.php'; - throw new Zend_Tool_Framework_Registry_Exception('isObjectRegistryEnablable() expects an object.'); - } - - return ($object instanceof Zend_Tool_Framework_Registry_EnabledInterface); - } - - /** - * enableRegistryOnObject() - make an object registry enabled - * - * @param object $object - * @return Zend_Tool_Framework_Registry - */ - public function enableRegistryOnObject($object) - { - if (!$this->isObjectRegistryEnablable($object)) { - #require_once 'Zend/Tool/Framework/Registry/Exception.php'; - throw new Zend_Tool_Framework_Registry_Exception('Object provided is not registry enablable, check first with Zend_Tool_Framework_Registry::isObjectRegistryEnablable()'); - } - - $object->setRegistry($this); - return $this; - } - -} diff --git a/library/Zend/Tool/Framework/Registry/EnabledInterface.php b/library/Zend/Tool/Framework/Registry/EnabledInterface.php deleted file mode 100644 index 5a97c8bd32..0000000000 --- a/library/Zend/Tool/Framework/Registry/EnabledInterface.php +++ /dev/null @@ -1,40 +0,0 @@ -_registry->getConfig(); - - $resp = $this->_registry->getResponse(); - if ($userConfig->exists()) { - #require_once "Zend/Tool/Framework/Exception.php"; - throw new Zend_Tool_Framework_Exception( - "A configuration already exists, cannot create a new one."); - } - - $homeDirectory = $this->_detectHomeDirectory(); - - $writer = new Zend_Config_Writer_Ini(); - $writer->setRenderWithoutSections(); - $filename = $homeDirectory."/.zf.ini"; - - $config = array( - 'php' => array( - 'include_path' => get_include_path(), - ), - ); - $writer->write($filename, new Zend_Config($config)); - - $resp = $this->_registry->getResponse(); - $resp->appendContent("Successfully written Zend Tool config."); - $resp->appendContent("It is located at: ".$filename); - } - - /** - * @return string - */ - protected function _detectHomeDirectory() - { - $envVars = array("ZF_HOME", "HOME", "HOMEPATH"); - foreach($envVars AS $env) { - $homeDirectory = getenv($env); - if ($homeDirectory != false && file_exists($homeDirectory)) { - return $homeDirectory; - } - } - #require_once "Zend/Tool/Framework/Exception.php"; - throw new Zend_Tool_Framework_Exception("Cannot detect user home directory, set ZF_HOME enviroment variable."); - } - - /** - * Show Zend Tool User Configuration - * - * @return void - */ - public function show() - { - $userConfig = $this->_loadUserConfigIfExists(); - $configArray = $userConfig->getConfigInstance()->toArray(); - - $resp = $this->_registry->getResponse(); - - $i = 0; - $tree = ""; - foreach($configArray AS $k => $v) { - $i++; - $tree .= $this->_printTree($k, $v, 1, count($configArray)==$i); - } - $resp->appendContent("User Configuration: ".$userConfig->getConfigFilepath(), array("color" => "green")); - $resp->appendContent($tree, array("indention" => 2)); - } - - /** - * - * @param string $key - * @param string $value - * @param int $level - * @return string - */ - protected function _printTree($key, $value, $level=1, $isLast=false) - { - $this->_levelCompleted[$level] = false; - - $prefix = ""; - for ($i = 1; $i < $level; $i++) { - if ($this->_levelCompleted[$i] == true) { - $prefix .= " "; - } else { - $prefix .= "| "; - } - } - if ($isLast) { - $pointer = "`-- "; - } else { - $pointer = "|-- "; - } - - $tree = ""; - if (is_array($value)) { - $tree .= $prefix.$pointer.$key.PHP_EOL; - - if ($isLast == true) { - $this->_levelCompleted[$level] = true; - } - - $i = 0; - foreach ($value as $k => $v) { - $i++; - $tree .= $this->_printTree($k, $v, $level+1, (count($value)==$i)); - } - } else { - $tree .= $prefix.$pointer.$key.": ".trim($value).PHP_EOL; - } - - return $tree; - } - - public function enable() - { - $resp = $this->_registry->getResponse(); - $resp->appendContent('Use either "zf enable config.provider" or "zf enable config.manifest".'); - } - - public function disable() - { - $resp = $this->_registry->getResponse(); - $resp->appendContent('Use either "zf disable config.provider" or "zf disable config.manifest".'); - } - - /** - * @param string $className - */ - public function enableProvider($className) - { - Zend_Loader::loadClass($className); - $reflClass = new ReflectionClass($className); - if (!in_array("Zend_Tool_Framework_Provider_Interface", $reflClass->getInterfaceNames())) { - #require_once "Zend/Tool/Framework/Exception.php"; - throw new Zend_Tool_Framework_Exception("Given class is not a provider"); - } - $this->_doEnable($className); - } - - protected function _doEnable($className) - { - - $userConfig = $this->_loadUserConfigIfExists(); - - if (!isset($userConfig->basicloader)) { - $userConfig->basicloader = array(); - } - if (!isset($userConfig->basicloader->classes)) { - $userConfig->basicloader->classes = array(); - } - - $providerClasses = $userConfig->basicloader->classes->toArray(); - if (!in_array($className, $providerClasses)) { - if (count($providerClasses)) { - $pos = max(array_keys($providerClasses))+1; - } else { - $pos = 0; - } - $userConfig->basicloader->classes->$pos = $className; - - if ($userConfig->save()) { - $this->_registry->getResponse()->appendContent( - "Provider/Manifest '".$className."' was enabled for usage with Zend Tool.", - array("color" => "green", "aligncenter" => true) - ); - } else { - #require_once "Zend/Tool/Framework/Exception.php"; - throw new Zend_Tool_Framework_Exception( - "Could not write user configuration to persistence." - ); - } - } else { - #require_once "Zend/Tool/Framework/Exception.php"; - throw new Zend_Tool_Framework_Exception( - "Provider/Manifest '".$className."' is already enabled." - ); - } - } - - /** - * @param string $className - */ - public function enableManifest($className) - { - Zend_Loader::loadClass($className); - $reflClass = new ReflectionClass($className); - if (!in_array("Zend_Tool_Framework_Manifest_Interface", $reflClass->getInterfaceNames())) { - #require_once "Zend/Tool/Framework/Exception.php"; - throw new Zend_Tool_Framework_Exception("Given class is not a manifest."); - } - $this->_doEnable($className); - } - - /** - * @param string $className - */ - public function disableManifest($className) - { - $this->disableProvider($className); - } - - /** - * @param string $className - */ - public function disableProvider($className) - { - $userConfig = $this->_loadUserConfigIfExists(); - - if (!isset($userConfig->basicloader)) { - $userConfig->basicloader = array(); - } - if (!isset($userConfig->basicloader->classes)) { - $userConfig->basicloader->classes = array(); - } - - $providerClasses = $userConfig->basicloader->classes->toArray(); - if (($key = array_search($className, $providerClasses)) !== false) { - unset($userConfig->basicloader->classes->$key); - - if ($userConfig->save()) { - $this->_registry->getResponse()->appendContent( - "Provider/Manifest '".$className."' was disabled.", - array("color" => "green", "aligncenter" => true) - ); - } else { - #require_once "Zend/Tool/Framework/Exception.php"; - throw new Zend_Tool_Framework_Exception( - "Could not write user configuration to persistence." - ); - } - } else { - #require_once "Zend/Tool/Framework/Exception.php"; - throw new Zend_Tool_Framework_Exception( - "Provider/Manifest '".$className."' is not enabled." - ); - } - } - - /** - * @return Zend_Tool_Framework_Client_Config - */ - protected function _loadUserConfigIfExists() - { - /* @var $userConfig Zend_Tool_Framework_Client_Config */ - $userConfig = $this->_registry->getConfig(); - - $resp = $this->_registry->getResponse(); - if (!$userConfig->exists()) { - $resp->appendContent("User has no config file.", array("aligncenter" => true, "color" => array('hiWhite', 'bgRed'))); - } - - return $userConfig; - } -} diff --git a/library/Zend/Tool/Framework/System/Provider/Manifest.php b/library/Zend/Tool/Framework/System/Provider/Manifest.php deleted file mode 100644 index 9bed8f5ca2..0000000000 --- a/library/Zend/Tool/Framework/System/Provider/Manifest.php +++ /dev/null @@ -1,114 +0,0 @@ -_registry = $registry; - } - - public function getName() - { - return 'Manifest'; - } - - public function show() - { - - $manifestRepository = $this->_registry->getManifestRepository(); - $response = $this->_registry->getResponse(); - - $metadataTree = array(); - - $longestAttrNameLen = 50; - - foreach ($manifestRepository as $metadata) { - - $metadataType = $metadata->getType(); - $metadataName = $metadata->getName(); - $metadataAttrs = $metadata->getAttributes('attributesParent'); - - if (!$metadataAttrs) { - $metadataAttrs = '(None)'; - } else { - $metadataAttrs = urldecode(http_build_query($metadataAttrs, null, ', ')); - } - - if (!array_key_exists($metadataType, $metadataTree)) { - $metadataTree[$metadataType] = array(); - } - - if (!array_key_exists($metadataName, $metadataTree[$metadataType])) { - $metadataTree[$metadataType][$metadataName] = array(); - } - - if (!array_key_exists($metadataAttrs, $metadataTree[$metadataType][$metadataName])) { - $metadataTree[$metadataType][$metadataName][$metadataAttrs] = array(); - } - - $longestAttrNameLen = (strlen($metadataAttrs) > $longestAttrNameLen) ? strlen($metadataAttrs) : $longestAttrNameLen; - - $metadataValue = $metadata->getValue(); - if (is_array($metadataValue) && count($metadataValue) > 0) { - $metadataValue = urldecode(http_build_query($metadataValue, null, ', ')); - } elseif (is_array($metadataValue)) { - $metadataValue = '(empty array)'; - } - - $metadataTree[$metadataType][$metadataName][$metadataAttrs][] = $metadataValue; - } - - foreach ($metadataTree as $metadataType => $metadatasByName) { - $response->appendContent($metadataType); - foreach ($metadatasByName as $metadataName => $metadatasByAttributes) { - $response->appendContent(" " . $metadataName); - foreach ($metadatasByAttributes as $metadataAttributeName => $metadataValues) { - foreach ($metadataValues as $metadataValue) { - $string = sprintf(" %-{$longestAttrNameLen}.{$longestAttrNameLen}s : ", $metadataAttributeName) - . $metadataValue; - $response->appendContent($string); - } - } - } - } - - } -} diff --git a/library/Zend/Tool/Framework/System/Provider/Phpinfo.php b/library/Zend/Tool/Framework/System/Provider/Phpinfo.php deleted file mode 100644 index b74e84fcdb..0000000000 --- a/library/Zend/Tool/Framework/System/Provider/Phpinfo.php +++ /dev/null @@ -1,38 +0,0 @@ -_registry = $registry; - return $this; - } - - /** - * Show Action - * - * @param string $mode The mode switch can be one of: major, minor, or mini (default) - * @param bool $nameIncluded - */ - public function show($mode = self::MODE_MINI, $nameIncluded = true) - { - - $versionInfo = $this->_splitVersion(); - - switch($mode) { - case self::MODE_MINOR: - unset($versionInfo['mini']); - break; - case self::MODE_MAJOR: - unset($versionInfo['mini'], $versionInfo['minor']); - break; - } - - $output = implode('.', $versionInfo); - - if ($nameIncluded) { - $output = 'Zend Framework Version: ' . $output; - } - - $this->_registry->response->appendContent($output); - } - - public function showMajorPart($nameIncluded = true) - { - $versionNumbers = $this->_splitVersion(); - $output = (($nameIncluded == true) ? 'ZF Major Version: ' : null) . $versionNumbers['major']; - $this->_registry->response->appendContent($output); - } - - public function showMinorPart($nameIncluded = true) - { - $versionNumbers = $this->_splitVersion(); - $output = (($nameIncluded == true) ? 'ZF Minor Version: ' : null) . $versionNumbers['minor']; - $this->_registry->response->appendContent($output); - } - - public function showMiniPart($nameIncluded = true) - { - $versionNumbers = $this->_splitVersion(); - $output = (($nameIncluded == true) ? 'ZF Mini Version: ' : null) . $versionNumbers['mini']; - $this->_registry->response->appendContent($output); - } - - protected function _splitVersion() - { - list($major, $minor, $mini) = explode('.', Zend_Version::VERSION); - return array('major' => $major, 'minor' => $minor, 'mini' => $mini); - } - -} diff --git a/library/Zend/Tool/Project/Context/Content/Engine.php b/library/Zend/Tool/Project/Context/Content/Engine.php deleted file mode 100644 index 849e79f82a..0000000000 --- a/library/Zend/Tool/Project/Context/Content/Engine.php +++ /dev/null @@ -1,106 +0,0 @@ -_storage = $storage; - $this->_engines = array( - new Zend_Tool_Project_Context_Content_Engine_CodeGenerator($storage, $this->_keyInStorage), - new Zend_Tool_Project_Context_Content_Engine_Phtml($storage, $this->_keyInStorage), - ); - } - - /** - * getContent() - * - * @param Zend_Tool_Project_Context_Interface $context - * @param string $methodName - * @param mixed $parameters - * @return string - */ - public function getContent(Zend_Tool_Project_Context_Interface $context, $methodName, $parameters) - { - $content = null; - - foreach ($this->_engines as $engine) { - if ($engine->hasContent($context, $methodName, $parameters)) { - $content = $engine->getContent($context, $methodName, $parameters); - - if ($content != null) { - break; - } - - } - - } - - if ($content == null) { - return false; - } - - return $content; - } - -} diff --git a/library/Zend/Tool/Project/Context/Content/Engine/CodeGenerator.php b/library/Zend/Tool/Project/Context/Content/Engine/CodeGenerator.php deleted file mode 100644 index b29346782a..0000000000 --- a/library/Zend/Tool/Project/Context/Content/Engine/CodeGenerator.php +++ /dev/null @@ -1,98 +0,0 @@ -_storage = $storage; - $this->_contentPrefix = $contentPrefix; - } - - /** - * hasContent() - * - * @param Zend_Tool_Project_Context_Interface $context - * @param string $method - * @return string - */ - public function hasContent(Zend_Tool_Project_Context_Interface $context, $method) - { - return $this->_storage->has($this->_contentPrefix . '/' . $context->getName() . '/' . $method . '.php'); - } - - /** - * getContent() - * - * @param Zend_Tool_Project_Context_Interface $context - * @param string $method - * @param mixed $parameters - * @return string - */ - public function getContent(Zend_Tool_Project_Context_Interface $context, $method, $parameters) - { - $streamUri = $this->_storage->getStreamUri($this->_contentPrefix . '/' . $context->getName() . '/' . $method . '.php'); - - if (method_exists($context, 'getCodeGenerator')) { - $codeGenerator = $context->getCodeGenerator(); - } else { - $codeGenerator = new Zend_CodeGenerator_Php_File(); - } - - $codeGenerator = include $streamUri; - - if (!$codeGenerator instanceof Zend_CodeGenerator_Abstract) { - throw new Zend_Tool_Project_Exception('Custom file at ' . $streamUri . ' did not return the $codeGenerator object.'); - } - - return $codeGenerator->generate(); - } - - -} diff --git a/library/Zend/Tool/Project/Context/Content/Engine/Phtml.php b/library/Zend/Tool/Project/Context/Content/Engine/Phtml.php deleted file mode 100644 index 7a7cbef0a2..0000000000 --- a/library/Zend/Tool/Project/Context/Content/Engine/Phtml.php +++ /dev/null @@ -1,89 +0,0 @@ -_storage = $storage; - $this->_contentPrefix = $contentPrefix; - } - - /** - * hasContext() - * - * @param Zend_Tool_Project_Context_Interface $context - * @param string $method - * @return string - */ - public function hasContent(Zend_Tool_Project_Context_Interface $context, $method) - { - return $this->_storage->has($this->_contentPrefix . '/' . $context . '/' . $method . '.phtml'); - } - - /** - * getContent() - * - * @param Zend_Tool_Project_Context_Interface $context - * @param string $method - * @param mixed $parameters - */ - public function getContent(Zend_Tool_Project_Context_Interface $context, $method, $parameters) - { - $streamUri = $this->_storage->getStreamUri($this->_contentPrefix . '/' . $context->getName() . '/' . $method . '.phtml'); - - ob_start(); - include $streamUri; - $content = ob_get_clean(); - - return $content; - } - -} diff --git a/library/Zend/Tool/Project/Context/Exception.php b/library/Zend/Tool/Project/Context/Exception.php deleted file mode 100644 index 373722b590..0000000000 --- a/library/Zend/Tool/Project/Context/Exception.php +++ /dev/null @@ -1,33 +0,0 @@ -_resource->getParentResource()->getContext()->getPath(); - $this->_baseDirectory = $parentBaseDirectory; - return $this; - } - - /** - * setResource() - * - * @param Zend_Tool_Project_Profile_Resource $resource - * @return Zend_Tool_Project_Context_Filesystem_Abstract - */ - public function setResource(Zend_Tool_Project_Profile_Resource $resource) - { - $this->_resource = $resource; - return $this; - } - - /** - * setBaseDirectory() - * - * @param string $baseDirectory - * @return Zend_Tool_Project_Context_Filesystem_Abstract - */ - public function setBaseDirectory($baseDirectory) - { - $this->_baseDirectory = rtrim(str_replace('\\', '/', $baseDirectory), '/'); - return $this; - } - - /** - * getBaseDirectory() - * - * @return string - */ - public function getBaseDirectory() - { - return $this->_baseDirectory; - } - - /** - * setFilesystemName() - * - * @param string $filesystemName - * @return Zend_Tool_Project_Context_Filesystem_Abstract - */ - public function setFilesystemName($filesystemName) - { - $this->_filesystemName = $filesystemName; - return $this; - } - - /** - * getFilesystemName() - * - * @return string - */ - public function getFilesystemName() - { - return $this->_filesystemName; - } - - /** - * getPath() - * - * @return string - */ - public function getPath() - { - $path = $this->_baseDirectory; - if ($this->_filesystemName) { - $path .= '/' . $this->_filesystemName; - } - return $path; - } - - /** - * exists() - * - * @return bool - */ - public function exists() - { - return file_exists($this->getPath()); - } - - /** - * create() - * - * Create this resource/context - * - */ - abstract public function create(); - - /** - * delete() - * - * Delete this resouce/context - * - */ - abstract public function delete(); - -} diff --git a/library/Zend/Tool/Project/Context/Filesystem/Directory.php b/library/Zend/Tool/Project/Context/Filesystem/Directory.php deleted file mode 100644 index aaf188762d..0000000000 --- a/library/Zend/Tool/Project/Context/Filesystem/Directory.php +++ /dev/null @@ -1,87 +0,0 @@ -_resource->getParentResource()) instanceof Zend_Tool_Project_Profile_Resource) { - if ((($parentContext = $parentResource->getContext()) instanceof Zend_Tool_Project_Context_Filesystem_Abstract) - && (!$parentContext->exists())) { - $parentResource->create(); - } - } - - if (!file_exists($this->getPath())) { - mkdir($this->getPath()); - } - - return $this; - } - - /** - * delete() - * - * @return Zend_Tool_Project_Context_Filesystem_Directory - */ - public function delete() - { - $this->_resource->setDeleted(true); - rmdir($this->getPath()); - - return $this; - } - -} diff --git a/library/Zend/Tool/Project/Context/Filesystem/File.php b/library/Zend/Tool/Project/Context/Filesystem/File.php deleted file mode 100644 index 129fc64ec5..0000000000 --- a/library/Zend/Tool/Project/Context/Filesystem/File.php +++ /dev/null @@ -1,174 +0,0 @@ -_resource->hasAttribute('filesystemName')) { - $this->_filesystemName = $this->_resource->getAttribute('filesystemName'); - } - - // check to see if this file is - if ($this->getName() == 'file') { - $this->_initFileOnlyContext(); - } - - // @potential-todo check to ensure that this 'file' resource has no children - parent::init(); - return $this; - } - - /** - * getPersistentAttributes() - * - * @return array - */ - public function getPersistentAttributes() - { - $returnAttrs = array(); - if ($this->_filesystemName !== null) { - $returnAttrs['filesystemName'] = $this->_filesystemName; - } - return $returnAttrs; - } - - /** - * setResource() - * - * @param unknown_type $resource - */ - public function setResource(Zend_Tool_Project_Profile_Resource $resource) - { - $this->_resource = $resource; - $this->_resource->setAppendable(false); - return $this; - } - - /** - * getResource() - * - * @return Zend_Tool_Project_Profile_Resource - */ - public function getResource() - { - return $this->_resource; - } - - /** - * create() - * - * @return Zend_Tool_Project_Context_Filesystem_File - */ - public function create() - { - // check to ensure the parent exists, if not, call it and create it - if (($parentResource = $this->_resource->getParentResource()) instanceof Zend_Tool_Project_Profile_Resource) { - if ((($parentContext = $parentResource->getContext()) instanceof Zend_Tool_Project_Context_Filesystem_Abstract) - && (!$parentContext->exists())) { - $parentResource->create(); - } - } - - - if (file_exists($this->getPath())) { - // @todo propt user to determine if its ok to overwrite file - } - - file_put_contents($this->getPath(), $this->getContents()); - return $this; - } - - /** - * delete() - * - * @return Zend_Tool_Project_Context_Filesystem_File - */ - public function delete() - { - unlink($this->getPath()); - $this->_resource->setDeleted(true); - return $this; - } - - /** - * getContents() - * - * @return null - */ - public function getContents() - { - return $this->_content; - } - - protected function _initFileOnlyContext() - { - if ($this->_resource->hasAttribute('defaultContentCallback')) { - $contentFunc = $this->_resource->getAttribute('defaultContentCallback'); - if (is_callable($contentFunc)) { - $this->_content = call_user_func_array($contentFunc, array($this)); - } - } - if ($this->_filesystemName == null) { - $this->_filesystemName = 'file.txt'; - } - } - -} diff --git a/library/Zend/Tool/Project/Context/Interface.php b/library/Zend/Tool/Project/Context/Interface.php deleted file mode 100644 index 6eb2af6f5d..0000000000 --- a/library/Zend/Tool/Project/Context/Interface.php +++ /dev/null @@ -1,38 +0,0 @@ -addContextClass('Zend_Tool_Project_Context_System_ProjectDirectory') - ->addContextClass('Zend_Tool_Project_Context_System_ProjectProfileFile') - ->addContextClass('Zend_Tool_Project_Context_System_ProjectProvidersDirectory'); - self::$_isInitialized = true; - } - } - - public function addContextsFromDirectory($directory, $prefix) - { - $prefix = trim($prefix, '_') . '_'; - foreach (new DirectoryIterator($directory) as $directoryItem) { - if ($directoryItem->isDot() || (substr($directoryItem->getFilename(), -4) !== '.php')) { - continue; - } - $class = $prefix . substr($directoryItem->getFilename(), 0, -4); - $this->addContextClass($class); - } - } - - - public function addContextClass($contextClass) - { - if (!class_exists($contextClass)) { - #require_once 'Zend/Loader.php'; - Zend_Loader::loadClass($contextClass); - } - $reflectionContextClass = new ReflectionClass($contextClass); - if ($reflectionContextClass->isInstantiable()) { - $context = new $contextClass(); - return $this->addContext($context); - } - return $this; - } - - /** - * Enter description here... - * - * @param Zend_Tool_Project_Context_Interface $context - * @return Zend_Tool_Project_Context_Repository - */ - public function addContext(Zend_Tool_Project_Context_Interface $context) - { - $isSystem = ($context instanceof Zend_Tool_Project_Context_System_Interface); - $isTopLevel = ($context instanceof Zend_Tool_Project_Context_System_TopLevelRestrictable); - $isOverwritable = !($context instanceof Zend_Tool_Project_Context_System_NotOverwritable); - - $index = (count($this->_contexts)) ? max(array_keys($this->_contexts)) + 1 : 1; - - $normalName = $this->_normalizeName($context->getName()); - - if (isset($this->_shortContextNames[$normalName]) && ($this->_contexts[$this->_shortContextNames[$normalName]]['isOverwritable'] === false) ) { - #require_once 'Zend/Tool/Project/Context/Exception.php'; - throw new Zend_Tool_Project_Context_Exception('Context ' . $context->getName() . ' is not overwriteable.'); - } - - $this->_shortContextNames[$normalName] = $index; - $this->_contexts[$index] = array( - 'isTopLevel' => $isTopLevel, - 'isSystem' => $isSystem, - 'isOverwritable' => $isOverwritable, - 'normalName' => $normalName, - 'context' => $context - ); - - return $this; - } - - public function getContext($name) - { - if (!$this->hasContext($name)) { - #require_once 'Zend/Tool/Project/Context/Exception.php'; - throw new Zend_Tool_Project_Context_Exception('Context by name ' . $name . ' does not exist in the registry.'); - } - - $name = $this->_normalizeName($name); - return clone $this->_contexts[$this->_shortContextNames[$name]]['context']; - } - - public function hasContext($name) - { - $name = $this->_normalizeName($name); - return (isset($this->_shortContextNames[$name]) ? true : false); - } - - public function isSystemContext($name) - { - if (!$this->hasContext($name)) { - return false; - } - - $name = $this->_normalizeName($name); - $index = $this->_shortContextNames[$name]; - return $this->_contexts[$index]['isSystemContext']; - } - - public function isTopLevelContext($name) - { - if (!$this->hasContext($name)) { - return false; - } - $name = $this->_normalizeName($name); - $index = $this->_shortContextNames[$name]; - return $this->_contexts[$index]['isTopLevel']; - } - - public function isOverwritableContext($name) - { - if (!$this->hasContext($name)) { - return false; - } - $name = $this->_normalizeName($name); - $index = $this->_shortContextNames[$name]; - return $this->_contexts[$index]['isOverwritable']; - } - - public function count() - { - return count($this->_contexts); - } - - protected function _normalizeName($name) - { - return strtolower($name); - } - -} diff --git a/library/Zend/Tool/Project/Context/System/Interface.php b/library/Zend/Tool/Project/Context/System/Interface.php deleted file mode 100644 index f79faa973e..0000000000 --- a/library/Zend/Tool/Project/Context/System/Interface.php +++ /dev/null @@ -1,37 +0,0 @@ -_resource->getAttribute('path'); - - // if not, get from profile - if ($projectDirectory == null) { - $projectDirectory = $this->_resource->getProfile()->getAttribute('projectDirectory'); - } - - // if not, exception. - if ($projectDirectory == null) { - #require_once 'Zend/Tool/Project/Exception.php'; - throw new Zend_Tool_Project_Exception('projectDirectory cannot find the directory for this project.'); - } - - $this->_baseDirectory = rtrim($projectDirectory, '\\/'); - return $this; - } - - /** - * create() - * - * @return Zend_Tool_Project_Context_System_ProjectDirectory - */ - public function create() - { - if (file_exists($this->getPath())) { - /* - foreach (new DirectoryIterator($this->getPath()) as $item) { - if (!$item->isDot()) { - if ($registry->getClient()->isInteractive()) { - // @todo prompt for override - } else { - #require_once 'Zend/Tool/Project/Context/Exception.php'; - throw new Zend_Tool_Project_Context_Exception('This directory is not empty, project creation aborted.'); - } - break; - } - } - */ - } - - parent::create(); - return $this; - } - -} diff --git a/library/Zend/Tool/Project/Context/System/ProjectProfileFile.php b/library/Zend/Tool/Project/Context/System/ProjectProfileFile.php deleted file mode 100644 index 90c1b7b1bf..0000000000 --- a/library/Zend/Tool/Project/Context/System/ProjectProfileFile.php +++ /dev/null @@ -1,118 +0,0 @@ -_profile = $profile; - return $this; - } - - /** - * save() - * - * Proxy to create - * - * @return Zend_Tool_Project_Context_System_ProjectProfileFile - */ - public function save() - { - parent::create(); - return $this; - } - - /** - * getContents() - * - * @return string - */ - public function getContents() - { - $parser = new Zend_Tool_Project_Profile_FileParser_Xml(); - $profile = $this->_resource->getProfile(); - $xml = $parser->serialize($profile); - return $xml; - } - -} diff --git a/library/Zend/Tool/Project/Context/System/ProjectProvidersDirectory.php b/library/Zend/Tool/Project/Context/System/ProjectProvidersDirectory.php deleted file mode 100644 index e1126bc09e..0000000000 --- a/library/Zend/Tool/Project/Context/System/ProjectProvidersDirectory.php +++ /dev/null @@ -1,87 +0,0 @@ -getPath())) { - - $providerRepository = $registry->getProviderRepository(); - - foreach (new DirectoryIterator($this->getPath()) as $item) { - if ($item->isFile() && (($suffixStart = strpos($item->getFilename(), 'Provider.php')) !== false)) { - $className = substr($item->getFilename(), 0, $suffixStart+8); - // $loadableFiles[$className] = $item->getPathname(); - include_once $item->getPathname(); - $providerRepository->addProvider(new $className()); - } - } - } - } - -} diff --git a/library/Zend/Tool/Project/Context/System/TopLevelRestrictable.php b/library/Zend/Tool/Project/Context/System/TopLevelRestrictable.php deleted file mode 100644 index 5680bb2539..0000000000 --- a/library/Zend/Tool/Project/Context/System/TopLevelRestrictable.php +++ /dev/null @@ -1,37 +0,0 @@ -_resource; - do { - $resourceName = $currentResource->getName(); - if ($resourceName == 'ApplicationDirectory' || $resourceName == 'ModuleDirectory') { - $containingResource = $currentResource; - break; - } - } while ($currentResource instanceof Zend_Tool_Project_Profile_Resource - && $currentResource = $currentResource->getParentResource()); - - $fullClassName = ''; - - // go find the proper prefix - if (isset($containingResource)) { - if ($containingResource->getName() == 'ApplicationDirectory') { - $prefix = $containingResource->getAttribute('classNamePrefix'); - $fullClassName = $prefix; - } elseif ($containingResource->getName() == 'ModuleDirectory') { - $filter = new Zend_Filter_Word_DashToCamelCase(); - $prefix = $filter->filter(ucfirst($containingResource->getAttribute('moduleName'))) . '_'; - $fullClassName = $prefix; - } - } - - if ($classContextName) { - $fullClassName .= rtrim($classContextName, '_') . '_'; - } - $fullClassName .= $localClassName; - - return $fullClassName; - } - -} diff --git a/library/Zend/Tool/Project/Context/Zf/ActionMethod.php b/library/Zend/Tool/Project/Context/Zf/ActionMethod.php deleted file mode 100644 index dc77f0f7a6..0000000000 --- a/library/Zend/Tool/Project/Context/Zf/ActionMethod.php +++ /dev/null @@ -1,224 +0,0 @@ -_actionName = $this->_resource->getAttribute('actionName'); - - $this->_resource->setAppendable(false); - $this->_controllerResource = $this->_resource->getParentResource(); - if (!$this->_controllerResource->getContext() instanceof Zend_Tool_Project_Context_Zf_ControllerFile) { - #require_once 'Zend/Tool/Project/Context/Exception.php'; - throw new Zend_Tool_Project_Context_Exception('ActionMethod must be a sub resource of a ControllerFile'); - } - // make the ControllerFile node appendable so we can tack on the actionMethod. - $this->_resource->getParentResource()->setAppendable(true); - - $this->_controllerPath = $this->_controllerResource->getContext()->getPath(); - - /* - * This code block is now commented, its doing to much for init() - * - if ($this->_controllerPath != '' && self::hasActionMethod($this->_controllerPath, $this->_actionName)) { - #require_once 'Zend/Tool/Project/Context/Exception.php'; - throw new Zend_Tool_Project_Context_Exception('An action named ' . $this->_actionName . 'Action already exists in this controller'); - } - */ - - return $this; - } - - /** - * getPersistentAttributes - * - * @return array - */ - public function getPersistentAttributes() - { - return array( - 'actionName' => $this->getActionName() - ); - } - - /** - * getName() - * - * @return string - */ - public function getName() - { - return 'ActionMethod'; - } - - /** - * setResource() - * - * @param Zend_Tool_Project_Profile_Resource $resource - * @return Zend_Tool_Project_Context_Zf_ActionMethod - */ - public function setResource(Zend_Tool_Project_Profile_Resource $resource) - { - $this->_resource = $resource; - return $this; - } - - /** - * setActionName() - * - * @param string $actionName - * @return Zend_Tool_Project_Context_Zf_ActionMethod - */ - public function setActionName($actionName) - { - $this->_actionName = $actionName; - return $this; - } - - /** - * getActionName() - * - * @return string - */ - public function getActionName() - { - return $this->_actionName; - } - - /** - * create() - * - * @return Zend_Tool_Project_Context_Zf_ActionMethod - */ - public function create() - { - if (self::createActionMethod($this->_controllerPath, $this->_actionName) === false) { - #require_once 'Zend/Tool/Project/Context/Exception.php'; - throw new Zend_Tool_Project_Context_Exception( - 'Could not create action within controller ' . $this->_controllerPath - . ' with action name ' . $this->_actionName - ); - } - return $this; - } - - /** - * delete() - * - * @return Zend_Tool_Project_Context_Zf_ActionMethod - */ - public function delete() - { - // @todo do this - return $this; - } - - /** - * createAcionMethod() - * - * @param string $controllerPath - * @param string $actionName - * @param string $body - * @return true - */ - public static function createActionMethod($controllerPath, $actionName, $body = ' // action body') - { - if (!file_exists($controllerPath)) { - return false; - } - - $controllerCodeGenFile = Zend_CodeGenerator_Php_File::fromReflectedFileName($controllerPath, true, true); - $controllerCodeGenFile->getClass()->setMethod(array( - 'name' => $actionName . 'Action', - 'body' => $body - )); - - file_put_contents($controllerPath, $controllerCodeGenFile->generate()); - return true; - } - - /** - * hasActionMethod() - * - * @param string $controllerPath - * @param string $actionName - * @return bool - */ - public static function hasActionMethod($controllerPath, $actionName) - { - if (!file_exists($controllerPath)) { - return false; - } - - $controllerCodeGenFile = Zend_CodeGenerator_Php_File::fromReflectedFileName($controllerPath, true, true); - return $controllerCodeGenFile->getClass()->hasMethod($actionName . 'Action'); - } - -} diff --git a/library/Zend/Tool/Project/Context/Zf/ApisDirectory.php b/library/Zend/Tool/Project/Context/Zf/ApisDirectory.php deleted file mode 100644 index 83fa5b9640..0000000000 --- a/library/Zend/Tool/Project/Context/Zf/ApisDirectory.php +++ /dev/null @@ -1,55 +0,0 @@ -_type = $this->_resource->getAttribute('type'); - parent::init(); - return $this; - } - - /** - * getPersistentAttributes() - * - * @return array - */ - public function getPersistentAttributes() - { - return array('type' => $this->_type); - } - - /** - * getContents() - * - * @return string - */ - public function getContents() - { - if ($this->_content === null) { - if (file_exists($this->getPath())) { - $this->_content = file_get_contents($this->getPath()); - } else { - $this->_content = $this->_getDefaultContents(); - } - - } - - return $this->_content; - } - - public function getAsZendConfig($section = 'production') - { - return new Zend_Config_Ini($this->getPath(), $section); - } - - /** - * addStringItem() - * - * @param string $key - * @param string $value - * @param string $section - * @param bool $quoteValue - * @return Zend_Tool_Project_Context_Zf_ApplicationConfigFile - */ - public function addStringItem($key, $value, $section = 'production', $quoteValue = true) - { - // null quote value means to auto-detect - if ($quoteValue === null) { - $quoteValue = preg_match('#[\"\']#', $value) ? false : true; - } - - if ($quoteValue == true) { - $value = '"' . $value . '"'; - } - - $contentLines = preg_split('#[\n\r]#', $this->getContents()); - - $newLines = array(); - $insideSection = false; - - foreach ($contentLines as $contentLineIndex => $contentLine) { - - if ($insideSection === false && preg_match('#^\[' . $section . '#', $contentLine)) { - $insideSection = true; - } - - $newLines[] = $contentLine; - if ($insideSection) { - // if its blank, or a section heading - if (isset($contentLines[$contentLineIndex + 1]{0}) && $contentLines[$contentLineIndex + 1]{0} == '[') { - $newLines[] = $key . ' = ' . $value; - $insideSection = null; - } else if (!isset($contentLines[$contentLineIndex + 1])){ - $newLines[] = $key . ' = ' . $value; - $insideSection = null; - } - } - } - - $this->_content = implode("\n", $newLines); - return $this; - } - - /** - * - * @param array $item - * @param string $section - * @param bool $quoteValue - * @return Zend_Tool_Project_Context_Zf_ApplicationConfigFile - */ - public function addItem($item, $section = 'production', $quoteValue = true) - { - $stringItems = array(); - $stringValues = array(); - $configKeyNames = array(); - - $rii = new RecursiveIteratorIterator( - new RecursiveArrayIterator($item), - RecursiveIteratorIterator::SELF_FIRST - ); - - $lastDepth = 0; - - // loop through array structure recursively to create proper keys - foreach ($rii as $name => $value) { - $lastDepth = $rii->getDepth(); - - if (is_array($value)) { - array_push($configKeyNames, $name); - } else { - $stringItems[] = implode('.', $configKeyNames) . '.' . $name; - $stringValues[] = $value; - } - } - - foreach ($stringItems as $stringItemIndex => $stringItem) { - $this->addStringItem($stringItem, $stringValues[$stringItemIndex], $section, $quoteValue); - } - - return $this; - } - - public function removeStringItem($key, $section = 'production') - { - $contentLines = file($this->getPath()); - - $newLines = array(); - $insideSection = false; - - foreach ($contentLines as $contentLineIndex => $contentLine) { - - if ($insideSection === false && preg_match('#^\[' . $section . '#', $contentLine)) { - $insideSection = true; - } - - if ($insideSection) { - // if its blank, or a section heading - if ((trim($contentLine) == null) || ($contentLines[$contentLineIndex + 1][0] == '[')) { - $insideSection = null; - } - } - - if (!preg_match('#' . $key . '\s?=.*#', $contentLine)) { - $newLines[] = $contentLine; - } - } - - $this->_content = implode('', $newLines); - } - - public function removeItem($item, $section = 'production') - { - $stringItems = array(); - $stringValues = array(); - $configKeyNames = array(); - - $rii = new RecursiveIteratorIterator( - new RecursiveArrayIterator($item), - RecursiveIteratorIterator::SELF_FIRST - ); - - $lastDepth = 0; - - // loop through array structure recursively to create proper keys - foreach ($rii as $name => $value) { - $lastDepth = $rii->getDepth(); - - if (is_array($value)) { - array_push($configKeyNames, $name); - } else { - $stringItems[] = implode('.', $configKeyNames) . '.' . $name; - $stringValues[] = $value; - } - } - - foreach ($stringItems as $stringItemIndex => $stringItem) { - $this->removeStringItem($stringItem, $section); - } - - return $this; - } - - protected function _getDefaultContents() - { - - $contents =<<_resource->hasAttribute('classNamePrefix')) { - $this->_classNamePrefix = $this->_resource->getAttribute('classNamePrefix'); - } - parent::init(); - } - - /** - * getPersistentAttributes - * - * @return array - */ - public function getPersistentAttributes() - { - return array( - 'classNamePrefix' => $this->getClassNamePrefix() - ); - } - - public function getName() - { - return 'ApplicationDirectory'; - } - - public function setClassNamePrefix($classNamePrefix) - { - $this->_classNamePrefix = $classNamePrefix; - } - - public function getClassNamePrefix() - { - return $this->_classNamePrefix; - } - -} diff --git a/library/Zend/Tool/Project/Context/Zf/BootstrapFile.php b/library/Zend/Tool/Project/Context/Zf/BootstrapFile.php deleted file mode 100644 index e815c9deb1..0000000000 --- a/library/Zend/Tool/Project/Context/Zf/BootstrapFile.php +++ /dev/null @@ -1,119 +0,0 @@ -_applicationConfigFile = $this->_resource->getProfile()->search('ApplicationConfigFile'); - $this->_applicationDirectory = $this->_resource->getProfile()->search('ApplicationDirectory'); - - if (($this->_applicationConfigFile === false) || ($this->_applicationDirectory === false)) { - throw new Exception('To use the BootstrapFile context, your project requires the use of both the "ApplicationConfigFile" and "ApplicationDirectory" contexts.'); - } - - - } - - /** - * getContents() - * - * @return array - */ - public function getContents() - { - - $codeGenFile = new Zend_CodeGenerator_Php_File(array( - 'classes' => array( - new Zend_CodeGenerator_Php_Class(array( - 'name' => 'Bootstrap', - 'extendedClass' => 'Zend_Application_Bootstrap_Bootstrap', - )), - ) - )); - - return $codeGenFile->generate(); - } - - public function getApplicationInstance() - { - if ($this->_applicationInstance == null) { - if ($this->_applicationConfigFile->getContext()->exists()) { - define('APPLICATION_PATH', $this->_applicationDirectory->getPath()); - $applicationOptions = array(); - $applicationOptions['config'] = $this->_applicationConfigFile->getPath(); - - $this->_applicationInstance = new Zend_Application( - 'development', - $applicationOptions - ); - } - } - - return $this->_applicationInstance; - } -} diff --git a/library/Zend/Tool/Project/Context/Zf/CacheDirectory.php b/library/Zend/Tool/Project/Context/Zf/CacheDirectory.php deleted file mode 100644 index 369d98abea..0000000000 --- a/library/Zend/Tool/Project/Context/Zf/CacheDirectory.php +++ /dev/null @@ -1,57 +0,0 @@ -_controllerName = $this->_resource->getAttribute('controllerName'); - $this->_moduleName = $this->_resource->getAttribute('moduleName'); - $this->_filesystemName = ucfirst($this->_controllerName) . 'Controller.php'; - parent::init(); - } - - /** - * getPersistentAttributes - * - * @return array - */ - public function getPersistentAttributes() - { - return array( - 'controllerName' => $this->getControllerName() - ); - } - - /** - * getName() - * - * @return string - */ - public function getName() - { - return 'ControllerFile'; - } - - /** - * getControllerName() - * - * @return string - */ - public function getControllerName() - { - return $this->_controllerName; - } - - /** - * getContents() - * - * @return string - */ - public function getContents() - { - $filter = new Zend_Filter_Word_DashToCamelCase(); - - $className = ($this->_moduleName) ? $filter->filter(ucfirst($this->_moduleName)) . '_' : ''; - $className .= ucfirst($this->_controllerName) . 'Controller'; - - $codeGenFile = new Zend_CodeGenerator_Php_File(array( - 'fileName' => $this->getPath(), - 'classes' => array( - new Zend_CodeGenerator_Php_Class(array( - 'name' => $className, - 'extendedClass' => 'Zend_Controller_Action', - 'methods' => array( - new Zend_CodeGenerator_Php_Method(array( - 'name' => 'init', - 'body' => '/* Initialize action controller here */', - )) - ) - )) - ) - )); - - - if ($className == 'ErrorController') { - - $codeGenFile = new Zend_CodeGenerator_Php_File(array( - 'fileName' => $this->getPath(), - 'classes' => array( - new Zend_CodeGenerator_Php_Class(array( - 'name' => $className, - 'extendedClass' => 'Zend_Controller_Action', - 'methods' => array( - new Zend_CodeGenerator_Php_Method(array( - 'name' => 'errorAction', - 'body' => <<_getParam('error_handler'); - -if (!\$errors || !\$errors instanceof ArrayObject) { - \$this->view->message = 'You have reached the error page'; - return; -} - -switch (\$errors->type) { - case Zend_Controller_Plugin_ErrorHandler::EXCEPTION_NO_ROUTE: - case Zend_Controller_Plugin_ErrorHandler::EXCEPTION_NO_CONTROLLER: - case Zend_Controller_Plugin_ErrorHandler::EXCEPTION_NO_ACTION: - // 404 error -- controller or action not found - \$this->getResponse()->setHttpResponseCode(404); - \$priority = Zend_Log::NOTICE; - \$this->view->message = 'Page not found'; - break; - default: - // application error - \$this->getResponse()->setHttpResponseCode(500); - \$priority = Zend_Log::CRIT; - \$this->view->message = 'Application error'; - break; -} - -// Log exception, if logger available -if (\$log = \$this->getLog()) { - \$log->log(\$this->view->message, \$priority, \$errors->exception); - \$log->log('Request Parameters', \$priority, \$errors->request->getParams()); -} - -// conditionally display exceptions -if (\$this->getInvokeArg('displayExceptions') == true) { - \$this->view->exception = \$errors->exception; -} - -\$this->view->request = \$errors->request; -EOS - )), - new Zend_CodeGenerator_Php_Method(array( - 'name' => 'getLog', - 'body' => <<getInvokeArg('bootstrap'); -if (!\$bootstrap->hasResource('Log')) { - return false; -} -\$log = \$bootstrap->getResource('Log'); -return \$log; -EOS - )), - ) - )) - ) - )); - - } - - // store the generator into the registry so that the addAction command can use the same object later - Zend_CodeGenerator_Php_File::registerFileCodeGenerator($codeGenFile); // REQUIRES filename to be set - return $codeGenFile->generate(); - } - - /** - * addAction() - * - * @param string $actionName - */ - public function addAction($actionName) - { - $classCodeGen = $this->getCodeGenerator(); - $classCodeGen->setMethod(array('name' => $actionName . 'Action', 'body' => ' // action body here')); - file_put_contents($this->getPath(), $classCodeGen->generate()); - } - - /** - * getCodeGenerator() - * - * @return Zend_CodeGenerator_Php_Class - */ - public function getCodeGenerator() - { - $codeGenFile = Zend_CodeGenerator_Php_File::fromReflectedFileName($this->getPath()); - $codeGenFileClasses = $codeGenFile->getClasses(); - $class = array_shift($codeGenFileClasses); - return $class; - } - -} diff --git a/library/Zend/Tool/Project/Context/Zf/ControllersDirectory.php b/library/Zend/Tool/Project/Context/Zf/ControllersDirectory.php deleted file mode 100644 index 99b4adf09c..0000000000 --- a/library/Zend/Tool/Project/Context/Zf/ControllersDirectory.php +++ /dev/null @@ -1,57 +0,0 @@ -_dbTableName = $this->_resource->getAttribute('dbTableName'); - $this->_actualTableName = $this->_resource->getAttribute('actualTableName'); - $this->_filesystemName = ucfirst($this->_dbTableName) . '.php'; - parent::init(); - } - - public function getPersistentAttributes() - { - return array('dbTableName' => $this->_dbTableName); - } - - public function getContents() - { - $className = $this->getFullClassName($this->_dbTableName, 'Model_DbTable'); - - $codeGenFile = new Zend_CodeGenerator_Php_File(array( - 'fileName' => $this->getPath(), - 'classes' => array( - new Zend_CodeGenerator_Php_Class(array( - 'name' => $className, - 'extendedClass' => 'Zend_Db_Table_Abstract', - 'properties' => array( - new Zend_CodeGenerator_Php_Property(array( - 'name' => '_name', - 'visibility' => Zend_CodeGenerator_Php_Property::VISIBILITY_PROTECTED, - 'defaultValue' => $this->_actualTableName - )) - ), - - )) - ) - )); - return $codeGenFile->generate(); - } - -} diff --git a/library/Zend/Tool/Project/Context/Zf/DocsDirectory.php b/library/Zend/Tool/Project/Context/Zf/DocsDirectory.php deleted file mode 100644 index 65f626ddae..0000000000 --- a/library/Zend/Tool/Project/Context/Zf/DocsDirectory.php +++ /dev/null @@ -1,61 +0,0 @@ -_formName = $this->_resource->getAttribute('formName'); - $this->_filesystemName = ucfirst($this->_formName) . '.php'; - parent::init(); - } - - /** - * getPersistentAttributes - * - * @return array - */ - public function getPersistentAttributes() - { - return array( - 'formName' => $this->getFormName() - ); - } - - /** - * getName() - * - * @return string - */ - public function getName() - { - return 'FormFile'; - } - - public function getFormName() - { - return $this->_formName; - } - - public function getContents() - { - - $className = $this->getFullClassName($this->_formName, 'Form'); - - $codeGenFile = new Zend_CodeGenerator_Php_File(array( - 'fileName' => $this->getPath(), - 'classes' => array( - new Zend_CodeGenerator_Php_Class(array( - 'name' => $className, - 'extendedClass' => 'Zend_Form', - 'methods' => array( - new Zend_CodeGenerator_Php_Method(array( - 'name' => 'init', - 'body' => '/* Form Elements & Other Definitions Here ... */', - )) - ) - - )) - ) - )); - return $codeGenFile->generate(); - } -} diff --git a/library/Zend/Tool/Project/Context/Zf/FormsDirectory.php b/library/Zend/Tool/Project/Context/Zf/FormsDirectory.php deleted file mode 100644 index 4b02a36209..0000000000 --- a/library/Zend/Tool/Project/Context/Zf/FormsDirectory.php +++ /dev/null @@ -1,57 +0,0 @@ -_resource->getAttribute('layoutName')) { - $this->_layoutName = $layoutName; - } else { - throw new Exception('Either a forActionName or scriptName is required.'); - } - - parent::init(); - return $this; - } - - /** - * getPersistentAttributes() - * - * @return unknown - */ - public function getPersistentAttributes() - { - $attributes = array(); - - if ($this->_layoutName) { - $attributes['layoutName'] = $this->_layoutName; - } - - return $attributes; - } - - /** - * getContents() - * - * @return string - */ - public function getContents() - { - $contents = <<layout()->content; ?> -EOS; - - return $contents; - } - -} diff --git a/library/Zend/Tool/Project/Context/Zf/LayoutScriptsDirectory.php b/library/Zend/Tool/Project/Context/Zf/LayoutScriptsDirectory.php deleted file mode 100644 index 31fea88a0b..0000000000 --- a/library/Zend/Tool/Project/Context/Zf/LayoutScriptsDirectory.php +++ /dev/null @@ -1,57 +0,0 @@ -_modelName = $this->_resource->getAttribute('modelName'); - $this->_filesystemName = ucfirst($this->_modelName) . '.php'; - parent::init(); - } - - /** - * getPersistentAttributes - * - * @return array - */ - public function getPersistentAttributes() - { - return array( - 'modelName' => $this->getModelName() - ); - } - - /** - * getName() - * - * @return string - */ - public function getName() - { - return 'ModelFile'; - } - - public function getModelName() - { - return $this->_modelName; - } - - public function getContents() - { - - $className = $this->getFullClassName($this->_modelName, 'Model'); - - $codeGenFile = new Zend_CodeGenerator_Php_File(array( - 'fileName' => $this->getPath(), - 'classes' => array( - new Zend_CodeGenerator_Php_Class(array( - 'name' => $className, - )) - ) - )); - return $codeGenFile->generate(); - } - - -} diff --git a/library/Zend/Tool/Project/Context/Zf/ModelsDirectory.php b/library/Zend/Tool/Project/Context/Zf/ModelsDirectory.php deleted file mode 100644 index d813adbc3a..0000000000 --- a/library/Zend/Tool/Project/Context/Zf/ModelsDirectory.php +++ /dev/null @@ -1,57 +0,0 @@ -_filesystemName = $this->_moduleName = $this->_resource->getAttribute('moduleName'); - parent::init(); - return $this; - } - - /** - * getName() - * - * @return string - */ - public function getName() - { - return 'ModuleDirectory'; - } - - /** - * getPersistentAttributes - * - * @return array - */ - public function getPersistentAttributes() - { - return array( - 'moduleName' => $this->getModuleName() - ); - } - - /** - * getModuleName() - * - * @return string - */ - public function getModuleName() - { - return $this->_moduleName; - } - - -} diff --git a/library/Zend/Tool/Project/Context/Zf/ModulesDirectory.php b/library/Zend/Tool/Project/Context/Zf/ModulesDirectory.php deleted file mode 100644 index 482b1f3c69..0000000000 --- a/library/Zend/Tool/Project/Context/Zf/ModulesDirectory.php +++ /dev/null @@ -1,57 +0,0 @@ -_projectProviderName = $this->_resource->getAttribute('projectProviderName'); - $this->_actionNames = $this->_resource->getAttribute('actionNames'); - $this->_filesystemName = ucfirst($this->_projectProviderName) . 'Provider.php'; - - if (strpos($this->_actionNames, ',')) { - $this->_actionNames = explode(',', $this->_actionNames); - } else { - $this->_actionNames = ($this->_actionNames) ? array($this->_actionNames) : array(); - } - - parent::init(); - return $this; - } - - /** - * getPersistentAttributes() - * - * @return array - */ - public function getPersistentAttributes() - { - return array( - 'projectProviderName' => $this->getProjectProviderName(), - 'actionNames' => implode(',', $this->_actionNames) - ); - } - - /** - * getName() - * - * @return string - */ - public function getName() - { - return 'ProjectProviderFile'; - } - - /** - * getProjectProviderName() - * - * @return string - */ - public function getProjectProviderName() - { - return $this->_projectProviderName; - } - - /** - * getContents() - * - * @return string - */ - public function getContents() - { - - $filter = new Zend_Filter_Word_DashToCamelCase(); - - $className = $filter->filter($this->_projectProviderName) . 'Provider'; - - $class = new Zend_CodeGenerator_Php_Class(array( - 'name' => $className, - 'extendedClass' => 'Zend_Tool_Project_Provider_Abstract' - )); - - $methods = array(); - foreach ($this->_actionNames as $actionName) { - $methods[] = new Zend_CodeGenerator_Php_Method(array( - 'name' => $actionName, - 'body' => ' /** @todo Implementation */' - )); - } - - if ($methods) { - $class->setMethods($methods); - } - - $codeGenFile = new Zend_CodeGenerator_Php_File(array( - 'requiredFiles' => array( - 'Zend/Tool/Project/Provider/Abstract.php', - 'Zend/Tool/Project/Provider/Exception.php' - ), - 'classes' => array($class) - )); - - return $codeGenFile->generate(); - } - -} diff --git a/library/Zend/Tool/Project/Context/Zf/PublicDirectory.php b/library/Zend/Tool/Project/Context/Zf/PublicDirectory.php deleted file mode 100644 index 0f5b38703d..0000000000 --- a/library/Zend/Tool/Project/Context/Zf/PublicDirectory.php +++ /dev/null @@ -1,57 +0,0 @@ - <<bootstrap() - ->run(); -EOS - )); - return $codeGenerator->generate(); - } - -} diff --git a/library/Zend/Tool/Project/Context/Zf/PublicScriptsDirectory.php b/library/Zend/Tool/Project/Context/Zf/PublicScriptsDirectory.php deleted file mode 100644 index a495420634..0000000000 --- a/library/Zend/Tool/Project/Context/Zf/PublicScriptsDirectory.php +++ /dev/null @@ -1,57 +0,0 @@ -_forActionName = $this->_resource->getAttribute('forActionName'); - - $this->_resource->setAppendable(false); - $this->_testApplicationControllerResource = $this->_resource->getParentResource(); - if (!$this->_testApplicationControllerResource->getContext() instanceof Zend_Tool_Project_Context_Zf_TestApplicationControllerFile) { - #require_once 'Zend/Tool/Project/Context/Exception.php'; - throw new Zend_Tool_Project_Context_Exception('ActionMethod must be a sub resource of a TestApplicationControllerFile'); - } - // make the ControllerFile node appendable so we can tack on the actionMethod. - $this->_resource->getParentResource()->setAppendable(true); - - $this->_testApplicationControllerPath = $this->_testApplicationControllerResource->getContext()->getPath(); - - return $this; - } - - /** - * getPersistentAttributes - * - * @return array - */ - public function getPersistentAttributes() - { - return array( - 'forActionName' => $this->getForActionName() - ); - } - - /** - * getName() - * - * @return string - */ - public function getName() - { - return 'TestApplicationActionMethod'; - } - - /** - * setResource() - * - * @param Zend_Tool_Project_Profile_Resource $resource - * @return Zend_Tool_Project_Context_Zf_ActionMethod - */ - public function setResource(Zend_Tool_Project_Profile_Resource $resource) - { - $this->_resource = $resource; - return $this; - } - - /** - * getActionName() - * - * @return string - */ - public function getForActionName() - { - return $this->_forActionName; - } - - /** - * create() - * - * @return Zend_Tool_Project_Context_Zf_ActionMethod - */ - public function create() - { - $file = $this->_testApplicationControllerPath; - - if (!file_exists($file)) { - #require_once 'Zend/Tool/Project/Context/Exception.php'; - throw new Zend_Tool_Project_Context_Exception( - 'Could not create action within test controller ' . $file - . ' with action name ' . $this->_forActionName - ); - } - - $actionParam = $this->getForActionName(); - $controllerParam = $this->_resource->getParentResource()->getForControllerName(); - //$moduleParam = null;// - - /* @var $controllerDirectoryResource Zend_Tool_Project_Profile_Resource */ - $controllerDirectoryResource = $this->_resource->getParentResource()->getParentResource(); - if ($controllerDirectoryResource->getParentResource()->getName() == 'TestApplicationModuleDirectory') { - $moduleParam = $controllerDirectoryResource->getParentResource()->getForModuleName(); - } else { - $moduleParam = 'default'; - } - - - - if ($actionParam == 'index' && $controllerParam == 'Index' && $moduleParam == 'default') { - $assert = '$this->assertQueryContentContains("div#welcome h3", "This is your project\'s main page");'; - } else { - $assert = <<assertQueryContentContains( - 'div#view-content p', - 'View script for controller ' . \$params['controller'] . ' and script/action name ' . \$params['action'] . '' - ); -EOS; - } - - $codeGenFile = Zend_CodeGenerator_Php_File::fromReflectedFileName($file, true, true); - $codeGenFile->getClass()->setMethod(array( - 'name' => 'test' . ucfirst($actionParam) . 'Action', - 'body' => << '$actionParam', 'controller' => '$controllerParam', 'module' => '$moduleParam'); -\$urlParams = \$this->urlizeOptions(\$params); -\$url = \$this->url(\$urlParams); -\$this->dispatch(\$url); - -// assertions -\$this->assertModule(\$urlParams['module']); -\$this->assertController(\$urlParams['controller']); -\$this->assertAction(\$urlParams['action']); -$assert - -EOS - )); - - file_put_contents($file, $codeGenFile->generate()); - - return $this; - } - - /** - * delete() - * - * @return Zend_Tool_Project_Context_Zf_ActionMethod - */ - public function delete() - { - // @todo do this - return $this; - } - - /** - * hasActionMethod() - * - * @param string $controllerPath - * @param string $actionName - * @return bool - */ - /* - public static function hasActionMethod($controllerPath, $actionName) - { - if (!file_exists($controllerPath)) { - return false; - } - - $controllerCodeGenFile = Zend_CodeGenerator_Php_File::fromReflectedFileName($controllerPath, true, true); - return $controllerCodeGenFile->getClass()->hasMethod('test' . $actionName . 'Action'); - } - */ - -} diff --git a/library/Zend/Tool/Project/Context/Zf/TestApplicationBootstrapFile.php b/library/Zend/Tool/Project/Context/Zf/TestApplicationBootstrapFile.php deleted file mode 100644 index 24da6fdcc9..0000000000 --- a/library/Zend/Tool/Project/Context/Zf/TestApplicationBootstrapFile.php +++ /dev/null @@ -1,57 +0,0 @@ -_forControllerName = $this->_resource->getAttribute('forControllerName'); - $this->_filesystemName = ucfirst($this->_forControllerName) . 'ControllerTest.php'; - parent::init(); - return $this; - } - - /** - * getPersistentAttributes() - * - * @return unknown - */ - public function getPersistentAttributes() - { - $attributes = array(); - - if ($this->_forControllerName) { - $attributes['forControllerName'] = $this->getForControllerName(); - } - - return $attributes; - } - - public function getForControllerName() - { - return $this->_forControllerName; - } - - /** - * getContents() - * - * @return string - */ - public function getContents() - { - - $filter = new Zend_Filter_Word_DashToCamelCase(); - - $className = $filter->filter($this->_forControllerName) . 'ControllerTest'; - - /* @var $controllerDirectoryResource Zend_Tool_Project_Profile_Resource */ - $controllerDirectoryResource = $this->_resource->getParentResource(); - if ($controllerDirectoryResource->getParentResource()->getName() == 'TestApplicationModuleDirectory') { - $className = $filter->filter(ucfirst($controllerDirectoryResource->getParentResource()->getForModuleName())) - . '_' . $className; - } - - $codeGenFile = new Zend_CodeGenerator_Php_File(array( - 'classes' => array( - new Zend_CodeGenerator_Php_Class(array( - 'name' => $className, - 'extendedClass' => 'Zend_Test_PHPUnit_ControllerTestCase', - 'methods' => array( - new Zend_CodeGenerator_Php_Method(array( - 'name' => 'setUp', - 'body' => <<bootstrap = new Zend_Application(APPLICATION_ENV, APPLICATION_PATH . '/configs/application.ini'); -parent::setUp(); -EOS - )) - ) - )) - ) - )); - - return $codeGenFile->generate(); - } - -} diff --git a/library/Zend/Tool/Project/Context/Zf/TestApplicationDirectory.php b/library/Zend/Tool/Project/Context/Zf/TestApplicationDirectory.php deleted file mode 100644 index f886b04b18..0000000000 --- a/library/Zend/Tool/Project/Context/Zf/TestApplicationDirectory.php +++ /dev/null @@ -1,57 +0,0 @@ -_filesystemName = $this->_forModuleName = $this->_resource->getAttribute('forModuleName'); - parent::init(); - return $this; - } - - /** - * getName() - * - * @return string - */ - public function getName() - { - return 'TestApplicationModuleDirectory'; - } - - /** - * getPersistentAttributes - * - * @return array - */ - public function getPersistentAttributes() - { - return array( - 'forModuleName' => $this->getForModuleName() - ); - } - - /** - * getModuleName() - * - * @return string - */ - public function getForModuleName() - { - return $this->_forModuleName; - } - - -} diff --git a/library/Zend/Tool/Project/Context/Zf/TestApplicationModulesDirectory.php b/library/Zend/Tool/Project/Context/Zf/TestApplicationModulesDirectory.php deleted file mode 100644 index 6d907cd044..0000000000 --- a/library/Zend/Tool/Project/Context/Zf/TestApplicationModulesDirectory.php +++ /dev/null @@ -1,57 +0,0 @@ -_forClassName = $this->_resource->getAttribute('forClassName'); - $this->_filesystemName = ucfirst(ltrim(strrchr($this->_forClassName, '_'), '_')) . 'Test.php'; - parent::init(); - return $this; - } - - /** - * getContents() - * - * @return string - */ - public function getContents() - { - - $filter = new Zend_Filter_Word_DashToCamelCase(); - - $className = $filter->filter($this->_forClassName) . 'Test'; - - $codeGenFile = new Zend_CodeGenerator_Php_File(array( - 'requiredFiles' => array( - 'PHPUnit/Framework/TestCase.php' - ), - 'classes' => array( - new Zend_CodeGenerator_Php_Class(array( - 'name' => $className, - 'extendedClass' => 'PHPUnit_Framework_TestCase', - 'methods' => array( - new Zend_CodeGenerator_Php_Method(array( - 'name' => 'setUp', - 'body' => ' /* Setup Routine */' - )), - new Zend_CodeGenerator_Php_Method(array( - 'name' => 'tearDown', - 'body' => ' /* Tear Down Routine */' - )) - ) - )) - ) - )); - - return $codeGenFile->generate(); - } - -} diff --git a/library/Zend/Tool/Project/Context/Zf/TestLibraryNamespaceDirectory.php b/library/Zend/Tool/Project/Context/Zf/TestLibraryNamespaceDirectory.php deleted file mode 100644 index 5e87e9e529..0000000000 --- a/library/Zend/Tool/Project/Context/Zf/TestLibraryNamespaceDirectory.php +++ /dev/null @@ -1,88 +0,0 @@ -_namespaceName = $this->_resource->getAttribute('namespaceName'); - $this->_filesystemName = $this->_namespaceName; - parent::init(); - return $this; - } - - /** - * getPersistentAttributes() - * - * @return array - */ - public function getPersistentAttributes() - { - $attributes = array(); - $attributes['namespaceName'] = $this->_namespaceName; - - return $attributes; - } - -} diff --git a/library/Zend/Tool/Project/Context/Zf/TestPHPUnitBootstrapFile.php b/library/Zend/Tool/Project/Context/Zf/TestPHPUnitBootstrapFile.php deleted file mode 100644 index da953fe886..0000000000 --- a/library/Zend/Tool/Project/Context/Zf/TestPHPUnitBootstrapFile.php +++ /dev/null @@ -1,88 +0,0 @@ - <<generate(); - } - -} diff --git a/library/Zend/Tool/Project/Context/Zf/TestPHPUnitConfigFile.php b/library/Zend/Tool/Project/Context/Zf/TestPHPUnitConfigFile.php deleted file mode 100644 index 48faaa9996..0000000000 --- a/library/Zend/Tool/Project/Context/Zf/TestPHPUnitConfigFile.php +++ /dev/null @@ -1,81 +0,0 @@ - - - ./application - - - ./library - - - - - - - - -EOS; - } - -} diff --git a/library/Zend/Tool/Project/Context/Zf/TestsDirectory.php b/library/Zend/Tool/Project/Context/Zf/TestsDirectory.php deleted file mode 100644 index b198268195..0000000000 --- a/library/Zend/Tool/Project/Context/Zf/TestsDirectory.php +++ /dev/null @@ -1,57 +0,0 @@ -_forControllerName = $this->_resource->getAttribute('forControllerName'); - $this->_filesystemName = $this->_convertControllerNameToFilesystemName($this->_forControllerName); - parent::init(); - return $this; - } - - /** - * getPersistentAttributes() - * - * @return array - */ - public function getPersistentAttributes() - { - return array( - 'forControllerName' => $this->_forControllerName - ); - } - - /** - * getName() - * - * @return string - */ - public function getName() - { - return 'ViewControllerScriptsDirectory'; - } - - protected function _convertControllerNameToFilesystemName($controllerName) - { - $filter = new Zend_Filter(); - $filter->addFilter(new Zend_Filter_Word_CamelCaseToDash()) - ->addFilter(new Zend_Filter_StringToLower()); - return $filter->filter($controllerName); - } - -} diff --git a/library/Zend/Tool/Project/Context/Zf/ViewFiltersDirectory.php b/library/Zend/Tool/Project/Context/Zf/ViewFiltersDirectory.php deleted file mode 100644 index cb49b3b14e..0000000000 --- a/library/Zend/Tool/Project/Context/Zf/ViewFiltersDirectory.php +++ /dev/null @@ -1,57 +0,0 @@ -_resource->getAttribute('forActionName')) { - $this->_forActionName = $forActionName; - $this->_filesystemName = $this->_convertActionNameToFilesystemName($forActionName) . '.phtml'; - } elseif ($scriptName = $this->_resource->getAttribute('scriptName')) { - $this->_scriptName = $scriptName; - $this->_filesystemName = $scriptName . '.phtml'; - } else { - throw new Exception('Either a forActionName or scriptName is required.'); - } - - parent::init(); - return $this; - } - - /** - * getPersistentAttributes() - * - * @return unknown - */ - public function getPersistentAttributes() - { - $attributes = array(); - - if ($this->_forActionName) { - $attributes['forActionName'] = $this->_forActionName; - } - - if ($this->_scriptName) { - $attributes['scriptName'] = $this->_scriptName; - } - - return $attributes; - } - - /** - * getContents() - * - * @return string - */ - public function getContents() - { - $contents = ''; - - $controllerName = $this->_resource->getParentResource()->getAttribute('forControllerName'); - - $viewsDirectoryResource = $this->_resource - ->getParentResource() // view script - ->getParentResource() // view controller dir - ->getParentResource(); // views dir - if ($viewsDirectoryResource->getParentResource()->getName() == 'ModuleDirectory') { - $moduleName = $viewsDirectoryResource->getParentResource()->getModuleName(); - } else { - $moduleName = 'default'; - } - - if ($this->_filesystemName == 'error.phtml') { // should also check that the above directory is forController=error - $contents .= << - - - - Zend Framework Default Application - - -

An error occurred

-

message ?>

- - exception)): ?> - -

Exception information:

-

- Message: exception->getMessage() ?> -

- -

Stack trace:

-
exception->getTraceAsString() ?>
-  
- -

Request Parameters:

-
escape(var_export(\$this->request->getParams(), true)) ?>
-  
- - - - - - -EOS; - } elseif ($this->_forActionName == 'index' && $controllerName == 'Index' && $moduleName == 'default') { - - $contents =<< - a:link, - a:visited - { - color: #0398CA; - } - - span#zf-name - { - color: #91BE3F; - } - - div#welcome - { - color: #FFFFFF; - background-image: url(http://framework.zend.com/images/bkg_header.jpg); - width: 600px; - height: 400px; - border: 2px solid #444444; - overflow: hidden; - text-align: center; - } - - div#more-information - { - background-image: url(http://framework.zend.com/images/bkg_body-bottom.gif); - height: 100%; - } - -
-

Welcome to the Zend Framework!

- -

This is your project's main page

- -
-

-

- Helpful Links:
- Zend Framework Website | - Zend Framework Manual -

-
-
-EOS; - - } else { - $controllerName = $this->_resource->getParentResource()->getAttribute('forControllerName'); - $actionName = $this->_forActionName; - $contents = <<
-
-

View script for controller $controllerName and script/action name $actionName

-
-EOS; - } - return $contents; - } - - protected function _convertActionNameToFilesystemName($actionName) - { - $filter = new Zend_Filter(); - $filter->addFilter(new Zend_Filter_Word_CamelCaseToDash()) - ->addFilter(new Zend_Filter_StringToLower()); - return $filter->filter($actionName); - } - -} diff --git a/library/Zend/Tool/Project/Context/Zf/ViewScriptsDirectory.php b/library/Zend/Tool/Project/Context/Zf/ViewScriptsDirectory.php deleted file mode 100644 index 7ab508a0e0..0000000000 --- a/library/Zend/Tool/Project/Context/Zf/ViewScriptsDirectory.php +++ /dev/null @@ -1,57 +0,0 @@ -_getZfPath(); - if ($zfPath != false) { - $zfIterator = new RecursiveDirectoryIterator($zfPath); - foreach ($rii = new RecursiveIteratorIterator($zfIterator, RecursiveIteratorIterator::SELF_FIRST) as $file) { - $relativePath = preg_replace('#^'.preg_quote(realpath($zfPath), '#').'#', '', realpath($file->getPath())) . DIRECTORY_SEPARATOR . $file->getFilename(); - if (strpos($relativePath, DIRECTORY_SEPARATOR . '.') !== false) { - continue; - } - - if ($file->isDir()) { - mkdir($this->getBaseDirectory() . DIRECTORY_SEPARATOR . $this->getFilesystemName() . $relativePath); - } else { - copy($file->getPathname(), $this->getBaseDirectory() . DIRECTORY_SEPARATOR . $this->getFilesystemName() . $relativePath); - } - - } - } - } - - /** - * _getZfPath() - * - * @return string|false - */ - protected function _getZfPath() - { - #require_once 'Zend/Loader.php'; - foreach (Zend_Loader::explodeIncludePath() as $includePath) { - if (!file_exists($includePath) || $includePath[0] == '.') { - continue; - } - - if (realpath($checkedPath = rtrim($includePath, '\\/') . '/Zend/Loader.php') !== false && file_exists($checkedPath)) { - return dirname($checkedPath); - } - } - - return false; - } - -} diff --git a/library/Zend/Tool/Project/Exception.php b/library/Zend/Tool/Project/Exception.php deleted file mode 100644 index c9fe2991ff..0000000000 --- a/library/Zend/Tool/Project/Exception.php +++ /dev/null @@ -1,37 +0,0 @@ -setOptions($options); - } - - $this->_topResources = new Zend_Tool_Project_Profile_Resource_Container(); - } - - /** - * Process options and either set a profile property or - * set a profile 'attribute' - * - * @param array $options - */ - public function setOptions(Array $options) - { - $this->setAttributes($options); - } - - /** - * getIterator() - reqruied by the RecursiveIterator interface - * - * @return RecursiveIteratorIterator - */ - public function getIterator() - { - #require_once 'Zend/Tool/Project/Profile/Iterator/EnabledResourceFilter.php'; - - return new RecursiveIteratorIterator( - new Zend_Tool_Project_Profile_Iterator_EnabledResourceFilter($this), - RecursiveIteratorIterator::SELF_FIRST - ); - } - - /** - * loadFromData() - Load a profile from data provided by the - * 'profilData' attribute - * - */ - public function loadFromData() - { - if (!isset($this->_attributes['profileData'])) { - #require_once 'Zend/Tool/Project/Exception.php'; - throw new Zend_Tool_Project_Exception('loadFromData() must have "profileData" set.'); - } - - $profileFileParser = new Zend_Tool_Project_Profile_FileParser_Xml(); - $profileFileParser->unserialize($this->_attributes['profileData'], $this); - - $this->rewind(); - } - - /** - * isLoadableFromFile() - can a profile be loaded from a file - * - * wether or not a profile can be loaded from the - * file in attribute 'projectProfileFile', or from a file named - * '.zfproject.xml' inside a directory in key 'projectDirectory' - * - * @return bool - */ - public function isLoadableFromFile() - { - if (!isset($this->_attributes['projectProfileFile']) && !isset($this->_attributes['projectDirectory'])) { - return false; - } - - if (isset($this->_attributes['projectProfileFile'])) { - $projectProfileFilePath = $this->_attributes['projectProfileFile']; - if (!file_exists($projectProfileFilePath)) { - return false; - } - } else { - $projectProfileFilePath = rtrim($this->_attributes['projectDirectory'], '/\\') . '/.zfproject.xml'; - if (!file_exists($projectProfileFilePath)) { - return false; - } - } - - return true; - } - - /** - * loadFromFile() - Load data from file - * - * this attempts to load a project profile file from a variety of locations depending - * on what information the user provided vie $options or attributes, specifically the - * 'projectDirectory' or 'projectProfileFile' - * - */ - public function loadFromFile() - { - // if no data is supplied, need either a projectProfileFile or a projectDirectory - if (!isset($this->_attributes['projectProfileFile']) && !isset($this->_attributes['projectDirectory'])) { - #require_once 'Zend/Tool/Project/Exception.php'; - throw new Zend_Tool_Project_Exception('loadFromFile() must have at least "projectProfileFile" or "projectDirectory" set.'); - } - - if (isset($this->_attributes['projectProfileFile'])) { - $projectProfileFilePath = $this->_attributes['projectProfileFile']; - if (!file_exists($projectProfileFilePath)) { - #require_once 'Zend/Tool/Project/Exception.php'; - throw new Zend_Tool_Project_Exception('"projectProfileFile" was supplied but file was not found at location ' . $projectProfileFilePath); - } - $this->_attributes['projectDirectory'] = dirname($projectProfileFilePath); - } else { - $projectProfileFilePath = rtrim($this->_attributes['projectDirectory'], '/\\') . '/.zfproject.xml'; - if (!file_exists($projectProfileFilePath)) { - #require_once 'Zend/Tool/Project/Exception.php'; - throw new Zend_Tool_Project_Exception('"projectDirectory" was supplied but no profile file file was not found at location ' . $projectProfileFilePath); - } - $this->_attributes['projectProfileFile'] = $projectProfileFilePath; - } - - $profileData = file_get_contents($projectProfileFilePath); - - $profileFileParser = new Zend_Tool_Project_Profile_FileParser_Xml(); - $profileFileParser->unserialize($profileData, $this); - - $this->rewind(); - } - - /** - * storeToFile() - store the current profile to file - * - * This will store the profile in memory to a place on disk determined by the attributes - * available, specifically if the key 'projectProfileFile' is available - * - */ - public function storeToFile() - { - $file = null; - - if (isset($this->_attributes['projectProfileFile'])) { - $file = $this->_attributes['projectProfileFile']; - } - - if ($file == null) { - #require_once 'Zend/Tool/Project/Exception.php'; - throw new Zend_Tool_Project_Exception('storeToFile() must have a "projectProfileFile" attribute set.'); - } - - $parser = new Zend_Tool_Project_Profile_FileParser_Xml(); - $xml = $parser->serialize($this); - file_put_contents($file, $xml); - } - - /** - * storeToData() - create a string representation of the profile in memory - * - * @return string - */ - public function storeToData() - { - $parser = new Zend_Tool_Project_Profile_FileParser_Xml(); - $xml = $parser->serialize($this); - return $xml; - } - - /** - * __toString() - cast this profile to string to be able to view it. - * - * @return string - */ - public function __toString() - { - $string = ''; - foreach ($this as $resource) { - $string .= $resource->getName() . PHP_EOL; - $rii = new RecursiveIteratorIterator($resource, RecursiveIteratorIterator::SELF_FIRST); - foreach ($rii as $item) { - $string .= str_repeat(' ', $rii->getDepth()+1) . $item->getName() - . ((count($attributes = $item->getAttributes()) > 0) ? ' [' . http_build_query($attributes) . ']' : '') - . PHP_EOL; - } - } - return $string; - } -} diff --git a/library/Zend/Tool/Project/Profile/Exception.php b/library/Zend/Tool/Project/Profile/Exception.php deleted file mode 100644 index b89fcd4404..0000000000 --- a/library/Zend/Tool/Project/Profile/Exception.php +++ /dev/null @@ -1,37 +0,0 @@ -_contextRepository = Zend_Tool_Project_Context_Repository::getInstance(); - } - - /** - * serialize() - * - * create an xml string from the provided profile - * - * @param Zend_Tool_Project_Profile $profile - * @return string - */ - public function serialize(Zend_Tool_Project_Profile $profile) - { - - $profile = clone $profile; - - $this->_profile = $profile; - $xmlElement = new SimpleXMLElement(''); - - if ($profile->hasAttribute('type')) { - $xmlElement->addAttribute('type', $profile->getAttribute('type')); - } - - if ($profile->hasAttribute('version')) { - $xmlElement->addAttribute('version', $profile->getAttribute('version')); - } - - self::_serializeRecurser($profile, $xmlElement); - - $doc = new DOMDocument('1.0'); - $doc->formatOutput = true; - $domnode = dom_import_simplexml($xmlElement); - $domnode = $doc->importNode($domnode, true); - $domnode = $doc->appendChild($domnode); - - return $doc->saveXML(); - } - - /** - * unserialize() - * - * Create a structure in the object $profile from the structure specficied - * in the xml string provided - * - * @param string xml data - * @param Zend_Tool_Project_Profile The profile to use as the top node - * @return Zend_Tool_Project_Profile - */ - public function unserialize($data, Zend_Tool_Project_Profile $profile) - { - if ($data == null) { - throw new Exception('contents not available to unserialize.'); - } - - $this->_profile = $profile; - - $xmlDataIterator = new SimpleXMLIterator($data); - - if ($xmlDataIterator->getName() != 'projectProfile') { - throw new Exception('Profiles must start with a projectProfile node'); - } - - if (isset($xmlDataIterator['type'])) { - $this->_profile->setAttribute('type', (string) $xmlDataIterator['type']); - } - - if (isset($xmlDataIterator['version'])) { - $this->_profile->setAttribute('version', (string) $xmlDataIterator['version']); - } - - // start un-serialization of the xml doc - $this->_unserializeRecurser($xmlDataIterator); - - // contexts should be initialized after the unwinding of the profile structure - $this->_lazyLoadContexts(); - - return $this->_profile; - - } - - /** - * _serializeRecurser() - * - * This method will be used to traverse the depths of the structure - * when *serializing* an xml structure into a string - * - * @param array $resources - * @param SimpleXmlElement $xmlNode - */ - protected function _serializeRecurser($resources, SimpleXmlElement $xmlNode) - { - // @todo find a better way to handle concurrency.. if no clone, _position in node gets messed up - //if ($resources instanceof Zend_Tool_Project_Profile_Resource) { - // $resources = clone $resources; - //} - - foreach ($resources as $resource) { - - if ($resource->isDeleted()) { - continue; - } - - $resourceName = $resource->getContext()->getName(); - $resourceName[0] = strtolower($resourceName[0]); - - $newNode = $xmlNode->addChild($resourceName); - - //$reflectionClass = new ReflectionClass($resource->getContext()); - - if ($resource->isEnabled() == false) { - $newNode->addAttribute('enabled', 'false'); - } - - foreach ($resource->getPersistentAttributes() as $paramName => $paramValue) { - $newNode->addAttribute($paramName, $paramValue); - } - - if ($resource->hasChildren()) { - self::_serializeRecurser($resource, $newNode); - } - - } - - } - - - /** - * _unserializeRecurser() - * - * This method will be used to traverse the depths of the structure - * as needed to *unserialize* the profile from an xmlIterator - * - * @param SimpleXMLIterator $xmlIterator - * @param Zend_Tool_Project_Profile_Resource $resource - */ - protected function _unserializeRecurser(SimpleXMLIterator $xmlIterator, Zend_Tool_Project_Profile_Resource $resource = null) - { - - foreach ($xmlIterator as $resourceName => $resourceData) { - - $contextName = $resourceName; - $subResource = new Zend_Tool_Project_Profile_Resource($contextName); - $subResource->setProfile($this->_profile); - - if ($resourceAttributes = $resourceData->attributes()) { - $attributes = array(); - foreach ($resourceAttributes as $attrName => $attrValue) { - $attributes[$attrName] = (string) $attrValue; - } - $subResource->setAttributes($attributes); - } - - if ($resource) { - $resource->append($subResource, false); - } else { - $this->_profile->append($subResource); - } - - if ($this->_contextRepository->isOverwritableContext($contextName) == false) { - $subResource->initializeContext(); - } - - if ($xmlIterator->hasChildren()) { - self::_unserializeRecurser($xmlIterator->getChildren(), $subResource); - } - } - } - - /** - * _lazyLoadContexts() - * - * This method will call initializeContext on the resources in a profile - * @todo determine if this method belongs inside the profile - * - */ - protected function _lazyLoadContexts() - { - - foreach ($this->_profile as $topResource) { - $rii = new RecursiveIteratorIterator($topResource, RecursiveIteratorIterator::SELF_FIRST); - foreach ($rii as $resource) { - $resource->initializeContext(); - } - } - - } - -} diff --git a/library/Zend/Tool/Project/Profile/Iterator/ContextFilter.php b/library/Zend/Tool/Project/Profile/Iterator/ContextFilter.php deleted file mode 100644 index b074614e43..0000000000 --- a/library/Zend/Tool/Project/Profile/Iterator/ContextFilter.php +++ /dev/null @@ -1,211 +0,0 @@ -_rawOptions = $options; - if ($options) { - $this->setOptions($options); - } - } - - /** - * setOptions() - * - * @param array $options - */ - public function setOptions(Array $options) - { - foreach ($options as $optionName => $optionValue) { - if (substr($optionName, -1, 1) != 's') { - $optionName .= 's'; - } - if (method_exists($this, 'set' . $optionName)) { - $this->{'set' . $optionName}($optionValue); - } - } - } - - /** - * setAcceptTypes() - * - * @param array|string $acceptTypes - * @return Zend_Tool_Project_Profile_Iterator_ContextFilter - */ - public function setAcceptTypes($acceptTypes) - { - if (!is_array($acceptTypes)) { - $acceptTypes = array($acceptTypes); - } - - $this->_acceptTypes = $acceptTypes; - return $this; - } - - /** - * setDenyTypes() - * - * @param array|string $denyTypes - * @return Zend_Tool_Project_Profile_Iterator_ContextFilter - */ - public function setDenyTypes($denyTypes) - { - if (!is_array($denyTypes)) { - $denyTypes = array($denyTypes); - } - - $this->_denyTypes = $denyTypes; - return $this; - } - - /** - * setAcceptNames() - * - * @param array|string $acceptNames - * @return Zend_Tool_Project_Profile_Iterator_ContextFilter - */ - public function setAcceptNames($acceptNames) - { - if (!is_array($acceptNames)) { - $acceptNames = array($acceptNames); - } - - foreach ($acceptNames as $n => $v) { - $acceptNames[$n] = strtolower($v); - } - - $this->_acceptNames = $acceptNames; - return $this; - } - - /** - * setDenyNames() - * - * @param array|string $denyNames - * @return Zend_Tool_Project_Profile_Iterator_ContextFilter - */ - public function setDenyNames($denyNames) - { - if (!is_array($denyNames)) { - $denyNames = array($denyNames); - } - - foreach ($denyNames as $n => $v) { - $denyNames[$n] = strtolower($v); - } - - $this->_denyNames = $denyNames; - return $this; - } - - /** - * accept() is required by teh RecursiveFilterIterator - * - * @return bool - */ - public function accept() - { - $currentItem = $this->current(); - - if (in_array(strtolower($currentItem->getName()), $this->_acceptNames)) { - return true; - } elseif (in_array(strtolower($currentItem->getName()), $this->_denyNames)) { - return false; - } - - foreach ($this->_acceptTypes as $acceptType) { - if ($currentItem->getContent() instanceof $acceptType) { - return true; - } - } - - foreach ($this->_denyTypes as $denyType) { - if ($currentItem->getContext() instanceof $denyType) { - return false; - } - } - - return true; - } - - /** - * getChildren() - * - * This is here due to a bug/design issue in PHP - * @link - * - * @return unknown - */ - function getChildren() - { - - if (empty($this->ref)) { - $this->ref = new ReflectionClass($this); - } - - return $this->ref->newInstance($this->getInnerIterator()->getChildren(), $this->_rawOptions); - } - -} diff --git a/library/Zend/Tool/Project/Profile/Iterator/EnabledResourceFilter.php b/library/Zend/Tool/Project/Profile/Iterator/EnabledResourceFilter.php deleted file mode 100644 index 65b46b6ff3..0000000000 --- a/library/Zend/Tool/Project/Profile/Iterator/EnabledResourceFilter.php +++ /dev/null @@ -1,43 +0,0 @@ -current()->isEnabled(); - } -} diff --git a/library/Zend/Tool/Project/Profile/Resource.php b/library/Zend/Tool/Project/Profile/Resource.php deleted file mode 100644 index 27bef92bfc..0000000000 --- a/library/Zend/Tool/Project/Profile/Resource.php +++ /dev/null @@ -1,262 +0,0 @@ -setContext($context); - } - - /** - * setContext() - * - * @param string|Zend_Tool_Project_Context_Interface $context - * @return Zend_Tool_Project_Profile_Resource - */ - public function setContext($context) - { - $this->_context = $context; - return $this; - } - - /** - * getContext() - * - * @return Zend_Tool_Project_Context_Interface - */ - public function getContext() - { - return $this->_context; - } - - /** - * getName() - Get the resource name - * - * Name is derived from the context name - * - * @return string - */ - public function getName() - { - if (is_string($this->_context)) { - return $this->_context; - } elseif ($this->_context instanceof Zend_Tool_Project_Context_Interface) { - return $this->_context->getName(); - } else { - throw new Zend_Tool_Project_Exception('Invalid context in resource'); - } - } - - /** - * setProfile() - * - * @param Zend_Tool_Project_Profile $profile - * @return Zend_Tool_Project_Profile_Resource - */ - public function setProfile(Zend_Tool_Project_Profile $profile) - { - $this->_profile = $profile; - return $this; - } - - /** - * getProfile - * - * @return Zend_Tool_Project_Profile - */ - public function getProfile() - { - return $this->_profile; - } - - /** - * getPersistentAttributes() - * - * @return array - */ - public function getPersistentAttributes() - { - if (method_exists($this->_context, 'getPersistentAttributes')) { - return $this->_context->getPersistentAttributes(); - } - - return array(); - } - - /** - * setEnabled() - * - * @param bool $enabled - * @return Zend_Tool_Project_Profile_Resource - */ - public function setEnabled($enabled = true) - { - // convert fuzzy types to bool - $this->_enabled = (!in_array($enabled, array('false', 'disabled', 0, -1, false), true)) ? true : false; - return $this; - } - - /** - * isEnabled() - * - * @return bool - */ - public function isEnabled() - { - return $this->_enabled; - } - - /** - * setDeleted() - * - * @param bool $deleted - * @return Zend_Tool_Project_Profile_Resource - */ - public function setDeleted($deleted = true) - { - $this->_deleted = (bool) $deleted; - return $this; - } - - /** - * isDeleted() - * - * @return Zend_Tool_Project_Profile_Resource - */ - public function isDeleted() - { - return $this->_deleted; - } - - /** - * initializeContext() - * - * @return Zend_Tool_Project_Profile_Resource - */ - public function initializeContext() - { - if ($this->_isContextInitialized) { - return; - } - if (is_string($this->_context)) { - $this->_context = Zend_Tool_Project_Context_Repository::getInstance()->getContext($this->_context); - } - - if (method_exists($this->_context, 'setResource')) { - $this->_context->setResource($this); - } - - if (method_exists($this->_context, 'init')) { - $this->_context->init(); - } - - $this->_isContextInitialized = true; - return $this; - } - - /** - * __toString() - * - * @return string - */ - public function __toString() - { - return $this->_context->getName(); - } - - /** - * __call() - * - * @param string $method - * @param array $arguments - * @return Zend_Tool_Project_Profile_Resource - */ - public function __call($method, $arguments) - { - if (method_exists($this->_context, $method)) { - if (!$this->isEnabled()) { - $this->setEnabled(true); - } - return call_user_func_array(array($this->_context, $method), $arguments); - } else { - throw new Zend_Tool_Project_Profile_Exception('cannot call ' . $method); - } - } - -} diff --git a/library/Zend/Tool/Project/Profile/Resource/Container.php b/library/Zend/Tool/Project/Profile/Resource/Container.php deleted file mode 100644 index 04d3d51a72..0000000000 --- a/library/Zend/Tool/Project/Profile/Resource/Container.php +++ /dev/null @@ -1,421 +0,0 @@ - - * - * - * - * @param Zend_Tool_Project_Profile_Resource_SearchConstraints|string|array $searchParameters - * @return Zend_Tool_Project_Profile_Resource - */ - public function search($matchSearchConstraints, $nonMatchSearchConstraints = null) - { - if (!$matchSearchConstraints instanceof Zend_Tool_Project_Profile_Resource_SearchConstraints) { - $matchSearchConstraints = new Zend_Tool_Project_Profile_Resource_SearchConstraints($matchSearchConstraints); - } - - $this->rewind(); - - /** - * @todo This should be re-written with better support for a filter iterator, its the way to go - */ - - if ($nonMatchSearchConstraints) { - $filterIterator = new Zend_Tool_Project_Profile_Iterator_ContextFilter($this, array('denyNames' => $nonMatchSearchConstraints)); - $riIterator = new RecursiveIteratorIterator($filterIterator, RecursiveIteratorIterator::SELF_FIRST); - } else { - $riIterator = new RecursiveIteratorIterator($this, RecursiveIteratorIterator::SELF_FIRST); - } - - $foundResource = false; - $currentConstraint = $matchSearchConstraints->getConstraint(); - $foundDepth = 0; - - foreach ($riIterator as $currentResource) { - - // if current depth is less than found depth, end - if ($riIterator->getDepth() < $foundDepth) { - break; - } - - if (strtolower($currentResource->getName()) == strtolower($currentConstraint->name)) { - - $paramsMatch = true; - - // @todo check to ensure params match (perhaps) - if (count($currentConstraint->params) > 0) { - $currentResourceAttributes = $currentResource->getAttributes(); - if (!is_array($currentConstraint->params)) { - #require_once 'Zend/Tool/Project/Profile/Exception.php'; - throw new Zend_Tool_Project_Profile_Exception('Search parameter specifics must be in the form of an array for key "' - . $currentConstraint->name .'"'); - } - foreach ($currentConstraint->params as $paramName => $paramValue) { - if (!isset($currentResourceAttributes[$paramName]) || $currentResourceAttributes[$paramName] != $paramValue) { - $paramsMatch = false; - break; - } - } - } - - if ($paramsMatch) { - $foundDepth = $riIterator->getDepth(); - - if (($currentConstraint = $matchSearchConstraints->getConstraint()) == null) { - $foundResource = $currentResource; - break; - } - } - - } - - } - - return $foundResource; - } - - /** - * createResourceAt() - * - * @param array|Zend_Tool_Project_Profile_Resource_SearchConstraints $appendResourceOrSearchConstraints - * @param string $context - * @param array $attributes - * @return Zend_Tool_Project_Profile_Resource - */ - public function createResourceAt($appendResourceOrSearchConstraints, $context, Array $attributes = array()) - { - if (!$appendResourceOrSearchConstraints instanceof Zend_Tool_Project_Profile_Resource_Container) { - if (($parentResource = $this->search($appendResourceOrSearchConstraints)) == false) { - #require_once 'Zend/Tool/Project/Profile/Exception.php'; - throw new Zend_Tool_Project_Profile_Exception('No node was found to append to.'); - } - } else { - $parentResource = $appendResourceOrSearchConstraints; - } - - return $parentResource->createResource($context, $attributes); - } - - /** - * createResource() - * - * Method to create a resource with a given context with specific attributes - * - * @param string $context - * @param array $attributes - * @return Zend_Tool_Project_Profile_Resource - */ - public function createResource($context, Array $attributes = array()) - { - if (is_string($context)) { - $contextRegistry = Zend_Tool_Project_Context_Repository::getInstance(); - if ($contextRegistry->hasContext($context)) { - $context = $contextRegistry->getContext($context); - } else { - #require_once 'Zend/Tool/Project/Profile/Exception.php'; - throw new Zend_Tool_Project_Profile_Exception('Context by name ' . $context . ' was not found in the context registry.'); - } - } elseif (!$context instanceof Zend_Tool_Project_Context_Interface) { - #require_once 'Zend/Tool/Project/Profile/Exception.php'; - throw new Zend_Tool_Project_Profile_Exception('Context must be of type string or Zend_Tool_Project_Context_Interface.'); - } - - $newResource = new Zend_Tool_Project_Profile_Resource($context); - - if ($attributes) { - $newResource->setAttributes($attributes); - } - - /** - * Interesting logic here: - * - * First set the parentResource (this will also be done inside append). This will allow - * the initialization routine to change the appendability of the parent resource. This - * is important to allow specific resources to be appendable by very specific sub-resources. - */ - $newResource->setParentResource($this); - $newResource->initializeContext(); - $this->append($newResource); - - return $newResource; - } - - /** - * setAttributes() - * - * persist the attributes if the resource will accept them - * - * @param array $attributes - * @return Zend_Tool_Project_Profile_Resource_Container - */ - public function setAttributes(Array $attributes) - { - foreach ($attributes as $attrName => $attrValue) { - $setMethod = 'set' . $attrName; - if (method_exists($this, $setMethod)) { - $this->{$setMethod}($attrValue); - } else { - $this->setAttribute($attrName, $attrValue); - } - } - return $this; - } - - /** - * getAttributes() - * - * @return array - */ - public function getAttributes() - { - return $this->_attributes; - } - - /** - * setAttribute() - * - * @param string $name - * @param mixed $value - * @return Zend_Tool_Project_Profile_Resource_Container - */ - public function setAttribute($name, $value) - { - $this->_attributes[$name] = $value; - return $this; - } - - /** - * getAttribute() - * - * @param string $name - * @return Zend_Tool_Project_Profile_Resource_Container - */ - public function getAttribute($name) - { - return (array_key_exists($name, $this->_attributes)) ? $this->_attributes[$name] : null; - } - - /** - * hasAttribute() - * - * @param string $name - * @return bool - */ - public function hasAttribute($name) - { - return array_key_exists($name, $this->_attributes); - } - - /** - * setAppendable() - * - * @param bool $appendable - * @return Zend_Tool_Project_Profile_Resource_Container - */ - public function setAppendable($appendable) - { - $this->_appendable = (bool) $appendable; - return $this; - } - - /** - * isAppendable() - * - * @return bool - */ - public function isAppendable() - { - return $this->_appendable; - } - - /** - * setParentResource() - * - * @param Zend_Tool_Project_Profile_Resource_Container $parentResource - * @return Zend_Tool_Project_Profile_Resource_Container - */ - public function setParentResource(Zend_Tool_Project_Profile_Resource_Container $parentResource) - { - $this->_parentResource = $parentResource; - return $this; - } - - /** - * getParentResource() - * - * @return Zend_Tool_Project_Profile_Resource_Container - */ - public function getParentResource() - { - return $this->_parentResource; - } - - /** - * append() - * - * @param Zend_Tool_Project_Profile_Resource_Container $resource - * @return Zend_Tool_Project_Profile_Resource_Container - */ - public function append(Zend_Tool_Project_Profile_Resource_Container $resource) - { - if (!$this->isAppendable()) { - throw new Exception('Resource by name ' . (string) $this . ' is not appendable'); - } - array_push($this->_subResources, $resource); - $resource->setParentResource($this); - - return $this; - } - - /** - * current() - required by RecursiveIterator - * - * @return Zend_Tool_Project_Profile_Resource - */ - public function current() - { - return current($this->_subResources); - } - - /** - * key() - required by RecursiveIterator - * - * @return int - */ - public function key() - { - return key($this->_subResources); - } - - /** - * next() - required by RecursiveIterator - * - * @return bool - */ - public function next() - { - return next($this->_subResources); - } - - /** - * rewind() - required by RecursiveIterator - * - * @return bool - */ - public function rewind() - { - return reset($this->_subResources); - } - - /** - * valid() - - required by RecursiveIterator - * - * @return bool - */ - public function valid() - { - return (bool) $this->current(); - } - - /** - * hasChildren() - * - * @return bool - */ - public function hasChildren() - { - return (count($this->_subResources > 0)) ? true : false; - } - - /** - * getChildren() - * - * @return array - */ - public function getChildren() - { - return $this->current(); - } - - /** - * count() - * - * @return int - */ - public function count() - { - return count($this->_subResources); - } - - /** - * __clone() - * - */ - public function __clone() - { - $this->rewind(); - foreach ($this->_subResources as $index => $resource) { - $this->_subResources[$index] = clone $resource; - } - } - -} diff --git a/library/Zend/Tool/Project/Profile/Resource/SearchConstraints.php b/library/Zend/Tool/Project/Profile/Resource/SearchConstraints.php deleted file mode 100644 index e43bbeb77f..0000000000 --- a/library/Zend/Tool/Project/Profile/Resource/SearchConstraints.php +++ /dev/null @@ -1,117 +0,0 @@ -addConstraint($options); - } elseif (is_array($options)) { - $this->setOptions($options); - } - } - - /** - * setOptions() - * - * @param array $option - * @return Zend_Tool_Project_Profile_Resource_SearchConstraints - */ - public function setOptions(Array $option) - { - foreach ($option as $optionName => $optionValue) { - if (is_int($optionName)) { - $this->addConstraint($optionValue); - } elseif (is_string($optionName)) { - $this->addConstraint(array('name' => $optionName, 'params' => $optionValue)); - } - } - - return $this; - } - - /** - * addConstraint() - * - * @param string|array $constraint - * @return Zend_Tool_Project_Profile_Resource_SearchConstraints - */ - public function addConstraint($constraint) - { - if (is_string($constraint)) { - $name = $constraint; - $params = array(); - } elseif (is_array($constraint)) { - $name = $constraint['name']; - $params = $constraint['params']; - } - - $constraint = $this->_makeConstraint($name, $params); - - array_push($this->_constraints, $constraint); - return $this; - } - - /** - * getConstraint() - * - * @return ArrayObject - */ - public function getConstraint() - { - return array_shift($this->_constraints); - } - - /** - * _makeConstraint - * - * @param string $name - * @param mixed $params - * @return ArrayObject - */ - protected function _makeConstraint($name, $params) - { - $value = array('name' => $name, 'params' => $params); - return new ArrayObject($value, ArrayObject::ARRAY_AS_PROPS); - } - -} diff --git a/library/Zend/Tool/Project/Provider/Abstract.php b/library/Zend/Tool/Project/Provider/Abstract.php deleted file mode 100644 index 3a85cb61f5..0000000000 --- a/library/Zend/Tool/Project/Provider/Abstract.php +++ /dev/null @@ -1,279 +0,0 @@ -addContextsFromDirectory( - dirname(dirname(__FILE__)) . '/Context/Zf/', 'Zend_Tool_Project_Context_Zf_' - ); - $contextRegistry->addContextsFromDirectory( - dirname(dirname(__FILE__)) . '/Context/Filesystem/', 'Zend_Tool_Project_Context_Filesystem_' - ); - - // determine if there are project specfic providers ONCE - $profilePath = $this->_findProfileDirectory(); - if ($this->_hasProjectProviderDirectory($profilePath . DIRECTORY_SEPARATOR . '.zfproject.xml')) { - $profile = $this->_loadProfile(); - // project providers directory resource - $ppd = $profile->search('ProjectProvidersDirectory'); - $ppd->loadProviders($this->_registry); - } - - self::$_isInitialized = true; - } - - // load up the extending providers required context classes - if ($contextClasses = $this->getContextClasses()) { - $this->_loadContextClassesIntoRegistry($contextClasses); - } - - } - - public function getContextClasses() - { - return array(); - } - - /** - * _getProject is designed to find if there is project file in the context of where - * the client has been called from.. The search order is as follows.. - * - traversing downwards from (PWD) - current working directory - * - if an enpoint variable has been registered in teh client registry - key=workingDirectory - * - if an ENV variable with the key ZFPROJECT_PATH is found - * - * @param bool $loadProfileFlag Whether or not to throw an exception when no profile is found - * @param string $projectDirectory The project directory to use to search - * @param bool $searchParentDirectories Whether or not to search upper level direcotries - * @return Zend_Tool_Project_Profile - */ - protected function _loadProfile($loadProfileFlag = self::NO_PROFILE_THROW_EXCEPTION, $projectDirectory = null, $searchParentDirectories = true) - { - $foundPath = $this->_findProfileDirectory($projectDirectory, $searchParentDirectories); - - if ($foundPath == false) { - if ($loadProfileFlag == self::NO_PROFILE_THROW_EXCEPTION) { - throw new Zend_Tool_Project_Provider_Exception('A project profile was not found.'); - } else { - return false; - } - } - - $profile = new Zend_Tool_Project_Profile(); - $profile->setAttribute('projectDirectory', $foundPath); - $profile->loadFromFile(); - $this->_loadedProfile = $profile; - return $profile; - } - - protected function _findProfileDirectory($projectDirectory = null, $searchParentDirectories = true) - { - // use the cwd if no directory was provided - if ($projectDirectory == null) { - $projectDirectory = getcwd(); - } elseif (realpath($projectDirectory) == false) { - throw new Zend_Tool_Project_Provider_Exception('The $projectDirectory supplied does not exist.'); - } - - $profile = new Zend_Tool_Project_Profile(); - - $parentDirectoriesArray = explode(DIRECTORY_SEPARATOR, ltrim($projectDirectory, DIRECTORY_SEPARATOR)); - while ($parentDirectoriesArray) { - $projectDirectoryAssembled = implode(DIRECTORY_SEPARATOR, $parentDirectoriesArray); - - if (DIRECTORY_SEPARATOR !== "\\") { - $projectDirectoryAssembled = DIRECTORY_SEPARATOR . $projectDirectoryAssembled; - } - - $profile->setAttribute('projectDirectory', $projectDirectoryAssembled); - if ($profile->isLoadableFromFile()) { - unset($profile); - return $projectDirectoryAssembled; - } - - // break after first run if we are not to check upper directories - if ($searchParentDirectories == false) { - break; - } - - array_pop($parentDirectoriesArray); - } - - return false; - } - - /** - * Load the project profile from the current working directory, if not throw exception - * - * @return Zend_Tool_Project_Profile - */ - protected function _loadProfileRequired() - { - $profile = $this->_loadProfile(); - if ($profile === false) { - #require_once 'Zend/Tool/Project/Provider/Exception.php'; - throw new Zend_Tool_Project_Provider_Exception('A project profile was not found in the current working directory.'); - } - return $profile; - } - - /** - * Return the currently loaded profile - * - * @return Zend_Tool_Project_Profile - */ - protected function _getProfile($loadProfileFlag = self::NO_PROFILE_THROW_EXCEPTION) - { - if (!$this->_loadedProfile) { - if (($this->_loadProfile($loadProfileFlag) === false) && ($loadProfileFlag === self::NO_PROFILE_RETURN_FALSE)) { - return false; - } - } - - return $this->_loadedProfile; - } - - /** - * _storeProfile() - * - * This method will store the profile into its proper location - * - */ - protected function _storeProfile() - { - $projectProfileFile = $this->_loadedProfile->search('ProjectProfileFile'); - - $name = $projectProfileFile->getContext()->getPath(); - - $this->_registry->getResponse()->appendContent('Updating project profile \'' . $name . '\''); - - $projectProfileFile->getContext()->save(); - } - - protected function _getContentForContext(Zend_Tool_Project_Context_Interface $context, $methodName, $parameters) - { - $storage = $this->_registry->getStorage(); - if (!$storage->isEnabled()) { - return false; - } - - if (!class_exists('Zend_Tool_Project_Context_Content_Engine')) { - #require_once 'Zend/Tool/Project/Context/Content/Engine.php'; - } - - $engine = new Zend_Tool_Project_Context_Content_Engine($storage); - return $engine->getContent($context, $methodName, $parameters); - } - - protected function _hasProjectProviderDirectory($pathToProfileFile) - { - // do some static analysis of the file so that we can determin whether or not to incure - // the cost of loading the profile before the system is fully bootstrapped - if (!file_exists($pathToProfileFile)) { - return false; - } - - $contents = file_get_contents($pathToProfileFile); - if (strstr($contents, 'addContextClass($contextClass); - } - } -} diff --git a/library/Zend/Tool/Project/Provider/Action.php b/library/Zend/Tool/Project/Provider/Action.php deleted file mode 100644 index a9a90e8902..0000000000 --- a/library/Zend/Tool/Project/Provider/Action.php +++ /dev/null @@ -1,242 +0,0 @@ -createResource('ActionMethod', array('actionName' => $actionName)); - - return $actionMethod; - } - - /** - * hasResource() - * - * @param Zend_Tool_Project_Profile $profile - * @param string $actionName - * @param string $controllerName - * @param string $moduleName - * @return Zend_Tool_Project_Profile_Resource - */ - public static function hasResource(Zend_Tool_Project_Profile $profile, $actionName, $controllerName, $moduleName = null) - { - if (!is_string($actionName)) { - throw new Zend_Tool_Project_Provider_Exception('Zend_Tool_Project_Provider_Action::createResource() expects \"actionName\" is the name of a action resource to create.'); - } - - if (!is_string($controllerName)) { - throw new Zend_Tool_Project_Provider_Exception('Zend_Tool_Project_Provider_Action::createResource() expects \"controllerName\" is the name of a controller resource to create.'); - } - - $controllerFile = self::_getControllerFileResource($profile, $controllerName, $moduleName); - - if ($controllerFile == null) { - throw new Zend_Tool_Project_Provider_Exception('Controller ' . $controllerName . ' was not found.'); - } - - return (($controllerFile->search(array('actionMethod' => array('actionName' => $actionName)))) instanceof Zend_Tool_Project_Profile_Resource); - } - - /** - * _getControllerFileResource() - * - * @param Zend_Tool_Project_Profile $profile - * @param string $controllerName - * @param string $moduleName - * @return Zend_Tool_Project_Profile_Resource - */ - protected static function _getControllerFileResource(Zend_Tool_Project_Profile $profile, $controllerName, $moduleName = null) - { - $profileSearchParams = array(); - - if ($moduleName != null && is_string($moduleName)) { - $profileSearchParams = array('modulesDirectory', 'moduleDirectory' => array('moduleName' => $moduleName)); - } - - $profileSearchParams[] = 'controllersDirectory'; - $profileSearchParams['controllerFile'] = array('controllerName' => $controllerName); - - return $profile->search($profileSearchParams); - } - - /** - * create() - * - * @param string $name Action name for controller, in camelCase format. - * @param string $controllerName Controller name action should be applied to. - * @param bool $viewIncluded Whether the view should the view be included. - * @param string $module Module name action should be applied to. - */ - public function create($name, $controllerName = 'Index', $viewIncluded = true, $module = null) - { - - $this->_loadProfile(); - - // get request/response object - $request = $this->_registry->getRequest(); - $response = $this->_registry->getResponse(); - - // determine if testing is enabled in the project - #require_once 'Zend/Tool/Project/Provider/Test.php'; - $testingEnabled = Zend_Tool_Project_Provider_Test::isTestingEnabled($this->_loadedProfile); - - if ($testingEnabled && !Zend_Tool_Project_Provider_Test::isPHPUnitAvailable()) { - $testingEnabled = false; - $response->appendContent( - 'Note: PHPUnit is required in order to generate controller test stubs.', - array('color' => array('yellow')) - ); - } - - // Check that there is not a dash or underscore, return if doesnt match regex - if (preg_match('#[_-]#', $name)) { - throw new Zend_Tool_Project_Provider_Exception('Action names should be camel cased.'); - } - - $originalName = $name; - $originalControllerName = $controllerName; - - // ensure it is camelCase (lower first letter) - $name = strtolower(substr($name, 0, 1)) . substr($name, 1); - - // ensure controller is MixedCase - $controllerName = ucfirst($controllerName); - - if (self::hasResource($this->_loadedProfile, $name, $controllerName, $module)) { - throw new Zend_Tool_Project_Provider_Exception('This controller (' . $controllerName . ') already has an action named (' . $name . ')'); - } - - $actionMethodResource = self::createResource($this->_loadedProfile, $name, $controllerName, $module); - - $testActionMethodResource = null; - if ($testingEnabled) { - $testActionMethodResource = Zend_Tool_Project_Provider_Test::createApplicationResource($this->_loadedProfile, $controllerName, $name, $module); - } - - // alert the user about inline converted names - $tense = (($request->isPretend()) ? 'would be' : 'is'); - - if ($name !== $originalName) { - $response->appendContent( - 'Note: The canonical action name that ' . $tense - . ' used with other providers is "' . $name . '";' - . ' not "' . $originalName . '" as supplied', - array('color' => array('yellow')) - ); - } - - if ($controllerName !== $originalControllerName) { - $response->appendContent( - 'Note: The canonical controller name that ' . $tense - . ' used with other providers is "' . $controllerName . '";' - . ' not "' . $originalControllerName . '" as supplied', - array('color' => array('yellow')) - ); - } - - unset($tense); - - if ($request->isPretend()) { - $response->appendContent( - 'Would create an action named ' . $name . - ' inside controller at ' . $actionMethodResource->getParentResource()->getContext()->getPath() - ); - - if ($testActionMethodResource) { - $response->appendContent('Would create an action test in ' . $testActionMethodResource->getParentResource()->getContext()->getPath()); - } - - } else { - $response->appendContent( - 'Creating an action named ' . $name . - ' inside controller at ' . $actionMethodResource->getParentResource()->getContext()->getPath() - ); - $actionMethodResource->create(); - - if ($testActionMethodResource) { - $response->appendContent('Creating an action test in ' . $testActionMethodResource->getParentResource()->getContext()->getPath()); - $testActionMethodResource->create(); - } - - $this->_storeProfile(); - } - - if ($viewIncluded) { - $viewResource = Zend_Tool_Project_Provider_View::createResource($this->_loadedProfile, $name, $controllerName, $module); - - if ($this->_registry->getRequest()->isPretend()) { - $response->appendContent( - 'Would create a view script for the ' . $name . ' action method at ' . $viewResource->getContext()->getPath() - ); - } else { - $response->appendContent( - 'Creating a view script for the ' . $name . ' action method at ' . $viewResource->getContext()->getPath() - ); - $viewResource->create(); - $this->_storeProfile(); - } - - } - - } - -} diff --git a/library/Zend/Tool/Project/Provider/Application.php b/library/Zend/Tool/Project/Provider/Application.php deleted file mode 100644 index d65f7feba8..0000000000 --- a/library/Zend/Tool/Project/Provider/Application.php +++ /dev/null @@ -1,87 +0,0 @@ -_loadProfile(self::NO_PROFILE_THROW_EXCEPTION); - - $originalClassNamePrefix = $classNamePrefix; - - if (substr($classNamePrefix, -1) != '_') { - $classNamePrefix .= '_'; - } - - $configFileResource = $profile->search('ApplicationConfigFile'); - $zc = $configFileResource->getAsZendConfig('production'); - if ($zc->appnamespace == $classNamePrefix) { - throw new Zend_Tool_Project_Exception('The requested name ' . $classNamePrefix . ' is already the prefix.'); - } - - // remove the old - $configFileResource->removeStringItem('appnamespace', 'production'); - $configFileResource->create(); - - // add the new - $configFileResource->addStringItem('appnamespace', $classNamePrefix, 'production', true); - $configFileResource->create(); - - // update the project profile - $applicationDirectory = $profile->search('ApplicationDirectory'); - $applicationDirectory->setClassNamePrefix($classNamePrefix); - - $response = $this->_registry->getResponse(); - - if ($originalClassNamePrefix !== $classNamePrefix) { - $response->appendContent( - 'Note: the name provided "' . $originalClassNamePrefix . '" was' - . ' altered to "' . $classNamePrefix . '" for correctness.', - array('color' => 'yellow') - ); - } - - // note to the user - $response->appendContent('Note: All existing models will need to be altered to this new namespace by hand', array('color' => 'yellow')); - $response->appendContent('application.ini updated with new appnamespace ' . $classNamePrefix); - - // store profile - $this->_storeProfile(); - } - -} diff --git a/library/Zend/Tool/Project/Provider/Controller.php b/library/Zend/Tool/Project/Provider/Controller.php deleted file mode 100644 index 5c8bf44a0c..0000000000 --- a/library/Zend/Tool/Project/Provider/Controller.php +++ /dev/null @@ -1,209 +0,0 @@ -createResource( - 'controllerFile', - array('controllerName' => $controllerName, 'moduleName' => $moduleName) - ); - - return $newController; - } - - /** - * hasResource() - * - * @param Zend_Tool_Project_Profile $profile - * @param string $controllerName - * @param string $moduleName - * @return boolean - */ - public static function hasResource(Zend_Tool_Project_Profile $profile, $controllerName, $moduleName = null) - { - if (!is_string($controllerName)) { - throw new Zend_Tool_Project_Provider_Exception('Zend_Tool_Project_Provider_Controller::createResource() expects \"controllerName\" is the name of a controller resource to create.'); - } - - $controllersDirectory = self::_getControllersDirectoryResource($profile, $moduleName); - return ($controllersDirectory &&($controllersDirectory->search(array('controllerFile' => array('controllerName' => $controllerName)))) instanceof Zend_Tool_Project_Profile_Resource); - } - - /** - * _getControllersDirectoryResource() - * - * @param Zend_Tool_Project_Profile $profile - * @param string $moduleName - * @return Zend_Tool_Project_Profile_Resource - */ - protected static function _getControllersDirectoryResource(Zend_Tool_Project_Profile $profile, $moduleName = null) - { - $profileSearchParams = array(); - - if ($moduleName != null && is_string($moduleName)) { - $profileSearchParams = array('modulesDirectory', 'moduleDirectory' => array('moduleName' => $moduleName)); - } - - $profileSearchParams[] = 'controllersDirectory'; - - return $profile->search($profileSearchParams); - } - - /** - * Create a new controller - * - * @param string $name The name of the controller to create, in camelCase. - * @param bool $indexActionIncluded Whether or not to create the index action. - */ - public function create($name, $indexActionIncluded = true, $module = null) - { - $this->_loadProfile(self::NO_PROFILE_THROW_EXCEPTION); - - // get request & response - $request = $this->_registry->getRequest(); - $response = $this->_registry->getResponse(); - - // determine if testing is enabled in the project - #require_once 'Zend/Tool/Project/Provider/Test.php'; - $testingEnabled = Zend_Tool_Project_Provider_Test::isTestingEnabled($this->_loadedProfile); - - if ($testingEnabled && !Zend_Tool_Project_Provider_Test::isPHPUnitAvailable()) { - $testingEnabled = false; - $response->appendContent( - 'Note: PHPUnit is required in order to generate controller test stubs.', - array('color' => array('yellow')) - ); - } - - $originalName = $name; - $name = ucfirst($name); - - if (self::hasResource($this->_loadedProfile, $name, $module)) { - throw new Zend_Tool_Project_Provider_Exception('This project already has a controller named ' . $name); - } - - // Check that there is not a dash or underscore, return if doesnt match regex - if (preg_match('#[_-]#', $name)) { - throw new Zend_Tool_Project_Provider_Exception('Controller names should be camel cased.'); - } - - try { - $controllerResource = self::createResource($this->_loadedProfile, $name, $module); - if ($indexActionIncluded) { - $indexActionResource = Zend_Tool_Project_Provider_Action::createResource($this->_loadedProfile, 'index', $name, $module); - $indexActionViewResource = Zend_Tool_Project_Provider_View::createResource($this->_loadedProfile, 'index', $name, $module); - } - if ($testingEnabled) { - $testActionResource = Zend_Tool_Project_Provider_Test::createApplicationResource($this->_loadedProfile, $name, 'index', $module); - } - - } catch (Exception $e) { - $response->setException($e); - return; - } - - // determime if we need to note to the user about the name - if (($name !== $originalName)) { - $tense = (($request->isPretend()) ? 'would be' : 'is'); - $response->appendContent( - 'Note: The canonical controller name that ' . $tense - . ' used with other providers is "' . $name . '";' - . ' not "' . $originalName . '" as supplied', - array('color' => array('yellow')) - ); - unset($tense); - } - - // do the creation - if ($request->isPretend()) { - - $response->appendContent('Would create a controller at ' . $controllerResource->getContext()->getPath()); - - if (isset($indexActionResource)) { - $response->appendContent('Would create an index action method in controller ' . $name); - $response->appendContent('Would create a view script for the index action method at ' . $indexActionViewResource->getContext()->getPath()); - } - - if ($testingEnabled) { - $response->appendContent('Would create a controller test file at ' . $testActionResource->getParentResource()->getContext()->getPath()); - } - - } else { - - $response->appendContent('Creating a controller at ' . $controllerResource->getContext()->getPath()); - $controllerResource->create(); - - if (isset($indexActionResource)) { - $response->appendContent('Creating an index action method in controller ' . $name); - $indexActionResource->create(); - $response->appendContent('Creating a view script for the index action method at ' . $indexActionViewResource->getContext()->getPath()); - $indexActionViewResource->create(); - } - - if ($testingEnabled) { - $response->appendContent('Creating a controller test file at ' . $testActionResource->getParentResource()->getContext()->getPath()); - $testActionResource->getParentResource()->create(); - $testActionResource->create(); - } - - $this->_storeProfile(); - } - - } - - - -} diff --git a/library/Zend/Tool/Project/Provider/DbAdapter.php b/library/Zend/Tool/Project/Provider/DbAdapter.php deleted file mode 100644 index 069b35f267..0000000000 --- a/library/Zend/Tool/Project/Provider/DbAdapter.php +++ /dev/null @@ -1,139 +0,0 @@ -_loadProfile(self::NO_PROFILE_THROW_EXCEPTION); - - $appConfigFileResource = $profile->search('applicationConfigFile'); - - if ($appConfigFileResource == false) { - throw new Zend_Tool_Project_Exception('A project with an application config file is required to use this provider.'); - } - - $this->_appConfigFilePath = $appConfigFileResource->getPath(); - - $this->_config = new Zend_Config_Ini($this->_appConfigFilePath, null, array('skipExtends' => true, 'allowModifications' => true)); - - if ($sectionName != 'production') { - $this->_sectionName = $sectionName; - } - - if (!isset($this->_config->{$this->_sectionName})) { - throw new Zend_Tool_Project_Exception('The config does not have a ' . $this->_sectionName . ' section.'); - } - - if (isset($this->_config->{$this->_sectionName}->resources->db)) { - throw new Zend_Tool_Project_Exception('The config already has a db resource configured in section ' . $this->_sectionName . '.'); - } - - if ($dsn) { - $this->_configureViaDSN($dsn); - //} elseif ($interactivelyPrompt) { - // $this->_promptForConfig(); - } else { - $this->_registry->getResponse()->appendContent('Nothing to do!'); - } - - - } - - protected function _configureViaDSN($dsn) - { - $dsnVars = array(); - - if (strpos($dsn, '=') === false) { - throw new Zend_Tool_Project_Provider_Exception('At least one name value pair is expected, typcially ' - . 'in the format of "adapter=Mysqli&username=uname&password=mypass&dbname=mydb"' - ); - } - - parse_str($dsn, $dsnVars); - - // parse_str suffers when magic_quotes is enabled - if (get_magic_quotes_gpc()) { - array_walk_recursive($dsnVars, array($this, '_cleanMagicQuotesInValues')); - } - - $dbConfigValues = array('resources' => array('db' => null)); - - if (isset($dsnVars['adapter'])) { - $dbConfigValues['resources']['db']['adapter'] = $dsnVars['adapter']; - unset($dsnVars['adapter']); - } - - $dbConfigValues['resources']['db']['params'] = $dsnVars; - - $isPretend = $this->_registry->getRequest()->isPretend(); - - // get the config resource - $applicationConfig = $this->_loadedProfile->search('ApplicationConfigFile'); - $applicationConfig->addItem($dbConfigValues, $this->_sectionName, null); - - $response = $this->_registry->getResponse(); - - if ($isPretend) { - $response->appendContent('A db configuration for the ' . $this->_sectionName - . ' section would be written to the application config file with the following contents: ' - ); - $response->appendContent($applicationConfig->getContents()); - } else { - $applicationConfig->create(); - $response->appendContent('A db configuration for the ' . $this->_sectionName - . ' section has been written to the application config file.' - ); - } - } - - protected function _cleanMagicQuotesInValues(&$value, $key) - { - $value = stripslashes($value); - } - -} diff --git a/library/Zend/Tool/Project/Provider/DbTable.php b/library/Zend/Tool/Project/Provider/DbTable.php deleted file mode 100644 index 128e519828..0000000000 --- a/library/Zend/Tool/Project/Provider/DbTable.php +++ /dev/null @@ -1,225 +0,0 @@ - array('moduleName' => $moduleName)); - } - - $profileSearchParams[] = 'modelsDirectory'; - - $modelsDirectory = $profile->search($profileSearchParams); - - if (!($modelsDirectory instanceof Zend_Tool_Project_Profile_Resource)) { - throw new Zend_Tool_Project_Provider_Exception( - 'A models directory was not found' . - (($moduleName) ? ' for module ' . $moduleName . '.' : '.') - ); - } - - if (!($dbTableDirectory = $modelsDirectory->search('DbTableDirectory'))) { - $dbTableDirectory = $modelsDirectory->createResource('DbTableDirectory'); - } - - $dbTableFile = $dbTableDirectory->createResource('DbTableFile', array('dbTableName' => $dbTableName, 'actualTableName' => $actualTableName)); - - return $dbTableFile; - } - - public static function hasResource(Zend_Tool_Project_Profile $profile, $dbTableName, $moduleName = null) - { - $profileSearchParams = array(); - - if ($moduleName != null && is_string($moduleName)) { - $profileSearchParams = array('modulesDirectory', 'moduleDirectory' => array('moduleName' => $moduleName)); - } - - $profileSearchParams[] = 'modelsDirectory'; - - $modelsDirectory = $profile->search($profileSearchParams); - - if (!($modelsDirectory instanceof Zend_Tool_Project_Profile_Resource) - || !($dbTableDirectory = $modelsDirectory->search('DbTableDirectory'))) { - return false; - } - - $dbTableFile = $dbTableDirectory->search(array('DbTableFile' => array('dbTableName' => $dbTableName))); - - return ($dbTableFile instanceof Zend_Tool_Project_Profile_Resource) ? true : false; - } - - - public function create($name, $actualTableName, $module = null, $forceOverwrite = false) - { - $this->_loadProfile(self::NO_PROFILE_THROW_EXCEPTION); - - // Check that there is not a dash or underscore, return if doesnt match regex - if (preg_match('#[_-]#', $name)) { - throw new Zend_Tool_Project_Provider_Exception('DbTable names should be camel cased.'); - } - - $originalName = $name; - $name = ucfirst($name); - - if ($actualTableName == '') { - throw new Zend_Tool_Project_Provider_Exception('You must provide both the DbTable name as well as the actual db table\'s name.'); - } - - if (self::hasResource($this->_loadedProfile, $name, $module)) { - throw new Zend_Tool_Project_Provider_Exception('This project already has a DbTable named ' . $name); - } - - // get request/response object - $request = $this->_registry->getRequest(); - $response = $this->_registry->getResponse(); - - // alert the user about inline converted names - $tense = (($request->isPretend()) ? 'would be' : 'is'); - - if ($name !== $originalName) { - $response->appendContent( - 'Note: The canonical model name that ' . $tense - . ' used with other providers is "' . $name . '";' - . ' not "' . $originalName . '" as supplied', - array('color' => array('yellow')) - ); - } - - try { - $tableResource = self::createResource($this->_loadedProfile, $name, $actualTableName, $module); - } catch (Exception $e) { - $response = $this->_registry->getResponse(); - $response->setException($e); - return; - } - - // do the creation - if ($request->isPretend()) { - $response->appendContent('Would create a DbTable at ' . $tableResource->getContext()->getPath()); - } else { - $response->appendContent('Creating a DbTable at ' . $tableResource->getContext()->getPath()); - $tableResource->create(); - $this->_storeProfile(); - } - } - - /** - * @param string $module Module name action should be applied to. - * @param bool $forceOverwrite Whether should force overwriting previous classes generated - * @return void - */ - public function createFromDatabase($module = null, $forceOverwrite = false) - { - $this->_loadProfile(self::NO_PROFILE_THROW_EXCEPTION); - - $bootstrapResource = $this->_loadedProfile->search('BootstrapFile'); - - /* @var $zendApp Zend_Application */ - $zendApp = $bootstrapResource->getApplicationInstance(); - - try { - $zendApp->bootstrap('db'); - } catch (Zend_Application_Exception $e) { - throw new Zend_Tool_Project_Provider_Exception('Db resource not available, you might need to configure a DbAdapter.'); - return; - } - - /* @var $db Zend_Db_Adapter_Abstract */ - $db = $zendApp->getBootstrap()->getResource('db'); - - $tableResources = array(); - foreach ($db->listTables() as $actualTableName) { - - $dbTableName = $this->_convertTableNameToClassName($actualTableName); - - if (!$forceOverwrite && self::hasResource($this->_loadedProfile, $dbTableName, $module)) { - throw new Zend_Tool_Project_Provider_Exception( - 'This DbTable resource already exists, if you wish to overwrite it, ' - . 'pass the "forceOverwrite" flag to this provider.' - ); - } - - $tableResources[] = self::createResource( - $this->_loadedProfile, - $dbTableName, - $actualTableName, - $module - ); - } - - if (count($tableResources) == 0) { - $this->_registry->getResponse()->appendContent('There are no tables in the selected database to write.'); - } - - // do the creation - if ($this->_registry->getRequest()->isPretend()) { - - foreach ($tableResources as $tableResource) { - $this->_registry->getResponse()->appendContent('Would create a DbTable at ' . $tableResource->getContext()->getPath()); - } - - } else { - - foreach ($tableResources as $tableResource) { - $this->_registry->getResponse()->appendContent('Creating a DbTable at ' . $tableResource->getContext()->getPath()); - $tableResource->create(); - } - - $this->_storeProfile(); - } - - - } - - protected function _convertTableNameToClassName($tableName) - { - if ($this->_nameFilter == null) { - $this->_nameFilter = new Zend_Filter(); - $this->_nameFilter - ->addFilter(new Zend_Filter_Word_UnderscoreToCamelCase()); - } - - return $this->_nameFilter->filter($tableName); - } - -} diff --git a/library/Zend/Tool/Project/Provider/Exception.php b/library/Zend/Tool/Project/Provider/Exception.php deleted file mode 100644 index d7c6ad7a6a..0000000000 --- a/library/Zend/Tool/Project/Provider/Exception.php +++ /dev/null @@ -1,37 +0,0 @@ -createResource( - 'formFile', - array('formName' => $formName, 'moduleName' => $moduleName) - ); - - return $newForm; - } - - /** - * hasResource() - * - * @param Zend_Tool_Project_Profile $profile - * @param string $formName - * @param string $moduleName - * @return Zend_Tool_Project_Profile_Resource - */ - public static function hasResource(Zend_Tool_Project_Profile $profile, $formName, $moduleName = null) - { - if (!is_string($formName)) { - throw new Zend_Tool_Project_Provider_Exception('Zend_Tool_Project_Provider_Form::createResource() expects \"formName\" is the name of a form resource to check for existence.'); - } - - $formsDirectory = self::_getFormsDirectoryResource($profile, $moduleName); - return (($formsDirectory->search(array('formFile' => array('formName' => $formName)))) instanceof Zend_Tool_Project_Profile_Resource); - } - - /** - * _getFormsDirectoryResource() - * - * @param Zend_Tool_Project_Profile $profile - * @param string $moduleName - * @return Zend_Tool_Project_Profile_Resource - */ - protected static function _getFormsDirectoryResource(Zend_Tool_Project_Profile $profile, $moduleName = null) - { - $profileSearchParams = array(); - - if ($moduleName != null && is_string($moduleName)) { - $profileSearchParams = array('modulesDirectory', 'moduleDirectory' => array('moduleName' => $moduleName)); - } - - $profileSearchParams[] = 'formsDirectory'; - - return $profile->search($profileSearchParams); - } - - public function enable($module = null) - { - $this->_loadProfile(self::NO_PROFILE_THROW_EXCEPTION); - - // determine if testing is enabled in the project - $testingEnabled = Zend_Tool_Project_Provider_Test::isTestingEnabled($this->_loadedProfile); - - $formDirectoryResource = self::_getFormsDirectoryResource($this->_loadedProfile, $module); - - if ($formDirectoryResource->isEnabled()) { - throw new Zend_Tool_Project_Provider_Exception('This project already has forms enabled.'); - } else { - if ($this->_registry->getRequest()->isPretend()) { - $this->_registry->getResponse()->appendContent('Would enable forms directory at ' . $formDirectoryResource->getContext()->getPath()); - } else { - $this->_registry->getResponse()->appendContent('Enabling forms directory at ' . $formDirectoryResource->getContext()->getPath()); - $formDirectoryResource->setEnabled(true); - $formDirectoryResource->create(); - $this->_storeProfile(); - } - - } - } - - /** - * Create a new form - * - * @param string $name - * @param string $module - */ - public function create($name, $module = null) - { - $this->_loadProfile(self::NO_PROFILE_THROW_EXCEPTION); - - // determine if testing is enabled in the project - $testingEnabled = Zend_Tool_Project_Provider_Test::isTestingEnabled($this->_loadedProfile); - - if (self::hasResource($this->_loadedProfile, $name, $module)) { - throw new Zend_Tool_Project_Provider_Exception('This project already has a form named ' . $name); - } - - // Check that there is not a dash or underscore, return if doesnt match regex - if (preg_match('#[_-]#', $name)) { - throw new Zend_Tool_Project_Provider_Exception('Form names should be camel cased.'); - } - - $name = ucwords($name); - - try { - $formResource = self::createResource($this->_loadedProfile, $name, $module); - - if ($testingEnabled) { - $testFormResource = null; - // $testFormResource = Zend_Tool_Project_Provider_Test::createApplicationResource($this->_loadedProfile, $name, 'index', $module); - } - - } catch (Exception $e) { - $response = $this->_registry->getResponse(); - $response->setException($e); - return; - } - - // do the creation - if ($this->_registry->getRequest()->isPretend()) { - - $this->_registry->getResponse()->appendContent('Would create a form at ' . $formResource->getContext()->getPath()); - - if ($testFormResource) { - $this->_registry->getResponse()->appendContent('Would create a form test file at ' . $testFormResource->getContext()->getPath()); - } - - } else { - - $this->_registry->getResponse()->appendContent('Creating a form at ' . $formResource->getContext()->getPath()); - $formResource->create(); - - if ($testFormResource) { - $this->_registry->getResponse()->appendContent('Creating a form test file at ' . $testFormResource->getContext()->getPath()); - $testFormResource->create(); - } - - $this->_storeProfile(); - } - - } - - -} diff --git a/library/Zend/Tool/Project/Provider/Layout.php b/library/Zend/Tool/Project/Provider/Layout.php deleted file mode 100644 index b0d0c20231..0000000000 --- a/library/Zend/Tool/Project/Provider/Layout.php +++ /dev/null @@ -1,140 +0,0 @@ -search('applicationDirectory'); - $layoutDirectory = $applicationDirectory->search('layoutsDirectory'); - - if ($layoutDirectory == false) { - $layoutDirectory = $applicationDirectory->createResource('layoutsDirectory'); - } - - $layoutScriptsDirectory = $layoutDirectory->search('layoutScriptsDirectory'); - - if ($layoutScriptsDirectory == false) { - $layoutScriptsDirectory = $layoutDirectory->createResource('layoutScriptsDirectory'); - } - - $layoutScriptFile = $layoutScriptsDirectory->search('layoutScriptFile', array('layoutName' => 'layout')); - - if ($layoutScriptFile == false) { - $layoutScriptFile = $layoutScriptsDirectory->createResource('layoutScriptFile', array('layoutName' => 'layout')); - } - - return $layoutScriptFile; - } - - public function enable() - { - $profile = $this->_loadProfile(self::NO_PROFILE_THROW_EXCEPTION); - - $applicationConfigResource = $profile->search('ApplicationConfigFile'); - - if (!$applicationConfigResource) { - throw new Zend_Tool_Project_Exception('A project with an application config file is required to use this provider.'); - } - - $zc = $applicationConfigResource->getAsZendConfig(); - - if (isset($zc->resources) && isset($zc->resources->layout)) { - $this->_registry->getResponse()->appendContent('A layout resource already exists in this project\'s application configuration file.'); - return; - } - - if ($this->_registry->getRequest()->isPretend()) { - $this->_registry->getResponse()->appendContent('Would add "resources.layout.layoutPath" key to the application config file.'); - } else { - $applicationConfigResource->addStringItem('resources.layout.layoutPath', $this->_layoutPath, 'production', false); - $applicationConfigResource->create(); - - $this->_registry->getResponse()->appendContent('A layout entry has been added to the application config file.'); - - $layoutScriptFile = self::createResource($profile); - if (!$layoutScriptFile->exists()) { - $layoutScriptFile->create(); - $this->_registry->getResponse()->appendContent( - 'A default layout has been created at ' - . $layoutScriptFile->getPath() - ); - - } - - $this->_storeProfile(); - } - } - - public function disable() - { - $profile = $this->_loadProfile(self::NO_PROFILE_THROW_EXCEPTION); - - $applicationConfigResource = $this->_getApplicationConfigResource($profile); - $zc = $applicationConfigResource->getAsZendConfig(); - - if (isset($zc->resources) && !isset($zc->resources->layout)) { - $this->_registry->getResponse()->appendContent('No layout configuration exists in application config file.'); - return; - } - - if ($this->_registry->getRequest()->isPretend()) { - $this->_registry->getResponse()->appendContent('Would remove "resources.layout.layoutPath" key from the application config file.'); - } else { - - // Remove the resources.layout.layoutPath directive from application config - $applicationConfigResource->removeStringItem('resources.layout.layoutPath', $this->_layoutPath, 'production', false); - $applicationConfigResource->create(); - - // Tell the user about the good work we've done - $this->_registry->getResponse()->appendContent('Layout entry has been removed from the application config file.'); - - $this->_storeProfile(); - } - } - - protected function _getApplicationConfigResource(Zend_Tool_Project_Profile $profile) - { - $applicationConfigResource = $profile->search('ApplicationConfigFile'); - if (!$applicationConfigResource) { - throw new Zend_Tool_Project_Exception('A project with an application config file is required to use this provider.'); - } - - return $applicationConfigResource; - } -} diff --git a/library/Zend/Tool/Project/Provider/Manifest.php b/library/Zend/Tool/Project/Provider/Manifest.php deleted file mode 100644 index 4ca948acdb..0000000000 --- a/library/Zend/Tool/Project/Provider/Manifest.php +++ /dev/null @@ -1,75 +0,0 @@ -createResource( - 'modelFile', - array('modelName' => $modelName, 'moduleName' => $moduleName) - ); - - return $newModel; - } - - /** - * hasResource() - * - * @param Zend_Tool_Project_Profile $profile - * @param string $modelName - * @param string $moduleName - * @return Zend_Tool_Project_Profile_Resource - */ - public static function hasResource(Zend_Tool_Project_Profile $profile, $modelName, $moduleName = null) - { - if (!is_string($modelName)) { - throw new Zend_Tool_Project_Provider_Exception('Zend_Tool_Project_Provider_Model::createResource() expects \"modelName\" is the name of a model resource to check for existence.'); - } - - $modelsDirectory = self::_getModelsDirectoryResource($profile, $moduleName); - - if (!$modelsDirectory instanceof Zend_Tool_Project_Profile_Resource) { - return false; - } - - return (($modelsDirectory->search(array('modelFile' => array('modelName' => $modelName)))) instanceof Zend_Tool_Project_Profile_Resource); - } - - /** - * _getModelsDirectoryResource() - * - * @param Zend_Tool_Project_Profile $profile - * @param string $moduleName - * @return Zend_Tool_Project_Profile_Resource - */ - protected static function _getModelsDirectoryResource(Zend_Tool_Project_Profile $profile, $moduleName = null) - { - $profileSearchParams = array(); - - if ($moduleName != null && is_string($moduleName)) { - $profileSearchParams = array('modulesDirectory', 'moduleDirectory' => array('moduleName' => $moduleName)); - } - - $profileSearchParams[] = 'modelsDirectory'; - - return $profile->search($profileSearchParams); - } - - /** - * Create a new model - * - * @param string $name - * @param string $module - */ - public function create($name, $module = null) - { - $this->_loadProfile(self::NO_PROFILE_THROW_EXCEPTION); - - $originalName = $name; - - $name = ucwords($name); - - // determine if testing is enabled in the project - $testingEnabled = false; //Zend_Tool_Project_Provider_Test::isTestingEnabled($this->_loadedProfile); - $testModelResource = null; - - // Check that there is not a dash or underscore, return if doesnt match regex - if (preg_match('#[_-]#', $name)) { - throw new Zend_Tool_Project_Provider_Exception('Model names should be camel cased.'); - } - - if (self::hasResource($this->_loadedProfile, $name, $module)) { - throw new Zend_Tool_Project_Provider_Exception('This project already has a model named ' . $name); - } - - // get request/response object - $request = $this->_registry->getRequest(); - $response = $this->_registry->getResponse(); - - // alert the user about inline converted names - $tense = (($request->isPretend()) ? 'would be' : 'is'); - - if ($name !== $originalName) { - $response->appendContent( - 'Note: The canonical model name that ' . $tense - . ' used with other providers is "' . $name . '";' - . ' not "' . $originalName . '" as supplied', - array('color' => array('yellow')) - ); - } - - try { - $modelResource = self::createResource($this->_loadedProfile, $name, $module); - - if ($testingEnabled) { - // $testModelResource = Zend_Tool_Project_Provider_Test::createApplicationResource($this->_loadedProfile, $name, 'index', $module); - } - - } catch (Exception $e) { - $response->setException($e); - return; - } - - // do the creation - if ($request->isPretend()) { - - $response->appendContent('Would create a model at ' . $modelResource->getContext()->getPath()); - - if ($testModelResource) { - $response->appendContent('Would create a model test file at ' . $testModelResource->getContext()->getPath()); - } - - } else { - - $response->appendContent('Creating a model at ' . $modelResource->getContext()->getPath()); - $modelResource->create(); - - if ($testModelResource) { - $response->appendContent('Creating a model test file at ' . $testModelResource->getContext()->getPath()); - $testModelResource->create(); - } - - $this->_storeProfile(); - } - - } - - -} diff --git a/library/Zend/Tool/Project/Provider/Module.php b/library/Zend/Tool/Project/Provider/Module.php deleted file mode 100644 index 4405bc8a1a..0000000000 --- a/library/Zend/Tool/Project/Provider/Module.php +++ /dev/null @@ -1,181 +0,0 @@ -search('applicationDirectory'); - $targetModuleEnabledResources = array( - 'ControllersDirectory', 'ModelsDirectory', 'ViewsDirectory', - 'ViewScriptsDirectory', 'ViewHelpersDirectory', 'ViewFiltersDirectory' - ); - } - - // find the actual modules directory we will use to house our module - $modulesDirectory = $profile->search('modulesDirectory'); - - // if there is a module directory already, except - if ($modulesDirectory->search(array('moduleDirectory' => array('moduleName' => $moduleName)))) { - throw new Zend_Tool_Project_Provider_Exception('A module named "' . $moduleName . '" already exists.'); - } - - // create the module directory - $moduleDirectory = $modulesDirectory->createResource('moduleDirectory', array('moduleName' => $moduleName)); - - // create a context filter so that we can pull out only what we need from the module skeleton - $moduleContextFilterIterator = new Zend_Tool_Project_Profile_Iterator_ContextFilter( - $targetModuleResource, - array( - 'denyNames' => array('ModulesDirectory', 'ViewControllerScriptsDirectory'), - 'denyType' => 'Zend_Tool_Project_Context_Filesystem_File' - ) - ); - - // the iterator for the module skeleton - $targetIterator = new RecursiveIteratorIterator($moduleContextFilterIterator, RecursiveIteratorIterator::SELF_FIRST); - - // initialize some loop state information - $currentDepth = 0; - $parentResources = array(); - $currentResource = $moduleDirectory; - - // loop through the target module skeleton - foreach ($targetIterator as $targetSubResource) { - - $depthDifference = $targetIterator->getDepth() - $currentDepth; - $currentDepth = $targetIterator->getDepth(); - - if ($depthDifference === 1) { - // if we went down into a child, make note - array_push($parentResources, $currentResource); - // this will have always been set previously by another loop - $currentResource = $currentChildResource; - } elseif ($depthDifference < 0) { - // if we went up to a parent, make note - $i = $depthDifference; - do { - // if we went out more than 1 parent, get to the correct parent - $currentResource = array_pop($parentResources); - } while ($i-- > 0); - } - - // get parameters for the newly created module resource - $params = $targetSubResource->getAttributes(); - $currentChildResource = $currentResource->createResource($targetSubResource->getName(), $params); - - // based of the provided list (Currently up top), enable specific resources - if (isset($targetModuleEnabledResources)) { - $currentChildResource->setEnabled(in_array($targetSubResource->getName(), $targetModuleEnabledResources)); - } else { - $currentChildResource->setEnabled($targetSubResource->isEnabled()); - } - - } - - return $moduleDirectory; - } - - /** - * create() - * - * @param string $name - */ - public function create($name) //, $moduleProfile = null) - { - $this->_loadProfile(self::NO_PROFILE_THROW_EXCEPTION); - - // determine if testing is enabled in the project - #require_once 'Zend/Tool/Project/Provider/Test.php'; - //$testingEnabled = Zend_Tool_Project_Provider_Test::isTestingEnabled($this->_loadedProfile); - - $resources = self::createResources($this->_loadedProfile, $name); - - $response = $this->_registry->getResponse(); - - if ($this->_registry->getRequest()->isPretend()) { - $response->appendContent('I would create the following module and artifacts:'); - foreach (new RecursiveIteratorIterator($resources, RecursiveIteratorIterator::SELF_FIRST) as $resource) { - if (is_callable(array($resource->getContext(), 'getPath'))) { - $response->appendContent($resource->getContext()->getPath()); - } - } - } else { - $response->appendContent('Creating the following module and artifacts:'); - $enabledFilter = new Zend_Tool_Project_Profile_Iterator_EnabledResourceFilter($resources); - foreach (new RecursiveIteratorIterator($enabledFilter, RecursiveIteratorIterator::SELF_FIRST) as $resource) { - $response->appendContent($resource->getContext()->getPath()); - $resource->create(); - } - - $response->appendContent('Added a key for path module directory to the application.ini file'); - $appConfigFile = $this->_loadedProfile->search('ApplicationConfigFile'); - $appConfigFile->removeStringItem('resources.frontController.moduleDirectory', 'production'); - $appConfigFile->addStringItem('resources.frontController.moduleDirectory', 'APPLICATION_PATH "/modules"', 'production', false); - - if (strtolower($name) == 'default') { - $response->appendContent('Added a key for the default module to the application.ini file'); - $appConfigFile->addStringItem('resources.frontController.params.prefixDefaultModule', '1', 'production'); - } - - $appConfigFile->create(); - - // store changes to the profile - $this->_storeProfile(); - } - - } - -} - diff --git a/library/Zend/Tool/Project/Provider/Profile.php b/library/Zend/Tool/Project/Provider/Profile.php deleted file mode 100644 index ecdf7ddc02..0000000000 --- a/library/Zend/Tool/Project/Provider/Profile.php +++ /dev/null @@ -1,54 +0,0 @@ -_loadProfile(); - - $profileIterator = $this->_loadedProfile->getIterator(); - - foreach ($profileIterator as $profileItem) { - $this->_registry->getResponse()->appendContent( - str_repeat(' ', $profileIterator->getDepth()) . $profileItem - ); - } - - } -} diff --git a/library/Zend/Tool/Project/Provider/Project.php b/library/Zend/Tool/Project/Provider/Project.php deleted file mode 100644 index f148983d1d..0000000000 --- a/library/Zend/Tool/Project/Provider/Project.php +++ /dev/null @@ -1,254 +0,0 @@ -_loadProfile(self::NO_PROFILE_RETURN_FALSE, $path); - - if ($profile !== false) { - #require_once 'Zend/Tool/Framework/Client/Exception.php'; - throw new Zend_Tool_Framework_Client_Exception('A project already exists here'); - } - - $profileData = null; - - if ($fileOfProfile != null && file_exists($fileOfProfile)) { - $profileData = file_get_contents($fileOfProfile); - } - - $storage = $this->_registry->getStorage(); - if ($profileData == '' && $nameOfProfile != null && $storage->isEnabled()) { - $profileData = $storage->get('project/profiles/' . $nameOfProfile . '.xml'); - } - - if ($profileData == '') { - $profileData = $this->_getDefaultProfile(); - } - - $newProfile = new Zend_Tool_Project_Profile(array( - 'projectDirectory' => $path, - 'profileData' => $profileData - )); - - $newProfile->loadFromData(); - - $response = $this->_registry->getResponse(); - - $response->appendContent('Creating project at ' . $path); - $response->appendContent('Note: ', array('separator' => false, 'color' => 'yellow')); - $response->appendContent( - 'This command created a web project, ' - . 'for more information setting up your VHOST, please see docs/README'); - - if (!Zend_Tool_Project_Provider_Test::isPHPUnitAvailable()) { - $response->appendContent('Testing Note: ', array('separator' => false, 'color' => 'yellow')); - $response->appendContent('PHPUnit was not found in your include_path, therefore no testing actions will be created.'); - } - - foreach ($newProfile->getIterator() as $resource) { - $resource->create(); - } - } - - public function show() - { - $this->_registry->getResponse()->appendContent('You probably meant to run "show project.info".', array('color' => 'yellow')); - } - - public function showInfo() - { - $profile = $this->_loadProfile(self::NO_PROFILE_RETURN_FALSE); - if (!$profile) { - $this->_registry->getResponse()->appendContent('No project found.'); - } else { - $this->_registry->getResponse()->appendContent('Working with project located at: ' . $profile->getAttribute('projectDirectory')); - } - } - - protected function _getDefaultProfile() - { - $testAction = ''; - if (Zend_Tool_Project_Provider_Test::isPHPUnitAvailable()) { - $testAction = ' '; - } - - $version = Zend_Version::VERSION; - - $data = << - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -$testAction - - - - - - - -EOS; - return $data; - } - - public static function getDefaultReadmeContents($caller = null) - { - $projectDirResource = $caller->getResource()->getProfile()->search('projectDirectory'); - if ($projectDirResource) { - $name = ltrim(strrchr($projectDirResource->getPath(), DIRECTORY_SEPARATOR), DIRECTORY_SEPARATOR); - $path = $projectDirResource->getPath() . '/public'; - } else { - $path = '/path/to/public'; - } - - return <<< EOS -README -====== - -This directory should be used to place project specfic documentation including -but not limited to project notes, generated API/phpdoc documentation, or -manual files generated or hand written. Ideally, this directory would remain -in your development environment only and should not be deployed with your -application to it's final production location. - - -Setting Up Your VHOST -===================== - -The following is a sample VHOST you might want to consider for your project. - - - DocumentRoot "$path" - ServerName $name.local - - # This should be omitted in the production environment - SetEnv APPLICATION_ENV development - - - Options Indexes MultiViews FollowSymLinks - AllowOverride All - Order allow,deny - Allow from all - - - - -EOS; - } -} diff --git a/library/Zend/Tool/Project/Provider/ProjectProvider.php b/library/Zend/Tool/Project/Provider/ProjectProvider.php deleted file mode 100644 index 54a3dd46da..0000000000 --- a/library/Zend/Tool/Project/Provider/ProjectProvider.php +++ /dev/null @@ -1,97 +0,0 @@ -createResourceAt($profileSearchParams, 'projectProviderFile', array('projectProviderName' => $projectProviderName, 'actionNames' => $actionNames)); - - return $projectProvider; - } - - /** - * getName() - * - * @return string - */ - public function getName() - { - return 'ProjectProvider'; - } - - /** - * Create stub for Zend_Tool Project Provider - * - * @var string $name class name for new Zend_Tool Project Provider - * @var array|string $actions list of provider methods - * @throws Zend_Tool_Project_Provider_Exception - */ - public function create($name, $actions = null) - { - $profile = $this->_loadProfileRequired(); - - $projectProvider = self::createResource($profile, $name, $actions); - - if ($this->_registry->getRequest()->isPretend()) { - $this->_registry->getResponse()->appendContent('Would create a project provider named ' . $name - . ' in location ' . $projectProvider->getPath() - ); - } else { - $this->_registry->getResponse()->appendContent('Creating a project provider named ' . $name - . ' in location ' . $projectProvider->getPath() - ); - $projectProvider->create(); - $this->_storeProfile(); - } - - } -} diff --git a/library/Zend/Tool/Project/Provider/Test.php b/library/Zend/Tool/Project/Provider/Test.php deleted file mode 100644 index 768e9e9bff..0000000000 --- a/library/Zend/Tool/Project/Provider/Test.php +++ /dev/null @@ -1,198 +0,0 @@ -search($profileSearchParams); - - return $testsDirectory->isEnabled(); - } - - public static function isPHPUnitAvailable() - { - if (class_exists('PHPUnit_Runner_Version', false)) { - return true; - } - - $included = @include 'PHPUnit/Runner/Version.php'; - - if ($included === false) { - return false; - } else { - return true; - } - } - - /** - * createApplicationResource() - * - * @param Zend_Tool_Project_Profile $profile - * @param string $controllerName - * @param string $actionName - * @param string $moduleName - * @return Zend_Tool_Project_Profile_Resource - */ - public static function createApplicationResource(Zend_Tool_Project_Profile $profile, $controllerName, $actionName, $moduleName = null) - { - if (!is_string($controllerName)) { - throw new Zend_Tool_Project_Provider_Exception('Zend_Tool_Project_Provider_View::createApplicationResource() expects \"controllerName\" is the name of a controller resource to create.'); - } - - if (!is_string($actionName)) { - throw new Zend_Tool_Project_Provider_Exception('Zend_Tool_Project_Provider_View::createApplicationResource() expects \"actionName\" is the name of a controller resource to create.'); - } - - $testsDirectoryResource = $profile->search('testsDirectory'); - - // parentOfController could either be application/ or a particular module folder, which is why we use this name - if (($testParentOfControllerDirectoryResource = $testsDirectoryResource->search('testApplicationDirectory')) === false) { - $testParentOfControllerDirectoryResource = $testsDirectoryResource->createResource('testApplicationDirectory'); - } - - if ($moduleName) { - if (($testAppModulesDirectoryResource = $testParentOfControllerDirectoryResource->search('testApplicationModulesDirectory')) === false) { - $testAppModulesDirectoryResource = $testParentOfControllerDirectoryResource->createResource('testApplicationModulesDirectory'); - } - - if (($testAppModuleDirectoryResource = $testAppModulesDirectoryResource->search(array('testApplicationModuleDirectory' => array('forModuleName' => $moduleName)))) === false) { - $testAppModuleDirectoryResource = $testAppModulesDirectoryResource->createResource('testApplicationModuleDirectory', array('forModuleName' => $moduleName)); - } - - $testParentOfControllerDirectoryResource = $testAppModuleDirectoryResource; - } - - if (($testAppControllerDirectoryResource = $testParentOfControllerDirectoryResource->search('testApplicationControllerDirectory', 'testApplicationModuleDirectory')) === false) { - $testAppControllerDirectoryResource = $testParentOfControllerDirectoryResource->createResource('testApplicationControllerDirectory'); - } - - if (($testAppControllerFileResource = $testAppControllerDirectoryResource->search(array('testApplicationControllerFile' => array('forControllerName' => $controllerName)))) === false) { - $testAppControllerFileResource = $testAppControllerDirectoryResource->createResource('testApplicationControllerFile', array('forControllerName' => $controllerName)); - } - - return $testAppControllerFileResource->createResource('testApplicationActionMethod', array('forActionName' => $actionName)); - } - - /** - * createLibraryResource() - * - * @param Zend_Tool_Project_Profile $profile - * @param string $libraryClassName - * @return Zend_Tool_Project_Profile_Resource - */ - public static function createLibraryResource(Zend_Tool_Project_Profile $profile, $libraryClassName) - { - $testLibraryDirectoryResource = $profile->search(array('TestsDirectory', 'TestLibraryDirectory')); - - - $fsParts = explode('_', $libraryClassName); - - $currentDirectoryResource = $testLibraryDirectoryResource; - - while ($nameOrNamespacePart = array_shift($fsParts)) { - - if (count($fsParts) > 0) { - - if (($libraryDirectoryResource = $currentDirectoryResource->search(array('TestLibraryNamespaceDirectory' => array('namespaceName' => $nameOrNamespacePart)))) === false) { - $currentDirectoryResource = $currentDirectoryResource->createResource('TestLibraryNamespaceDirectory', array('namespaceName' => $nameOrNamespacePart)); - } else { - $currentDirectoryResource = $libraryDirectoryResource; - } - - } else { - - if (($libraryFileResource = $currentDirectoryResource->search(array('TestLibraryFile' => array('forClassName' => $libraryClassName)))) === false) { - $libraryFileResource = $currentDirectoryResource->createResource('TestLibraryFile', array('forClassName' => $libraryClassName)); - } - - } - - } - - return $libraryFileResource; - } - - public function enable() - { - - } - - public function disable() - { - - } - - /** - * create() - * - * @param string $libraryClassName - */ - public function create($libraryClassName) - { - $profile = $this->_loadProfile(); - - if (!self::isTestingEnabled($profile)) { - $this->_registry->getResponse()->appendContent('Testing is not enabled for this project.'); - } - - $testLibraryResource = self::createLibraryResource($profile, $libraryClassName); - - $response = $this->_registry->getResponse(); - - if ($this->_registry->getRequest()->isPretend()) { - $response->appendContent('Would create a library stub in location ' . $testLibraryResource->getContext()->getPath()); - } else { - $response->appendContent('Creating a library stub in location ' . $testLibraryResource->getContext()->getPath()); - $testLibraryResource->create(); - $this->_storeProfile(); - } - - } - -} diff --git a/library/Zend/Tool/Project/Provider/View.php b/library/Zend/Tool/Project/Provider/View.php deleted file mode 100644 index 9bb0d684b8..0000000000 --- a/library/Zend/Tool/Project/Provider/View.php +++ /dev/null @@ -1,118 +0,0 @@ - array('moduleName' => $moduleName)); - $noModuleSearch = null; - } else { - $noModuleSearch = array('modulesDirectory'); - } - - $profileSearchParams[] = 'viewsDirectory'; - $profileSearchParams[] = 'viewScriptsDirectory'; - - if (($viewScriptsDirectory = $profile->search($profileSearchParams, $noModuleSearch)) === false) { - #require_once 'Zend/Tool/Project/Provider/Exception.php'; - throw new Zend_Tool_Project_Provider_Exception('This project does not have a viewScriptsDirectory resource.'); - } - - $profileSearchParams['viewControllerScriptsDirectory'] = array('forControllerName' => $controllerName); - - // @todo check if below is failing b/c of above search params - if (($viewControllerScriptsDirectory = $viewScriptsDirectory->search($profileSearchParams)) === false) { - $viewControllerScriptsDirectory = $viewScriptsDirectory->createResource('viewControllerScriptsDirectory', array('forControllerName' => $controllerName)); - } - - $newViewScriptFile = $viewControllerScriptsDirectory->createResource('ViewScriptFile', array('forActionName' => $actionName)); - - return $newViewScriptFile; - } - - /** - * create() - * - * @param string $controllerName - * @param string $actionNameOrSimpleName - */ - public function create($controllerName, $actionNameOrSimpleName, $module = null) - { - - if ($controllerName == '' || $actionNameOrSimpleName == '') { - #require_once 'Zend/Tool/Project/Provider/Exception.php'; - throw new Zend_Tool_Project_Provider_Exception('ControllerName and/or ActionName are empty.'); - } - - $profile = $this->_loadProfile(); - - $view = self::createResource($profile, $actionNameOrSimpleName, $controllerName, $module); - - if ($this->_registry->getRequest()->isPretend()) { - $this->_registry->getResponse( - 'Would create a view script in location ' . $view->getContext()->getPath() - ); - } else { - $this->_registry->getResponse( - 'Creating a view script in location ' . $view->getContext()->getPath() - ); - $view->create(); - $this->_storeProfile(); - } - - } -} diff --git a/library/Zend/Validate/Ldap/Dn.php b/library/Zend/Validate/Ldap/Dn.php deleted file mode 100644 index 892b011f14..0000000000 --- a/library/Zend/Validate/Ldap/Dn.php +++ /dev/null @@ -1,65 +0,0 @@ - 'DN is malformed', - ); - - /** - * Defined by Zend_Validate_Interface. - * - * Returns true if and only if $value is a valid DN. - * - * @param string $value The value to be validated. - * - * @return boolean - */ - public function isValid($value) - { - $valid = Zend_Ldap_Dn::checkDn($value); - if ($valid === false) { - $this->_error(self::MALFORMED); - return false; - } - return true; - } -} diff --git a/library/Zend/Wildfire/Channel/HttpHeaders.php b/library/Zend/Wildfire/Channel/HttpHeaders.php deleted file mode 100644 index 17cd60e7a3..0000000000 --- a/library/Zend/Wildfire/Channel/HttpHeaders.php +++ /dev/null @@ -1,343 +0,0 @@ -_protocols[$uri])) { - $this->_protocols[$uri] = $this->_initProtocol($uri); - } - - $this->_registerControllerPlugin(); - - return $this->_protocols[$uri]; - } - - /** - * Initialize a new protocol - * - * @param string $uri The URI for the protocol to be initialized - * @return object Returns the new initialized protocol instance - * @throws Zend_Wildfire_Exception - */ - protected function _initProtocol($uri) - { - switch ($uri) { - case Zend_Wildfire_Protocol_JsonStream::PROTOCOL_URI; - return new Zend_Wildfire_Protocol_JsonStream(); - } - #require_once 'Zend/Wildfire/Exception.php'; - throw new Zend_Wildfire_Exception('Tyring to initialize unknown protocol for URI "'.$uri.'".'); - } - - - /** - * Flush all data from all protocols and send all data to response headers. - * - * @return boolean Returns TRUE if data was flushed - */ - public function flush() - { - if (!$this->_protocols || !$this->isReady()) { - return false; - } - - foreach ( $this->_protocols as $protocol ) { - - $payload = $protocol->getPayload($this); - - if ($payload) { - foreach( $payload as $message ) { - - $this->getResponse()->setHeader(self::$_headerPrefix.$message[0], - $message[1], true); - } - } - } - return true; - } - - /** - * Set the index of the plugin in the controller dispatch loop plugin stack - * - * @param integer $index The index of the plugin in the stack - * @return integer The previous index. - */ - public static function setControllerPluginStackIndex($index) - { - $previous = self::$_controllerPluginStackIndex; - self::$_controllerPluginStackIndex = $index; - return $previous; - } - - /** - * Register this object as a controller plugin. - * - * @return void - */ - protected function _registerControllerPlugin() - { - $controller = Zend_Controller_Front::getInstance(); - if (!$controller->hasPlugin(get_class($this))) { - $controller->registerPlugin($this, self::$_controllerPluginStackIndex); - } - } - - - /* - * Zend_Wildfire_Channel_Interface - */ - - /** - * Determine if channel is ready. - * - * The channel is ready as long as the request and response objects are initialized, - * can send headers and the FirePHP header exists in the User-Agent. - * - * If the header does not exist in the User-Agent, no appropriate client - * is making this request and the messages should not be sent. - * - * A timing issue arises when messages are logged before the request/response - * objects are initialized. In this case we do not yet know if the client - * will be able to accept the messages. If we consequently indicate that - * the channel is not ready, these messages will be dropped which is in - * most cases not the intended behaviour. The intent is to send them at the - * end of the request when the request/response objects will be available - * for sure. - * - * If the request/response objects are not yet initialized we assume if messages are - * logged, the client will be able to receive them. As soon as the request/response - * objects are availoable and a message is logged this assumption is challenged. - * If the client cannot accept the messages any further messages are dropped - * and messages sent prior are kept but discarded when the channel is finally - * flushed at the end of the request. - * - * When the channel is flushed the $forceCheckRequest option is used to force - * a check of the request/response objects. This is the last verification to ensure - * messages are only sent when the client can accept them. - * - * @param boolean $forceCheckRequest OPTIONAL Set to TRUE if the request must be checked - * @return boolean Returns TRUE if channel is ready. - */ - public function isReady($forceCheckRequest=false) - { - if (!$forceCheckRequest - && !$this->_request - && !$this->_response - ) { - return true; - } - - if (!($this->getRequest() instanceof Zend_Controller_Request_Http)) { - return false; - } - - return ($this->getResponse()->canSendHeaders() - && (preg_match_all( - '/\s?FirePHP\/([\.\d]*)\s?/si', - $this->getRequest()->getHeader('User-Agent'), - $m - ) || - (($header = $this->getRequest()->getHeader('X-FirePHP-Version')) - && preg_match_all('/^([\.\d]*)$/si', $header, $m) - )) - ); - } - - - /* - * Zend_Controller_Plugin_Abstract - */ - - /** - * Flush messages to headers as late as possible but before headers have been sent. - * - * @return void - */ - public function dispatchLoopShutdown() - { - $this->flush(); - } - - /** - * Get the request object - * - * @return Zend_Controller_Request_Abstract - * @throws Zend_Wildfire_Exception - */ - public function getRequest() - { - if (!$this->_request) { - $controller = Zend_Controller_Front::getInstance(); - $this->setRequest($controller->getRequest()); - } - if (!$this->_request) { - #require_once 'Zend/Wildfire/Exception.php'; - throw new Zend_Wildfire_Exception('Request objects not initialized.'); - } - return $this->_request; - } - - /** - * Get the response object - * - * @return Zend_Controller_Response_Abstract - * @throws Zend_Wildfire_Exception - */ - public function getResponse() - { - if (!$this->_response) { - $response = Zend_Controller_Front::getInstance()->getResponse(); - if ($response) { - $this->setResponse($response); - } - } - if (!$this->_response) { - #require_once 'Zend/Wildfire/Exception.php'; - throw new Zend_Wildfire_Exception('Response objects not initialized.'); - } - return $this->_response; - } -} diff --git a/library/Zend/Wildfire/Channel/Interface.php b/library/Zend/Wildfire/Channel/Interface.php deleted file mode 100644 index fccec351c9..0000000000 --- a/library/Zend/Wildfire/Channel/Interface.php +++ /dev/null @@ -1,38 +0,0 @@ - 1, /* The offset in the trace which identifies the source of the message */ - 'maxTraceDepth' => 99, /* Maximum depth for stack traces */ - 'maxObjectDepth' => 10, /* The maximum depth to traverse objects when encoding */ - 'maxArrayDepth' => 20, /* The maximum depth to traverse nested arrays when encoding */ - 'includeLineNumbers' => true /* Whether to include line and file info for each message */ - ); - - /** - * Filters used to exclude object members when encoding - * @var array - */ - protected $_objectFilters = array(); - - /** - * A stack of objects used during encoding to detect recursion - * @var array - */ - protected $_objectStack = array(); - - /** - * Create singleton instance. - * - * @param string $class OPTIONAL Subclass of Zend_Wildfire_Plugin_FirePhp - * @return Zend_Wildfire_Plugin_FirePhp Returns the singleton Zend_Wildfire_Plugin_FirePhp instance - * @throws Zend_Wildfire_Exception - */ - public static function init($class = null) - { - if (self::$_instance !== null) { - #require_once 'Zend/Wildfire/Exception.php'; - throw new Zend_Wildfire_Exception('Singleton instance of Zend_Wildfire_Plugin_FirePhp already exists!'); - } - if ($class !== null) { - if (!is_string($class)) { - #require_once 'Zend/Wildfire/Exception.php'; - throw new Zend_Wildfire_Exception('Third argument is not a class string'); - } - - if (!class_exists($class)) { - #require_once 'Zend/Loader.php'; - Zend_Loader::loadClass($class); - } - self::$_instance = new $class(); - if (!self::$_instance instanceof Zend_Wildfire_Plugin_FirePhp) { - self::$_instance = null; - #require_once 'Zend/Wildfire/Exception.php'; - throw new Zend_Wildfire_Exception('Invalid class to third argument. Must be subclass of Zend_Wildfire_Plugin_FirePhp.'); - } - } else { - self::$_instance = new self(); - } - - return self::$_instance; - } - - /** - * Constructor - * @return void - */ - protected function __construct() - { - $this->_channel = Zend_Wildfire_Channel_HttpHeaders::getInstance(); - $this->_channel->getProtocol(self::PROTOCOL_URI)->registerPlugin($this); - } - - /** - * Get or create singleton instance - * - * @param bool $skipCreate True if an instance should not be created - * @return Zend_Wildfire_Plugin_FirePhp - */ - public static function getInstance($skipCreate=false) - { - if (self::$_instance===null && $skipCreate!==true) { - return self::init(); - } - return self::$_instance; - } - - /** - * Destroys the singleton instance - * - * Primarily used for testing. - * - * @return void - */ - public static function destroyInstance() - { - self::$_instance = null; - } - - /** - * Enable or disable sending of messages to user-agent. - * If disabled all headers to be sent will be removed. - * - * @param boolean $enabled Set to TRUE to enable sending of messages. - * @return boolean The previous value. - */ - public function setEnabled($enabled) - { - $previous = $this->_enabled; - $this->_enabled = $enabled; - if (!$this->_enabled) { - $this->_messages = array(); - $this->_channel->getProtocol(self::PROTOCOL_URI)->clearMessages($this); - } - return $previous; - } - - /** - * Determine if logging to user-agent is enabled. - * - * @return boolean Returns TRUE if logging is enabled. - */ - public function getEnabled() - { - return $this->_enabled; - } - - /** - * Set a single option - * - * @param string $key The name of the option - * @param mixed $value The value of the option - * @return mixed The previous value of the option - */ - public function setOption($key, $value) - { - if (!array_key_exists($key,$this->_options)) { - throw new Zend_Wildfire_Exception('Option with name "'.$key.'" does not exist!'); - } - $previous = $this->_options[$key]; - $this->_options[$key] = $value; - return $previous; - } - - /** - * Retrieve a single option - * - * @param string $key The name of the option - * @return mixed The value of the option - */ - public function getOption($key) - { - if (!array_key_exists($key,$this->_options)) { - throw new Zend_Wildfire_Exception('Option with name "'.$key.'" does not exist!'); - } - return $this->_options[$key]; - } - - /** - * Retrieve all options - * - * @return array All options - */ - public function getOptions() - { - return $this->_options; - } - - /** - * Specify a filter to be used when encoding an object - * - * Filters are used to exclude object members. - * - * @param string $Class The class name of the object - * @param array $Filter An array of members to exclude - * @return void - */ - public function setObjectFilter($class, $filter) { - $this->_objectFilters[$class] = $filter; - } - - /** - * Starts a group in the Firebug Console - * - * @param string $title The title of the group - * @param array $options OPTIONAL Setting 'Collapsed' to true will initialize group collapsed instead of expanded - * @return TRUE if the group instruction was added to the response headers or buffered. - */ - public static function group($title, $options=array()) - { - return self::send(null, $title, self::GROUP_START, $options); - } - - /** - * Ends a group in the Firebug Console - * - * @return TRUE if the group instruction was added to the response headers or buffered. - */ - public static function groupEnd() - { - return self::send(null, null, self::GROUP_END); - } - - /** - * Logs variables to the Firebug Console - * via HTTP response headers and the FirePHP Firefox Extension. - * - * @param mixed $var The variable to log. - * @param string $label OPTIONAL Label to prepend to the log event. - * @param string $style OPTIONAL Style of the log event. - * @param array $options OPTIONAL Options to change how messages are processed and sent - * @return boolean Returns TRUE if the variable was added to the response headers or buffered. - * @throws Zend_Wildfire_Exception - */ - public static function send($var, $label=null, $style=null, $options=array()) - { - $firephp = self::getInstance(); - - if (!$firephp->getEnabled()) { - return false; - } - - if ($var instanceof Zend_Wildfire_Plugin_FirePhp_Message) { - - if ($var->getBuffered()) { - if (!in_array($var, self::$_instance->_messages)) { - self::$_instance->_messages[] = $var; - } - return true; - } - - if ($var->getDestroy()) { - return false; - } - - $style = $var->getStyle(); - $label = $var->getLabel(); - $options = $var->getOptions(); - $var = $var->getMessage(); - } - - if (!self::$_instance->_channel->isReady()) { - return false; - } - - foreach ($options as $name => $value) { - if ($value===null) { - unset($options[$name]); - } - } - $options = array_merge($firephp->getOptions(), $options); - - $trace = null; - - $skipFinalEncode = false; - - $meta = array(); - $meta['Type'] = $style; - - if ($var instanceof Exception) { - - $eTrace = $var->getTrace(); - $eTrace = array_splice($eTrace, 0, $options['maxTraceDepth']); - - $var = array('Class'=>get_class($var), - 'Message'=>$var->getMessage(), - 'File'=>$var->getFile(), - 'Line'=>$var->getLine(), - 'Type'=>'throw', - 'Trace'=>$firephp->_encodeTrace($eTrace)); - - $meta['Type'] = self::EXCEPTION; - - $skipFinalEncode = true; - - } else - if ($meta['Type']==self::TRACE) { - - if (!$label && $var) { - $label = $var; - $var = null; - } - - if (!$trace) { - $trace = $firephp->_getStackTrace(array_merge($options, - array('maxTraceDepth'=>$options['maxTraceDepth']+1))); - } - - $var = array('Class'=>$trace[0]['class'], - 'Type'=>$trace[0]['type'], - 'Function'=>$trace[0]['function'], - 'Message'=>$label, - 'File'=>isset($trace[0]['file'])?$trace[0]['file']:'', - 'Line'=>isset($trace[0]['line'])?$trace[0]['line']:'', - 'Args'=>isset($trace[0]['args'])?$firephp->_encodeObject($trace[0]['args']):'', - 'Trace'=>$firephp->_encodeTrace(array_splice($trace,1))); - - $skipFinalEncode = true; - - } else - if ($meta['Type']==self::TABLE) { - - $var = $firephp->_encodeTable($var); - - $skipFinalEncode = true; - - } else { - if ($meta['Type']===null) { - $meta['Type'] = self::LOG; - } - } - - if ($label!=null) { - $meta['Label'] = $label; - } - - switch ($meta['Type']) { - case self::LOG: - case self::INFO: - case self::WARN: - case self::ERROR: - case self::EXCEPTION: - case self::TRACE: - case self::TABLE: - case self::DUMP: - case self::GROUP_START: - case self::GROUP_END: - break; - default: - #require_once 'Zend/Wildfire/Exception.php'; - throw new Zend_Wildfire_Exception('Log style "'.$meta['Type'].'" not recognized!'); - break; - } - - if ($meta['Type'] != self::DUMP && $options['includeLineNumbers']) { - if (!isset($meta['File']) || !isset($meta['Line'])) { - - if (!$trace) { - $trace = $firephp->_getStackTrace(array_merge($options, - array('maxTraceDepth'=>$options['maxTraceDepth']+1))); - } - - $meta['File'] = isset($trace[0]['file'])?$trace[0]['file']:''; - $meta['Line'] = isset($trace[0]['line'])?$trace[0]['line']:''; - - } - } else { - unset($meta['File']); - unset($meta['Line']); - } - - if ($meta['Type'] == self::GROUP_START) { - if (isset($options['Collapsed'])) { - $meta['Collapsed'] = ($options['Collapsed'])?'true':'false'; - } - } - - if ($meta['Type'] == self::DUMP) { - - return $firephp->_recordMessage(self::STRUCTURE_URI_DUMP, - array('key'=>$meta['Label'], - 'data'=>$var), - $skipFinalEncode); - - } else { - - return $firephp->_recordMessage(self::STRUCTURE_URI_FIREBUGCONSOLE, - array('data'=>$var, - 'meta'=>$meta), - $skipFinalEncode); - } - } - - /** - * Gets a stack trace - * - * @param array $options Options to change how the stack trace is returned - * @return array The stack trace - */ - protected function _getStackTrace($options) - { - $trace = debug_backtrace(); - - $trace = array_splice($trace, $options['traceOffset']); - - if (!count($trace)) { - return $trace; - } - - if (isset($options['fixZendLogOffsetIfApplicable']) && $options['fixZendLogOffsetIfApplicable']) { - if (count($trace) >=3 && - isset($trace[0]['file']) && substr($trace[0]['file'], -7, 7)=='Log.php' && - isset($trace[1]['function']) && $trace[1]['function']=='__call') { - - $spliceOffset = 2; - //Debug backtrace changed in PHP 7.0.0 - if (version_compare(PHP_VERSION, '7.0.0', '>=')) { - $spliceOffset = 1; - } - $trace = array_splice($trace, $spliceOffset); - } - } - - return array_splice($trace, 0, $options['maxTraceDepth']); - } - - /** - * Record a message with the given data in the given structure - * - * @param string $structure The structure to be used for the data - * @param array $data The data to be recorded - * @param boolean $skipEncode TRUE if variable encoding should be skipped - * @return boolean Returns TRUE if message was recorded - * @throws Zend_Wildfire_Exception - */ - protected function _recordMessage($structure, $data, $skipEncode=false) - { - switch($structure) { - - case self::STRUCTURE_URI_DUMP: - - if (!isset($data['key'])) { - #require_once 'Zend/Wildfire/Exception.php'; - throw new Zend_Wildfire_Exception('You must supply a key.'); - } - if (!array_key_exists('data',$data)) { - #require_once 'Zend/Wildfire/Exception.php'; - throw new Zend_Wildfire_Exception('You must supply data.'); - } - - $value = $data['data']; - if (!$skipEncode) { - $value = $this->_encodeObject($data['data']); - } - - return $this->_channel->getProtocol(self::PROTOCOL_URI)-> - recordMessage($this, - $structure, - array($data['key']=>$value)); - - case self::STRUCTURE_URI_FIREBUGCONSOLE: - - if (!isset($data['meta']) || - !is_array($data['meta']) || - !array_key_exists('Type',$data['meta'])) { - - #require_once 'Zend/Wildfire/Exception.php'; - throw new Zend_Wildfire_Exception('You must supply a "Type" in the meta information.'); - } - if (!array_key_exists('data',$data)) { - #require_once 'Zend/Wildfire/Exception.php'; - throw new Zend_Wildfire_Exception('You must supply data.'); - } - - $value = $data['data']; - if (!$skipEncode) { - $value = $this->_encodeObject($data['data']); - } - - return $this->_channel->getProtocol(self::PROTOCOL_URI)-> - recordMessage($this, - $structure, - array($data['meta'], - $value)); - - default: - #require_once 'Zend/Wildfire/Exception.php'; - throw new Zend_Wildfire_Exception('Structure of name "'.$structure.'" is not recognized.'); - break; - } - return false; - } - - /** - * Encodes a table by encoding each row and column with _encodeObject() - * - * @param array $Table The table to be encoded - * @return array - */ - protected function _encodeTable($table) - { - if (!$table) { - return $table; - } - for ($i=0 ; $i_encodeObject($table[$i][$j]); - } - } - } - return $table; - } - - /** - * Encodes a trace by encoding all "args" with _encodeObject() - * - * @param array $Trace The trace to be encoded - * @return array The encoded trace - */ - protected function _encodeTrace($trace) - { - if (!$trace) { - return $trace; - } - for ($i=0 ; $i_encodeObject($trace[$i]['args']); - } - } - return $trace; - } - - /** - * Encode an object by generating an array containing all object members. - * - * All private and protected members are included. Some meta info about - * the object class is added. - * - * @param mixed $object The object/array/value to be encoded - * @return array The encoded object - */ - protected function _encodeObject($object, $objectDepth = 1, $arrayDepth = 1) - { - $return = array(); - - if (is_resource($object)) { - - return '** '.(string)$object.' **'; - - } else - if (is_object($object)) { - - if ($objectDepth > $this->_options['maxObjectDepth']) { - return '** Max Object Depth ('.$this->_options['maxObjectDepth'].') **'; - } - - foreach ($this->_objectStack as $refVal) { - if ($refVal === $object) { - return '** Recursion ('.get_class($object).') **'; - } - } - array_push($this->_objectStack, $object); - - $return['__className'] = $class = get_class($object); - - $reflectionClass = new ReflectionClass($class); - $properties = array(); - foreach ( $reflectionClass->getProperties() as $property) { - $properties[$property->getName()] = $property; - } - - $members = (array)$object; - - foreach ($properties as $just_name => $property) { - - $name = $raw_name = $just_name; - - if ($property->isStatic()) { - $name = 'static:'.$name; - } - if ($property->isPublic()) { - $name = 'public:'.$name; - } else - if ($property->isPrivate()) { - $name = 'private:'.$name; - $raw_name = "\0".$class."\0".$raw_name; - } else - if ($property->isProtected()) { - $name = 'protected:'.$name; - $raw_name = "\0".'*'."\0".$raw_name; - } - - if (!(isset($this->_objectFilters[$class]) - && is_array($this->_objectFilters[$class]) - && in_array($just_name,$this->_objectFilters[$class]))) { - - if (array_key_exists($raw_name,$members) - && !$property->isStatic()) { - - $return[$name] = $this->_encodeObject($members[$raw_name], $objectDepth + 1, 1); - - } else { - if (method_exists($property,'setAccessible')) { - $property->setAccessible(true); - $return[$name] = $this->_encodeObject($property->getValue($object), $objectDepth + 1, 1); - } else - if ($property->isPublic()) { - $return[$name] = $this->_encodeObject($property->getValue($object), $objectDepth + 1, 1); - } else { - $return[$name] = '** Need PHP 5.3 to get value **'; - } - } - } else { - $return[$name] = '** Excluded by Filter **'; - } - } - - // Include all members that are not defined in the class - // but exist in the object - foreach($members as $just_name => $value) { - - $name = $raw_name = $just_name; - - if ($name{0} == "\0") { - $parts = explode("\0", $name); - $name = $parts[2]; - } - if (!isset($properties[$name])) { - $name = 'undeclared:'.$name; - - if (!(isset($this->objectFilters[$class]) - && is_array($this->objectFilters[$class]) - && in_array($just_name,$this->objectFilters[$class]))) { - - $return[$name] = $this->_encodeObject($value, $objectDepth + 1, 1); - } else { - $return[$name] = '** Excluded by Filter **'; - } - } - } - - array_pop($this->_objectStack); - - } elseif (is_array($object)) { - - if ($arrayDepth > $this->_options['maxArrayDepth']) { - return '** Max Array Depth ('.$this->_options['maxArrayDepth'].') **'; - } - - foreach ($object as $key => $val) { - - // Encoding the $GLOBALS PHP array causes an infinite loop - // if the recursion is not reset here as it contains - // a reference to itself. This is the only way I have come up - // with to stop infinite recursion in this case. - if ($key=='GLOBALS' - && is_array($val) - && array_key_exists('GLOBALS',$val)) { - - $val['GLOBALS'] = '** Recursion (GLOBALS) **'; - } - $return[$key] = $this->_encodeObject($val, 1, $arrayDepth + 1); - } - } else { - return $object; - } - return $return; - } - - /* - * Zend_Wildfire_Plugin_Interface - */ - - /** - * Get the unique indentifier for this plugin. - * - * @return string Returns the URI of the plugin. - */ - public function getUri() - { - return self::PLUGIN_URI; - } - - /** - * Flush any buffered data. - * - * @param string $protocolUri The URI of the protocol that should be flushed to - * @return void - */ - public function flushMessages($protocolUri) - { - if (!$this->_messages || $protocolUri!=self::PROTOCOL_URI) { - return; - } - - foreach( $this->_messages as $message ) { - if (!$message->getDestroy()) { - $this->send($message->getMessage(), - $message->getLabel(), - $message->getStyle(), - $message->getOptions()); - } - } - - $this->_messages = array(); - } -} diff --git a/library/Zend/Wildfire/Plugin/FirePhp/Message.php b/library/Zend/Wildfire/Plugin/FirePhp/Message.php deleted file mode 100644 index 78e98005a2..0000000000 --- a/library/Zend/Wildfire/Plugin/FirePhp/Message.php +++ /dev/null @@ -1,246 +0,0 @@ - null, /* The offset in the trace which identifies the source of the message */ - 'includeLineNumbers' => null /* Whether to include line and file info for this message */ - ); - - /** - * Creates a new message with the given style and message - * - * @param string $style Style of the message. - * @param mixed $message The message - * @return void - */ - function __construct($style, $message) - { - $this->_style = $style; - $this->_message = $message; - $this->_ruid = md5(microtime().mt_rand()); - } - - /** - * Set the label of the message - * - * @param string $label The label to be set - * @return void - */ - public function setLabel($label) - { - $this->_label = $label; - } - - /** - * Get the label of the message - * - * @return string The label of the message - */ - public function getLabel() - { - return $this->_label; - } - - /** - * Enable or disable message buffering - * - * If a message is buffered it can be updated for the duration of the - * request and is only flushed at the end of the request. - * - * @param boolean $buffered TRUE to enable buffering FALSE otherwise - * @return boolean Returns previous buffering value - */ - public function setBuffered($buffered) - { - $previous = $this->_buffered; - $this->_buffered = $buffered; - return $previous; - } - - /** - * Determine if buffering is enabled or disabled - * - * @return boolean Returns TRUE if buffering is enabled, FALSE otherwise. - */ - public function getBuffered() - { - return $this->_buffered; - } - - /** - * Destroy the message to prevent delivery - * - * @param boolean $destroy TRUE to destroy FALSE otherwise - * @return boolean Returns previous destroy value - */ - public function setDestroy($destroy) - { - $previous = $this->_destroy; - $this->_destroy = $destroy; - return $previous; - } - - /** - * Determine if message should be destroyed - * - * @return boolean Returns TRUE if message should be destroyed, FALSE otherwise. - */ - public function getDestroy() - { - return $this->_destroy; - } - - /** - * Set the style of the message - * - * @return void - */ - public function setStyle($style) - { - $this->_style = $style; - } - - /** - * Get the style of the message - * - * @return string The style of the message - */ - public function getStyle() - { - return $this->_style; - } - - /** - * Set the actual message to be sent in its final format. - * - * @return void - */ - public function setMessage($message) - { - $this->_message = $message; - } - - /** - * Get the actual message to be sent in its final format. - * - * @return mixed Returns the message to be sent. - */ - public function getMessage() - { - return $this->_message; - } - - /** - * Set a single option - * - * @param string $key The name of the option - * @param mixed $value The value of the option - * @return mixed The previous value of the option - */ - public function setOption($key, $value) - { - if(!array_key_exists($key,$this->_options)) { - throw new Zend_Wildfire_Exception('Option with name "'.$key.'" does not exist!'); - } - $previous = $this->_options[$key]; - $this->_options[$key] = $value; - return $previous; - } - - /** - * Retrieve a single option - * - * @param string $key The name of the option - * @return mixed The value of the option - */ - public function getOption($key) - { - if(!array_key_exists($key,$this->_options)) { - throw new Zend_Wildfire_Exception('Option with name "'.$key.'" does not exist!'); - } - return $this->_options[$key]; - } - - /** - * Retrieve all options - * - * @return array All options - */ - public function getOptions() - { - return $this->_options; - } -} - diff --git a/library/Zend/Wildfire/Plugin/FirePhp/TableMessage.php b/library/Zend/Wildfire/Plugin/FirePhp/TableMessage.php deleted file mode 100644 index eff631eb4c..0000000000 --- a/library/Zend/Wildfire/Plugin/FirePhp/TableMessage.php +++ /dev/null @@ -1,165 +0,0 @@ -setLabel($label); - } - - /** - * Set the table header - * - * @param array $header The header columns - * @return void - */ - public function setHeader($header) - { - $this->_header = $header; - } - - /** - * Append a row to the end of the table. - * - * @param array $row An array of column values representing a row. - * @return void - */ - public function addRow($row) - { - $this->_rows[] = $row; - } - - /** - * Get the actual message to be sent in its final format. - * - * @return mixed Returns the message to be sent. - */ - public function getMessage() - { - $table = $this->_rows; - if($this->_header) { - array_unshift($table,$this->_header); - } - return $table; - } - - /** - * Returns the row at the given index - * - * @param integer $index The index of the row - * @return array Returns the row - * @throws Zend_Wildfire_Exception - */ - public function getRowAt($index) - { - $count = $this->getRowCount(); - - if($index < 0 || $index > $count-1) { - #require_once 'Zend/Wildfire/Exception.php'; - throw new Zend_Wildfire_Exception('Row index('.$index.') out of bounds('.$count.')!'); - } - - return $this->_rows[$index]; - } - - /** - * Sets the row on the given index to a new row - * - * @param integer $index The index of the row - * @param array $row The new data for the row - * @throws Zend_Wildfire_Exception - */ - public function setRowAt($index, $row) - { - $count = $this->getRowCount(); - - if($index < 0 || $index > $count-1) { - #require_once 'Zend/Wildfire/Exception.php'; - throw new Zend_Wildfire_Exception('Row index('.$index.') out of bounds('.$count.')!'); - } - - $this->_rows[$index] = $row; - } - - /** - * Returns the number of rows - * - * @return integer - */ - public function getRowCount() - { - return count($this->_rows); - } - - /** - * Returns the last row of the table - * - * @return array Returns the last row - * @throws Zend_Wildfire_Exception - */ - public function getLastRow() - { - $count = $this->getRowCount(); - - if($count==0) { - #require_once 'Zend/Wildfire/Exception.php'; - throw new Zend_Wildfire_Exception('Cannot get last row as no rows exist!'); - } - - return $this->_rows[$count-1]; - } -} diff --git a/library/Zend/Wildfire/Plugin/Interface.php b/library/Zend/Wildfire/Plugin/Interface.php deleted file mode 100644 index 2943ca8e8a..0000000000 --- a/library/Zend/Wildfire/Plugin/Interface.php +++ /dev/null @@ -1,48 +0,0 @@ -_plugins)) { - return false; - } - $this->_plugins[] = $plugin; - return true; - } - - /** - * Record a message with the given data in the given structure - * - * @param Zend_Wildfire_Plugin_Interface $plugin The plugin recording the message - * @param string $structure The structure to be used for the data - * @param array $data The data to be recorded - * @return boolean Returns TRUE if message was recorded - */ - public function recordMessage(Zend_Wildfire_Plugin_Interface $plugin, $structure, $data) - { - if(!isset($this->_messages[$structure])) { - $this->_messages[$structure] = array(); - } - - $uri = $plugin->getUri(); - - if(!isset($this->_messages[$structure][$uri])) { - $this->_messages[$structure][$uri] = array(); - } - - $this->_messages[$structure][$uri][] = $this->_encode($data); - return true; - } - - /** - * Remove all qued messages - * - * @param Zend_Wildfire_Plugin_Interface $plugin The plugin for which to clear messages - * @return boolean Returns TRUE if messages were present - */ - public function clearMessages(Zend_Wildfire_Plugin_Interface $plugin) - { - $uri = $plugin->getUri(); - - $present = false; - foreach ($this->_messages as $structure => $messages) { - - if(!isset($this->_messages[$structure][$uri])) { - continue; - } - - $present = true; - - unset($this->_messages[$structure][$uri]); - - if (!$this->_messages[$structure]) { - unset($this->_messages[$structure]); - } - } - return $present; - } - - /** - * Get all qued messages - * - * @return mixed Returns qued messages or FALSE if no messages are qued - */ - public function getMessages() - { - if (!$this->_messages) { - return false; - } - return $this->_messages; - } - - /** - * Use the JSON encoding scheme for the value specified - * - * @param mixed $value The value to be encoded - * @return string The encoded value - */ - protected function _encode($value) - { - return Zend_Json::encode($value, true, array('silenceCyclicalExceptions'=>true)); - } - - /** - * Retrieves all formatted data ready to be sent by the channel. - * - * @param Zend_Wildfire_Channel_Interface $channel The instance of the channel that will be transmitting the data - * @return mixed Returns the data to be sent by the channel. - * @throws Zend_Wildfire_Exception - */ - public function getPayload(Zend_Wildfire_Channel_Interface $channel) - { - if (!$channel instanceof Zend_Wildfire_Channel_HttpHeaders) { - #require_once 'Zend/Wildfire/Exception.php'; - throw new Zend_Wildfire_Exception('The '.get_class($channel).' channel is not supported by the '.get_class($this).' protocol.'); - } - - if ($this->_plugins) { - foreach ($this->_plugins as $plugin) { - $plugin->flushMessages(self::PROTOCOL_URI); - } - } - - if (!$this->_messages) { - return false; - } - - $protocol_index = 1; - $structure_index = 1; - $plugin_index = 1; - $message_index = 1; - - $payload = array(); - - $payload[] = array('Protocol-'.$protocol_index, self::PROTOCOL_URI); - - foreach ($this->_messages as $structure_uri => $plugin_messages ) { - - $payload[] = array($protocol_index.'-Structure-'.$structure_index, $structure_uri); - - foreach ($plugin_messages as $plugin_uri => $messages ) { - - $payload[] = array($protocol_index.'-Plugin-'.$plugin_index, $plugin_uri); - - foreach ($messages as $message) { - - $parts = explode("\n",chunk_split($message, 5000, "\n")); - - for ($i=0 ; $i2) { - $msg = (($i==0)?strlen($message):'') - . '|' . $part . '|' - . (($i 99999) { - #require_once 'Zend/Wildfire/Exception.php'; - throw new Zend_Wildfire_Exception('Maximum number (99,999) of messages reached!'); - } - } - } - } - $plugin_index++; - } - $structure_index++; - } - - return $payload; - } - -} - diff --git a/library/Zend/XmlRpc/Client.php b/library/Zend/XmlRpc/Client.php deleted file mode 100644 index a731e268ff..0000000000 --- a/library/Zend/XmlRpc/Client.php +++ /dev/null @@ -1,403 +0,0 @@ -_httpClient = new Zend_Http_Client(); - } else { - $this->_httpClient = $httpClient; - } - - $this->_introspector = new Zend_XmlRpc_Client_ServerIntrospection($this); - $this->_serverAddress = $server; - } - - - /** - * Sets the HTTP client object to use for connecting the XML-RPC server. - * - * @param Zend_Http_Client $httpClient - * @return Zend_Http_Client - */ - public function setHttpClient(Zend_Http_Client $httpClient) - { - return $this->_httpClient = $httpClient; - } - - - /** - * Gets the HTTP client object. - * - * @return Zend_Http_Client - */ - public function getHttpClient() - { - return $this->_httpClient; - } - - - /** - * Sets the object used to introspect remote servers - * - * @param Zend_XmlRpc_Client_ServerIntrospection - * @return Zend_XmlRpc_Client_ServerIntrospection - */ - public function setIntrospector(Zend_XmlRpc_Client_ServerIntrospection $introspector) - { - return $this->_introspector = $introspector; - } - - - /** - * Gets the introspection object. - * - * @return Zend_XmlRpc_Client_ServerIntrospection - */ - public function getIntrospector() - { - return $this->_introspector; - } - - - /** - * The request of the last method call - * - * @return Zend_XmlRpc_Request - */ - public function getLastRequest() - { - return $this->_lastRequest; - } - - - /** - * The response received from the last method call - * - * @return Zend_XmlRpc_Response - */ - public function getLastResponse() - { - return $this->_lastResponse; - } - - - /** - * Returns a proxy object for more convenient method calls - * - * @param string $namespace Namespace to proxy or empty string for none - * @return Zend_XmlRpc_Client_ServerProxy - */ - public function getProxy($namespace = '') - { - if (empty($this->_proxyCache[$namespace])) { - $proxy = new Zend_XmlRpc_Client_ServerProxy($this, $namespace); - $this->_proxyCache[$namespace] = $proxy; - } - return $this->_proxyCache[$namespace]; - } - - /** - * Set skip system lookup flag - * - * @param bool $flag - * @return Zend_XmlRpc_Client - */ - public function setSkipSystemLookup($flag = true) - { - $this->_skipSystemLookup = (bool) $flag; - return $this; - } - - /** - * Skip system lookup when determining if parameter should be array or struct? - * - * @return bool - */ - public function skipSystemLookup() - { - return $this->_skipSystemLookup; - } - - /** - * Perform an XML-RPC request and return a response. - * - * @param Zend_XmlRpc_Request $request - * @param null|Zend_XmlRpc_Response $response - * @return void - * @throws Zend_XmlRpc_Client_HttpException - */ - public function doRequest($request, $response = null) - { - $this->_lastRequest = $request; - - if (PHP_VERSION_ID < 50600) { - iconv_set_encoding('input_encoding', 'UTF-8'); - iconv_set_encoding('output_encoding', 'UTF-8'); - iconv_set_encoding('internal_encoding', 'UTF-8'); - } else { - ini_set('input_encoding', 'UTF-8'); - ini_set('output_encoding', 'UTF-8'); - ini_set('default_charset', 'UTF-8'); - } - - $http = $this->getHttpClient(); - if($http->getUri() === null) { - $http->setUri($this->_serverAddress); - } - - $http->setHeaders(array( - 'Content-Type: text/xml; charset=utf-8', - 'Accept: text/xml', - )); - - if ($http->getHeader('user-agent') === null) { - $http->setHeaders(array('User-Agent: Zend_XmlRpc_Client')); - } - - $xml = $this->_lastRequest->__toString(); - $http->setRawData($xml); - $httpResponse = $http->request(Zend_Http_Client::POST); - - if (! $httpResponse->isSuccessful()) { - /** - * Exception thrown when an HTTP error occurs - * @see Zend_XmlRpc_Client_HttpException - */ - #require_once 'Zend/XmlRpc/Client/HttpException.php'; - throw new Zend_XmlRpc_Client_HttpException( - $httpResponse->getMessage(), - $httpResponse->getStatus()); - } - - if ($response === null) { - $response = new Zend_XmlRpc_Response(); - } - $this->_lastResponse = $response; - $this->_lastResponse->loadXml(trim($httpResponse->getBody())); - } - - /** - * Send an XML-RPC request to the service (for a specific method) - * - * @param string $method Name of the method we want to call - * @param array $params Array of parameters for the method - * @return mixed - * @throws Zend_XmlRpc_Client_FaultException - */ - public function call($method, $params=array()) - { - if (!$this->skipSystemLookup() && ('system.' != substr($method, 0, 7))) { - // Ensure empty array/struct params are cast correctly - // If system.* methods are not available, bypass. (ZF-2978) - $success = true; - try { - $signatures = $this->getIntrospector()->getMethodSignature($method); - } catch (Zend_XmlRpc_Exception $e) { - $success = false; - } - if ($success) { - $validTypes = array( - Zend_XmlRpc_Value::XMLRPC_TYPE_ARRAY, - Zend_XmlRpc_Value::XMLRPC_TYPE_BASE64, - Zend_XmlRpc_Value::XMLRPC_TYPE_BOOLEAN, - Zend_XmlRpc_Value::XMLRPC_TYPE_DATETIME, - Zend_XmlRpc_Value::XMLRPC_TYPE_DOUBLE, - Zend_XmlRpc_Value::XMLRPC_TYPE_I4, - Zend_XmlRpc_Value::XMLRPC_TYPE_INTEGER, - Zend_XmlRpc_Value::XMLRPC_TYPE_NIL, - Zend_XmlRpc_Value::XMLRPC_TYPE_STRING, - Zend_XmlRpc_Value::XMLRPC_TYPE_STRUCT, - ); - - if (!is_array($params)) { - $params = array($params); - } - - foreach ($params as $key => $param) - { - if ($param instanceof Zend_XmlRpc_Value) { - continue; - } - - if (count($signatures) > 1) { - $type = Zend_XmlRpc_Value::getXmlRpcTypeByValue($param); - foreach ($signatures as $signature) { - if (!is_array($signature)) { - continue; - } - if (isset($signature['parameters'][$key])) { - if ($signature['parameters'][$key] == $type) { - break; - } - } - } - } elseif (isset($signatures[0]['parameters'][$key])) { - $type = $signatures[0]['parameters'][$key]; - } else { - $type = null; - } - - if (empty($type) || !in_array($type, $validTypes)) { - $type = Zend_XmlRpc_Value::AUTO_DETECT_TYPE; - } - - $params[$key] = Zend_XmlRpc_Value::getXmlRpcValue($param, $type); - } - } - } - - $request = $this->_createRequest($method, $params); - - $this->doRequest($request); - - if ($this->_lastResponse->isFault()) { - $fault = $this->_lastResponse->getFault(); - /** - * Exception thrown when an XML-RPC fault is returned - * @see Zend_XmlRpc_Client_FaultException - */ - #require_once 'Zend/XmlRpc/Client/FaultException.php'; - throw new Zend_XmlRpc_Client_FaultException($fault->getMessage(), - $fault->getCode()); - } - - return $this->_lastResponse->getReturnValue(); - } - - /** - * Create request object - * - * @return Zend_XmlRpc_Request - */ - protected function _createRequest($method, $params) - { - return new Zend_XmlRpc_Request($method, $params); - } -} diff --git a/library/Zend/XmlRpc/Client/Exception.php b/library/Zend/XmlRpc/Client/Exception.php deleted file mode 100644 index 000b993f3e..0000000000 --- a/library/Zend/XmlRpc/Client/Exception.php +++ /dev/null @@ -1,40 +0,0 @@ -_system = $client->getProxy('system'); - } - - /** - * Returns the signature for each method on the server, - * autodetecting whether system.multicall() is supported and - * using it if so. - * - * @return array - */ - public function getSignatureForEachMethod() - { - $methods = $this->listMethods(); - - #require_once 'Zend/XmlRpc/Client/FaultException.php'; - try { - $signatures = $this->getSignatureForEachMethodByMulticall($methods); - } catch (Zend_XmlRpc_Client_FaultException $e) { - // degrade to looping - } - - if (empty($signatures)) { - $signatures = $this->getSignatureForEachMethodByLooping($methods); - } - - return $signatures; - } - - /** - * Attempt to get the method signatures in one request via system.multicall(). - * This is a boxcar feature of XML-RPC and is found on fewer servers. However, - * can significantly improve performance if present. - * - * @param array $methods - * @return array array(array(return, param, param, param...)) - */ - public function getSignatureForEachMethodByMulticall($methods = null) - { - if ($methods === null) { - $methods = $this->listMethods(); - } - - $multicallParams = array(); - foreach ($methods as $method) { - $multicallParams[] = array('methodName' => 'system.methodSignature', - 'params' => array($method)); - } - - $serverSignatures = $this->_system->multicall($multicallParams); - - if (! is_array($serverSignatures)) { - $type = gettype($serverSignatures); - $error = "Multicall return is malformed. Expected array, got $type"; - #require_once 'Zend/XmlRpc/Client/IntrospectException.php'; - throw new Zend_XmlRpc_Client_IntrospectException($error); - } - - if (count($serverSignatures) != count($methods)) { - $error = 'Bad number of signatures received from multicall'; - #require_once 'Zend/XmlRpc/Client/IntrospectException.php'; - throw new Zend_XmlRpc_Client_IntrospectException($error); - } - - // Create a new signatures array with the methods name as keys and the signature as value - $signatures = array(); - foreach ($serverSignatures as $i => $signature) { - $signatures[$methods[$i]] = $signature; - } - - return $signatures; - } - - /** - * Get the method signatures for every method by - * successively calling system.methodSignature - * - * @param array $methods - * @return array - */ - public function getSignatureForEachMethodByLooping($methods = null) - { - if ($methods === null) { - $methods = $this->listMethods(); - } - - $signatures = array(); - foreach ($methods as $method) { - $signatures[$method] = $this->getMethodSignature($method); - } - - return $signatures; - } - - /** - * Call system.methodSignature() for the given method - * - * @param array $method - * @return array array(array(return, param, param, param...)) - */ - public function getMethodSignature($method) - { - $signature = $this->_system->methodSignature($method); - if (!is_array($signature)) { - $error = 'Invalid signature for method "' . $method . '"'; - #require_once 'Zend/XmlRpc/Client/IntrospectException.php'; - throw new Zend_XmlRpc_Client_IntrospectException($error); - } - return $signature; - } - - /** - * Call system.listMethods() - * - * @param array $method - * @return array array(method, method, method...) - */ - public function listMethods() - { - return $this->_system->listMethods(); - } - -} diff --git a/library/Zend/XmlRpc/Client/ServerProxy.php b/library/Zend/XmlRpc/Client/ServerProxy.php deleted file mode 100644 index 516619773b..0000000000 --- a/library/Zend/XmlRpc/Client/ServerProxy.php +++ /dev/null @@ -1,95 +0,0 @@ -foo->bar->baz()". - * - * @category Zend - * @package Zend_XmlRpc - * @subpackage Client - * @copyright Copyright (c) 2005-2015 Zend Technologies USA Inc. (http://www.zend.com) - * @license http://framework.zend.com/license/new-bsd New BSD License - */ -class Zend_XmlRpc_Client_ServerProxy -{ - /** - * @var Zend_XmlRpc_Client - */ - private $_client = null; - - /** - * @var string - */ - private $_namespace = ''; - - - /** - * @var array of Zend_XmlRpc_Client_ServerProxy - */ - private $_cache = array(); - - - /** - * Class constructor - * - * @param string $namespace - * @param Zend_XmlRpc_Client $client - */ - public function __construct($client, $namespace = '') - { - $this->_namespace = $namespace; - $this->_client = $client; - } - - - /** - * Get the next successive namespace - * - * @param string $name - * @return Zend_XmlRpc_Client_ServerProxy - */ - public function __get($namespace) - { - $namespace = ltrim("$this->_namespace.$namespace", '.'); - if (!isset($this->_cache[$namespace])) { - $this->_cache[$namespace] = new $this($this->_client, $namespace); - } - return $this->_cache[$namespace]; - } - - - /** - * Call a method in this namespace. - * - * @param string $methodN - * @param array $args - * @return mixed - */ - public function __call($method, $args) - { - $method = ltrim("$this->_namespace.$method", '.'); - return $this->_client->call($method, $args); - } -} diff --git a/library/Zend/XmlRpc/Exception.php b/library/Zend/XmlRpc/Exception.php deleted file mode 100644 index 8b07919235..0000000000 --- a/library/Zend/XmlRpc/Exception.php +++ /dev/null @@ -1,37 +0,0 @@ - messages - * @var array - */ - protected $_internal = array( - 404 => 'Unknown Error', - - // 610 - 619 reflection errors - 610 => 'Invalid method class', - 611 => 'Unable to attach function or callback; not callable', - 612 => 'Unable to load array; not an array', - 613 => 'One or more method records are corrupt or otherwise unusable', - - // 620 - 629 dispatch errors - 620 => 'Method does not exist', - 621 => 'Error instantiating class to invoke method', - 622 => 'Method missing implementation', - 623 => 'Calling parameters do not match signature', - - // 630 - 639 request errors - 630 => 'Unable to read request', - 631 => 'Failed to parse request', - 632 => 'Invalid request, no method passed; request must contain a \'methodName\' tag', - 633 => 'Param must contain a value', - 634 => 'Invalid method name', - 635 => 'Invalid XML provided to request', - 636 => 'Error creating xmlrpc value', - - // 640 - 649 system.* errors - 640 => 'Method does not exist', - - // 650 - 659 response errors - 650 => 'Invalid XML provided for response', - 651 => 'Failed to parse response', - 652 => 'Invalid response', - 653 => 'Invalid XMLRPC value in response', - ); - - /** - * Constructor - * - * @return Zend_XmlRpc_Fault - */ - public function __construct($code = 404, $message = '') - { - $this->setCode($code); - $code = $this->getCode(); - - if (empty($message) && isset($this->_internal[$code])) { - $message = $this->_internal[$code]; - } elseif (empty($message)) { - $message = 'Unknown error'; - } - $this->setMessage($message); - } - - /** - * Set the fault code - * - * @param int $code - * @return Zend_XmlRpc_Fault - */ - public function setCode($code) - { - $this->_code = (int) $code; - return $this; - } - - /** - * Return fault code - * - * @return int - */ - public function getCode() - { - return $this->_code; - } - - /** - * Retrieve fault message - * - * @param string - * @return Zend_XmlRpc_Fault - */ - public function setMessage($message) - { - $this->_message = (string) $message; - return $this; - } - - /** - * Retrieve fault message - * - * @return string - */ - public function getMessage() - { - return $this->_message; - } - - /** - * Set encoding to use in fault response - * - * @param string $encoding - * @return Zend_XmlRpc_Fault - */ - public function setEncoding($encoding) - { - $this->_encoding = $encoding; - Zend_XmlRpc_Value::setEncoding($encoding); - return $this; - } - - /** - * Retrieve current fault encoding - * - * @return string - */ - public function getEncoding() - { - return $this->_encoding; - } - - /** - * Load an XMLRPC fault from XML - * - * @param string $fault - * @return boolean Returns true if successfully loaded fault response, false - * if response was not a fault response - * @throws Zend_XmlRpc_Exception if no or faulty XML provided, or if fault - * response does not contain either code or message - */ - public function loadXml($fault) - { - if (!is_string($fault)) { - #require_once 'Zend/XmlRpc/Exception.php'; - throw new Zend_XmlRpc_Exception('Invalid XML provided to fault'); - } - - try { - $xml = @new SimpleXMLElement($fault); - } catch (Exception $e) { - // Not valid XML - #require_once 'Zend/XmlRpc/Exception.php'; - throw new Zend_XmlRpc_Exception('Failed to parse XML fault: ' . $e->getMessage(), 500, $e); - } - - // Check for fault - if (!$xml->fault) { - // Not a fault - return false; - } - - if (!$xml->fault->value->struct) { - // not a proper fault - #require_once 'Zend/XmlRpc/Exception.php'; - throw new Zend_XmlRpc_Exception('Invalid fault structure', 500); - } - - $structXml = $xml->fault->value->asXML(); - $struct = Zend_XmlRpc_Value::getXmlRpcValue($structXml, Zend_XmlRpc_Value::XML_STRING); - $struct = $struct->getValue(); - - if (isset($struct['faultCode'])) { - $code = $struct['faultCode']; - } - if (isset($struct['faultString'])) { - $message = $struct['faultString']; - } - - if (empty($code) && empty($message)) { - #require_once 'Zend/XmlRpc/Exception.php'; - throw new Zend_XmlRpc_Exception('Fault code and string required'); - } - - if (empty($code)) { - $code = '404'; - } - - if (empty($message)) { - if (isset($this->_internal[$code])) { - $message = $this->_internal[$code]; - } else { - $message = 'Unknown Error'; - } - } - - $this->setCode($code); - $this->setMessage($message); - - return true; - } - - /** - * Determine if an XML response is an XMLRPC fault - * - * @param string $xml - * @return boolean - */ - public static function isFault($xml) - { - $fault = new self(); - #require_once 'Zend/XmlRpc/Exception.php'; - try { - $isFault = $fault->loadXml($xml); - } catch (Zend_XmlRpc_Exception $e) { - $isFault = false; - } - - return $isFault; - } - - /** - * Serialize fault to XML - * - * @return string - */ - public function saveXml() - { - // Create fault value - $faultStruct = array( - 'faultCode' => $this->getCode(), - 'faultString' => $this->getMessage() - ); - $value = Zend_XmlRpc_Value::getXmlRpcValue($faultStruct); - - $generator = Zend_XmlRpc_Value::getGenerator(); - $generator->openElement('methodResponse') - ->openElement('fault'); - $value->generateXml(); - $generator->closeElement('fault') - ->closeElement('methodResponse'); - - return $generator->flush(); - } - - /** - * Return XML fault response - * - * @return string - */ - public function __toString() - { - return $this->saveXML(); - } -} diff --git a/library/Zend/XmlRpc/Generator/DomDocument.php b/library/Zend/XmlRpc/Generator/DomDocument.php deleted file mode 100644 index 99138427a3..0000000000 --- a/library/Zend/XmlRpc/Generator/DomDocument.php +++ /dev/null @@ -1,101 +0,0 @@ -_dom->createElement($name); - - $this->_currentElement = $this->_currentElement->appendChild($newElement); - } - - /** - * Write XML text data into the currently opened XML element - * - * @param string $text - */ - protected function _writeTextData($text) - { - $this->_currentElement->appendChild($this->_dom->createTextNode($text)); - } - - /** - * Close an previously opened XML element - * - * Resets $_currentElement to the next parent node in the hierarchy - * - * @param string $name - * @return void - */ - protected function _closeElement($name) - { - if (isset($this->_currentElement->parentNode)) { - $this->_currentElement = $this->_currentElement->parentNode; - } - } - - /** - * Save XML as a string - * - * @return string - */ - public function saveXml() - { - return $this->_dom->saveXml(); - } - - /** - * Initializes internal objects - * - * @return void - */ - protected function _init() - { - $this->_dom = new DOMDocument('1.0', $this->_encoding); - $this->_currentElement = $this->_dom; - } -} diff --git a/library/Zend/XmlRpc/Generator/GeneratorAbstract.php b/library/Zend/XmlRpc/Generator/GeneratorAbstract.php deleted file mode 100644 index 03afcd696f..0000000000 --- a/library/Zend/XmlRpc/Generator/GeneratorAbstract.php +++ /dev/null @@ -1,150 +0,0 @@ -_encoding = $encoding; - $this->_init(); - } - - /** - * Start XML element - * - * Method opens a new XML element with an element name and an optional value - * - * @param string $name XML tag name - * @param string $value Optional value of the XML tag - * @return Zend_XmlRpc_Generator_Abstract Fluent interface - */ - public function openElement($name, $value = null) - { - $this->_openElement($name); - if ($value !== null) { - $this->_writeTextData($value); - } - - return $this; - } - - /** - * End of an XML element - * - * Method marks the end of an XML element - * - * @param string $name XML tag name - * @return Zend_XmlRpc_Generator_Abstract Fluent interface - */ - public function closeElement($name) - { - $this->_closeElement($name); - - return $this; - } - - /** - * Return XML as a string - * - * @return string - */ - abstract public function saveXml(); - - /** - * Return encoding - * - * @return string - */ - public function getEncoding() - { - return $this->_encoding; - } - - /** - * Returns the XML as a string and flushes all internal buffers - * - * @return string - */ - public function flush() - { - $xml = $this->saveXml(); - $this->_init(); - return $xml; - } - - /** - * Returns XML without document declaration - * - * @return string - */ - public function __toString() - { - return $this->stripDeclaration($this->saveXml()); - } - - /** - * Removes XML declaration from a string - * - * @param string $xml - * @return string - */ - public function stripDeclaration($xml) - { - return preg_replace('/<\?xml version="1.0"( encoding="[^\"]*")?\?>\n/u', '', $xml); - } - - /** - * Start XML element - * - * @param string $name XML element name - */ - abstract protected function _openElement($name); - - /** - * Write XML text data into the currently opened XML element - * - * @param string $text - */ - abstract protected function _writeTextData($text); - - /** - * End XML element - * - * @param string $name - */ - abstract protected function _closeElement($name); -} diff --git a/library/Zend/XmlRpc/Generator/XmlWriter.php b/library/Zend/XmlRpc/Generator/XmlWriter.php deleted file mode 100644 index 62dc84fa33..0000000000 --- a/library/Zend/XmlRpc/Generator/XmlWriter.php +++ /dev/null @@ -1,93 +0,0 @@ -_xmlWriter = new XMLWriter(); - $this->_xmlWriter->openMemory(); - $this->_xmlWriter->startDocument('1.0', $this->_encoding); - } - - - /** - * Open a new XML element - * - * @param string $name XML element name - * @return void - */ - protected function _openElement($name) - { - $this->_xmlWriter->startElement($name); - } - - /** - * Write XML text data into the currently opened XML element - * - * @param string $text XML text data - * @return void - */ - protected function _writeTextData($text) - { - $this->_xmlWriter->text($text); - } - - /** - * Close an previously opened XML element - * - * @param string $name - * @return void - */ - protected function _closeElement($name) - { - $this->_xmlWriter->endElement(); - - return $this; - } - - public function saveXml() - { - $xml = $this->_xmlWriter->flush(false); - return $xml; - } -} diff --git a/library/Zend/XmlRpc/Request.php b/library/Zend/XmlRpc/Request.php deleted file mode 100644 index b796025ab5..0000000000 --- a/library/Zend/XmlRpc/Request.php +++ /dev/null @@ -1,445 +0,0 @@ -setMethod($method); - } - - if ($params !== null) { - $this->setParams($params); - } - } - - - /** - * Set encoding to use in request - * - * @param string $encoding - * @return Zend_XmlRpc_Request - */ - public function setEncoding($encoding) - { - $this->_encoding = $encoding; - Zend_XmlRpc_Value::setEncoding($encoding); - return $this; - } - - /** - * Retrieve current request encoding - * - * @return string - */ - public function getEncoding() - { - return $this->_encoding; - } - - /** - * Set method to call - * - * @param string $method - * @return boolean Returns true on success, false if method name is invalid - */ - public function setMethod($method) - { - if (!is_string($method) || !preg_match('/^[a-z0-9_.:\/]+$/i', $method)) { - $this->_fault = new Zend_XmlRpc_Fault(634, 'Invalid method name ("' . $method . '")'); - $this->_fault->setEncoding($this->getEncoding()); - return false; - } - - $this->_method = $method; - return true; - } - - /** - * Retrieve call method - * - * @return string - */ - public function getMethod() - { - return $this->_method; - } - - /** - * Add a parameter to the parameter stack - * - * Adds a parameter to the parameter stack, associating it with the type - * $type if provided - * - * @param mixed $value - * @param string $type Optional; type hinting - * @return void - */ - public function addParam($value, $type = null) - { - $this->_params[] = $value; - if (null === $type) { - // Detect type if not provided explicitly - if ($value instanceof Zend_XmlRpc_Value) { - $type = $value->getType(); - } else { - $xmlRpcValue = Zend_XmlRpc_Value::getXmlRpcValue($value); - $type = $xmlRpcValue->getType(); - } - } - $this->_types[] = $type; - $this->_xmlRpcParams[] = array('value' => $value, 'type' => $type); - } - - /** - * Set the parameters array - * - * If called with a single, array value, that array is used to set the - * parameters stack. If called with multiple values or a single non-array - * value, the arguments are used to set the parameters stack. - * - * Best is to call with array of the format, in order to allow type hinting - * when creating the XMLRPC values for each parameter: - * - * $array = array( - * array( - * 'value' => $value, - * 'type' => $type - * )[, ... ] - * ); - * - * - * @access public - * @return void - */ - public function setParams() - { - $argc = func_num_args(); - $argv = func_get_args(); - if (0 == $argc) { - return; - } - - if ((1 == $argc) && is_array($argv[0])) { - $params = array(); - $types = array(); - $wellFormed = true; - foreach ($argv[0] as $arg) { - if (!is_array($arg) || !isset($arg['value'])) { - $wellFormed = false; - break; - } - $params[] = $arg['value']; - - if (!isset($arg['type'])) { - $xmlRpcValue = Zend_XmlRpc_Value::getXmlRpcValue($arg['value']); - $arg['type'] = $xmlRpcValue->getType(); - } - $types[] = $arg['type']; - } - if ($wellFormed) { - $this->_xmlRpcParams = $argv[0]; - $this->_params = $params; - $this->_types = $types; - } else { - $this->_params = $argv[0]; - $this->_types = array(); - $xmlRpcParams = array(); - foreach ($argv[0] as $arg) { - if ($arg instanceof Zend_XmlRpc_Value) { - $type = $arg->getType(); - } else { - $xmlRpcValue = Zend_XmlRpc_Value::getXmlRpcValue($arg); - $type = $xmlRpcValue->getType(); - } - $xmlRpcParams[] = array('value' => $arg, 'type' => $type); - $this->_types[] = $type; - } - $this->_xmlRpcParams = $xmlRpcParams; - } - return; - } - - $this->_params = $argv; - $this->_types = array(); - $xmlRpcParams = array(); - foreach ($argv as $arg) { - if ($arg instanceof Zend_XmlRpc_Value) { - $type = $arg->getType(); - } else { - $xmlRpcValue = Zend_XmlRpc_Value::getXmlRpcValue($arg); - $type = $xmlRpcValue->getType(); - } - $xmlRpcParams[] = array('value' => $arg, 'type' => $type); - $this->_types[] = $type; - } - $this->_xmlRpcParams = $xmlRpcParams; - } - - /** - * Retrieve the array of parameters - * - * @return array - */ - public function getParams() - { - return $this->_params; - } - - /** - * Return parameter types - * - * @return array - */ - public function getTypes() - { - return $this->_types; - } - - /** - * Load XML and parse into request components - * - * @param string $request - * @return boolean True on success, false if an error occurred. - */ - public function loadXml($request) - { - if (!is_string($request)) { - $this->_fault = new Zend_XmlRpc_Fault(635); - $this->_fault->setEncoding($this->getEncoding()); - return false; - } - - try { - $xml = Zend_Xml_Security::scan($request); - } catch (Zend_Xml_Exception $e) { - // Not valid XML - $this->_fault = new Zend_XmlRpc_Fault(631); - $this->_fault->setEncoding($this->getEncoding()); - return false; - } - - // Check for method name - if (empty($xml->methodName)) { - // Missing method name - $this->_fault = new Zend_XmlRpc_Fault(632); - $this->_fault->setEncoding($this->getEncoding()); - return false; - } - - $this->_method = (string) $xml->methodName; - - // Check for parameters - if (!empty($xml->params)) { - $types = array(); - $argv = array(); - foreach ($xml->params->children() as $param) { - if (!isset($param->value)) { - $this->_fault = new Zend_XmlRpc_Fault(633); - $this->_fault->setEncoding($this->getEncoding()); - return false; - } - - try { - $param = Zend_XmlRpc_Value::getXmlRpcValue($param->value, Zend_XmlRpc_Value::XML_STRING); - $types[] = $param->getType(); - $argv[] = $param->getValue(); - } catch (Exception $e) { - $this->_fault = new Zend_XmlRpc_Fault(636); - $this->_fault->setEncoding($this->getEncoding()); - return false; - } - } - - $this->_types = $types; - $this->_params = $argv; - } - - $this->_xml = $request; - - return true; - } - - /** - * Does the current request contain errors and should it return a fault - * response? - * - * @return boolean - */ - public function isFault() - { - return $this->_fault instanceof Zend_XmlRpc_Fault; - } - - /** - * Retrieve the fault response, if any - * - * @return null|Zend_XmlRpc_Fault - */ - public function getFault() - { - return $this->_fault; - } - - /** - * Retrieve method parameters as XMLRPC values - * - * @return array - */ - protected function _getXmlRpcParams() - { - $params = array(); - if (is_array($this->_xmlRpcParams)) { - foreach ($this->_xmlRpcParams as $param) { - $value = $param['value']; - $type = isset($param['type']) ? $param['type'] : Zend_XmlRpc_Value::AUTO_DETECT_TYPE; - - if (!$value instanceof Zend_XmlRpc_Value) { - $value = Zend_XmlRpc_Value::getXmlRpcValue($value, $type); - } - $params[] = $value; - } - } - - return $params; - } - - /** - * Create XML request - * - * @return string - */ - public function saveXml() - { - $args = $this->_getXmlRpcParams(); - $method = $this->getMethod(); - - $generator = Zend_XmlRpc_Value::getGenerator(); - $generator->openElement('methodCall') - ->openElement('methodName', $method) - ->closeElement('methodName'); - - if (is_array($args) && count($args)) { - $generator->openElement('params'); - - foreach ($args as $arg) { - $generator->openElement('param'); - $arg->generateXml(); - $generator->closeElement('param'); - } - $generator->closeElement('params'); - } - $generator->closeElement('methodCall'); - - return $generator->flush(); - } - - /** - * Return XML request - * - * @return string - */ - public function __toString() - { - return $this->saveXML(); - } -} diff --git a/library/Zend/XmlRpc/Request/Http.php b/library/Zend/XmlRpc/Request/Http.php deleted file mode 100644 index a116bfd13c..0000000000 --- a/library/Zend/XmlRpc/Request/Http.php +++ /dev/null @@ -1,124 +0,0 @@ -_fault = new Zend_XmlRpc_Fault(630); - return; - } - - $this->_xml = $xml; - - $this->loadXml($xml); - } - - /** - * Retrieve the raw XML request - * - * @return string - */ - public function getRawRequest() - { - return $this->_xml; - } - - /** - * Get headers - * - * Gets all headers as key => value pairs and returns them. - * - * @return array - */ - public function getHeaders() - { - if (null === $this->_headers) { - $this->_headers = array(); - foreach ($_SERVER as $key => $value) { - if ('HTTP_' == substr($key, 0, 5)) { - $header = str_replace(' ', '-', ucwords(strtolower(str_replace('_', ' ', substr($key, 5))))); - $this->_headers[$header] = $value; - } - } - } - - return $this->_headers; - } - - /** - * Retrieve the full HTTP request, including headers and XML - * - * @return string - */ - public function getFullRequest() - { - $request = ''; - foreach ($this->getHeaders() as $key => $value) { - $request .= $key . ': ' . $value . "\n"; - } - - $request .= $this->_xml; - - return $request; - } -} diff --git a/library/Zend/XmlRpc/Request/Stdin.php b/library/Zend/XmlRpc/Request/Stdin.php deleted file mode 100644 index 92e8e736cb..0000000000 --- a/library/Zend/XmlRpc/Request/Stdin.php +++ /dev/null @@ -1,84 +0,0 @@ -_fault = new Zend_XmlRpc_Server_Exception(630); - return; - } - - $xml = ''; - while (!feof($fh)) { - $xml .= fgets($fh); - } - fclose($fh); - - $this->_xml = $xml; - - $this->loadXml($xml); - } - - /** - * Retrieve the raw XML request - * - * @return string - */ - public function getRawRequest() - { - return $this->_xml; - } -} diff --git a/library/Zend/XmlRpc/Response.php b/library/Zend/XmlRpc/Response.php deleted file mode 100644 index 3cdffb7c15..0000000000 --- a/library/Zend/XmlRpc/Response.php +++ /dev/null @@ -1,255 +0,0 @@ -setReturnValue($return, $type); - } - - /** - * Set encoding to use in response - * - * @param string $encoding - * @return Zend_XmlRpc_Response - */ - public function setEncoding($encoding) - { - $this->_encoding = $encoding; - Zend_XmlRpc_Value::setEncoding($encoding); - return $this; - } - - /** - * Retrieve current response encoding - * - * @return string - */ - public function getEncoding() - { - return $this->_encoding; - } - - /** - * Set the return value - * - * Sets the return value, with optional type hinting if provided. - * - * @param mixed $value - * @param string $type - * @return void - */ - public function setReturnValue($value, $type = null) - { - $this->_return = $value; - $this->_type = (string) $type; - } - - /** - * Retrieve the return value - * - * @return mixed - */ - public function getReturnValue() - { - return $this->_return; - } - - /** - * Retrieve the XMLRPC value for the return value - * - * @return Zend_XmlRpc_Value - */ - protected function _getXmlRpcReturn() - { - return Zend_XmlRpc_Value::getXmlRpcValue($this->_return); - } - - /** - * Is the response a fault response? - * - * @return boolean - */ - public function isFault() - { - return $this->_fault instanceof Zend_XmlRpc_Fault; - } - - /** - * Returns the fault, if any. - * - * @return null|Zend_XmlRpc_Fault - */ - public function getFault() - { - return $this->_fault; - } - - /** - * Load a response from an XML response - * - * Attempts to load a response from an XMLRPC response, autodetecting if it - * is a fault response. - * - * @param string $response - * @return boolean True if a valid XMLRPC response, false if a fault - * response or invalid input - */ - public function loadXml($response) - { - if (!is_string($response)) { - $this->_fault = new Zend_XmlRpc_Fault(650); - $this->_fault->setEncoding($this->getEncoding()); - return false; - } - - try { - $xml = Zend_Xml_Security::scan($response); - } catch (Zend_Xml_Exception $e) { - // Not valid XML - $this->_fault = new Zend_XmlRpc_Fault(651); - $this->_fault->setEncoding($this->getEncoding()); - return false; - } - - if (!empty($xml->fault)) { - // fault response - $this->_fault = new Zend_XmlRpc_Fault(); - $this->_fault->setEncoding($this->getEncoding()); - $this->_fault->loadXml($response); - return false; - } - - if (empty($xml->params)) { - // Invalid response - $this->_fault = new Zend_XmlRpc_Fault(652); - $this->_fault->setEncoding($this->getEncoding()); - return false; - } - - try { - if (!isset($xml->params) || !isset($xml->params->param) || !isset($xml->params->param->value)) { - #require_once 'Zend/XmlRpc/Value/Exception.php'; - throw new Zend_XmlRpc_Value_Exception('Missing XML-RPC value in XML'); - } - $valueXml = $xml->params->param->value->asXML(); - $value = Zend_XmlRpc_Value::getXmlRpcValue($valueXml, Zend_XmlRpc_Value::XML_STRING); - } catch (Zend_XmlRpc_Value_Exception $e) { - $this->_fault = new Zend_XmlRpc_Fault(653); - $this->_fault->setEncoding($this->getEncoding()); - return false; - } - - $this->setReturnValue($value->getValue()); - return true; - } - - /** - * Return response as XML - * - * @return string - */ - public function saveXml() - { - $value = $this->_getXmlRpcReturn(); - $generator = Zend_XmlRpc_Value::getGenerator(); - $generator->openElement('methodResponse') - ->openElement('params') - ->openElement('param'); - $value->generateXml(); - $generator->closeElement('param') - ->closeElement('params') - ->closeElement('methodResponse'); - - return $generator->flush(); - } - - /** - * Return XML response - * - * @return string - */ - public function __toString() - { - return $this->saveXML(); - } -} diff --git a/library/Zend/XmlRpc/Response/Http.php b/library/Zend/XmlRpc/Response/Http.php deleted file mode 100644 index e4d8257cfe..0000000000 --- a/library/Zend/XmlRpc/Response/Http.php +++ /dev/null @@ -1,51 +0,0 @@ -getEncoding())); - } - - return parent::__toString(); - } -} diff --git a/library/Zend/XmlRpc/Server.php b/library/Zend/XmlRpc/Server.php deleted file mode 100644 index 1f79a0cc31..0000000000 --- a/library/Zend/XmlRpc/Server.php +++ /dev/null @@ -1,615 +0,0 @@ - - * #require_once 'Zend/XmlRpc/Server.php'; - * #require_once 'Zend/XmlRpc/Server/Cache.php'; - * #require_once 'Zend/XmlRpc/Server/Fault.php'; - * #require_once 'My/Exception.php'; - * #require_once 'My/Fault/Observer.php'; - * - * // Instantiate server - * $server = new Zend_XmlRpc_Server(); - * - * // Allow some exceptions to report as fault responses: - * Zend_XmlRpc_Server_Fault::attachFaultException('My_Exception'); - * Zend_XmlRpc_Server_Fault::attachObserver('My_Fault_Observer'); - * - * // Get or build dispatch table: - * if (!Zend_XmlRpc_Server_Cache::get($filename, $server)) { - * #require_once 'Some/Service/Class.php'; - * #require_once 'Another/Service/Class.php'; - * - * // Attach Some_Service_Class in 'some' namespace - * $server->setClass('Some_Service_Class', 'some'); - * - * // Attach Another_Service_Class in 'another' namespace - * $server->setClass('Another_Service_Class', 'another'); - * - * // Create dispatch table cache file - * Zend_XmlRpc_Server_Cache::save($filename, $server); - * } - * - * $response = $server->handle(); - * echo $response; - * - * - * @category Zend - * @package Zend_XmlRpc - * @subpackage Server - * @copyright Copyright (c) 2005-2015 Zend Technologies USA Inc. (http://www.zend.com) - * @license http://framework.zend.com/license/new-bsd New BSD License - */ -class Zend_XmlRpc_Server extends Zend_Server_Abstract -{ - /** - * Character encoding - * @var string - */ - protected $_encoding = 'UTF-8'; - - /** - * Request processed - * @var null|Zend_XmlRpc_Request - */ - protected $_request = null; - - /** - * Class to use for responses; defaults to {@link Zend_XmlRpc_Response_Http} - * @var string - */ - protected $_responseClass = 'Zend_XmlRpc_Response_Http'; - - /** - * Dispatch table of name => method pairs - * @var Zend_Server_Definition - */ - protected $_table; - - /** - * PHP types => XML-RPC types - * @var array - */ - protected $_typeMap = array( - 'i4' => 'i4', - 'int' => 'int', - 'integer' => 'int', - 'Zend_Crypt_Math_BigInteger' => 'i8', - 'i8' => 'i8', - 'ex:i8' => 'i8', - 'double' => 'double', - 'float' => 'double', - 'real' => 'double', - 'boolean' => 'boolean', - 'bool' => 'boolean', - 'true' => 'boolean', - 'false' => 'boolean', - 'string' => 'string', - 'str' => 'string', - 'base64' => 'base64', - 'dateTime.iso8601' => 'dateTime.iso8601', - 'date' => 'dateTime.iso8601', - 'time' => 'dateTime.iso8601', - 'time' => 'dateTime.iso8601', - 'Zend_Date' => 'dateTime.iso8601', - 'DateTime' => 'dateTime.iso8601', - 'array' => 'array', - 'struct' => 'struct', - 'null' => 'nil', - 'nil' => 'nil', - 'ex:nil' => 'nil', - 'void' => 'void', - 'mixed' => 'struct', - ); - - /** - * Send arguments to all methods or just constructor? - * - * @var bool - */ - protected $_sendArgumentsToAllMethods = true; - - /** - * Constructor - * - * Creates system.* methods. - * - * @return void - */ - public function __construct() - { - $this->_table = new Zend_Server_Definition(); - $this->_registerSystemMethods(); - } - - /** - * Proxy calls to system object - * - * @param string $method - * @param array $params - * @return mixed - * @throws Zend_XmlRpc_Server_Exception - */ - public function __call($method, $params) - { - $system = $this->getSystem(); - if (!method_exists($system, $method)) { - #require_once 'Zend/XmlRpc/Server/Exception.php'; - throw new Zend_XmlRpc_Server_Exception('Unknown instance method called on server: ' . $method); - } - return call_user_func_array(array($system, $method), $params); - } - - /** - * Attach a callback as an XMLRPC method - * - * Attaches a callback as an XMLRPC method, prefixing the XMLRPC method name - * with $namespace, if provided. Reflection is done on the callback's - * docblock to create the methodHelp for the XMLRPC method. - * - * Additional arguments to pass to the function at dispatch may be passed; - * any arguments following the namespace will be aggregated and passed at - * dispatch time. - * - * @param string|array $function Valid callback - * @param string $namespace Optional namespace prefix - * @return void - * @throws Zend_XmlRpc_Server_Exception - */ - public function addFunction($function, $namespace = '') - { - if (!is_string($function) && !is_array($function)) { - #require_once 'Zend/XmlRpc/Server/Exception.php'; - throw new Zend_XmlRpc_Server_Exception('Unable to attach function; invalid', 611); - } - - $argv = null; - if (2 < func_num_args()) { - $argv = func_get_args(); - $argv = array_slice($argv, 2); - } - - $function = (array) $function; - foreach ($function as $func) { - if (!is_string($func) || !function_exists($func)) { - #require_once 'Zend/XmlRpc/Server/Exception.php'; - throw new Zend_XmlRpc_Server_Exception('Unable to attach function; invalid', 611); - } - $reflection = Zend_Server_Reflection::reflectFunction($func, $argv, $namespace); - $this->_buildSignature($reflection); - } - } - - /** - * Attach class methods as XMLRPC method handlers - * - * $class may be either a class name or an object. Reflection is done on the - * class or object to determine the available public methods, and each is - * attached to the server as an available method; if a $namespace has been - * provided, that namespace is used to prefix the XMLRPC method names. - * - * Any additional arguments beyond $namespace will be passed to a method at - * invocation. - * - * @param string|object $class - * @param string $namespace Optional - * @param mixed $argv Optional arguments to pass to methods - * @return void - * @throws Zend_XmlRpc_Server_Exception on invalid input - */ - public function setClass($class, $namespace = '', $argv = null) - { - if (is_string($class) && !class_exists($class)) { - #require_once 'Zend/XmlRpc/Server/Exception.php'; - throw new Zend_XmlRpc_Server_Exception('Invalid method class', 610); - } - - $args = null; - if (2 < func_num_args()) { - $args = func_get_args(); - $args = array_slice($args, 2); - } - - $dispatchable = Zend_Server_Reflection::reflectClass($class, $args, $namespace); - foreach ($dispatchable->getMethods() as $reflection) { - $this->_buildSignature($reflection, $class); - } - } - - /** - * Raise an xmlrpc server fault - * - * @param string|Exception $fault - * @param int $code - * @return Zend_XmlRpc_Server_Fault - */ - public function fault($fault = null, $code = 404) - { - if (!$fault instanceof Exception) { - $fault = (string) $fault; - if (empty($fault)) { - $fault = 'Unknown Error'; - } - #require_once 'Zend/XmlRpc/Server/Exception.php'; - $fault = new Zend_XmlRpc_Server_Exception($fault, $code); - } - - return Zend_XmlRpc_Server_Fault::getInstance($fault); - } - - /** - * Handle an xmlrpc call - * - * @param Zend_XmlRpc_Request $request Optional - * @return Zend_XmlRpc_Response|Zend_XmlRpc_Fault - */ - public function handle($request = false) - { - // Get request - if ((!$request || !$request instanceof Zend_XmlRpc_Request) - && (null === ($request = $this->getRequest())) - ) { - #require_once 'Zend/XmlRpc/Request/Http.php'; - $request = new Zend_XmlRpc_Request_Http(); - $request->setEncoding($this->getEncoding()); - } - - $this->setRequest($request); - - if ($request->isFault()) { - $response = $request->getFault(); - } else { - try { - $response = $this->_handle($request); - } catch (Exception $e) { - $response = $this->fault($e); - } - } - - // Set output encoding - $response->setEncoding($this->getEncoding()); - - return $response; - } - - /** - * Load methods as returned from {@link getFunctions} - * - * Typically, you will not use this method; it will be called using the - * results pulled from {@link Zend_XmlRpc_Server_Cache::get()}. - * - * @param array|Zend_Server_Definition $definition - * @return void - * @throws Zend_XmlRpc_Server_Exception on invalid input - */ - public function loadFunctions($definition) - { - if (!is_array($definition) && (!$definition instanceof Zend_Server_Definition)) { - if (is_object($definition)) { - $type = get_class($definition); - } else { - $type = gettype($definition); - } - #require_once 'Zend/XmlRpc/Server/Exception.php'; - throw new Zend_XmlRpc_Server_Exception('Unable to load server definition; must be an array or Zend_Server_Definition, received ' . $type, 612); - } - - $this->_table->clearMethods(); - $this->_registerSystemMethods(); - - if ($definition instanceof Zend_Server_Definition) { - $definition = $definition->getMethods(); - } - - foreach ($definition as $key => $method) { - if ('system.' == substr($key, 0, 7)) { - continue; - } - $this->_table->addMethod($method, $key); - } - } - - /** - * Set encoding - * - * @param string $encoding - * @return Zend_XmlRpc_Server - */ - public function setEncoding($encoding) - { - $this->_encoding = $encoding; - Zend_XmlRpc_Value::setEncoding($encoding); - return $this; - } - - /** - * Retrieve current encoding - * - * @return string - */ - public function getEncoding() - { - return $this->_encoding; - } - - /** - * Do nothing; persistence is handled via {@link Zend_XmlRpc_Server_Cache} - * - * @param mixed $mode - * @return void - */ - public function setPersistence($mode) - { - } - - /** - * Set the request object - * - * @param string|Zend_XmlRpc_Request $request - * @return Zend_XmlRpc_Server - * @throws Zend_XmlRpc_Server_Exception on invalid request class or object - */ - public function setRequest($request) - { - if (is_string($request) && class_exists($request)) { - $request = new $request(); - if (!$request instanceof Zend_XmlRpc_Request) { - #require_once 'Zend/XmlRpc/Server/Exception.php'; - throw new Zend_XmlRpc_Server_Exception('Invalid request class'); - } - $request->setEncoding($this->getEncoding()); - } elseif (!$request instanceof Zend_XmlRpc_Request) { - #require_once 'Zend/XmlRpc/Server/Exception.php'; - throw new Zend_XmlRpc_Server_Exception('Invalid request object'); - } - - $this->_request = $request; - return $this; - } - - /** - * Return currently registered request object - * - * @return null|Zend_XmlRpc_Request - */ - public function getRequest() - { - return $this->_request; - } - - /** - * Set the class to use for the response - * - * @param string $class - * @return boolean True if class was set, false if not - */ - public function setResponseClass($class) - { - if (!class_exists($class) or - ($c = new ReflectionClass($class) and !$c->isSubclassOf('Zend_XmlRpc_Response'))) { - - #require_once 'Zend/XmlRpc/Server/Exception.php'; - throw new Zend_XmlRpc_Server_Exception('Invalid response class'); - } - $this->_responseClass = $class; - return true; - } - - /** - * Retrieve current response class - * - * @return string - */ - public function getResponseClass() - { - return $this->_responseClass; - } - - /** - * Retrieve dispatch table - * - * @return array - */ - public function getDispatchTable() - { - return $this->_table; - } - - /** - * Returns a list of registered methods - * - * Returns an array of dispatchables (Zend_Server_Reflection_Function, - * _Method, and _Class items). - * - * @return array - */ - public function getFunctions() - { - return $this->_table->toArray(); - } - - /** - * Retrieve system object - * - * @return Zend_XmlRpc_Server_System - */ - public function getSystem() - { - return $this->_system; - } - - /** - * Send arguments to all methods? - * - * If setClass() is used to add classes to the server, this flag defined - * how to handle arguments. If set to true, all methods including constructor - * will receive the arguments. If set to false, only constructor will receive the - * arguments - */ - public function sendArgumentsToAllMethods($flag = null) - { - if ($flag === null) { - return $this->_sendArgumentsToAllMethods; - } - - $this->_sendArgumentsToAllMethods = (bool)$flag; - return $this; - } - - /** - * Map PHP type to XML-RPC type - * - * @param string $type - * @return string - */ - protected function _fixType($type) - { - if (isset($this->_typeMap[$type])) { - return $this->_typeMap[$type]; - } - return 'void'; - } - - /** - * Handle an xmlrpc call (actual work) - * - * @param Zend_XmlRpc_Request $request - * @return Zend_XmlRpc_Response - * @throws Zend_XmlRpcServer_Exception|Exception - * Zend_XmlRpcServer_Exceptions are thrown for internal errors; otherwise, - * any other exception may be thrown by the callback - */ - protected function _handle(Zend_XmlRpc_Request $request) - { - $method = $request->getMethod(); - - // Check for valid method - if (!$this->_table->hasMethod($method)) { - #require_once 'Zend/XmlRpc/Server/Exception.php'; - throw new Zend_XmlRpc_Server_Exception('Method "' . $method . '" does not exist', 620); - } - - $info = $this->_table->getMethod($method); - $params = $request->getParams(); - $argv = $info->getInvokeArguments(); - if (0 < count($argv) and $this->sendArgumentsToAllMethods()) { - $params = array_merge($params, $argv); - } - - // Check calling parameters against signatures - $matched = false; - $sigCalled = $request->getTypes(); - - $sigLength = count($sigCalled); - $paramsLen = count($params); - if ($sigLength < $paramsLen) { - for ($i = $sigLength; $i < $paramsLen; ++$i) { - $xmlRpcValue = Zend_XmlRpc_Value::getXmlRpcValue($params[$i]); - $sigCalled[] = $xmlRpcValue->getType(); - } - } - - $signatures = $info->getPrototypes(); - foreach ($signatures as $signature) { - $sigParams = $signature->getParameters(); - if ($sigCalled === $sigParams) { - $matched = true; - break; - } - } - if (!$matched) { - #require_once 'Zend/XmlRpc/Server/Exception.php'; - throw new Zend_XmlRpc_Server_Exception('Calling parameters do not match signature', 623); - } - - $return = $this->_dispatch($info, $params); - $responseClass = $this->getResponseClass(); - return new $responseClass($return); - } - - /** - * Register system methods with the server - * - * @return void - */ - protected function _registerSystemMethods() - { - $system = new Zend_XmlRpc_Server_System($this); - $this->_system = $system; - $this->setClass($system, 'system'); - } -} diff --git a/library/Zend/XmlRpc/Server/Cache.php b/library/Zend/XmlRpc/Server/Cache.php deleted file mode 100644 index c77178d6fb..0000000000 --- a/library/Zend/XmlRpc/Server/Cache.php +++ /dev/null @@ -1,46 +0,0 @@ - true); - - /** - * @var array Array of fault observers - */ - protected static $_observers = array(); - - /** - * Constructor - * - * @param Exception $e - * @return Zend_XmlRpc_Server_Fault - */ - public function __construct(Exception $e) - { - $this->_exception = $e; - $code = 404; - $message = 'Unknown error'; - $exceptionClass = get_class($e); - - foreach (array_keys(self::$_faultExceptionClasses) as $class) { - if ($e instanceof $class) { - $code = $e->getCode(); - $message = $e->getMessage(); - break; - } - } - - parent::__construct($code, $message); - - // Notify exception observers, if present - if (!empty(self::$_observers)) { - foreach (array_keys(self::$_observers) as $observer) { - call_user_func(array($observer, 'observe'), $this); - } - } - } - - /** - * Return Zend_XmlRpc_Server_Fault instance - * - * @param Exception $e - * @return Zend_XmlRpc_Server_Fault - */ - public static function getInstance(Exception $e) - { - return new self($e); - } - - /** - * Attach valid exceptions that can be used to define xmlrpc faults - * - * @param string|array $classes Class name or array of class names - * @return void - */ - public static function attachFaultException($classes) - { - if (!is_array($classes)) { - $classes = (array) $classes; - } - - foreach ($classes as $class) { - if (is_string($class) && class_exists($class)) { - self::$_faultExceptionClasses[$class] = true; - } - } - } - - /** - * Detach fault exception classes - * - * @param string|array $classes Class name or array of class names - * @return void - */ - public static function detachFaultException($classes) - { - if (!is_array($classes)) { - $classes = (array) $classes; - } - - foreach ($classes as $class) { - if (is_string($class) && isset(self::$_faultExceptionClasses[$class])) { - unset(self::$_faultExceptionClasses[$class]); - } - } - } - - /** - * Attach an observer class - * - * Allows observation of xmlrpc server faults, thus allowing logging or mail - * notification of fault responses on the xmlrpc server. - * - * Expects a valid class name; that class must have a public static method - * 'observe' that accepts an exception as its sole argument. - * - * @param string $class - * @return boolean - */ - public static function attachObserver($class) - { - if (!is_string($class) - || !class_exists($class) - || !is_callable(array($class, 'observe'))) - { - return false; - } - - if (!isset(self::$_observers[$class])) { - self::$_observers[$class] = true; - } - - return true; - } - - /** - * Detach an observer - * - * @param string $class - * @return boolean - */ - public static function detachObserver($class) - { - if (!isset(self::$_observers[$class])) { - return false; - } - - unset(self::$_observers[$class]); - return true; - } - - /** - * Retrieve the exception - * - * @access public - * @return Exception - */ - public function getException() - { - return $this->_exception; - } -} diff --git a/library/Zend/XmlRpc/Server/System.php b/library/Zend/XmlRpc/Server/System.php deleted file mode 100644 index 21beb4c913..0000000000 --- a/library/Zend/XmlRpc/Server/System.php +++ /dev/null @@ -1,162 +0,0 @@ -_server = $server; - } - - /** - * List all available XMLRPC methods - * - * Returns an array of methods. - * - * @return array - */ - public function listMethods() - { - $table = $this->_server->getDispatchTable()->getMethods(); - return array_keys($table); - } - - /** - * Display help message for an XMLRPC method - * - * @param string $method - * @return string - */ - public function methodHelp($method) - { - $table = $this->_server->getDispatchTable(); - if (!$table->hasMethod($method)) { - #require_once 'Zend/XmlRpc/Server/Exception.php'; - throw new Zend_XmlRpc_Server_Exception('Method "' . $method . '" does not exist', 640); - } - - return $table->getMethod($method)->getMethodHelp(); - } - - /** - * Return a method signature - * - * @param string $method - * @return array - */ - public function methodSignature($method) - { - $table = $this->_server->getDispatchTable(); - if (!$table->hasMethod($method)) { - #require_once 'Zend/XmlRpc/Server/Exception.php'; - throw new Zend_XmlRpc_Server_Exception('Method "' . $method . '" does not exist', 640); - } - $method = $table->getMethod($method)->toArray(); - return $method['prototypes']; - } - - /** - * Multicall - boxcar feature of XML-RPC for calling multiple methods - * in a single request. - * - * Expects a an array of structs representing method calls, each element - * having the keys: - * - methodName - * - params - * - * Returns an array of responses, one for each method called, with the value - * returned by the method. If an error occurs for a given method, returns a - * struct with a fault response. - * - * @see http://www.xmlrpc.com/discuss/msgReader$1208 - * @param array $methods - * @return array - */ - public function multicall($methods) - { - $responses = array(); - foreach ($methods as $method) { - $fault = false; - if (!is_array($method)) { - $fault = $this->_server->fault('system.multicall expects each method to be a struct', 601); - } elseif (!isset($method['methodName'])) { - $fault = $this->_server->fault('Missing methodName: ' . var_export($methods, 1), 602); - } elseif (!isset($method['params'])) { - $fault = $this->_server->fault('Missing params', 603); - } elseif (!is_array($method['params'])) { - $fault = $this->_server->fault('Params must be an array', 604); - } else { - if ('system.multicall' == $method['methodName']) { - // don't allow recursive calls to multicall - $fault = $this->_server->fault('Recursive system.multicall forbidden', 605); - } - } - - if (!$fault) { - try { - $request = new Zend_XmlRpc_Request(); - $request->setMethod($method['methodName']); - $request->setParams($method['params']); - $response = $this->_server->handle($request); - if ($response instanceof Zend_XmlRpc_Fault - || $response->isFault() - ) { - $fault = $response; - } else { - $responses[] = $response->getReturnValue(); - } - } catch (Exception $e) { - $fault = $this->_server->fault($e); - } - } - - if ($fault) { - $responses[] = array( - 'faultCode' => $fault->getCode(), - 'faultString' => $fault->getMessage() - ); - } - } - - return $responses; - } -} diff --git a/library/Zend/XmlRpc/Value.php b/library/Zend/XmlRpc/Value.php deleted file mode 100644 index 2af87bdff6..0000000000 --- a/library/Zend/XmlRpc/Value.php +++ /dev/null @@ -1,525 +0,0 @@ -_type; - } - - /** - * Get XML generator instance - * - * @return Zend_XmlRpc_Generator_GeneratorAbstract - */ - public static function getGenerator() - { - if (!self::$_generator) { - if (extension_loaded('xmlwriter')) { - #require_once 'Zend/XmlRpc/Generator/XmlWriter.php'; - self::$_generator = new Zend_XmlRpc_Generator_XmlWriter(); - } else { - #require_once 'Zend/XmlRpc/Generator/DomDocument.php'; - self::$_generator = new Zend_XmlRpc_Generator_DomDocument(); - } - } - - return self::$_generator; - } - - /** - * Sets XML generator instance - * - * @param Zend_XmlRpc_Generator_GeneratorAbstract $generator - * @return void - */ - public static function setGenerator(Zend_XmlRpc_Generator_GeneratorAbstract $generator) - { - self::$_generator = $generator; - } - - /** - * Changes the encoding of the generator - * - * @param string $encoding - * @return void - */ - public static function setEncoding($encoding) - { - $generator = self::getGenerator(); - $newGenerator = new $generator($encoding); - self::setGenerator($newGenerator); - } - - /** - * Return the value of this object, convert the XML-RPC native value into a PHP variable - * - * @return mixed - */ - abstract public function getValue(); - - - /** - * Return the XML code that represent a native MXL-RPC value - * - * @return string - */ - public function saveXml() - { - if (!$this->_xml) { - $this->generateXml(); - $this->_xml = (string) $this->getGenerator(); - } - return $this->_xml; - } - - /** - * Generate XML code that represent a native XML/RPC value - * - * @return void - */ - public function generateXml() - { - $this->_generateXml(); - } - - /** - * Creates a Zend_XmlRpc_Value* object, representing a native XML-RPC value - * A XmlRpcValue object can be created in 3 ways: - * 1. Autodetecting the native type out of a PHP variable - * (if $type is not set or equal to Zend_XmlRpc_Value::AUTO_DETECT_TYPE) - * 2. By specifing the native type ($type is one of the Zend_XmlRpc_Value::XMLRPC_TYPE_* constants) - * 3. From a XML string ($type is set to Zend_XmlRpc_Value::XML_STRING) - * - * By default the value type is autodetected according to it's PHP type - * - * @param mixed $value - * @param Zend_XmlRpc_Value::constant $type - * - * @return Zend_XmlRpc_Value - * @static - */ - public static function getXmlRpcValue($value, $type = self::AUTO_DETECT_TYPE) - { - switch ($type) { - case self::AUTO_DETECT_TYPE: - // Auto detect the XML-RPC native type from the PHP type of $value - return self::_phpVarToNativeXmlRpc($value); - - case self::XML_STRING: - // Parse the XML string given in $value and get the XML-RPC value in it - return self::_xmlStringToNativeXmlRpc($value); - - case self::XMLRPC_TYPE_I4: - // fall through to the next case - case self::XMLRPC_TYPE_INTEGER: - #require_once 'Zend/XmlRpc/Value/Integer.php'; - return new Zend_XmlRpc_Value_Integer($value); - - case self::XMLRPC_TYPE_I8: - // fall through to the next case - case self::XMLRPC_TYPE_APACHEI8: - #require_once 'Zend/XmlRpc/Value/BigInteger.php'; - return new Zend_XmlRpc_Value_BigInteger($value); - - case self::XMLRPC_TYPE_DOUBLE: - #require_once 'Zend/XmlRpc/Value/Double.php'; - return new Zend_XmlRpc_Value_Double($value); - - case self::XMLRPC_TYPE_BOOLEAN: - #require_once 'Zend/XmlRpc/Value/Boolean.php'; - return new Zend_XmlRpc_Value_Boolean($value); - - case self::XMLRPC_TYPE_STRING: - #require_once 'Zend/XmlRpc/Value/String.php'; - return new Zend_XmlRpc_Value_String($value); - - case self::XMLRPC_TYPE_BASE64: - #require_once 'Zend/XmlRpc/Value/Base64.php'; - return new Zend_XmlRpc_Value_Base64($value); - - case self::XMLRPC_TYPE_NIL: - // fall through to the next case - case self::XMLRPC_TYPE_APACHENIL: - #require_once 'Zend/XmlRpc/Value/Nil.php'; - return new Zend_XmlRpc_Value_Nil(); - - case self::XMLRPC_TYPE_DATETIME: - #require_once 'Zend/XmlRpc/Value/DateTime.php'; - return new Zend_XmlRpc_Value_DateTime($value); - - case self::XMLRPC_TYPE_ARRAY: - #require_once 'Zend/XmlRpc/Value/Array.php'; - return new Zend_XmlRpc_Value_Array($value); - - case self::XMLRPC_TYPE_STRUCT: - #require_once 'Zend/XmlRpc/Value/Struct.php'; - return new Zend_XmlRpc_Value_Struct($value); - - default: - #require_once 'Zend/XmlRpc/Value/Exception.php'; - throw new Zend_XmlRpc_Value_Exception('Given type is not a '. __CLASS__ .' constant'); - } - } - - /** - * Get XML-RPC type for a PHP native variable - * - * @static - * @param mixed $value - * @return string - */ - public static function getXmlRpcTypeByValue($value) - { - if (is_object($value)) { - if ($value instanceof Zend_XmlRpc_Value) { - return $value->getType(); - } elseif (($value instanceof Zend_Date) || ($value instanceof DateTime)) { - return self::XMLRPC_TYPE_DATETIME; - } - return self::getXmlRpcTypeByValue(get_object_vars($value)); - } elseif (is_array($value)) { - if (!empty($value) && is_array($value) && (array_keys($value) !== range(0, count($value) - 1))) { - return self::XMLRPC_TYPE_STRUCT; - } - return self::XMLRPC_TYPE_ARRAY; - } elseif (is_int($value)) { - return ($value > PHP_INT_MAX) ? self::XMLRPC_TYPE_I8 : self::XMLRPC_TYPE_INTEGER; - } elseif (is_double($value)) { - return self::XMLRPC_TYPE_DOUBLE; - } elseif (is_bool($value)) { - return self::XMLRPC_TYPE_BOOLEAN; - } elseif (is_null($value)) { - return self::XMLRPC_TYPE_NIL; - } elseif (is_string($value)) { - return self::XMLRPC_TYPE_STRING; - } - throw new Zend_XmlRpc_Value_Exception(sprintf( - 'No matching XMLRPC type found for php type %s.', - gettype($value) - )); - } - - /** - * Transform a PHP native variable into a XML-RPC native value - * - * @param mixed $value The PHP variable for convertion - * - * @return Zend_XmlRpc_Value - * @static - */ - protected static function _phpVarToNativeXmlRpc($value) - { - // @see http://framework.zend.com/issues/browse/ZF-8623 - if (is_object($value)) { - if ($value instanceof Zend_XmlRpc_Value) { - return $value; - } - if ($value instanceof Zend_Crypt_Math_BigInteger) { - #require_once 'Zend/XmlRpc/Value/Exception.php'; - throw new Zend_XmlRpc_Value_Exception( - 'Using Zend_Crypt_Math_BigInteger to get an ' . - 'instance of Zend_XmlRpc_Value_BigInteger is not ' . - 'available anymore.' - ); - } - } - - switch (self::getXmlRpcTypeByValue($value)) - { - case self::XMLRPC_TYPE_DATETIME: - #require_once 'Zend/XmlRpc/Value/DateTime.php'; - return new Zend_XmlRpc_Value_DateTime($value); - - case self::XMLRPC_TYPE_ARRAY: - #require_once 'Zend/XmlRpc/Value/Array.php'; - return new Zend_XmlRpc_Value_Array($value); - - case self::XMLRPC_TYPE_STRUCT: - #require_once 'Zend/XmlRpc/Value/Struct.php'; - return new Zend_XmlRpc_Value_Struct($value); - - case self::XMLRPC_TYPE_INTEGER: - #require_once 'Zend/XmlRpc/Value/Integer.php'; - return new Zend_XmlRpc_Value_Integer($value); - - case self::XMLRPC_TYPE_DOUBLE: - #require_once 'Zend/XmlRpc/Value/Double.php'; - return new Zend_XmlRpc_Value_Double($value); - - case self::XMLRPC_TYPE_BOOLEAN: - #require_once 'Zend/XmlRpc/Value/Boolean.php'; - return new Zend_XmlRpc_Value_Boolean($value); - - case self::XMLRPC_TYPE_NIL: - #require_once 'Zend/XmlRpc/Value/Nil.php'; - return new Zend_XmlRpc_Value_Nil; - - case self::XMLRPC_TYPE_STRING: - // Fall through to the next case - default: - // If type isn't identified (or identified as string), it treated as string - #require_once 'Zend/XmlRpc/Value/String.php'; - return new Zend_XmlRpc_Value_String($value); - } - } - - - /** - * Transform an XML string into a XML-RPC native value - * - * @param string|SimpleXMLElement $xml A SimpleXMLElement object represent the XML string - * It can be also a valid XML string for convertion - * - * @return Zend_XmlRpc_Value - * @static - */ - protected static function _xmlStringToNativeXmlRpc($xml) - { - self::_createSimpleXMLElement($xml); - - self::_extractTypeAndValue($xml, $type, $value); - - switch ($type) { - // All valid and known XML-RPC native values - case self::XMLRPC_TYPE_I4: - // Fall through to the next case - case self::XMLRPC_TYPE_INTEGER: - #require_once 'Zend/XmlRpc/Value/Integer.php'; - $xmlrpcValue = new Zend_XmlRpc_Value_Integer($value); - break; - case self::XMLRPC_TYPE_APACHEI8: - // Fall through to the next case - case self::XMLRPC_TYPE_I8: - #require_once 'Zend/XmlRpc/Value/BigInteger.php'; - $xmlrpcValue = new Zend_XmlRpc_Value_BigInteger($value); - break; - case self::XMLRPC_TYPE_DOUBLE: - #require_once 'Zend/XmlRpc/Value/Double.php'; - $xmlrpcValue = new Zend_XmlRpc_Value_Double($value); - break; - case self::XMLRPC_TYPE_BOOLEAN: - #require_once 'Zend/XmlRpc/Value/Boolean.php'; - $xmlrpcValue = new Zend_XmlRpc_Value_Boolean($value); - break; - case self::XMLRPC_TYPE_STRING: - #require_once 'Zend/XmlRpc/Value/String.php'; - $xmlrpcValue = new Zend_XmlRpc_Value_String($value); - break; - case self::XMLRPC_TYPE_DATETIME: // The value should already be in a iso8601 format - #require_once 'Zend/XmlRpc/Value/DateTime.php'; - $xmlrpcValue = new Zend_XmlRpc_Value_DateTime($value); - break; - case self::XMLRPC_TYPE_BASE64: // The value should already be base64 encoded - #require_once 'Zend/XmlRpc/Value/Base64.php'; - $xmlrpcValue = new Zend_XmlRpc_Value_Base64($value, true); - break; - case self::XMLRPC_TYPE_NIL: - // Fall through to the next case - case self::XMLRPC_TYPE_APACHENIL: - // The value should always be NULL - #require_once 'Zend/XmlRpc/Value/Nil.php'; - $xmlrpcValue = new Zend_XmlRpc_Value_Nil(); - break; - case self::XMLRPC_TYPE_ARRAY: - // PHP 5.2.4 introduced a regression in how empty($xml->value) - // returns; need to look for the item specifically - $data = null; - foreach ($value->children() as $key => $value) { - if ('data' == $key) { - $data = $value; - break; - } - } - - if (null === $data) { - #require_once 'Zend/XmlRpc/Value/Exception.php'; - throw new Zend_XmlRpc_Value_Exception('Invalid XML for XML-RPC native '. self::XMLRPC_TYPE_ARRAY .' type: ARRAY tag must contain DATA tag'); - } - $values = array(); - // Parse all the elements of the array from the XML string - // (simple xml element) to Zend_XmlRpc_Value objects - foreach ($data->value as $element) { - $values[] = self::_xmlStringToNativeXmlRpc($element); - } - #require_once 'Zend/XmlRpc/Value/Array.php'; - $xmlrpcValue = new Zend_XmlRpc_Value_Array($values); - break; - case self::XMLRPC_TYPE_STRUCT: - $values = array(); - // Parse all the memebers of the struct from the XML string - // (simple xml element) to Zend_XmlRpc_Value objects - foreach ($value->member as $member) { - // @todo? If a member doesn't have a tag, we don't add it to the struct - // Maybe we want to throw an exception here ? - if (!isset($member->value) or !isset($member->name)) { - continue; - //throw new Zend_XmlRpc_Value_Exception('Member of the '. self::XMLRPC_TYPE_STRUCT .' XML-RPC native type must contain a VALUE tag'); - } - $values[(string)$member->name] = self::_xmlStringToNativeXmlRpc($member->value); - } - #require_once 'Zend/XmlRpc/Value/Struct.php'; - $xmlrpcValue = new Zend_XmlRpc_Value_Struct($values); - break; - default: - #require_once 'Zend/XmlRpc/Value/Exception.php'; - throw new Zend_XmlRpc_Value_Exception('Value type \''. $type .'\' parsed from the XML string is not a known XML-RPC native type'); - break; - } - $xmlrpcValue->_setXML($xml->asXML()); - - return $xmlrpcValue; - } - - protected static function _createSimpleXMLElement(&$xml) - { - if ($xml instanceof SimpleXMLElement) { - return; - } - - try { - $xml = new SimpleXMLElement($xml); - } catch (Exception $e) { - // The given string is not a valid XML - #require_once 'Zend/XmlRpc/Value/Exception.php'; - throw new Zend_XmlRpc_Value_Exception('Failed to create XML-RPC value from XML string: ' . $e->getMessage(), $e->getCode(), $e); - } - } - - /** - * Extract XML/RPC type and value from SimpleXMLElement object - * - * @param SimpleXMLElement $xml - * @param string &$type Type bind variable - * @param string &$value Value bind variable - * @return void - */ - protected static function _extractTypeAndValue(SimpleXMLElement $xml, &$type, &$value) - { - list($type, $value) = each($xml); - - if (!$type and $value === null) { - $namespaces = array('ex' => 'http://ws.apache.org/xmlrpc/namespaces/extensions'); - foreach ($namespaces as $namespaceName => $namespaceUri) { - $namespaceXml = $xml->children($namespaceUri); - list($type, $value) = each($namespaceXml); - if ($type !== null) { - $type = $namespaceName . ':' . $type; - break; - } - } - } - - //if there is a child element, try to parse type for it - if (!$type && $value instanceof SimpleXMLElement) { - self::_extractTypeAndValue($value->children(), $type, $value); - } - - // If no type was specified, the default is string - if (!$type) { - $type = self::XMLRPC_TYPE_STRING; - if (preg_match('#^.*$#', $xml->asXML())) { - $value = str_replace(array('', ''), '', $xml->asXML()); - } - } - } - - /** - * @param string $xml - * @return void - */ - protected function _setXML($xml) - { - $this->_xml = $this->getGenerator()->stripDeclaration($xml); - } -} diff --git a/library/Zend/XmlRpc/Value/Array.php b/library/Zend/XmlRpc/Value/Array.php deleted file mode 100644 index 828682a1eb..0000000000 --- a/library/Zend/XmlRpc/Value/Array.php +++ /dev/null @@ -1,73 +0,0 @@ -_type = self::XMLRPC_TYPE_ARRAY; - parent::__construct($value); - } - - - /** - * Generate the XML code that represent an array native MXL-RPC value - * - * @return void - */ - protected function _generateXml() - { - $generator = $this->getGenerator(); - $generator->openElement('value') - ->openElement('array') - ->openElement('data'); - - if (is_array($this->_value)) { - foreach ($this->_value as $val) { - $val->generateXml(); - } - } - $generator->closeElement('data') - ->closeElement('array') - ->closeElement('value'); - } -} - diff --git a/library/Zend/XmlRpc/Value/Base64.php b/library/Zend/XmlRpc/Value/Base64.php deleted file mode 100644 index 92bc9ce069..0000000000 --- a/library/Zend/XmlRpc/Value/Base64.php +++ /dev/null @@ -1,68 +0,0 @@ -_type = self::XMLRPC_TYPE_BASE64; - - $value = (string)$value; // Make sure this value is string - if (!$alreadyEncoded) { - $value = base64_encode($value); // We encode it in base64 - } - $this->_value = $value; - } - - /** - * Return the value of this object, convert the XML-RPC native base64 value into a PHP string - * We return this value decoded (a normal string) - * - * @return string - */ - public function getValue() - { - return base64_decode($this->_value); - } -} diff --git a/library/Zend/XmlRpc/Value/BigInteger.php b/library/Zend/XmlRpc/Value/BigInteger.php deleted file mode 100644 index 925410a791..0000000000 --- a/library/Zend/XmlRpc/Value/BigInteger.php +++ /dev/null @@ -1,58 +0,0 @@ -_value = $integer->init($value); - $this->_type = self::XMLRPC_TYPE_I8; - } - - /** - * Return bigint value - * - * @return string - */ - public function getValue() - { - return $this->_value; - } -} diff --git a/library/Zend/XmlRpc/Value/Boolean.php b/library/Zend/XmlRpc/Value/Boolean.php deleted file mode 100644 index b4e8366b89..0000000000 --- a/library/Zend/XmlRpc/Value/Boolean.php +++ /dev/null @@ -1,63 +0,0 @@ -_type = self::XMLRPC_TYPE_BOOLEAN; - // Make sure the value is boolean and then convert it into a integer - // The double convertion is because a bug in the ZendOptimizer in PHP version 5.0.4 - $this->_value = (int)(bool)$value; - } - - /** - * Return the value of this object, convert the XML-RPC native boolean value into a PHP boolean - * - * @return bool - */ - public function getValue() - { - return (bool)$this->_value; - } -} diff --git a/library/Zend/XmlRpc/Value/Collection.php b/library/Zend/XmlRpc/Value/Collection.php deleted file mode 100644 index 0930ac14ae..0000000000 --- a/library/Zend/XmlRpc/Value/Collection.php +++ /dev/null @@ -1,73 +0,0 @@ - $value) { - // If the elements of the given array are not Zend_XmlRpc_Value objects, - // we need to convert them as such (using auto-detection from PHP value) - if (!$value instanceof parent) { - $value = self::getXmlRpcValue($value, self::AUTO_DETECT_TYPE); - } - $this->_value[$key] = $value; - } - } - - - /** - * Return the value of this object, convert the XML-RPC native collection values into a PHP array - * - * @return arary - */ - public function getValue() - { - $values = (array)$this->_value; - foreach ($values as $key => $value) { - /* @var $value Zend_XmlRpc_Value */ - $values[$key] = $value->getValue(); - } - return $values; - } -} diff --git a/library/Zend/XmlRpc/Value/DateTime.php b/library/Zend/XmlRpc/Value/DateTime.php deleted file mode 100644 index 21403c4927..0000000000 --- a/library/Zend/XmlRpc/Value/DateTime.php +++ /dev/null @@ -1,91 +0,0 @@ -_type = self::XMLRPC_TYPE_DATETIME; - - if ($value instanceof Zend_Date) { - $this->_value = $value->toString($this->_isoFormatString); - } elseif ($value instanceof DateTime) { - $this->_value = $value->format($this->_phpFormatString); - } elseif (is_numeric($value)) { // The value is numeric, we make sure it is an integer - $this->_value = date($this->_phpFormatString, (int)$value); - } else { - $timestamp = new DateTime($value); - if ($timestamp === false) { // cannot convert the value to a timestamp - #require_once 'Zend/XmlRpc/Value/Exception.php'; - throw new Zend_XmlRpc_Value_Exception('Cannot convert given value \''. $value .'\' to a timestamp'); - } - - $this->_value = $timestamp->format($this->_phpFormatString); // Convert the timestamp to iso8601 format - } - } - - /** - * Return the value of this object as iso8601 dateTime value - * - * @return int As a Unix timestamp - */ - public function getValue() - { - return $this->_value; - } -} diff --git a/library/Zend/XmlRpc/Value/Double.php b/library/Zend/XmlRpc/Value/Double.php deleted file mode 100644 index 9962efd7d8..0000000000 --- a/library/Zend/XmlRpc/Value/Double.php +++ /dev/null @@ -1,62 +0,0 @@ -_type = self::XMLRPC_TYPE_DOUBLE; - $precision = (int)ini_get('precision'); - $formatString = '%1.' . $precision . 'F'; - $this->_value = rtrim(sprintf($formatString, (float)$value), '0'); - } - - /** - * Return the value of this object, convert the XML-RPC native double value into a PHP float - * - * @return float - */ - public function getValue() - { - return (float)$this->_value; - } -} diff --git a/library/Zend/XmlRpc/Value/Exception.php b/library/Zend/XmlRpc/Value/Exception.php deleted file mode 100644 index 84f2d051a5..0000000000 --- a/library/Zend/XmlRpc/Value/Exception.php +++ /dev/null @@ -1,39 +0,0 @@ - PHP_INT_MAX) { - #require_once 'Zend/XmlRpc/Value/Exception.php'; - throw new Zend_XmlRpc_Value_Exception('Overlong integer given'); - } - - $this->_type = self::XMLRPC_TYPE_INTEGER; - $this->_value = (int)$value; // Make sure this value is integer - } - - /** - * Return the value of this object, convert the XML-RPC native integer value into a PHP integer - * - * @return int - */ - public function getValue() - { - return $this->_value; - } -} diff --git a/library/Zend/XmlRpc/Value/Nil.php b/library/Zend/XmlRpc/Value/Nil.php deleted file mode 100644 index b95825e9fc..0000000000 --- a/library/Zend/XmlRpc/Value/Nil.php +++ /dev/null @@ -1,60 +0,0 @@ -_type = self::XMLRPC_TYPE_NIL; - $this->_value = null; - } - - /** - * Return the value of this object, convert the XML-RPC native nill value into a PHP NULL - * - * @return null - */ - public function getValue() - { - return null; - } -} - diff --git a/library/Zend/XmlRpc/Value/Scalar.php b/library/Zend/XmlRpc/Value/Scalar.php deleted file mode 100644 index 0e2210f896..0000000000 --- a/library/Zend/XmlRpc/Value/Scalar.php +++ /dev/null @@ -1,53 +0,0 @@ -getGenerator(); - - $generator->openElement('value') - ->openElement($this->_type, $this->_value) - ->closeElement($this->_type) - ->closeElement('value'); - } -} diff --git a/library/Zend/XmlRpc/Value/String.php b/library/Zend/XmlRpc/Value/String.php deleted file mode 100644 index 5980a825b4..0000000000 --- a/library/Zend/XmlRpc/Value/String.php +++ /dev/null @@ -1,60 +0,0 @@ -_type = self::XMLRPC_TYPE_STRING; - - // Make sure this value is string and all XML characters are encoded - $this->_value = (string)$value; - } - - /** - * Return the value of this object, convert the XML-RPC native string value into a PHP string - * - * @return string - */ - public function getValue() - { - return (string)$this->_value; - } -} diff --git a/library/Zend/XmlRpc/Value/Struct.php b/library/Zend/XmlRpc/Value/Struct.php deleted file mode 100644 index e4a2d810fc..0000000000 --- a/library/Zend/XmlRpc/Value/Struct.php +++ /dev/null @@ -1,75 +0,0 @@ -_type = self::XMLRPC_TYPE_STRUCT; - parent::__construct($value); - } - - - /** - * Generate the XML code that represent struct native MXL-RPC value - * - * @return void - */ - protected function _generateXML() - { - $generator = $this->getGenerator(); - $generator->openElement('value') - ->openElement('struct'); - - if (is_array($this->_value)) { - foreach ($this->_value as $name => $val) { - /* @var $val Zend_XmlRpc_Value */ - $generator->openElement('member') - ->openElement('name', $name) - ->closeElement('name'); - $val->generateXml(); - $generator->closeElement('member'); - } - } - $generator->closeElement('struct') - ->closeElement('value'); - } -}