diff --git a/.gitmodules b/.gitmodules deleted file mode 100644 index 21d57da5945..00000000000 --- a/.gitmodules +++ /dev/null @@ -1,3 +0,0 @@ -[submodule "tools/phptools"] - path = tools/phptools - url = git://github.com/ralphschindler/PHPTools.git diff --git a/README.md b/README.md index 2de9e02c20a..fbf572fe7b4 100644 --- a/README.md +++ b/README.md @@ -4,155 +4,152 @@ Master: [![Build Status](https://secure.travis-ci.org/zendframework/zf2.png?bran ## RELEASE INFORMATION -*Zend Framework 2.0.0beta4* +*Zend Framework 2.0.0beta5* + +6 July 2012 THIS RELEASE IS A DEVELOPMENT RELEASE AND NOT INTENDED FOR PRODUCTION USE. PLEASE USE AT YOUR OWN RISK. -This is the fourth in a series of planned beta releases. The beta release -cycle will follow the "gmail" style of betas, whereby new features will -be added in each new release, and BC will not be guaranteed; beta -releases will happen _approximately_ every six weeks. - -Once the established milestones have been reached and the featureset has reached -maturity and reasonable stability, we will freeze the API and prepare for -Release Candidate (RC) status. At this time, we are only planning for one more -beta release (beta5) before starting the RC process. - -### NEW FEATURES IN BETA4 - -PLEASE NOTE: this beta includes a large number of breaks from the previous beta, -due to introduction of the ServiceManager, changes to the EventManager, renaming -of the ModuleManager, rewrite of the Form component (and removal of the Dojo -component), and several changes in the View layer. Please consult the -ZendSkeletonApplication to get an idea of the changes necessary to make your -application work with beta4. - - - Config component (Enrico Zimuel) - - Added reader and writer implementations for JSON and YAML configuration - - Crypt and Math (Enrico Zimuel) - - Creates a generic API for string and stream en/decryption - - Provides bcrypt support - - Provides `BigInteger` support - - Provides common methodology surrounding credential encryption and hashing - - Db layer (Ralph Schindler) - - Zend\Db\Adapter: added buffer() to the ResultInterface, added that feature - to Mysqli Result object - - Zend\Db\Adapter: added ability to subselect Sqlite for returning a true - count() - - Zend\Db\Adapter: added API to return helper closures from the Adapter API - - Renamed "database" to "schema" in all usages across Zend\Db - - Zend\Db\Adapter: Various fixes for PDO connection parameters - - Zend\Db\Sql: created a shared AbstractSql implementation to share - expression processing - - Zend\Db\Sql: created a more robust "Expression" object for use in Select - and Predicates - - Zend\Db\Sql: created an internal workflow and architecture to handle the - creation of platform specific queries - - Zend\Db\Sql: implemented limit() and offset() API to Select - - Zend\Db\Sql: added having(), order() to SELECT API - - Zend\Db\Sql: added alias support to Select::columns() - - Zend\Db\TableGateway: reorganized AbstractTableGateway and TableGateway, - removed other extensions in favor of "Features" - - Zend\Db\TableGateway: created a "Features" API in TableGatway to promote - horizontal extension of TableGatway - - Di (Ralph Schindler, Marco Pivetta) - - Added method injectDependencies($instance), to allow injecting an object - after an instance is already available (used in the ServiceManager) - - Various fixes based on issue reports - - Dojo - - REMOVED. Support was for out-dated versions of Dojo, and with the new Form - rewrite, it needs to be completely rewritten. This is targetted for post - 2.0.0 at this time. - - EventManager (Matthew Weier O'Phinney) - - New SharedEventManager, a non-static version of the original - StaticEventManager - - StaticEventManager now extends SharedEventManager and implements a - singleton pattern - - New ServiceManager creates a shared instance of SharedEventManager and - injects it in a non-shared EventManager instance per service; static usage - is discouraged at this time. - - attachAggregate() now accepts an optional $priority, which, when present, - will be passed to the ListenerAggregate, allowing specifying a priority - during attachment of its events. - - EventManager now can handle arrays of events as well as wildcard events - - SharedEventManager now can handle arrays of contexts, wildcard contexts, - and arrays/wildcard events. - - Form (Matthew Weier O'Phinney, Kyle Spraggs, Guilherme Blanco) - - Complete rewrite - - Elements compose a name and attributes - - Fieldsets compose a name, attributes, and elements and fieldsets - - Forms compose a name, attributes, elements, fieldsets, an InputFilter, and - optionally a Hydrator and bound object. - - New form view helpers accept the Form objects in order to generate markup. - - Object binding allows direct binding of model data to and from the Form. - - InputFilter (Matthew Weier O'Phinney) - - New component for object-oriented creation of input filters - - Input objects compose filter and validator chains, as well as metadata - such as required, allow empty, break on failure, and more. - - InputFilter objects compose Input and InputFilter objects, and allow - validating the entire set or specified validation groups. - - Log (Enrico Zimuel, Benoit Durand) - - Refactored to provide more flexibility - - Adds API discoverability (instead of method overloading) - - Uses the PluginBroker for loading writers and formatters - - Uses PriorityQueue to manage writer priority - - Uses FilterChain for filtering messages - - Adds a renderer for exceptions, a JSON formatter, and additional interfaces - - Mail (Enrico Zimuel) - - Allow batch sending via the SMTP transport - - ModuleManager (Evan Coury, Matthew Weier O'Phinney) - - Renamed from "Module" to "ModuleManager" - - Renamed "Consumer" subnamespace to "Feature" - - Added new listeners: - - OnBootstrapListener (Module classes defining onBootstrap() will have - that method attached as a listener on the Application bootstrap event) - - LocatorRegistrationListener (Module classes implementing the - LocatorRegisteredInterface feature will be injected in the - ServiceManager) - - ServiceListener (Module classes defining getServiceConfiguration() will - have that method called, and the configuration merged; once all modules - are loaded, that merged configuration will be passed to the - ServiceManager) - - MVC (Matthew Weier O'Phinney, Ralph Schindler, Evan Coury) - - Removed Bootstrap class and rewrote Application class - - Composes a ServiceManager, and simply fires events - - Added RouteListener and DispatchListener classes, implementing the default - route and dispatch strategies. - - Created a new "Service" subnamespace, with ServiceManager configuration - and factories for the default MVC services. - - Created a new "ViewManager" class, which triggers on the bootstrap event, - at which time it creates the various objects of the view layer and wires - them together as well as registers them with the appropriate events. - - InjectTemplateListener now uses the controller namespace to further - namespace the view template; the default is now - "//" - - ServiceManager component (Ralph Schindler, Matthew Weier O'Phinney) - - Highly performant, programmatic service creation - - Largely replaces DI, but can also consume Zend\Di - - Allows: - - Service registration - - Lazy-loaded service objects - - Service factories - - Service aliasing - - Abstract (fallback) factories - - Initializers (manipulate instances after creation) - - Fully integrated in the MVC solution - - Renamed interfaces (Gabriel Baker, Sascha Prolic, Maks3w) - - Most, if not all, interfaces were renamed to suffix with the word - "Interface". This is to promote discovery of interfaces, as well as make - naming simpler. - - Exceptions are affected by this as well. Exception marker interfaces were - renamed to ExceptionInterface and pushed into the Exception subnamespace of - each component - - Composer support (Rob Allen, Marco Pivetta, Kyle Spraggs) - - Zend Framework is now installable via Composer (http://packagist.org/), as - are each of its individual components - - Travis CI integration (Marco Pivetta, Maks3w) - - ZF2 is tested on each commit by http://travis-ci.org/ +This is the fifth and last in a series of planned beta releases. The +beta release cycle has followed the "gmail" style of betas, whereby new +features have been added in each new release, and BC has not been +guaranteed. + +Following this release, we plan to perform some repository cleanup, a +standards audit, and documentation migration. Once these tasks are +complete, we will prepare our first Release Candidate (RC). + +### NEW FEATURES IN BETA5 + +PLEASE NOTE: this beta includes a number of breaks from the previous +beta. Please read the notes below prefixed with "BC BREAK" for specific +breakages. The ZendSkeletonApplication typically reflects any BC changes +that have been made, and is a good resource. + + - Escaper component (Padraic Brady) + - Provides context-specific escaping mechanisms for HTML content, + HTML attributes, URLs, CSS, and JavaScript. + - BC BREAK: The escape() view helper was removed, and replaced with + escapeHtml(), escapeHtmlAttr(), escapeJs(), escapeCss(), and + escapeUrl() implementations. + - New I18n component (Ben Scholzen, Chris Martin, Dennis Portnov, + Matthew Weier O'Phinney) + - New component leveraging PHP's ext/intl extension to provide + internationalization (i18n) and localization (L10n) features and + capabilities to applications. + - LEVERAGES: + - DateTime, DateTimezone, IntlDateFormatter + - Locale + - NumberFormatter + - BC BREAK: REMOVES the following components: + - Zend\Currency + - Zend\Date + - Zend\Locale + - Zend\Measure + - Zend\Translator + - All filters, validators, and view helpers that relied on the + above. + - PROVIDES: + - Zend\I18n\Translator, including support for gettext and + PHP-array-based translations (more are planned). + - Zend\I18n\Filter, containing localized filtering capabilites + for Alnum (alphanumeric), Alpha (alphabetic), and NumberFormat + (numerical strings). + - Zend\I18n\Validator, containing localized validation + capabilities for Alnum (alphanumeric), Alpha (alphabetic), + Iban (international bank account number standard), Int + (integer), and PostCode (localized postal codes). + - Zend\I18n\View, containing localized view helpers for + CurrencyFormat, DateFormat, NumberFormat, Translate, and + TranslatePlural. + - Db layer additions (Ralph Schindler, Rob Allen, Guillaume Metayer, + Sascha Howe, Chris Testroet, Evan Coury, Ben Youngblood) + - Metadata support + - Postgresql adapter/driver + - New HydratingResultSet, allowing the ability to specify a custom + hydrator (from Zend\Stdlib\Hydrator) for hydrating row objects. + - Many bugfixes and stabilizations + - Form additions (Matthew Weier O'Phinney, Michaƫl Gallego, Yanick Rochon) + - Annotations support: Ability to use annotations with a domain + object in order to define a form, fieldsets, elements, inputs and + input filters, and more. + - Hydration of fieldsets; fieldsets may compose their own hydrators + if desired. + - Collection support; allows multiple instances of the same + fieldset. As an example, you might have an interface that + allows adding a set of form elements via an XHR call; on the + backend, these would be defined as a collection, allowing + arbitrary numbers of these fieldsets to be submitted. + - New view helpers covering most HTML5-specific element types, most + XHTML-specific element types. Additionally, a number of the + HTML5-specific element types now have Element implementations to + create turn-key solutions that include validation and filtering. + - BC BREAK: Options support. Many attributes were being used not as + HTML attributes but to define behavior. The ElementInterface now + has an accessor and mutator for options. Examples of options + include labels for non-radio/checkbox/select elements, the CAPTCHA + adapter for CAPTCHA elements, CSRF tokens, etc. If you were + defining labels in your forms, please move the label and label + attributes definitions from the "attributes" to the "options" of + the element, fieldset, or form. + - BC BREAK: new interface, ElementPrepareAwareInterface, defining + the method "prepareElement(Form $form)". The FieldsetInterface, + and, by extension, FormInterface, extend this new interface. It is + used to allow preparing elements prior to creating a + representation. + - MVC additions (Kyle Spraggs, Evan Coury, Matthew Weier O'Phinney) + - New "Params" controller plugin. Allows retrieving query, post, + cookie, header, and route parameters. Usage is + $this->params()->fromQuery($name, $default). + - New listener, Zend\Mvc\ModuleRouteListener. When enabled, if a + route match contains a "\__NAMESPACE__" key, that namespace value + will be prepended to the value of the "controller" key. This + should typically be used in the root route for a given module, to + ensure controller names do not clash. + - Bootstrap simplification. A new "init()" method was created that + accepts the path to a configuration file, and then creates and + bootstraps the application; this eliminates all common boilerplate + for the bootstrap scripts. + - Hydrator changes (Adam Lundrigan) + - BC BREAK: the ClassMethods hydrator now assumes by default that + it should convert between underscore_separated names and + camelCase. + - BC BREAK: Doctrine Annotations Parser (Matthew Weier O'Phinney, Marco + Pivetta, Guilherme Blanco) + - Zend\Code\Annotation now has a dependency on Doctrine\Common for + its annotation parser. + - Annotations now conform to Doctrine's standards by default, but + the AnnotationManager in ZF2 allows attaching alternate parsers + for specific annotation types. + - BC BREAK: Removal of Plugin Broker usage (Matthew Weier O'Phinney, + Evan Coury) + - All uses of the Plugin Broker / Plugin Class Locator combination + were removed. A new class, Zend\ServiceManager\AbstractPluginManager, + was created and used to replace all previous usages of the plugin + broker. This provides more flexibility in creation of plugins, as + well as reduces the number of APIs developers need to learn. + - Configuration of plugin managers is now done at the top-level. All + plugin manager configuration follows the format utilized by + Zend\ServiceManager\ServiceConfiguration, and + Zend\ModuleManager\Listener\ServiceListener has been updated to + allow informing it of plugin manager instances it should manage, + as well as the configuration key to utilize. + - BC BREAK: Coding Standards (Maks3w, Sascha Prolic, Rob Allen) + - Renamed most abstract classes to prefix them with the term + "Abstract". In particular, ActionController and RestfulController + are now AbstractActionController and AbstractRestfulController. + - Renamed getters in HTTP, EventManager, and Mail components. These + components were using accessors such as "events()", "query()", + "headers()", etc. All such accessors were renamed to prepend + "get", and, in the case of "events()", renamed to indicate the + actual object retrieved ("getEventManager()"). + - SECURITY FIX: XmlRpc (Matthew Weier O'Phinney) + - A security issue arising from XML eXternal Entity (XXE) injection + was patched; see http://framework.zend.com/security/advisory/ZF2012-01 Over *400* pull requests for a variety of features and bugfixes were handled -since beta3! +since beta4! ### SYSTEM REQUIREMENTS diff --git a/bin/classmap_generator.php b/bin/classmap_generator.php index 70633a2733e..7d69c3f4eca 100755 --- a/bin/classmap_generator.php +++ b/bin/classmap_generator.php @@ -1,23 +1,11 @@ #!/usr/bin/env php filename, where the filename is relative to the library path $map = new stdClass; foreach ($l as $file) { - $namespace = empty($file->namespace) ? '' : $file->namespace . '\\'; $filename = str_replace($libraryPath . '/', '', str_replace(DIRECTORY_SEPARATOR, '/', $file->getPath()) . '/' . $file->getFilename()); // Add in relative path to library $filename = $relativePathForClassmap . $filename; - $map->{$namespace . $file->classname} = $filename; + foreach ($file->getClasses() as $class) { + $map->{$class} = $filename; + } } if ($appending) { diff --git a/composer.json b/composer.json index e6f0c66ffbb..10c4dc621cd 100644 --- a/composer.json +++ b/composer.json @@ -37,13 +37,12 @@ "zendframework/zend-config": "self.version", "zendframework/zend-console": "self.version", "zendframework/zend-crypt": "self.version", - "zendframework/zend-currency": "self.version", - "zendframework/zend-date": "self.version", "zendframework/zend-db": "self.version", "zendframework/zend-di": "self.version", "zendframework/zend-docbook": "self.version", "zendframework/zend-dojo": "self.version", "zendframework/zend-dom": "self.version", + "zendframework/zend-escaper": "self.version", "zendframework/zend-eventmanager": "self.version", "zendframework/zend-feed": "self.version", "zendframework/zend-file": "self.version", @@ -51,17 +50,16 @@ "zendframework/zend-form": "self.version", "zendframework/zend-gdata": "self.version", "zendframework/zend-http": "self.version", + "zendframework/zend-i18n": "self.version", "zendframework/zend-infocard": "self.version", "zendframework/zend-inputfilter": "self.version", "zendframework/zend-json": "self.version", "zendframework/zend-ldap": "self.version", "zendframework/zend-loader": "self.version", - "zendframework/zend-locale": "self.version", "zendframework/zend-log": "self.version", "zendframework/zend-mail": "self.version", "zendframework/zend-markup": "self.version", "zendframework/zend-math": "self.version", - "zendframework/zend-measure": "self.version", "zendframework/zend-memory": "self.version", "zendframework/zend-mime": "self.version", "zendframework/zend-modulemanager": "self.version", @@ -94,7 +92,6 @@ "zendframework/zend-service-technorati": "self.version", "zendframework/zend-service-twitter": "self.version", "zendframework/zend-service-windowsazure": "self.version", - "zendframework/zend-service-yahoo": "self.version", "zendframework/zend-servicemanager": "self.version", "zendframework/zend-session": "self.version", "zendframework/zend-soap": "self.version", @@ -103,7 +100,6 @@ "zendframework/zend-test": "self.version", "zendframework/zend-text": "self.version", "zendframework/zend-timesync": "self.version", - "zendframework/zend-translator": "self.version", "zendframework/zend-uri": "self.version", "zendframework/zend-validator": "self.version", "zendframework/zend-view": "self.version", diff --git a/demos/Zend/Feeds/consume-feed.php b/demos/Zend/Feeds/consume-feed.php index 5506804f172..44f410764d0 100644 --- a/demos/Zend/Feeds/consume-feed.php +++ b/demos/Zend/Feeds/consume-feed.php @@ -1,22 +1,11 @@ true)); $loader->register(); $rss = Reader::import('http://news.google.com/?output=rss'); foreach ($rss as $item) { - - echo "

" . $item->getTitle() . "
", "\n"; - echo $item->getLink() . "

"; + echo '

' . $item->getTitle() . '
', "\n"; + echo $item->getLink() . '

'; } diff --git a/demos/Zend/Gdata/3LeggedOAuth/Gdata_OAuth_Helper.php b/demos/Zend/Gdata/3LeggedOAuth/Gdata_OAuth_Helper.php deleted file mode 100644 index f0edd577639..00000000000 --- a/demos/Zend/Gdata/3LeggedOAuth/Gdata_OAuth_Helper.php +++ /dev/null @@ -1,109 +0,0 @@ - Zend_Oauth::REQUEST_SCHEME_HEADER, - 'version' => '1.0', - 'requestTokenUrl' => 'https://www.google.com/accounts/OAuthGetRequestToken', - 'userAuthorizationUrl' => 'https://www.google.com/accounts/OAuthAuthorizeToken', - 'accessTokenUrl' => 'https://www.google.com/accounts/OAuthGetAccessToken' - ); - - /** - * Create Gdata_OAuth_Helper object - * - * @param string $consumerKey OAuth consumer key (domain). - * @param string $consumerSecret (optional) OAuth consumer secret. Required if - * using HMAC-SHA1 for a signature method. - * @param string $sigMethod (optional) The oauth_signature method to use. - * Defaults to HMAC-SHA1. RSA-SHA1 is also supported. - */ - public function __construct($consumerKey, $consumerSecret=null, - $sigMethod='HMAC-SHA1') { - $this->_defaultOptions['consumerKey'] = $consumerKey; - $this->_defaultOptions['consumerSecret'] = $consumerSecret; - $this->_defaultOptions['signatureMethod'] = $sigMethod; - parent::__construct($this->_defaultOptions); - } - - /** - * Getter for the oauth options array. - * - * @return array - */ - public function getOauthOptions() { - return $this->_defaultOptions; - } - - /** - * Fetches a request token. - * - * @param string $scope The API scope or scopes separated by spaces to - * restrict data access to. - * @param mixed $callback The URL to redirect the user to after they have - * granted access on the approval page. Either a string or - * Zend_Gdata_Query object. - * @return Zend_OAuth_Token_Request|null - */ - public function fetchRequestToken($scope, $callback) { - if ($callback instanceof Zend_Gdata_Query) { - $uri = $callback->getQueryUrl(); - } else { - $uri = $callback; - } - - $this->_defaultOptions['callbackUrl'] = $uri; - $this->_config->setCallbackUrl($uri); - if (!isset($_SESSION['ACCESS_TOKEN'])) { - return parent::getRequestToken(array('scope' => $scope)); - } - return null; - } - - /** - * Redirects the user to the approval page - * - * @param string $domain (optional) The Google Apps domain to logged users in - * under or 'default' for Google Accounts. Leaving this parameter off - * will give users the universal login to choose an account to login - * under. - * @return void - */ - public function authorizeRequestToken($domain=null) { - $params = array(); - if ($domain != null) { - $params = array('hd' => $domain); - } - $this->redirect($params); - } - - /** - * Upgrades an authorized request token to an access token. - * - * @return Zend_OAuth_Token_Access||null - */ - public function fetchAccessToken() { - if (!isset($_SESSION['ACCESS_TOKEN'])) { - if (!empty($_GET) && isset($_SESSION['REQUEST_TOKEN'])) { - return parent::getAccessToken( - $_GET, unserialize($_SESSION['REQUEST_TOKEN'])); - } - } - return null; - } -} diff --git a/demos/Zend/Gdata/3LeggedOAuth/data-api-72.png b/demos/Zend/Gdata/3LeggedOAuth/data-api-72.png deleted file mode 100755 index e77c52375a4..00000000000 Binary files a/demos/Zend/Gdata/3LeggedOAuth/data-api-72.png and /dev/null differ diff --git a/demos/Zend/Gdata/3LeggedOAuth/doclist-72.png b/demos/Zend/Gdata/3LeggedOAuth/doclist-72.png deleted file mode 100755 index 39de3a1ae15..00000000000 Binary files a/demos/Zend/Gdata/3LeggedOAuth/doclist-72.png and /dev/null differ diff --git a/demos/Zend/Gdata/3LeggedOAuth/index.php b/demos/Zend/Gdata/3LeggedOAuth/index.php deleted file mode 100755 index 59aab08e8d7..00000000000 --- a/demos/Zend/Gdata/3LeggedOAuth/index.php +++ /dev/null @@ -1,190 +0,0 @@ -fetchRequestToken( - implode(' ', $scopes), $APP_URL . '?action=access_token')); - $consumer->authorizeRequestToken(); - break; - case 'access_token': - $_SESSION['ACCESS_TOKEN'] = serialize($consumer->fetchAccessToken()); - header('Location: ' . $APP_URL); - break; - default: - if (isset($_SESSION['ACCESS_TOKEN'])) { - $accessToken = unserialize($_SESSION['ACCESS_TOKEN']); - - $httpClient = $accessToken->getHttpClient( - $consumer->getOauthOptions()); - $docsService = new Zend_Gdata_Docs($httpClient, $APP_NAME); - $spreadsheetsService = new Zend_Gdata_Spreadsheets($httpClient, - $APP_NAME); - - // Retrieve user's list of Google Docs and spreadsheet list. - $docsFeed = $docsService->getDocumentListFeed(); - $spreadsheetFeed = $spreadsheetsService->getSpreadsheetFeed( - 'http://spreadsheets.google.com/feeds/spreadsheets/private/full?max-results=100'); - - renderHTML($accessToken, array($docsFeed, $spreadsheetFeed)); - } else { - renderHTML(); - } -} - -/** - * Returns a the base URL of the current running web app. - * - * @return string - */ -function getAppURL() { - $pageURL = 'http'; - if ($_SERVER['HTTPS'] == 'on') { - $pageURL .= 's'; - } - $pageURL .= '://'; - if ($_SERVER['SERVER_PORT'] != '80') { - $pageURL .= $_SERVER['SERVER_NAME'] . ':' . - $_SERVER['SERVER_PORT'] . $_SERVER['PHP_SELF']; - } else { - $pageURL .= $_SERVER['SERVER_NAME'] . $_SERVER['PHP_SELF']; - } - return $pageURL; -} - -/** - * Removes session data and redirects the user to a URL. - * - * @param string $redirectUrl The URL to direct the user to after session data - * is destroyed. - * @return void - */ -function logout($redirectUrl) { - session_destroy(); - header('Location: ' . $redirectUrl); - exit; -} - -/** - * Prints the token string and secret of the token passed in. - * - * @param Zend_OAuth_Token $token An access or request token object to print. - * @return void - */ -function printToken($token) { - echo 'Token:' . $token->getToken() . '
'; - echo 'Token secret:' . $token->getTokenSecret() . '
'; -} - -/** - * Prints basic properties of a Google Data feed. - * - * @param Zend_Gdata_Feed $feed A feed object to print. - * @return void - */ -function printFeed($feed) { - echo '
    '; - foreach ($feed->entries as $entry) { - $alternateLink = ''; - foreach ($entry->link as $link) { - if ($link->getRel() == 'alternate') { - $alternateLink = $link->getHref(); - } - } - echo "
  1. $entry->title
  2. "; - } - echo '
'; -} - -/** - * Renders the page's HTML. - * - * @param Zend_OAuth_Token $token (optional) The user's current OAuth token. - * @param array $feeds (optional) An array of Zend_Gdata_Feed to print - * information for. - * @return void - */ -function renderHTML($token=null, $feeds=null) { -?> - - - - - - - - - - -
- -
-
- -
-
-

First 100 documents from the Documents List Data API:

-
-
-
-

First 100 spreadsheets from the Spreadsheets Data API:

-
-
-
- - - -gdClient = new Zend_Gdata($client); - } - - /** - * This function retrieves all the blogs associated with the authenticated - * user and prompts the user to choose which to manipulate. - * - * Once the index is selected by the user, the corresponding blogID is - * extracted and stored for easy access. - * - * @return void - */ - public function promptForBlogID() - { - $query = new Zend_Gdata_Query('http://www.blogger.com/feeds/default/blogs'); - $feed = $this->gdClient->getFeed($query); - $this->printFeed($feed); - $input = getInput("\nSelection"); - - //id text is of the form: tag:blogger.com,1999:user-blogID.blogs - $idText = explode('-', $feed->entries[$input]->id->text); - $this->blogID = $idText[2]; - } - - /** - * This function creates a new Zend_Gdata_Entry representing a blog - * post, and inserts it into the user's blog. It also checks for - * whether the post should be added as a draft or as a published - * post. - * - * @param string $title The title of the blog post. - * @param string $content The body of the post. - * @param boolean $isDraft Whether the post should be added as a draft or as a published post - * @return string The newly created post's ID - */ - public function createPost($title, $content, $isDraft=False) - { - // We're using the magic factory method to create a Zend_Gdata_Entry. - // http://framework.zend.com/manual/en/zend.gdata.html#zend.gdata.introdduction.magicfactory - $entry = $this->gdClient->newEntry(); - - $entry->title = $this->gdClient->newTitle(trim($title)); - $entry->content = $this->gdClient->newContent(trim($content)); - $entry->content->setType('text'); - $uri = "http://www.blogger.com/feeds/" . $this->blogID . "/posts/default"; - - if ($isDraft) - { - $control = $this->gdClient->newControl(); - $draft = $this->gdClient->newDraft('yes'); - $control->setDraft($draft); - $entry->control = $control; - } - - $createdPost = $this->gdClient->insertEntry($entry, $uri); - //format of id text: tag:blogger.com,1999:blog-blogID.post-postID - $idText = explode('-', $createdPost->id->text); - $postID = $idText[2]; - - return $postID; - } - - /** - * Prints the titles of all the posts in the user's blog. - * - * @return void - */ - public function printAllPosts() - { - $query = new Zend_Gdata_Query('http://www.blogger.com/feeds/' . $this->blogID . '/posts/default'); - $feed = $this->gdClient->getFeed($query); - $this->printFeed($feed); - } - - /** - * Retrieves the specified post and updates the title and body. Also sets - * the post's draft status. - * - * @param string $postID The ID of the post to update. PostID in field: - * tag:blogger.com,1999:blog-blogID.post-postID - * @param string $updatedTitle The new title of the post. - * @param string $updatedContent The new body of the post. - * @param boolean $isDraft Whether the post will be published or saved as a draft. - * @return Zend_Gdata_Entry The updated post. - */ - public function updatePost($postID, $updatedTitle, $updatedContent, $isDraft) - { - $query = new Zend_Gdata_Query('http://www.blogger.com/feeds/' . $this->blogID . '/posts/default/' . $postID); - $postToUpdate = $this->gdClient->getEntry($query); - $postToUpdate->title->text = $this->gdClient->newTitle(trim($updatedTitle)); - $postToUpdate->content->text = $this->gdClient->newContent(trim($updatedContent)); - - if ($isDraft) { - $draft = $this->gdClient->newDraft('yes'); - } else { - $draft = $this->gdClient->newDraft('no'); - } - - $control = $this->gdClient->newControl(); - $control->setDraft($draft); - $postToUpdate->control = $control; - $updatedPost = $postToUpdate->save(); - - return $updatedPost; - } - - /** - * This function uses query parameters to retrieve and print all posts - * within a specified date range. - * - * @param string $startDate Beginning date, inclusive. Preferred format is a RFC-3339 date, - * though other formats are accepted. - * @param string $endDate End date, exclusive. - * @return void - */ - public function printPostsInDateRange($startDate, $endDate) - { - $query = new Zend_Gdata_Query('http://www.blogger.com/feeds/' . $this->blogID . '/posts/default'); - $query->setParam('published-min', $startDate); - $query->setParam('published-max', $endDate); - - $feed = $this->gdClient->getFeed($query); - $this->printFeed($feed); - } - - /** - * This function creates a new comment and adds it to the specified post. - * A comment is created as a Zend_Gdata_Entry. - * - * @param string $postID The ID of the post to add the comment to. PostID - * in the field: tag:blogger.com,1999:blog-blogID.post-postID - * @param string $commentText The text of the comment to add. - * @return string The ID of the newly created comment. - */ - public function createComment($postID, $commentText) - { - $uri = 'http://www.blogger.com/feeds/' . $this->blogID . '/' . $postID . '/comments/default'; - - $newComment = $this->gdClient->newEntry(); - $newComment->content = $this->gdClient->newContent($commentText); - $newComment->content->setType('text'); - $createdComment = $this->gdClient->insertEntry($newComment, $uri); - - echo 'Added new comment: ' . $createdComment->content->text . "\n"; - // Edit link follows format: /feeds/blogID/postID/comments/default/commentID - $editLink = explode('/', $createdComment->getEditLink()->href); - $commentID = $editLink[8]; - - return $commentID; - } - - /** - * This function prints all comments associated with the specified post. - * - * @param string $postID The ID of the post whose comments we'll print. - * @return void - */ - public function printAllComments($postID) - { - $query = new Zend_Gdata_Query('http://www.blogger.com/feeds/' . $this->blogID . '/' . $postID . '/comments/default'); - $feed = $this->gdClient->getFeed($query); - $this->printFeed($feed); - } - - /** - * This function deletes the specified comment from a post. - * - * @param string $postID The ID of the post where the comment is. PostID in - * the field: tag:blogger.com,1999:blog-blogID.post-postID - * @param string $commentID The ID of the comment to delete. The commentID - * in the editURL: /feeds/blogID/postID/comments/default/commentID - * @return void - */ - public function deleteComment($postID, $commentID) - { - $uri = 'http://www.blogger.com/feeds/' . $this->blogID . '/' . $postID . '/comments/default/' . $commentID; - $this->gdClient->delete($uri); - } - - /** - * This function deletes the specified post. - * - * @param string $postID The ID of the post to delete. - * @return void - */ - public function deletePost($postID) - { - $uri = 'http://www.blogger.com/feeds/' . $this->blogID . '/posts/default/' . $postID; - $this->gdClient->delete($uri); - } - - /** - * Helper function to print out the titles of all supplied Blogger - * feeds. - * - * @param Zend_Gdata_Feed The feed to print. - * @return void - */ - public function printFeed($feed) - { - $i = 0; - foreach($feed->entries as $entry) - { - echo "\t" . $i ." ". $entry->title->text . "\n"; - $i++; - } - } - - /** - * Runs the sample. - * - * @return void - */ - public function run() - { - echo "Note: This sample may Create, Read, Update and Delete data " . - "stored in the account provided. Please exit now if you provided " . - "an account which contains important data.\n\n"; - $this->promptForBlogID(); - - echo "Creating a post.\n"; - $this->createPost('Hello, world!', 'I am on the intarweb!', False); - - echo "Creating a draft post.\n"; - $postID = $this->createPost('Salutations, world!', 'Does not sound right.. must work on title.', True); - - echo "Updating the previous post and publishing it.\n"; - $updatedPost = $this->updatePost($postID, 'Hello, world, it is.', 'There we go.', False); - echo "The new title of the post is: " . $updatedPost->title->text . "\n"; - echo "The new body of the post is: " . $updatedPost->content->text . "\n"; - - echo "Adding a comment to the previous post.\n"; - $this->createComment($postID, 'I am so glad this is public now.'); - - echo "Adding another comment.\n"; - $commentID = $this->createComment($postID, 'This is a spammy comment.'); - - echo "Deleting the previous comment.\n"; - $this->deleteComment($postID, $commentID); - - echo "Printing all posts.\n"; - $this->printAllPosts(); - - echo "Printing posts between 2007-01-01 and 2007-03-01.\n"; - $this->printPostsInDateRange('2007-01-01','2007-06-30'); - - echo "Deleting the post titled: " . $updatedPost->title->text . "\n"; - $this->deletePost($postID); - } -} - -/** - * Gets credentials from user. - * - * @param string $text - * @return string Index of the blog the user has chosen. - */ -function getInput($text) -{ - echo $text.': '; - return trim(fgets(STDIN)); -} - -$user = null; -$pass = null; - -// process command line options -foreach ($argv as $argument) { - $argParts = explode('=', $argument); - if ($argParts[0] == '--user') { - $user = $argParts[1]; - } else if ($argParts[0] == '--pass') { - $pass = $argParts[1]; - } -} - -if (($user == null) || ($pass == null)) { - exit("php Blogger.php --user=[username] --pass=[password]\n"); -} - -$sample = new SimpleCRUD($user, $pass); -$sample->run(); diff --git a/demos/Zend/Gdata/BooksBrowser/books_browser.css b/demos/Zend/Gdata/BooksBrowser/books_browser.css deleted file mode 100755 index 6ad2bbeaba7..00000000000 --- a/demos/Zend/Gdata/BooksBrowser/books_browser.css +++ /dev/null @@ -1,136 +0,0 @@ -body { - background-color: white; - color: black; - font-family: Arial, sans-serif; - font-size: small; - margin: 8px; - margin-top: 3px; -} - -.thumbnail img { - border-color:black; - border-width:1; - border-style:solid; -} - -table { - border-collapse: collapse; -} - -th, td { - padding: 0; - vertical-align: top; - text-align: left; - font-size: small; -} - -a:link { - color: #0000cc; -} - -a:active { - color: #cc0000; -} - -a:visited { - color: #551a8b; -} - -h1 { - font-size: x-large; - margin-top: 0px; - margin-bottom: 5px; -} - -h2 { - font-size: large; -} - -form { - display: inline; - margin: 0; - padding: 0; -} - -.volumeList td { - padding-bottom: 5px; - padding-right: 5px; -} - -#titleBar { - border: 1px solid silver; - background-color: #e5ecf9; - font-size: large; - font-weight: bold; - margin: 0; - padding: 0; - padding-top: 5px; - padding-bottom: 10px; - padding-left: 10px; - padding-right: 10px; - margin-top: 5px; - margin-bottom: 15px; -} - -#titleText { - float: left; -} - -#mainSearchBox { - background-color: #e5ecf9; - border: 1px solid silver; - width: 300; - padding-top: 5px; - padding-bottom: 10px; - padding-left: 10px; - padding-right: 10px; -} - -#searchResults { - width: 100%; -} - -.volumeList td -{ - border-top: 1px solid #aaaaaa; - padding: 6px; -} - -.thumbnail -{ - height: 80px; - padding: 3px; -} - -.previewbutton -{ - border: 0px; - margin: 6px 0px 6px 0px; -} - -#resultcell -{ - padding-right: 20px; -} - -#previewcell -{ - border-left: 1px dotted #aaa; - padding-left: 20px; - display: none; - padding-right: 20px; -} - -#viewport { - height: 500px; - width: 100%; - border: 1px solid #aaa; - -} - -/* Google Preview: Boilerplate styling */ -#viewport { font-size: 16px; line-height: 1; } -#viewport img, #viewport table, #viewport div, #viewport td -{ border: 0; padding: 0; margin: 0; background: none } -#viewport td { vertical-align: middle } - diff --git a/demos/Zend/Gdata/BooksBrowser/index.php b/demos/Zend/Gdata/BooksBrowser/index.php deleted file mode 100755 index 8d5e9ad145b..00000000000 --- a/demos/Zend/Gdata/BooksBrowser/index.php +++ /dev/null @@ -1,155 +0,0 @@ - -
- -HTML; - $flipflop = false; - foreach ($feed as $entry) { - $title = printArray($entry->getTitles()); - $volumeId = $entry->getVolumeId(); - if ($thumbnailLink = $entry->getThumbnailLink()) { - $thumbnail = $thumbnailLink->href; - } else { - $thumbnail = null; - } - $preview = $entry->getPreviewLink()->href; - $embeddability = $entry->getEmbeddability()->getValue(); - $creators = printArray($entry->getCreators()); - if (!empty($creators)) $creators = "by " . $creators; - if ($embeddability == - "http://schemas.google.com/books/2008#embeddable") { - $preview_link = ''. - '' . - '
'; - } else { - $preview_link = ''; - } - $thumbnail_img = (!$thumbnail) ? '' : ''; - - print << - - -HTML; - } - print << -
- $thumbnail_img -
- $title
- $creators
- $preview_link -
  -

-HTML; -} - -/* - * The main controller logic of the Books volume browser demonstration app. - */ -$queryType = isset($_GET['queryType']) ? $_GET['queryType'] : null; - -include 'interface.html'; - -if ($queryType === null) { - /* display the entire interface */ -} else { - $books = new Zend_Gdata_Books(); - $query = $books->newVolumeQuery(); - - /* display a list of volumes */ - if (isset($_GET['searchTerm'])) { - $searchTerm = $_GET['searchTerm']; - $query->setQuery($searchTerm); - } - if (isset($_GET['startIndex'])) { - $startIndex = $_GET['startIndex']; - $query->setStartIndex($startIndex); - } - if (isset($_GET['maxResults'])) { - $maxResults = $_GET['maxResults']; - $query->setMaxResults($maxResults); - } - if (isset($_GET['minViewability'])) { - $minViewability = $_GET['minViewability']; - $query->setMinViewability($minViewability); - } - - /* check for one of the restricted feeds, or list from 'all' videos */ - switch ($queryType) { - case 'full_view': - case 'partial_view': - $query->setMinViewability($queryType); - echo 'Requesting feed: ' . ($query->getQueryUrl()) . '

'; - $feed = $books->getVolumeFeed($query); - break; - case 'all': - echo 'Requesting feed: ' . ($query->getQueryUrl()) . '

'; - $feed = $books->getVolumeFeed($query); - break; - default: - echo 'ERROR - unknown queryType - "' . $queryType . '"'; - break; - } - echoBookList($feed); -} - diff --git a/demos/Zend/Gdata/BooksBrowser/interface.html b/demos/Zend/Gdata/BooksBrowser/interface.html deleted file mode 100644 index e4a6a24dc06..00000000000 --- a/demos/Zend/Gdata/BooksBrowser/interface.html +++ /dev/null @@ -1,81 +0,0 @@ - - - - Books Data API Browser in PHP - - - - - - - -
-

Books Data API Browser in PHP

-
-
-
-
-

Search Books:

-
- - - - - -
-
-
-
- - diff --git a/demos/Zend/Gdata/Calendar.php b/demos/Zend/Gdata/Calendar.php deleted file mode 100644 index fa3cf706135..00000000000 --- a/demos/Zend/Gdata/Calendar.php +++ /dev/null @@ -1,841 +0,0 @@ -= 5.1.4 - * - * You can run this sample both from the command line (CLI) and also - * from a web browser. When running through a web browser, only - * AuthSub and outputting a list of calendars is demonstrated. When - * running via CLI, all functionality except AuthSub is available and dependent - * upon the command line options passed. Run this script without any - * command line options to see usage, eg: - * /usr/local/bin/php -f Calendar.php - * - * More information on the Command Line Interface is available at: - * http://www.php.net/features.commandline - * - * NOTE: You must ensure that the Zend Framework is in your PHP include - * path. You can do this via php.ini settings, or by modifying the - * argument to set_include_path in the code below. - * - * NOTE: As this is sample code, not all of the functions do full error - * handling. Please see getEvent for an example of how errors could - * be handled and the online code samples for additional information. - */ - -/** - * @see Zend_Loader - */ -require_once 'Zend/Loader.php'; - -/** - * @see Zend_Gdata - */ -Zend_Loader::loadClass('Zend_Gdata'); - -/** - * @see Zend_Gdata_AuthSub - */ -Zend_Loader::loadClass('Zend_Gdata_AuthSub'); - -/** - * @see Zend_Gdata_ClientLogin - */ -Zend_Loader::loadClass('Zend_Gdata_ClientLogin'); - -/** - * @see Zend_Gdata_HttpClient - */ -Zend_Loader::loadClass('Zend_Gdata_HttpClient'); - -/** - * @see Zend_Gdata_Calendar - */ -Zend_Loader::loadClass('Zend_Gdata_Calendar'); - -/** - * @var string Location of AuthSub key file. include_path is used to find this - */ -$_authSubKeyFile = null; // Example value for secure use: 'mykey.pem' - -/** - * @var string Passphrase for AuthSub key file. - */ -$_authSubKeyFilePassphrase = null; - -/** - * Returns the full URL of the current page, based upon env variables - * - * Env variables used: - * $_SERVER['HTTPS'] = (on|off|) - * $_SERVER['HTTP_HOST'] = value of the Host: header - * $_SERVER['SERVER_PORT'] = port number (only used if not http/80,https/443) - * $_SERVER['REQUEST_URI'] = the URI after the method of the HTTP request - * - * @return string Current URL - */ -function getCurrentUrl() -{ - global $_SERVER; - - /** - * Filter php_self to avoid a security vulnerability. - */ - $php_request_uri = htmlentities(substr($_SERVER['REQUEST_URI'], 0, strcspn($_SERVER['REQUEST_URI'], "\n\r")), ENT_QUOTES); - - if (isset($_SERVER['HTTPS']) && strtolower($_SERVER['HTTPS']) == 'on') { - $protocol = 'https://'; - } else { - $protocol = 'http://'; - } - $host = $_SERVER['HTTP_HOST']; - if ($_SERVER['SERVER_PORT'] != '' && - (($protocol == 'http://' && $_SERVER['SERVER_PORT'] != '80') || - ($protocol == 'https://' && $_SERVER['SERVER_PORT'] != '443'))) { - $port = ':' . $_SERVER['SERVER_PORT']; - } else { - $port = ''; - } - return $protocol . $host . $port . $php_request_uri; -} - -/** - * Returns the AuthSub URL which the user must visit to authenticate requests - * from this application. - * - * Uses getCurrentUrl() to get the next URL which the user will be redirected - * to after successfully authenticating with the Google service. - * - * @return string AuthSub URL - */ -function getAuthSubUrl() -{ - global $_authSubKeyFile; - $next = getCurrentUrl(); - $scope = 'http://www.google.com/calendar/feeds/'; - $session = true; - if ($_authSubKeyFile != null) { - $secure = true; - } else { - $secure = false; - } - return Zend_Gdata_AuthSub::getAuthSubTokenUri($next, $scope, $secure, - $session); -} - -/** - * Outputs a request to the user to login to their Google account, including - * a link to the AuthSub URL. - * - * Uses getAuthSubUrl() to get the URL which the user must visit to authenticate - * - * @return void - */ -function requestUserLogin($linkText) -{ - $authSubUrl = getAuthSubUrl(); - echo "{$linkText}"; -} - -/** - * Returns a HTTP client object with the appropriate headers for communicating - * with Google using AuthSub authentication. - * - * Uses the $_SESSION['sessionToken'] to store the AuthSub session token after - * it is obtained. The single use token supplied in the URL when redirected - * after the user succesfully authenticated to Google is retrieved from the - * $_GET['token'] variable. - * - * @return Zend_Http_Client - */ -function getAuthSubHttpClient() -{ - global $_SESSION, $_GET, $_authSubKeyFile, $_authSubKeyFilePassphrase; - $client = new Zend_Gdata_HttpClient(); - if ($_authSubKeyFile != null) { - // set the AuthSub key - $client->setAuthSubPrivateKeyFile($_authSubKeyFile, $_authSubKeyFilePassphrase, true); - } - if (!isset($_SESSION['sessionToken']) && isset($_GET['token'])) { - $_SESSION['sessionToken'] = - Zend_Gdata_AuthSub::getAuthSubSessionToken($_GET['token'], $client); - } - $client->setAuthSubToken($_SESSION['sessionToken']); - return $client; -} - -/** - * Processes loading of this sample code through a web browser. Uses AuthSub - * authentication and outputs a list of a user's calendars if succesfully - * authenticated. - * - * @return void - */ -function processPageLoad() -{ - global $_SESSION, $_GET; - if (!isset($_SESSION['sessionToken']) && !isset($_GET['token'])) { - requestUserLogin('Please login to your Google Account.'); - } else { - $client = getAuthSubHttpClient(); - outputCalendarList($client); - } -} - -/** - * Returns a HTTP client object with the appropriate headers for communicating - * with Google using the ClientLogin credentials supplied. - * - * @param string $user The username, in e-mail address format, to authenticate - * @param string $pass The password for the user specified - * @return Zend_Http_Client - */ -function getClientLoginHttpClient($user, $pass) -{ - $service = Zend_Gdata_Calendar::AUTH_SERVICE_NAME; - - $client = Zend_Gdata_ClientLogin::getHttpClient($user, $pass, $service); - return $client; -} - -/** - * Outputs an HTML unordered list (ul), with each list item representing an event - * in the user's calendar. The calendar is retrieved using the magic cookie - * which allows read-only access to private calendar data using a special token - * available from within the Calendar UI. - * - * @param string $user The username or address of the calendar to be retrieved. - * @param string $magicCookie The magic cookie token - * @return void - */ -function outputCalendarMagicCookie($user, $magicCookie) -{ - $gdataCal = new Zend_Gdata_Calendar(); - $query = $gdataCal->newEventQuery(); - $query->setUser($user); - $query->setVisibility('private-' . $magicCookie); - $query->setProjection('full'); - $eventFeed = $gdataCal->getCalendarEventFeed($query); - echo "
    \n"; - foreach ($eventFeed as $event) { - echo "\t
  • " . $event->title->text . "
  • \n"; - $sl = $event->getLink('self')->href; - } - echo "
\n"; -} - -/** - * Outputs an HTML unordered list (ul), with each list item representing a - * calendar in the authenticated user's calendar list. - * - * @param Zend_Http_Client $client The authenticated client object - * @return void - */ -function outputCalendarList($client) -{ - $gdataCal = new Zend_Gdata_Calendar($client); - $calFeed = $gdataCal->getCalendarListFeed(); - echo "

" . $calFeed->title->text . "

\n"; - echo "
    \n"; - foreach ($calFeed as $calendar) { - echo "\t
  • " . $calendar->title->text . "
  • \n"; - } - echo "
\n"; -} - -/** - * Outputs an HTML unordered list (ul), with each list item representing an - * event on the authenticated user's calendar. Includes the start time and - * event ID in the output. Events are ordered by starttime and include only - * events occurring in the future. - * - * @param Zend_Http_Client $client The authenticated client object - * @return void - */ -function outputCalendar($client) -{ - $gdataCal = new Zend_Gdata_Calendar($client); - $query = $gdataCal->newEventQuery(); - $query->setUser('default'); - $query->setVisibility('private'); - $query->setProjection('full'); - $query->setOrderby('starttime'); - $query->setFutureevents(true); - $eventFeed = $gdataCal->getCalendarEventFeed($query); - // option 2 - // $eventFeed = $gdataCal->getCalendarEventFeed($query->getQueryUrl()); - echo "
    \n"; - foreach ($eventFeed as $event) { - echo "\t
  • " . $event->title->text . " (" . $event->id->text . ")\n"; - // Zend_Gdata_App_Extensions_Title->__toString() is defined, so the - // following will also work on PHP >= 5.2.0 - //echo "\t
  • " . $event->title . " (" . $event->id . ")\n"; - echo "\t\t
      \n"; - foreach ($event->when as $when) { - echo "\t\t\t
    • Starts: " . $when->startTime . "
    • \n"; - } - echo "\t\t
    \n"; - echo "\t
  • \n"; - } - echo "
\n"; -} - -/** - * Outputs an HTML unordered list (ul), with each list item representing an - * event on the authenticated user's calendar which occurs during the - * specified date range. - * - * To query for all events occurring on 2006-12-24, you would query for - * a startDate of '2006-12-24' and an endDate of '2006-12-25' as the upper - * bound for date queries is exclusive. See the 'query parameters reference': - * http://code.google.com/apis/gdata/calendar.html#Parameters - * - * @param Zend_Http_Client $client The authenticated client object - * @param string $startDate The start date in YYYY-MM-DD format - * @param string $endDate The end date in YYYY-MM-DD format - * @return void - */ -function outputCalendarByDateRange($client, $startDate='2007-05-01', - $endDate='2007-08-01') -{ - $gdataCal = new Zend_Gdata_Calendar($client); - $query = $gdataCal->newEventQuery(); - $query->setUser('default'); - $query->setVisibility('private'); - $query->setProjection('full'); - $query->setOrderby('starttime'); - $query->setStartMin($startDate); - $query->setStartMax($endDate); - $eventFeed = $gdataCal->getCalendarEventFeed($query); - echo "
    \n"; - foreach ($eventFeed as $event) { - echo "\t
  • " . $event->title->text . " (" . $event->id->text . ")\n"; - echo "\t\t
      \n"; - foreach ($event->when as $when) { - echo "\t\t\t
    • Starts: " . $when->startTime . "
    • \n"; - } - echo "\t\t
    \n"; - echo "\t
  • \n"; - } - echo "
\n"; -} - -/** - * Outputs an HTML unordered list (ul), with each list item representing an - * event on the authenticated user's calendar which matches the search string - * specified as the $fullTextQuery parameter - * - * @param Zend_Http_Client $client The authenticated client object - * @param string $fullTextQuery The string for which you are searching - * @return void - */ -function outputCalendarByFullTextQuery($client, $fullTextQuery='tennis') -{ - $gdataCal = new Zend_Gdata_Calendar($client); - $query = $gdataCal->newEventQuery(); - $query->setUser('default'); - $query->setVisibility('private'); - $query->setProjection('full'); - $query->setQuery($fullTextQuery); - $eventFeed = $gdataCal->getCalendarEventFeed($query); - echo "
    \n"; - foreach ($eventFeed as $event) { - echo "\t
  • " . $event->title->text . " (" . $event->id->text . ")\n"; - echo "\t\t
      \n"; - foreach ($event->when as $when) { - echo "\t\t\t
    • Starts: " . $when->startTime . "
    • \n"; - echo "\t\t
    \n"; - echo "\t
  • \n"; - } - } - echo "
\n"; -} - -/** - * Creates an event on the authenticated user's default calendar with the - * specified event details. - * - * @param Zend_Http_Client $client The authenticated client object - * @param string $title The event title - * @param string $desc The detailed description of the event - * @param string $where - * @param string $startDate The start date of the event in YYYY-MM-DD format - * @param string $startTime The start time of the event in HH:MM 24hr format - * @param string $endDate The end date of the event in YYYY-MM-DD format - * @param string $endTime The end time of the event in HH:MM 24hr format - * @param string $tzOffset The offset from GMT/UTC in [+-]DD format (eg -08) - * @return string The ID URL for the event. - */ -function createEvent ($client, $title = 'Tennis with Beth', - $desc='Meet for a quick lesson', $where = 'On the courts', - $startDate = '2008-01-20', $startTime = '10:00', - $endDate = '2008-01-20', $endTime = '11:00', $tzOffset = '-08') -{ - $gc = new Zend_Gdata_Calendar($client); - $newEntry = $gc->newEventEntry(); - $newEntry->title = $gc->newTitle(trim($title)); - $newEntry->where = array($gc->newWhere($where)); - - $newEntry->content = $gc->newContent($desc); - $newEntry->content->type = 'text'; - - $when = $gc->newWhen(); - $when->startTime = "{$startDate}T{$startTime}:00.000{$tzOffset}:00"; - $when->endTime = "{$endDate}T{$endTime}:00.000{$tzOffset}:00"; - $newEntry->when = array($when); - - $createdEntry = $gc->insertEvent($newEntry); - return $createdEntry->id->text; -} - -/** - * Creates an event on the authenticated user's default calendar using - * the specified QuickAdd string. - * - * @param Zend_Http_Client $client The authenticated client object - * @param string $quickAddText The QuickAdd text for the event - * @return string The ID URL for the event - */ -function createQuickAddEvent ($client, $quickAddText) { - $gdataCal = new Zend_Gdata_Calendar($client); - $event = $gdataCal->newEventEntry(); - $event->content = $gdataCal->newContent($quickAddText); - $event->quickAdd = $gdataCal->newQuickAdd(true); - - $newEvent = $gdataCal->insertEvent($event); - return $newEvent->id->text; -} - -/** - * Creates a new web content event on the authenticated user's default - * calendar with the specified event details. For simplicity, the event - * is created as an all day event and does not include a description. - * - * @param Zend_Http_Client $client The authenticated client object - * @param string $title The event title - * @param string $startDate The start date of the event in YYYY-MM-DD format - * @param string $endDate The end time of the event in HH:MM 24hr format - * @param string $icon URL pointing to a 16x16 px icon representing the event. - * @param string $url The URL containing the web content for the event. - * @param string $height The desired height of the web content pane. - * @param string $width The desired width of the web content pane. - * @param string $type The MIME type of the web content. - * @return string The ID URL for the event. - */ -function createWebContentEvent ($client, $title = 'World Cup 2006', - $startDate = '2006-06-09', $endDate = '2006-06-09', - $icon = 'http://www.google.com/calendar/images/google-holiday.gif', - $url = 'http://www.google.com/logos/worldcup06.gif', - $height = '120', $width = '276', $type = 'image/gif' - ) -{ - $gc = new Zend_Gdata_Calendar($client); - $newEntry = $gc->newEventEntry(); - $newEntry->title = $gc->newTitle(trim($title)); - - $when = $gc->newWhen(); - $when->startTime = $startDate; - $when->endTime = $endDate; - $newEntry->when = array($when); - - $wc = $gc->newWebContent(); - $wc->url = $url; - $wc->height = $height; - $wc->width = $width; - - $wcLink = $gc->newLink(); - $wcLink->rel = "http://schemas.google.com/gCal/2005/webContent"; - $wcLink->title = $title; - $wcLink->type = $type; - $wcLink->href = $icon; - - $wcLink->webContent = $wc; - $newEntry->link = array($wcLink); - - $createdEntry = $gc->insertEvent($newEntry); - return $createdEntry->id->text; -} - -/** - * Creates a recurring event on the authenticated user's default calendar with - * the specified event details. - * - * @param Zend_Http_Client $client The authenticated client object - * @param string $title The event title - * @param string $desc The detailed description of the event - * @param string $where - * @param string $recurData The iCalendar recurring event syntax (RFC2445) - * @return void - */ -function createRecurringEvent ($client, $title = 'Tennis with Beth', - $desc='Meet for a quick lesson', $where = 'On the courts', - $recurData = null) -{ - $gc = new Zend_Gdata_Calendar($client); - $newEntry = $gc->newEventEntry(); - $newEntry->title = $gc->newTitle(trim($title)); - $newEntry->where = array($gc->newWhere($where)); - - $newEntry->content = $gc->newContent($desc); - $newEntry->content->type = 'text'; - - /** - * Due to the length of this recurrence syntax, we did not specify - * it as a default parameter value directly - */ - if ($recurData == null) { - $recurData = - "DTSTART;VALUE=DATE:20070501\r\n" . - "DTEND;VALUE=DATE:20070502\r\n" . - "RRULE:FREQ=WEEKLY;BYDAY=Tu;UNTIL=20070904\r\n"; - } - - $newEntry->recurrence = $gc->newRecurrence($recurData); - - $gc->post($newEntry->saveXML()); -} - -/** - * Returns an entry object representing the event with the specified ID. - * - * @param Zend_Http_Client $client The authenticated client object - * @param string $eventId The event ID string - * @return Zend_Gdata_Calendar_EventEntry|null if the event is found, null if it's not - */ -function getEvent($client, $eventId) -{ - $gdataCal = new Zend_Gdata_Calendar($client); - $query = $gdataCal->newEventQuery(); - $query->setUser('default'); - $query->setVisibility('private'); - $query->setProjection('full'); - $query->setEvent($eventId); - - try { - $eventEntry = $gdataCal->getCalendarEventEntry($query); - return $eventEntry; - } catch (Zend_Gdata_App_Exception $e) { - var_dump($e); - return null; - } -} - -/** - * Updates the title of the event with the specified ID to be - * the title specified. Also outputs the new and old title - * with HTML br elements separating the lines - * - * @param Zend_Http_Client $client The authenticated client object - * @param string $eventId The event ID string - * @param string $newTitle The new title to set on this event - * @return Zend_Gdata_Calendar_EventEntry|null The updated entry - */ -function updateEvent ($client, $eventId, $newTitle) -{ - $gdataCal = new Zend_Gdata_Calendar($client); - if ($eventOld = getEvent($client, $eventId)) { - echo "Old title: " . $eventOld->title->text . "
\n"; - $eventOld->title = $gdataCal->newTitle($newTitle); - try { - $eventOld->save(); - } catch (Zend_Gdata_App_Exception $e) { - var_dump($e); - return null; - } - $eventNew = getEvent($client, $eventId); - echo "New title: " . $eventNew->title->text . "
\n"; - return $eventNew; - } else { - return null; - } -} - -/** - * Adds an extended property to the event specified as a parameter. - * An extended property is an arbitrary name/value pair that can be added - * to an event and retrieved via the API. It is not accessible from the - * calendar web interface. - * - * @param Zend_Http_Client $client The authenticated client object - * @param string $eventId The event ID string - * @param string $name The name of the extended property - * @param string $value The value of the extended property - * @return Zend_Gdata_Calendar_EventEntry|null The updated entry - */ -function addExtendedProperty ($client, $eventId, - $name='http://www.example.com/schemas/2005#mycal.id', $value='1234') -{ - $gc = new Zend_Gdata_Calendar($client); - if ($event = getEvent($client, $eventId)) { - $extProp = $gc->newExtendedProperty($name, $value); - $extProps = array_merge($event->extendedProperty, array($extProp)); - $event->extendedProperty = $extProps; - $eventNew = $event->save(); - return $eventNew; - } else { - return null; - } -} - - -/** - * Adds a reminder to the event specified as a parameter. - * - * @param Zend_Http_Client $client The authenticated client object - * @param string $eventId The event ID string - * @param integer $minutes Minutes before event to set reminder - * @return Zend_Gdata_Calendar_EventEntry|null The updated entry - */ -function setReminder($client, $eventId, $minutes=15) -{ - $gc = new Zend_Gdata_Calendar($client); - $method = "alert"; - if ($event = getEvent($client, $eventId)) { - $times = $event->when; - foreach ($times as $when) { - $reminder = $gc->newReminder(); - $reminder->setMinutes($minutes); - $reminder->setMethod($method); - $when->reminder = array($reminder); - } - $eventNew = $event->save(); - return $eventNew; - } else { - return null; - } -} - -/** - * Deletes the event specified by retrieving the atom entry object - * and calling Zend_Feed_EntryAtom::delete() method. This is for - * example purposes only, as it is inefficient to retrieve the entire - * atom entry only for the purposes of deleting it. - * - * @param Zend_Http_Client $client The authenticated client object - * @param string $eventId The event ID string - * @return void - */ -function deleteEventById ($client, $eventId) -{ - $event = getEvent($client, $eventId); - $event->delete(); -} - -/** - * Deletes the event specified by calling the Zend_Gdata::delete() - * method. The URL is typically in the format of: - * http://www.google.com/calendar/feeds/default/private/full/ - * - * @param Zend_Http_Client $client The authenticated client object - * @param string $url The url for the event to be deleted - * @return void - */ -function deleteEventByUrl ($client, $url) -{ - $gdataCal = new Zend_Gdata_Calendar($client); - $gdataCal->delete($url); -} - -/** - * Main logic for running this sample code via the command line or, - * for AuthSub functionality only, via a web browser. The output of - * many of the functions is in HTML format for demonstration purposes, - * so you may wish to pipe the output to Tidy when running from the - * command-line for clearer results. - * - * Run without any arguments to get usage information - */ -if (isset($argc) && $argc >= 2) { - switch ($argv[1]) { - case 'outputCalendar': - if ($argc == 4) { - $client = getClientLoginHttpClient($argv[2], $argv[3]); - outputCalendar($client); - } else { - echo "Usage: php {$argv[0]} {$argv[1]} " . - " \n"; - } - break; - case 'outputCalendarMagicCookie': - if ($argc == 4) { - outputCalendarMagicCookie($argv[2], $argv[3]); - } else { - echo "Usage: php {$argv[0]} {$argv[1]} " . - " \n"; - } - break; - case 'outputCalendarByDateRange': - if ($argc == 6) { - $client = getClientLoginHttpClient($argv[2], $argv[3]); - outputCalendarByDateRange($client, $argv[4], $argv[5]); - } else { - echo "Usage: php {$argv[0]} {$argv[1]} " . - " \n"; - } - break; - case 'outputCalendarByFullTextQuery': - if ($argc == 5) { - $client = getClientLoginHttpClient($argv[2], $argv[3]); - outputCalendarByFullTextQuery($client, $argv[4]); - } else { - echo "Usage: php {$argv[0]} {$argv[1]} " . - " \n"; - } - break; - case 'outputCalendarList': - if ($argc == 4) { - $client = getClientLoginHttpClient($argv[2], $argv[3]); - outputCalendarList($client); - } else { - echo "Usage: php {$argv[0]} {$argv[1]} " . - " \n"; - } - break; - case 'updateEvent': - if ($argc == 6) { - $client = getClientLoginHttpClient($argv[2], $argv[3]); - updateEvent($client, $argv[4], $argv[5]); - } else { - echo "Usage: php {$argv[0]} {$argv[1]} " . - " \n"; - } - break; - case 'setReminder': - if ($argc == 6) { - $client = getClientLoginHttpClient($argv[2], $argv[3]); - setReminder($client, $argv[4], $argv[5]); - } else { - echo "Usage: php {$argv[0]} {$argv[1]} " . - " \n"; - } - break; - case 'addExtendedProperty': - if ($argc == 7) { - $client = getClientLoginHttpClient($argv[2], $argv[3]); - addExtendedProperty($client, $argv[4], $argv[5], $argv[6]); - } else { - echo "Usage: php {$argv[0]} {$argv[1]} " . - " \n"; - } - break; - case 'deleteEventById': - if ($argc == 5) { - $client = getClientLoginHttpClient($argv[2], $argv[3]); - deleteEventById($client, $argv[4]); - } else { - echo "Usage: php {$argv[0]} {$argv[1]} " . - "\n"; - } - break; - case 'deleteEventByUrl': - if ($argc == 5) { - $client = getClientLoginHttpClient($argv[2], $argv[3]); - deleteEventByUrl($client, $argv[4]); - } else { - echo "Usage: php {$argv[0]} {$argv[1]} " . - "\n"; - } - break; - case 'createEvent': - if ($argc == 12) { - $client = getClientLoginHttpClient($argv[2], $argv[3]); - $id = createEvent($client, $argv[4], $argv[5], $argv[6], $argv[7], - $argv[8], $argv[9], $argv[10], $argv[11]); - print "Event created with ID: $id\n"; - } else { - echo "Usage: php {$argv[0]} {$argv[1]} " . - " <description> <where> " . - "<startDate> <startTime> <endDate> <endTime> <tzOffset>\n"; - echo "EXAMPLE: php {$argv[0]} {$argv[1]} <username> <password> " . - "'Tennis with Beth' 'Meet for a quick lesson' 'On the courts' " . - "'2008-01-01' '10:00' '2008-01-01' '11:00' '-08'\n"; - } - break; - case 'createQuickAddEvent': - if ($argc == 5) { - $client = getClientLoginHttpClient($argv[2], $argv[3]); - $id = createQuickAddEvent($client, $argv[4]); - print "Event created with ID: $id\n"; - } else { - echo "Usage: php {$argv[0]} {$argv[1]} <username> <password> " . - "<quickAddText>\n"; - echo "EXAMPLE: php {$argv[0]} {$argv[1]} <username> <password> " . - "'Dinner at the beach on Thursday 8 PM'\n"; - } - break; - case 'createWebContentEvent': - if ($argc == 12) { - $client = getClientLoginHttpClient($argv[2], $argv[3]); - $id = createWebContentEvent($client, $argv[4], $argv[5], $argv[6], - $argv[7], $argv[8], $argv[9], $argv[10], $argv[11]); - print "Event created with ID: $id\n"; - } else { - echo "Usage: php {$argv[0]} {$argv[1]} <username> <password> " . - "<title> <startDate> <endDate> <icon> <url> <height> <width> <type>\n\n"; - echo "This creates a web content event on 2007/06/09.\n"; - echo "EXAMPLE: php {$argv[0]} {$argv[1]} <username> <password> " . - "'World Cup 2006' '2007-06-09' '2007-06-10' " . - "'http://www.google.com/calendar/images/google-holiday.gif' " . - "'http://www.google.com/logos/worldcup06.gif' " . - "'120' '276' 'image/gif'\n"; - } - break; - case 'createRecurringEvent': - if ($argc == 7) { - $client = getClientLoginHttpClient($argv[2], $argv[3]); - createRecurringEvent($client, $argv[4], $argv[5], $argv[6]); - } else { - echo "Usage: php {$argv[0]} {$argv[1]} <username> <password> " . - "<title> <description> <where>\n\n"; - echo "This creates an all-day event which occurs first on 2007/05/01" . - "and repeats weekly on Tuesdays until 2007/09/04\n"; - echo "EXAMPLE: php {$argv[0]} {$argv[1]} <username> <password> " . - "'Tennis with Beth' 'Meet for a quick lesson' 'On the courts'\n"; - } - break; - } -} else if (!isset($_SERVER["HTTP_HOST"])) { - // running from command line, but action left unspecified - echo "Usage: php {$argv[0]} <action> [<username>] [<password>] " . - "[<arg1> <arg2> ...]\n\n"; - echo "Possible action values include:\n" . - "outputCalendar\n" . - "outputCalendarMagicCookie\n" . - "outputCalendarByDateRange\n" . - "outputCalendarByFullTextQuery\n" . - "outputCalendarList\n" . - "updateEvent\n" . - "deleteEventById\n" . - "deleteEventByUrl\n" . - "createEvent\n" . - "createQuickAddEvent\n" . - "createWebContentEvent\n" . - "createRecurringEvent\n" . - "setReminder\n" . - "addExtendedProperty\n"; -} else { - // running through web server - demonstrate AuthSub - processPageLoad(); -} diff --git a/demos/Zend/Gdata/Docs.php b/demos/Zend/Gdata/Docs.php deleted file mode 100755 index 7f187d68666..00000000000 --- a/demos/Zend/Gdata/Docs.php +++ /dev/null @@ -1,940 +0,0 @@ -<?php -/** - * Zend Framework - * - * LICENSE - * - * This source file is subject to the new BSD license that is bundled - * with this package in the file LICENSE.txt. - * It is also available through the world-wide-web at this URL: - * http://framework.zend.com/license/new-bsd - * If you did not receive a copy of the license and are unable to - * obtain it through the world-wide-web, please send an email - * to license@zend.com so we can send you a copy immediately. - * - * @category Zend - * @package Zend_Gdata - * @subpackage Demos - * @copyright Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com) - * @license http://framework.zend.com/license/new-bsd New BSD License - */ - -/** - * PHP sample code for the Google Documents List data API. Utilizes the - * Zend Framework Gdata components to communicate with the Google API. - * - * Requires the Zend Framework Gdata components and PHP >= 5.1.4 - * - * You can run this sample both from the command line (CLI) and also - * from a web browser. When running through a web browser, only - * AuthSub and outputting a list of documents is demonstrated. When - * running via CLI, all functionality except AuthSub is available and dependent - * upon the command line options passed. Run this script without any - * command line options to see usage, eg: - * /usr/local/bin/php -f Docs.php - * - * More information on the Command Line Interface is available at: - * http://www.php.net/features.commandline - * - * NOTE: You must ensure that Zend Framework is in your PHP include - * path. You can do this via php.ini settings, or by modifying the - * argument to set_include_path in the code below. - * - * NOTE: As this is sample code, not all of the functions do full error - * handling. - */ - -/** - * @see Zend_Loader - */ -require_once 'Zend/Loader.php'; - -/** - * @see Zend_Gdata - */ -Zend_Loader::loadClass('Zend_Gdata'); - -/** - * @see Zend_Gdata_AuthSub - */ -Zend_Loader::loadClass('Zend_Gdata_AuthSub'); - -/** - * @see Zend_Gdata_ClientLogin - */ -Zend_Loader::loadClass('Zend_Gdata_ClientLogin'); - -/** - * @see Zend_Gdata_Docs - */ -Zend_Loader::loadClass('Zend_Gdata_Docs'); - -/** - * Returns a HTTP client object with the appropriate headers for communicating - * with Google using the ClientLogin credentials supplied. - * - * @param string $user The username, in e-mail address format, to authenticate - * @param string $pass The password for the user specified - * @return Zend_Http_Client - */ -function getClientLoginHttpClient($user, $pass) -{ - $service = Zend_Gdata_Docs::AUTH_SERVICE_NAME; - $client = Zend_Gdata_ClientLogin::getHttpClient($user, $pass, $service); - return $client; -} - -// ************************ BEGIN CLI SPECIFIC CODE ************************ - -/** - * Display list of valid commands. - * - * @param string $executable The name of the current script. This is usually available as $argv[0]. - * @return void - */ -function displayHelp($executable) -{ - echo "Usage: php {$executable} <action> [<username>] [<password>] " . - "[<arg1> <arg2> ...]\n\n"; - echo "Possible action values include:\n" . - "retrieveAllDocuments\n" . - "retrieveWPDocs\n" . - "retrieveSpreadsheets\n" . - "fullTextSearch\n" . - "uploadDocument\n"; -} - -/** - * Parse command line arguments and execute appropriate function when - * running from the command line. - * - * If no arguments are provided, usage information will be provided. - * - * @param array $argv The array of command line arguments provided by PHP. - * $argv[0] should be the current executable name or '-' if not available. - * @param integer $argc The size of $argv. - * @return void - */ -function runCLIVersion($argv, $argc) -{ - if (isset($argc) && $argc >= 2) { - # Prepare a server connection - if ($argc >= 4) { - try { - $client = getClientLoginHttpClient($argv[2], $argv[3]); - $docs = new Zend_Gdata_Docs($client); - } catch (Zend_Gdata_App_AuthException $e) { - echo "Error: Unable to authenticate. Please check your"; - echo " credentials.\n"; - exit(1); - } - } - - # Dispatch arguments to the desired method - switch ($argv[1]) { - case 'retrieveAllDocuments': - if ($argc >= 4) { - retrieveAllDocuments($docs, false); - } else { - echo "Usage: php {$argv[0]} {$argv[1]} <username>"; - echo " <password>\n\n"; - echo "This lists all of the documents in the user's"; - echo " account.\n"; - } - break; - case 'retrieveWPDocs': - if ($argc >= 4) { - //echo "!WP Docs:"; - //var_dump($docs); - retrieveWPDocs($docs, false); - } else { - echo "Usage: php {$argv[0]} {$argv[1]} <username>"; - echo " <password>\n\n"; - echo "This lists all of the word processing documents in"; - echo " the user's account.\n"; - } - break; - case 'retrieveSpreadsheets': - if ($argc >= 4) { - retrieveAllDocuments($docs, false); - } else { - echo "Usage: php {$argv[0]} {$argv[1]} <username>"; - echo " <password>\n\n"; - echo "This lists all of the spreadsheets in the user's"; - echo " account.\n"; - } - break; - case 'fullTextSearch': - if ($argc >= 4) { - // Combine all of the query args into one query string. - // The command line split the query string on space - // characters. - $queryString = implode(' ', array_slice($argv, 4)); - fullTextSearch($docs, false, $queryString); - } else { - echo "Usage: php {$argv[0]} {$argv[1]} <username>"; - echo " <password> <query string>\n\n"; - echo "This lists all of the documents which contain the"; - echo " query string.\n"; - } - break; - case 'uploadDocument': - if ($argc >= 5) { - // Pass in the file name of the document to be uploaded. - // Since the document is on this machine, we do not need - // to set the temporary file name. The temp file name is - // used only when uploading to a webserver. - uploadDocument($docs, false, $argv[4], null); - } else { - echo "Usage: php {$argv[0]} {$argv[1]} <username>"; - echo " <password> <file_with_path>\n\n"; - echo "This lists all of the documents which contain the"; - echo " query string.\n"; - echo "\nExample: php {$argv[0]} {$argv[1]} <username>"; - echo " <password> /tmp/testSpreadsheet.ods\n"; - } - break; - default: - // Invalid action entered - displayHelp($argv[0]); - // End switch block - } - } else { - // action left unspecified - displayHelp($argv[0]); - } -} - -/** - * Displays the titles for the Google Documents entries in the feed. In HTML - * mode, the titles are links which point to the HTML version of the document. - * - * @param Zend_Gdata_Docs_DocumentListFeed $feed - * @param boolean $html True if output should be formatted for display in - * a web browser - * @return void - */ -function printDocumentsFeed($feed, $html) -{ - if ($html) {echo "<ul>\n";} - - // Iterate over the document entries in the feed and display each document's - // title. - foreach ($feed->entries as $entry) { - - if ($html) { - // Find the URL of the HTML view of the document. - $alternateLink = ''; - foreach ($entry->link as $link) { - if ($link->getRel() === 'alternate') { - $alternateLink = $link->getHref(); - } - } - // Make the title link to the document on docs.google.com. - echo "<li><a href=\"$alternateLink\">\n"; - } - - echo "$entry->title\n"; - - if ($html) {echo "</a></li>\n";} - } - - if ($html) {echo "</ul>\n";} -} - -/** - * Obtain a list of all of a user's docs.google.com documents and print the - * titles to the command line. - * - * @param Zend_Gdata_Docs $client The service object to use for communicating with the Google - * Documents server. - * @param boolean $html True if output should be formatted for display in a web browser. - * @return void - */ -function retrieveAllDocuments($client, $html) -{ - if ($html) {echo "<h2>Your documents</h2>\n";} - - $feed = $client->getDocumentListFeed(); - - printDocumentsFeed($feed, $html); -} - -/** - * Obtain a list of all of a user's docs.google.com word processing - * documents and print the titles to the command line. - * - * @param Zend_Gdata_Docs $client The service object to use for communicating with the Google - * Documents server. - * @param boolean $html True if output should be formatted for display in a web browser. - * @return void - */ -function retrieveWPDocs($client, $html) -{ - if ($html) {echo "<h2>Your word processing documents</h2>\n";} - - $feed = $client->getDocumentListFeed( - 'http://docs.google.com/feeds/documents/private/full/-/document'); - - printDocumentsFeed($feed, $html); -} - -/** - * Obtain a list of all of a user's docs.google.com spreadsheets - * documents and print the titles to the command line. - * - * @param Zend_Gdata_Docs $client The service object to use for communicating with the Google - * Documents server. - * @param boolean $html True if output should be formatted for display in a web browser. - * @return void - */ -function retrieveSpreadsheets($client, $html) -{ - if ($html) {echo "<h2>Your spreadsheets</h2>\n";} - - $feed = $client->getDocumentListFeed( - 'http://docs.google.com/feeds/documents/private/full/-/spreadsheet'); - - printDocumentsFeed($feed, $html); -} - -/** - * Obtain a list of all of a user's docs.google.com documents - * which match the specified search criteria and print the titles to the - * command line. - * - * @param Zend_Gdata_Docs $client The service object to use for communicating with the Google - * Documents server. - * @param boolean $html True if output should be formatted for display in a web browser. - * @param string $query The search query to use - * @return void - */ -function fullTextSearch($client, $html, $query) -{ - if ($html) {echo "<h2>Documents containing $query</h2>\n";} - - $feed = $client->getDocumentListFeed( - 'http://docs.google.com/feeds/documents/private/full?q=' . $query); - - printDocumentsFeed($feed, $html); -} - -/** - * Upload the specified document - * - * @param Zend_Gdata_Docs $docs The service object to use for communicating with - * the Google Documents server. - * @param boolean $html True if output should be formatted for display in - * a web browser. - * @param string $originalFileName The name of the file to be uploaded. The mime type - * of the file is determined from the extension on - * this file name. For example, test.csv is uploaded - * as a comma seperated volume and converted into a - * spreadsheet. - * @param string $temporaryFileLocation (optional) The file in which the data for the - * document is stored. This is used when the file has - * been uploaded from the client's machine to the - * server and is stored in a temporary file which - * does not have an extension. If this parameter is - * null, the file is read from the originalFileName. - * @return void - */ -function uploadDocument($docs, $html, $originalFileName, - $temporaryFileLocation) { - $fileToUpload = $originalFileName; - if ($temporaryFileLocation) { - $fileToUpload = $temporaryFileLocation; - } - - // Upload the file and convert it into a Google Document. The original - // file name is used as the title of the document and the mime type - // is determined based on the extension on the original file name. - $newDocumentEntry = $docs->uploadFile($fileToUpload, $originalFileName, - null, Zend_Gdata_Docs::DOCUMENTS_LIST_FEED_URI); - - echo "New Document Title: "; - - if ($html) { - // Find the URL of the HTML view of this document. - $alternateLink = ''; - foreach ($newDocumentEntry->link as $link) { - if ($link->getRel() === 'alternate') { - $alternateLink = $link->getHref(); - } - } - // Make the title link to the document on docs.google.com. - echo "<a href=\"$alternateLink\">\n"; - } - echo $newDocumentEntry->title."\n"; - if ($html) {echo "</a>\n";} -} - -// ************************ BEGIN WWW SPECIFIC CODE ************************ - -/** - * Writes the HTML prologue for this app. - * - * NOTE: We would normally keep the HTML/CSS markup separate from the business - * logic above, but have decided to include it here for simplicity of - * having a single-file sample. - * - * - * @param boolean $displayMenu (optional) If set to true, a navigation menu is displayed at the top - * of the page. Default is true. - * @return void - */ -function startHTML($displayMenu = true) -{ -?> -<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" - "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> - -<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> -<head> - <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/> - - <title>Documents List API Demo - - - - - - - - - -
-'; - echo '← Back
'; - } -?> -
- - - -
-

Almost there...

-

Before using this demo, you must set an application password - to protect your account. You will also need to set your - Google Apps credentials in order to communicate with the Google - Apps servers.

-

To continue, open this file in a text editor and fill - out the information in the configuration section.

-
- -
-

Google Docs Authentication Failed

-

Authentication with the Google Apps servers failed.

-

Please open this file in a text editor and make - sure your credentials are correct.

-
-{$linkText}"; -} - -/** - * Returns the AuthSub URL which the user must visit to authenticate requests - * from this application. - * - * Uses getCurrentUrl() to get the next URL which the user will be redirected - * to after successfully authenticating with the Google service. - * - * @return string AuthSub URL - */ -function getAuthSubUrl() -{ - $next = getCurrentUrl(); - $scope = 'http://docs.google.com/feeds/documents'; - $secure = false; - $session = true; - return Zend_Gdata_AuthSub::getAuthSubTokenUri($next, $scope, $secure, - $session); -} - -/** - * Returns a HTTP client object with the appropriate headers for communicating - * with Google using AuthSub authentication. - * - * Uses the $_SESSION['sessionToken'] to store the AuthSub session token after - * it is obtained. The single use token supplied in the URL when redirected - * after the user succesfully authenticated to Google is retrieved from the - * $_GET['token'] variable. - * - * @return Zend_Http_Client - */ -function getAuthSubHttpClient() -{ - global $_SESSION, $_GET; - if (!isset($_SESSION['docsSampleSessionToken']) && isset($_GET['token'])) { - $_SESSION['docsSampleSessionToken'] = - Zend_Gdata_AuthSub::getAuthSubSessionToken($_GET['token']); - } - $client = Zend_Gdata_AuthSub::getHttpClient($_SESSION['docsSampleSessionToken']); - return $client; -} - -/** - * Returns the full URL of the current page, based upon env variables - * - * Env variables used: - * $_SERVER['HTTPS'] = (on|off|) - * $_SERVER['HTTP_HOST'] = value of the Host: header - * $_SERVER['SERVER_PORT'] = port number (only used if not http/80,https/443) - * $_SERVER['REQUEST_URI'] = the URI after the method of the HTTP request - * - * @return string Current URL - */ -function getCurrentUrl() -{ - global $_SERVER; - - /** - * Filter php_self to avoid a security vulnerability. - */ - $php_request_uri = htmlentities(substr($_SERVER['REQUEST_URI'], 0, - strcspn($_SERVER['REQUEST_URI'], "\n\r")), ENT_QUOTES); - - if (isset($_SERVER['HTTPS']) && strtolower($_SERVER['HTTPS']) == 'on') { - $protocol = 'https://'; - } else { - $protocol = 'http://'; - } - $host = $_SERVER['HTTP_HOST']; - if ($_SERVER['SERVER_PORT'] != '' && - (($protocol == 'http://' && $_SERVER['SERVER_PORT'] != '80') || - ($protocol == 'https://' && $_SERVER['SERVER_PORT'] != '443'))) { - $port = ':' . $_SERVER['SERVER_PORT']; - } else { - $port = ''; - } - return $protocol . $host . $port . $php_request_uri; -} - -/** - * Display the main menu for running in a web browser. - * - * @return void - */ -function displayMenu() -{ -?> -

Main Menu

- -

Welcome to the Google Documents List API demo page. Please select - from one of the following three options to see a list of commands.

- - - -

Tip: You can also run this demo from the command line if your system - has PHP CLI support enabled.

- -

Logout

- -

Logout successful.

- - -Invalid mode.\n"; - echo "

Please check your request and try again.

"; - endHTML(true); - } - } - } - - // Check for an invalid command. If so, display an error and exit. - if (!empty($_REQUEST['command'])) { - header('HTTP/1.1 400 Bad Request'); - startHTML(); - echo "

Invalid command.

\n"; - echo "

Please check your request and try again.

"; - endHTML(true); - } - // If a menu parameter is available, display a submenu. - - if (!empty($_REQUEST['menu'])) { - switch ($_REQUEST['menu']) { - case 'list': - startHTML(); - displayListMenu(); - endHTML(); - case 'query': - startHTML(); - displayQueryMenu(); - endHTML(); - case 'upload': - startHTML(); - displayUploadMenu(); - endHTML(); - case 'logout': - startHTML(false); - logout(); - endHTML(); - default: - header('HTTP/1.1 400 Bad Request'); - startHTML(); - echo "

Invalid menu selection.

\n"; - echo "

Please check your request and try again.

"; - endHTML(true); - } - } - // If we get this far, that means there's nothing to do. Display - // the main menu. - // If no command was issued and no menu was selected, display the - // main menu. - startHTML(); - displayMenu(); - endHTML(); - } -} - -/** - * Display the menu for running in a web browser. - * - * @return void - */ -function displayListMenu() -{ -?> -

List Documents Menu

- -
-

Retrieve Google Documents Feed

-

Retrieve the feed for all of your documents.

-

- -

-

-
- -
-

Retrieve Google Word Processing Documents

-

Query the documents list feed for all word processing documents.

-

- -

-

-
- -
-

Retrieve Google Spreadsheets

-

Query the documents list feed for all spreadsheets.

-

- -

-

-
- -

Query the Documents List Feed

- -
-

Search the Documents List Feed

-

Find documents which contain the desired text.

-

- - -

-

-
- - -

Upload a document

- -
-

Select a Document to Upload

-

Upload a file from your computer to Google Documents.

-

- - -

-

-
- -Service Error Encountered

\n"; - echo "
" . htmlspecialchars($e->__toString()) . "
"; - endHTML(true); - } -} diff --git a/demos/Zend/Gdata/Gapps.php b/demos/Zend/Gdata/Gapps.php deleted file mode 100644 index 4da1ffbef8e..00000000000 --- a/demos/Zend/Gdata/Gapps.php +++ /dev/null @@ -1,1992 +0,0 @@ -= 5.1.4 - * - * You can run this sample both from the command line (CLI) and also - * from a web browser. Run this script without any command line options to - * see usage, eg: - * /usr/bin/env php Gapps.php - * - * More information on the Command Line Interface is available at: - * http://www.php.net/features.commandline - * - * When running this code from a web browser, be sure to fill in your - * Google Apps credentials below and choose a password for authentication - * via the web browser. - * - * Since this is a demo, only minimal error handling and input validation - * are performed. THIS CODE IS FOR DEMONSTRATION PURPOSES ONLY. NOT TO BE - * USED IN A PRODUCTION ENVIRONMENT. - * - * NOTE: You must ensure that Zend Framework is in your PHP include - * path. You can do this via php.ini settings, or by modifying the - * argument to set_include_path in the code below. - */ - -// ************************ BEGIN WWW CONFIGURATION ************************ - -/** - * Google Apps username. This is the username (without domain) used - * to administer your Google Apps account. This value is only - * used when accessing this demo on a web server. - * - * For example, if you login to Google Apps as 'foo@bar.com.inavlid', - * your username is 'foo'. - */ -define('GAPPS_USERNAME', 'username'); - -/** - * Google Apps domain. This is the domain associated with your - * Google Apps account. This value is only used when accessing this demo - * on a web server. - * - * For example, if you login to Google Apps as foo@bar.com.inavlid, - * your domain is 'bar.com.invalid'. - */ -define('GAPPS_DOMAIN', 'example.com.invalid'); - -/** - * Google Apps password. This is the password associated with the above - * username. This value is only used when accessing this demo on a - * web server. - */ -define('GAPPS_PASSWORD', 'your password here'); - -/** - * Login password. This password is used to protect your account from - * unauthorized access when running this demo on a web server. - * - * If this field is blank, all access will be denied. A blank password - * field is not the same as no password (which is disallowed for - * security reasons). - * - * NOTE: While we could technically just ask the user for their Google Apps - * credentials, the ClientLogin API is not intended for direct use by - * web applications. If you are the only user of the application, this - * is fine--- but you should not ask other users to enter their - * credentials via your web application. - */ -define('LOGIN_PASSWORD', ''); - -// ************************* END WWW CONFIGURATION ************************* - -/** - * @see Zend_Loader - */ -require_once 'Zend/Loader.php'; - -/** - * @see Zend_Gdata - */ -Zend_Loader::loadClass('Zend_Gdata'); - -/** - * @see Zend_Gdata_ClientLogin - */ -Zend_Loader::loadClass('Zend_Gdata_ClientLogin'); - -/** - * @see Zend_Gdata_Gapps - */ -Zend_Loader::loadClass('Zend_Gdata_Gapps'); - -/** - * Returns a HTTP client object with the appropriate headers for communicating - * with Google using the ClientLogin credentials supplied. - * - * @param string $user The username, in e-mail address format, to authenticate - * @param string $pass The password for the user specified - * @return Zend_Http_Client - */ -function getClientLoginHttpClient($user, $pass) -{ - $service = Zend_Gdata_Gapps::AUTH_SERVICE_NAME; - $client = Zend_Gdata_ClientLogin::getHttpClient($user, $pass, $service); - return $client; -} - -/** - * Creates a new user for the current domain. The user will be created - * without admin privileges. - * - * @param Zend_Gdata_Gapps $gapps The service object to use for communicating with the Google - * Apps server. - * @param boolean $html True if output should be formatted for display in a web browser. - * @param string $username The desired username for the user. - * @param string $givenName The given name for the user. - * @param string $familyName The family name for the user. - * @param string $password The plaintext password for the user. - * @return void - */ -function createUser($gapps, $html, $username, $givenName, $familyName, - $password) -{ - if ($html) {echo "

Create User

\n";} - $gapps->createUser($username, $givenName, $familyName, - $password); - if ($html) {echo "

Done.

\n";} -} - -/** - * Retrieves a user for the current domain by username. Information about - * that user is then output. - * - * @param Zend_Gdata_Gapps $gapps The service object to use for communicating with the Google Apps server. - * @param boolean $html True if output should be formatted for display in a web browser. - * @param string $username The desired username for the user. - * @return void - */ -function retrieveUser($gapps, $html, $username) -{ - if ($html) {echo "

User Information

\n";} - - $user = $gapps->retrieveUser($username); - - if ($html) {echo '

';} - - if ($user !== null) { - echo ' Username: ' . $user->login->username; - if ($html) {echo '
';} - echo "\n"; - - echo ' Given Name: '; - if ($html) { - echo htmlspecialchars($user->name->givenName); - } else { - echo $user->name->givenName; - } - if ($html) {echo '
';} - echo "\n"; - - echo ' Family Name: '; - if ($html) { - echo htmlspecialchars($user->name->familyName); - } else { - echo $user->name->familyName; - } - if ($html) {echo '
';} - echo "\n"; - - echo ' Suspended: ' . ($user->login->suspended ? 'Yes' : 'No'); - if ($html) {echo '
';} - echo "\n"; - - echo ' Admin: ' . ($user->login->admin ? 'Yes' : 'No'); - if ($html) {echo '
';} - echo "\n"; - - echo ' Must Change Password: ' . - ($user->login->changePasswordAtNextLogin ? 'Yes' : 'No'); - if ($html) {echo '
';} - echo "\n"; - - echo ' Has Agreed To Terms: ' . - ($user->login->agreedToTerms ? 'Yes' : 'No'); - - } else { - echo 'Error: Specified user not found.'; - } - if ($html) {echo '

';} - echo "\n"; -} - -/** - * Retrieves the list of users for the current domain and outputs - * that list. - * - * @param Zend_Gdata_Gapps $gapps The service object to use for communicating with the Google Apps server. - * @param boolean $html True if output should be formatted for display in a web browser. - * @return void - */ -function retrieveAllUsers($gapps, $html) -{ - if ($html) {echo "

Registered Users

\n";} - - $feed = $gapps->retrieveAllUsers(); - - if ($html) {echo "
    \n";} - - foreach ($feed as $user) { - if ($html) { - echo "
  • "; - } else { - echo " * "; - } - echo $user->login->username . ' ('; - if ($html) { - echo htmlspecialchars($user->name->givenName . ' ' . - $user->name->familyName); - } else { - echo $user->name->givenName . ' ' . $user->name->familyName; - } - echo ')'; - if ($html) {echo '
  • ';} - echo "\n"; - } - if ($html) {echo "
\n";} -} - -/** - * Change the name for an existing user. - * - * @param Zend_Gdata_Gapps $gapps The service object to use for communicating with the Google - * Apps server. - * @param boolean $html True if output should be formatted for display in a web browser. - * @param string $username The username which should be updated - * @param string $newGivenName The new given name for the user. - * @param string $newFamilyName The new family name for the user. - * @return void - */ -function updateUserName($gapps, $html, $username, $newGivenName, $newFamilyName) -{ - if ($html) {echo "

Update User Name

\n";} - - $user = $gapps->retrieveUser($username); - - if ($user !== null) { - $user->name->givenName = $newGivenName; - $user->name->familyName = $newFamilyName; - $user->save(); - } else { - if ($html) {echo '

';} - echo 'Error: Specified user not found.'; - if ($html) {echo '

';} - echo "\n"; - } - - if ($html) {echo "

Done.

\n";} -} - -/** - * Change the password for an existing user. - * - * @param Zend_Gdata_Gapps $gapps The service object to use for communicating with the Google - * Apps server. - * @param boolean $html True if output should be formatted for display in a web browser. - * @param string $username The username which should be updated - * @param string $newPassword The new password for the user. - * @return void - */ -function updateUserPassword($gapps, $html, $username, $newPassword) -{ - if ($html) {echo "

Update User Password

\n";} - - $user = $gapps->retrieveUser($username); - - if ($user !== null) { - $user->login->password = $newPassword; - $user->save(); - } else { - if ($html) {echo '

';} - echo 'Error: Specified user not found.'; - if ($html) {echo '

';} - echo "\n"; - } - - if ($html) {echo "

Done.

\n";} -} - -/** - * Suspend a given user. The user will not be able to login until restored. - * - * @param Zend_Gdata_Gapps $gapps The service object to use for communicating with the Google - * Apps server. - * @param boolean $html True if output should be formatted for display in a web browser. - * @param string $username The username which should be updated. - * @return void - */ -function suspendUser($gapps, $html, $username) -{ - if ($html) {echo "

Suspend User

\n";} - - $user = $gapps->retrieveUser($username); - - if ($user !== null) { - $user->login->suspended = true; - $user->save(); - } else { - if ($html) {echo '

';} - echo 'Error: Specified user not found.'; - if ($html) {echo '

';} - echo "\n"; - } - - if ($html) {echo "

Done.

\n";} -} - -/** - * Restore a given user after being suspended. - * - * @param Zend_Gdata_Gapps $gapps The service object to use for communicating with the Google - * Apps server. - * @param boolean $html True if output should be formatted for display in a web browser. - * @param string $username The username which should be updated. - * @return void - */ -function restoreUser($gapps, $html, $username) -{ - if ($html) {echo "

Restore User

\n";} - - $user = $gapps->retrieveUser($username); - - if ($user !== null) { - $user->login->suspended = false; - $user->save(); - } else { - if ($html) {echo '

';} - echo 'Error: Specified user not found.'; - if ($html) {echo '

';} - echo "\n"; - } - - if ($html) {echo "

Done.

\n";} -} - -/** - * Give a user admin rights. - * - * @param Zend_Gdata_Gapps $gapps The service object to use for communicating with the Google - * Apps server. - * @param boolean $html True if output should be formatted for display in a web browser. - * @param string $username The username which should be updated. - * @return void - */ -function giveUserAdminRights($gapps, $html, $username) -{ - if ($html) {echo "

Grant Administrative Rights

\n";} - - $user = $gapps->retrieveUser($username); - - if ($user !== null) { - $user->login->admin = true; - $user->save(); - } else { - if ($html) {echo '

';} - echo 'Error: Specified user not found.'; - if ($html) {echo '

';} - echo "\n"; - } - - if ($html) {echo "

Done.

\n";} -} - -/** - * Revoke a user's admin rights. - * - * @param Zend_Gdata_Gapps $gapps The service object to use for communicating with the Google - * Apps server. - * @param boolean $html True if output should be formatted for display in a web browser. - * @param string $username The username which should be updated. - * @return void - */ -function revokeUserAdminRights($gapps, $html, $username) -{ - if ($html) {echo "

Revoke Administrative Rights

\n";} - - $user = $gapps->retrieveUser($username); - - if ($user !== null) { - $user->login->admin = false; - $user->save(); - } else { - if ($html) {echo '

';} - echo 'Error: Specified user not found.'; - if ($html) {echo '

';} - echo "\n"; - } - - if ($html) {echo "

Done.

\n";} -} - -/** - * Force a user to change their password at next login. - * - * @param Zend_Gdata_Gapps $gapps The service object to use for communicating with the Google - * Apps server. - * @param boolean $html True if output should be formatted for display in a web browser. - * @param string $username The username which should be updated. - * @return void - */ -function setUserMustChangePassword($gapps, $html, $username) -{ - if ($html) {echo "

Force User To Change Password

\n";} - - $user = $gapps->retrieveUser($username); - - if ($user !== null) { - $user->login->changePasswordAtNextLogin = true; - $user->save(); - } else { - if ($html) {echo '

';} - echo 'Error: Specified user not found.'; - if ($html) {echo '

';} - echo "\n"; - } - - if ($html) {echo "

Done.

\n";} -} - -/** - * Undo forcing a user to change their password at next login. - * - * @param Zend_Gdata_Gapps $gapps The service object to use for communicating with the Google - * Apps server. - * @param boolean $html True if output should be formatted for display in a web browser. - * @param string $username The username which should be updated. - * @return void - */ -function clearUserMustChangePassword($gapps, $html, $username) -{ - if ($html) {echo "

Undo Force User To Change Password

\n";} - - $user = $gapps->retrieveUser($username); - - if ($user !== null) { - $user->login->changePasswordAtNextLogin = false; - $user->save(); - } else { - if ($html) {echo '

';} - echo 'Error: Specified user not found.'; - if ($html) {echo '

';} - echo "\n"; - } - - if ($html) {echo "

Done.

\n";} -} - -/** - * Delete the user who owns a given username. - * - * @param Zend_Gdata_Gapps $gapps The service object to use for communicating with the Google - * Apps server. - * @param boolean $html True if output should be formatted for display in a web browser. - * @param string $username The username which should be deleted. - * @return void - */ -function deleteUser($gapps, $html, $username) -{ - if ($html) {echo "

Delete User

\n";} - - $gapps->deleteUser($username); - - if ($html) {echo "

Done.

\n";} -} - -/** - * Create a new nickname. - * - * @param Zend_Gdata_Gapps $gapps The service object to use for communicating with the Google - * Apps server. - * @param boolean $html True if output should be formatted for display in a web browser. - * @param string $username The username to which the nickname should be assigned. - * @param string $nickname The name of the nickname to be created. - * @return void - */ -function createNickname($gapps, $html, $username, $nickname) -{ - if ($html) {echo "

Create Nickname

\n";} - - $gapps->createNickname($username, $nickname); - - if ($html) {echo "

Done.

\n";} -} - -/** - * Retrieve a specified nickname and output its ownership information. - * - * @param Zend_Gdata_Gapps $gapps The service object to use for communicating with the Google - * Apps server. - * @param boolean $html True if output should be formatted for display in a web browser. - * @param string $nickname The name of the nickname to be retrieved. - * @return void - */ -function retrieveNickname($gapps, $html, $nickname) -{ - if ($html) {echo "

Nickname Information

\n";} - - $nickname = $gapps->retrieveNickname($nickname); - - if ($html) {echo '

';} - - if ($nickname !== null) { - echo ' Nickname: ' . $nickname->nickname->name; - if ($html) {echo '
';} - echo "\n"; - - echo ' Owner: ' . $nickname->login->username; - } else { - echo 'Error: Specified nickname not found.'; - } - if ($html) {echo '

';} - echo "\n"; -} - -/** - * Outputs all nicknames owned by a specific username. - * - * @param Zend_Gdata_Gapps $gapps The service object to use for communicating with the Google - * Apps server. - * @param boolean $html True if output should be formatted for display in a web browser. - * @param string $username The username whose nicknames should be displayed. - * @return void - */ -function retrieveNicknames($gapps, $html, $username) -{ - if ($html) {echo "

Registered Nicknames For {$username}

\n";} - - $feed = $gapps->retrieveNicknames($username); - - if ($html) {echo "
    \n";} - - foreach ($feed as $nickname) { - if ($html) { - echo "
  • "; - } else { - echo " * "; - } - echo $nickname->nickname->name; - if ($html) {echo '
  • ';} - echo "\n"; - } - if ($html) {echo "
\n";} -} - - -/** - * Retrieves the list of nicknames for the current domain and outputs - * that list. - * - * @param Zend_Gdata_Gapps $gapps The service object to use for communicating with the Google - * Apps server. - * @param boolean $html True if output should be formatted for display in a web browser. - * @return void - */ -function retrieveAllNicknames($gapps, $html) -{ - if ($html) {echo "

Registered Nicknames

\n";} - - $feed = $gapps->retrieveAllNicknames(); - - if ($html) {echo "
    \n";} - - foreach ($feed as $nickname) { - if ($html) { - echo "
  • "; - } else { - echo " * "; - } - echo $nickname->nickname->name . ' => ' . $nickname->login->username; - if ($html) {echo '
  • ';} - echo "\n"; - } - if ($html) {echo "
\n";} -} - -/** - * Delete's a specific nickname from the current domain. - * - * @param Zend_Gdata_Gapps $gapps The service object to use for communicating with the Google - * Apps server. - * @param boolean $html True if output should be formatted for display in a web browser. - * @param string $nickname The nickname that should be deleted. - * @return void - */ -function deleteNickname($gapps, $html, $nickname) -{ - if ($html) {echo "

Delete Nickname

\n";} - - $gapps->deleteNickname($nickname); - - if ($html) {echo "

Done.

\n";} - -} - -/** - * Create a new email list. - * - * @param Zend_Gdata_Gapps $gapps The service object to use for communicating with the Google - * Apps server. - * @param boolean $html True if output should be formatted for display in a web browser. - * @param string $emailList The name of the email list to be created. - * @return void - */ -function createEmailList($gapps, $html, $emailList) -{ - if ($html) {echo "

Create Email List

\n";} - - $gapps->createEmailList($emailList); - - if ($html) {echo "

Done.

\n";} -} - -/** - * Outputs the list of email lists to which the specified address is - * subscribed. - * - * @param Zend_Gdata_Gapps $gapps The service object to use for communicating with the Google - * Apps server. - * @param boolean $html True if output should be formatted for display in a web browser. - * @param string $recipient The email address of the recipient whose subscriptions should - * be retrieved. Only a username is required if the recipient is a - * member of the current domain. - * @return void - */ -function retrieveEmailLists($gapps, $html, $recipient) -{ - if ($html) {echo "

Email List Subscriptions For {$recipient}

\n";} - - $feed = $gapps->retrieveEmailLists($recipient); - - if ($html) {echo "
    \n";} - - foreach ($feed as $list) { - if ($html) { - echo "
  • "; - } else { - echo " * "; - } - echo $list->emailList->name; - if ($html) {echo '
  • ';} - echo "\n"; - } - if ($html) {echo "
\n";} -} - -/** - * Outputs the list of all email lists on the current domain. - * - * @param Zend_Gdata_Gapps $gapps The service object to use for communicating with the Google - * Apps server. - * @param boolean $html True if output should be formatted for display in a web browser. - * @return void - */ -function retrieveAllEmailLists($gapps, $html) -{ - if ($html) {echo "

Registered Email Lists

\n";} - - $feed = $gapps->retrieveAllEmailLists(); - - if ($html) {echo "
    \n";} - - foreach ($feed as $list) { - if ($html) { - echo "
  • "; - } else { - echo " * "; - } - echo $list->emailList->name; - if ($html) {echo '
  • ';} - echo "\n"; - } - if ($html) {echo "
\n";} -} - -/** - * Delete's a specific email list from the current domain. - * - * @param Zend_Gdata_Gapps $gapps The service object to use for communicating with the Google - * Apps server. - * @param boolean $html True if output should be formatted for display in a web browser. - * @param string $emailList The email list that should be deleted. - * @return void - */ -function deleteEmailList($gapps, $html, $emailList) -{ - if ($html) {echo "

Delete Email List

\n";} - - $gapps->deleteEmailList($emailList); - - if ($html) {echo "

Done.

\n";} -} - -/** - * Add a recipient to an existing email list. - * - * @param Zend_Gdata_Gapps $gapps The service object to use for communicating with the - * Google Apps server. - * @param boolean $html True if output should be formatted for display in a - * web browser. - * @param string $recipientAddress The address of the recipient who should be added. - * @param string $emailList The name of the email address the recipient be added to. - * @return void - */ -function addRecipientToEmailList($gapps, $html, $recipientAddress, - $emailList) -{ - if ($html) {echo "

Subscribe Recipient

\n";} - - $gapps->addRecipientToEmailList($recipientAddress, $emailList); - - if ($html) {echo "

Done.

\n";} -} - -/** - * Outputs the list of all recipients for a given email list. - * - * @param Zend_Gdata_Gapps $gapps The service object to use for communicating with the Google - * Apps server. - * @param boolean $html True if output should be formatted for display in a web browser. - * @param string $emailList The email list whose recipients should be output. - * @return void - */ -function retrieveAllRecipients($gapps, $html, $emailList) -{ - if ($html) {echo "

Email List Recipients For {$emailList}

\n";} - - $feed = $gapps->retrieveAllRecipients($emailList); - - if ($html) {echo "
    \n";} - - foreach ($feed as $recipient) { - if ($html) { - echo "
  • "; - } else { - echo " * "; - } - echo $recipient->who->email; - if ($html) {echo '
  • ';} - echo "\n"; - } - if ($html) {echo "
\n";} -} - -/** - * Remove an existing recipient from an email list. - * - * @param Zend_Gdata_Gapps $gapps The service object to use for communicating with the - * Google Apps server. - * @param boolean $html True if output should be formatted for display in a - * web browser. - * @param string $recipientAddress The address of the recipient who should be removed. - * @param string $emailList The email list from which the recipient should be removed. - * @return void - */ -function removeRecipientFromEmailList($gapps, $html, $recipientAddress, - $emailList) -{ - if ($html) {echo "

Unsubscribe Recipient

\n";} - - $gapps->removeRecipientFromEmailList($recipientAddress, $emailList); - - if ($html) {echo "

Done.

\n";} - -} - -// ************************ BEGIN CLI SPECIFIC CODE ************************ - -/** - * Display list of valid commands. - * - * @param string $executable The name of the current script. This is usually available as $argv[0]. - * @return void - */ -function displayHelp($executable) -{ - echo "Usage: php {$executable} [] [] " . - "[ ...]\n\n"; - echo "Possible action values include:\n" . - "createUser\n" . - "retrieveUser\n" . - "retrieveAllUsers\n" . - "updateUserName\n" . - "updateUserPassword\n" . - "suspendUser\n" . - "restoreUser\n" . - "giveUserAdminRights\n" . - "revokeUserAdminRights\n" . - "setUserMustChangePassword\n" . - "clearUserMustChangePassword\n" . - "deleteUser\n" . - "createNickname\n" . - "retrieveNickname\n" . - "retrieveNicknames\n" . - "retrieveAllNicknames\n" . - "deleteNickname\n" . - "createEmailList\n" . - "retrieveEmailLists\n" . - "retrieveAllEmailLists\n" . - "deleteEmailList\n" . - "addRecipientToEmailList\n" . - "retrieveAllRecipients\n" . - "removeRecipientFromEmailList\n"; -} - -/** - * Parse command line arguments and execute appropriate function when - * running from the command line. - * - * If no arguments are provided, usage information will be provided. - * - * @param array $argv The array of command line arguments provided by PHP. - * $argv[0] should be the current executable name or '-' if not available. - * @param integer $argc The size of $argv. - * @return void - */ -function runCLIVersion($argv, $argc) -{ - if (isset($argc) && $argc >= 2) { - # Prepare a server connection - if ($argc >= 5) { - try { - $client = getClientLoginHttpClient($argv[2] . '@' . $argv[3], $argv[4]); - $gapps = new Zend_Gdata_Gapps($client, $argv[3]); - } catch (Zend_Gdata_App_AuthException $e) { - echo "Error: Unable to authenticate. Please check your credentials.\n"; - exit(1); - } - } - - # Dispatch arguments to the desired method - switch ($argv[1]) { - case 'createUser': - if ($argc == 9) { - createUser($gapps, false, $argv[5], $argv[6], $argv[7], $argv[8]); - } else { - echo "Usage: php {$argv[0]} {$argv[1]} " . - " \n\n"; - echo "This creates a new user with the given username.\n"; - echo "EXAMPLE: php {$argv[0]} {$argv[1]} " . - "jdoe John Doe p4ssw0rd\n"; - } - break; - case 'retrieveUser': - if ($argc == 6) { - retrieveUser($gapps, false, $argv[5]); - } else { - echo "Usage: php {$argv[0]} {$argv[1]} " . - "\n\n"; - echo "This retrieves the user with the specified " . - "username and displays information about that user.\n"; - echo "EXAMPLE: php {$argv[0]} {$argv[1]} " . - "jdoe\n"; - } - break; - case 'retrieveAllUsers': - if ($argc == 5) { - retrieveAllUsers($gapps, false); - } else { - echo "Usage: php {$argv[0]} {$argv[1]} " . - "\n\n"; - echo "This lists all users on the current domain.\n"; - echo "EXAMPLE: php {$argv[0]} {$argv[1]} \n"; - } - break; - case 'updateUserName': - if ($argc == 8) { - updateUserName($gapps, false, $argv[5], $argv[6], $argv[7]); - } else { - echo "Usage: php {$argv[0]} {$argv[1]} " . - " \n\n"; - echo "Renames an existing user.\n"; - echo "EXAMPLE: php {$argv[0]} {$argv[1]} " . - "jdoe Jane Doe\n"; - } - break; - case 'updateUserPassword': - if ($argc == 7) { - updateUserPassword($gapps, false, $argv[5], $argv[6]); - } else { - echo "Usage: php {$argv[0]} {$argv[1]} " . - " \n\n"; - echo "Changes the password for an existing user.\n"; - echo "EXAMPLE: php {$argv[0]} {$argv[1]} " . - "jdoe password1\n"; - } - break; - case 'suspendUser': - if ($argc == 6) { - suspendUser($gapps, false, $argv[5]); - } else { - echo "Usage: php {$argv[0]} {$argv[1]} " . - "\n\n"; - echo "This suspends the given user.\n"; - echo "EXAMPLE: php {$argv[0]} {$argv[1]} " . - "jdoe\n"; - } - break; - case 'restoreUser': - if ($argc == 6) { - restoreUser($gapps, false, $argv[5]); - } else { - echo "Usage: php {$argv[0]} {$argv[1]} " . - "\n\n"; - echo "This restores the given user after being suspended.\n"; - echo "EXAMPLE: php {$argv[0]} {$argv[1]} " . - "jdoe\n"; - } - break; - case 'giveUserAdminRights': - if ($argc == 6) { - giveUserAdminRights($gapps, false, $argv[5]); - } else { - echo "Usage: php {$argv[0]} {$argv[1]} " . - "\n\n"; - echo "Give a user admin rights for this domain.\n"; - echo "EXAMPLE: php {$argv[0]} {$argv[1]} " . - "jdoe\n"; - } - break; - case 'revokeUserAdminRights': - if ($argc == 6) { - revokeUserAdminRights($gapps, false, $argv[5]); - } else { - echo "Usage: php {$argv[0]} {$argv[1]} " . - "\n\n"; - echo "Remove a user's admin rights for this domain.\n"; - echo "EXAMPLE: php {$argv[0]} {$argv[1]} " . - "jdoe\n"; - } - break; - case 'setUserMustChangePassword': - if ($argc == 6) { - setUserMustChangePassword($gapps, false, $argv[5]); - } else { - echo "Usage: php {$argv[0]} {$argv[1]} " . - "\n\n"; - echo "Force a user to change their password at next login.\n"; - echo "EXAMPLE: php {$argv[0]} {$argv[1]} " . - "jdoe\n"; - } - break; - case 'clearUserMustChangePassword': - if ($argc == 6) { - clearUserMustChangePassword($gapps, false, $argv[5]); - } else { - echo "Usage: php {$argv[0]} {$argv[1]} " . - "\n\n"; - echo "Clear the flag indicating that a user must change " . - "their password at next login.\n"; - echo "EXAMPLE: php {$argv[0]} {$argv[1]} " . - "jdoe\n"; - } - break; - case 'deleteUser': - if ($argc == 6) { - deleteUser($gapps, false, $argv[5]); - } else { - echo "Usage: php {$argv[0]} {$argv[1]} " . - "\n\n"; - echo "Delete the user who owns a given username.\n"; - echo "EXAMPLE: php {$argv[0]} {$argv[1]} " . - "jdoe\n"; - } - break; - case 'createNickname': - if ($argc == 7) { - createNickname($gapps, false, $argv[5], $argv[6]); - } else { - echo "Usage: php {$argv[0]} {$argv[1]} " . - " \n\n"; - echo "Create a new nickname for the specified user.\n"; - echo "EXAMPLE: php {$argv[0]} {$argv[1]} " . - "jdoe johnny\n"; - } - break; - case 'retrieveNickname': - if ($argc == 6) { - retrieveNickname($gapps, false, $argv[5]); - } else { - echo "Usage: php {$argv[0]} {$argv[1]} " . - "\n\n"; - echo "Retrieve a nickname and display its ownership " . - "information.\n"; - echo "EXAMPLE: php {$argv[0]} {$argv[1]} " . - "johnny\n"; - } - break; - case 'retrieveNicknames': - if ($argc == 6) { - retrieveNicknames($gapps, false, $argv[5]); - } else { - echo "Usage: php {$argv[0]} {$argv[1]} " . - "\n\n"; - echo "Output all nicknames owned by a specific username.\n"; - echo "EXAMPLE: php {$argv[0]} {$argv[1]} " . - "jdoe\n"; - } - break; - case 'retrieveAllNicknames': - if ($argc == 5) { - retrieveAllNicknames($gapps, false); - } else { - echo "Usage: php {$argv[0]} {$argv[1]} " . - "\n\n"; - echo "Output all registered nicknames on the system.\n"; - echo "EXAMPLE: php {$argv[0]} {$argv[1]} " . - "\n"; - } - break; - case 'deleteNickname': - if ($argc == 6) { - deleteNickname($gapps, false, $argv[5]); - } else { - echo "Usage: php {$argv[0]} {$argv[1]} " . - "\n\n"; - echo "Delete a specific nickname.\n"; - echo "EXAMPLE: php {$argv[0]} {$argv[1]} " . - "johnny\n"; - } - break; - case 'createEmailList': - if ($argc == 6) { - createEmailList($gapps, false, $argv[5]); - } else { - echo "Usage: php {$argv[0]} {$argv[1]} " . - "\n\n"; - echo "Create a new email list with the specified name.\n"; - echo "EXAMPLE: php {$argv[0]} {$argv[1]} " . - "friends\n"; - } - break; - case 'retrieveEmailLists': - if ($argc == 6) { - retrieveEmailLists($gapps, false, $argv[5]); - } else { - echo "Usage: php {$argv[0]} {$argv[1]} " . - "\n\n"; - echo "Retrieve all email lists to which the specified " . - "address is subscribed.\n"; - echo "EXAMPLE: php {$argv[0]} {$argv[1]} " . - "johnny@somewhere.com.invalid\n"; - } - break; - case 'retrieveAllEmailLists': - if ($argc == 5) { - retrieveAllEmailLists($gapps, false); - } else { - echo "Usage: php {$argv[0]} {$argv[1]} " . - "\n\n"; - echo "Retrieve a list of all email lists on the current " . - "domain.\n"; - echo "EXAMPLE: php {$argv[0]} {$argv[1]} " . - "\n"; - } - break; - case 'deleteEmailList': - if ($argc == 6) { - deleteEmailList($gapps, false, $argv[5]); - } else { - echo "Usage: php {$argv[0]} {$argv[1]} " . - "\n\n"; - echo "Delete a specified email list.\n"; - echo "EXAMPLE: php {$argv[0]} {$argv[1]} " . - "friends\n"; - } - break; - case 'addRecipientToEmailList': - if ($argc == 7) { - addRecipientToEmailList($gapps, false, $argv[5], $argv[6]); - } else { - echo "Usage: php {$argv[0]} {$argv[1]} " . - " \n\n"; - echo "Add a recipient to an existing email list.\n"; - echo "EXAMPLE: php {$argv[0]} {$argv[1]} " . - "johnny@somewhere.com.invalid friends\n"; - } - break; - case 'retrieveAllRecipients': - if ($argc == 6) { - retrieveAllRecipients($gapps, false, $argv[5]); - } else { - echo "Usage: php {$argv[0]} {$argv[1]} " . - "\n\n"; - echo "Retrieve all recipients for an existing email list.\n"; - echo "EXAMPLE: php {$argv[0]} {$argv[1]} " . - "friends\n"; - } - break; - case 'removeRecipientFromEmailList': - if ($argc == 7) { - removeRecipientFromEmailList($gapps, false, $argv[5], $argv[6]); - } else { - echo "Usage: php {$argv[0]} {$argv[1]} " . - " \n\n"; - echo "Remove an existing recipient from an email list.\n"; - echo "EXAMPLE: php {$argv[0]} {$argv[1]} " . - "johnny@somewhere.com.invalid friends\n"; - } - break; - default: - // Invalid action entered - displayHelp($argv[0]); - // End switch block - } - } else { - // action left unspecified - displayHelp($argv[0]); - } -} - -// ************************ BEGIN WWW SPECIFIC CODE ************************ - -/** - * Writes the HTML prologue for this app. - * - * NOTE: We would normally keep the HTML/CSS markup separate from the business - * logic above, but have decided to include it here for simplicity of - * having a single-file sample. - * - * - * @param boolean $displayMenu (optional) If set to true, a navigation - * menu is displayed at the top of the page. Default is true. - * @return void - */ -function startHTML($displayMenu = true) -{ -?> - - - - - - - Google Apps Provisioning API Demo - - - - - - - - - -
-← Back'; - } -?> -
- - - -
-

Almost there...

-

Before using this demo, you must set an application password - to protect your account. You will also need to set your - Google Apps credentials in order to communicate with the Google - Apps servers.

-

To continue, open this file in a text editor and fill - out the information in the configuration section.

-
- -
-

Google Apps Authentication Failed

-

Authentication with the Google Apps servers failed.

-

Please open this file in a text editor and make - sure your credentials are correct.

-
- -
-

Authentication Required

- ' . $errorText . "\n"; - } - ?> -

Please enter your login password to continue.

-

-

-

Notice: This application is for demonstration - purposes only. Not for use in a production environment.

-

-
- -

Main Menu

- -

Welcome to the Google Apps Provisioning API demo page. Please select - from one of the following three options to see a list of commands.

- - - -

Tip: You can also run this demo from the command line if your system - has PHP CLI support enabled.

- -

User Maintenance Menu

- -
-

Create User

-

Create a new user with the given properties.

-

- - -
- -
- -
- - -

- -

-
-
-

Retrieve User

-

Retrieve the information for an existing user.

-

- - -
-

- -

-
-
-

Retrieve All Users

-

Retrieve the list of all users on the current domain.

-

- -

- -

-
-
-

Update Name

-

Update the name for an existing user.

-

- - -
- -
- -
-

- -

-
-
-

Update Password

-

Update the password for an existing user.

-

- - -
- -

-

- -

-
-
-

Suspend/Restore User

-

Mark an existing user as suspended or restore a suspended user. - While suspended, the user will be prohibited from logging into - this domain.

-

- - - -

-
- User may log into - this domain.
- User - may not log into this domain. -
- -

-
-
-

Issue/Revoke Admin Rights

-

Set whether an existing user has administrative rights for the current - domain.

-

- - - -

-
- User - may administer this domain.
- User - may not administer this domain. -
- -

-
-
-

Force User To Change Password

-

Set whether an existing user must change their password at - their next login.

-

- - - -

-
- User is required to - change their password at next login.
- User is - not required to change their password at next - login. -
- -

-
-
-

Delete User

-

Delete an existing user on the current domain.

-

- - -
-

- -

-
- -

Nickname Maintenance Menu

- -
-

Create Nickname

-

Create a nickname for an existing user.

-

- - -
- -
-

- -

-
-
-

Retrieve Nickname

-

Retrieve the information for an existing nickname.

-

- - -
-

- -

-
-
-

Retrieve Nicknames

-

Retrieve the nicknames associated with an existing username.

-

- - -
-

- -

-
-
-

Retrieve All Nicknames

-

Retrieve the nicknames on the current domain.

-

- -

- -

-
-
-

Delete Nickname

-

Delete an existing nickname from the current domain.

-

- - -
-

- -

-
- -

Email List Maintenance Menu

- -
-

Create Email List

-

Create a new email list for the current domain.

-

- - -
-

- -

-
-
-

Retrieve Email Lists

-

Retrieve all email lists to which a given email address is - subscribed.

-

- - -
-

- -

-
-
-

Retrieve All Email Lists

-

Retrieve all email lists on the current domain.

-

- -

- -

-
-
-

Delete Email List

-

Delete an existing email list from the current domain.

-

- - -
-

- -

-
-
-

Add Recipient To Email List

-

Add or remove a recipient from an existing email list. A complete - email address is required for recipients outside the current - domain.

-

- - -
- -
-

- Subscribe - recipient.
- Unsubscribe recipient. -
-

- -

-
-
-

Retrieve All Recipients

-

Retrieve all recipients subscribed to an existing email list.

-

- - -
-

- -

-
- -

Logout

- -

Logout successful.

- - -Invalid mode.\n"; - echo "

Please check your request and try again.

"; - endHTML(true); - } - case 'setUserAdmin': - if ($_POST['mode'] == 'issue') { - startHTML(); - giveUserAdminRights($gapps, true, $_POST['user']); - endHTML(true); - } elseif ($_POST['mode'] == 'revoke') { - startHTML(); - revokeUserAdminRights($gapps, true, $_POST['user']); - endHTML(true); - } else { - header('HTTP/1.1 400 Bad Request'); - startHTML(); - echo "

Invalid mode.

\n"; - echo "

Please check your request and try again.

"; - endHTML(true); - } - case 'setForceChangePassword': - if ($_POST['mode'] == 'set') { - startHTML(); - setUserMustChangePassword($gapps, true, $_POST['user']); - endHTML(true); - } elseif ($_POST['mode'] == 'clear') { - startHTML(); - clearUserMustChangePassword($gapps, true, $_POST['user']); - endHTML(true); - } else { - header('HTTP/1.1 400 Bad Request'); - startHTML(); - echo "

Invalid mode.

\n"; - echo "

Please check your request and try again.

"; - endHTML(true); - } - case 'deleteUser': - startHTML(); - deleteUser($gapps, true, $_POST['user']); - endHTML(true); - case 'createNickname': - startHTML(); - createNickname($gapps, true, $_POST['user'], - $_POST['nickname']); - endHTML(true); - case 'deleteNickname': - startHTML(); - deleteNickname($gapps, true, $_POST['nickname']); - endHTML(true); - case 'createEmailList': - startHTML(); - createEmailList($gapps, true, $_POST['emailList']); - endHTML(true); - case 'deleteEmailList': - startHTML(); - deleteEmailList($gapps, true, $_POST['emailList']); - endHTML(true); - case 'modifySubscription': - if ($_POST['mode'] == 'subscribe') { - startHTML(); - addRecipientToEmailList($gapps, true, $_POST['recipient'], - $_POST['emailList']); - endHTML(true); - } elseif ($_POST['mode'] == 'unsubscribe') { - startHTML(); - removeRecipientFromEmailList($gapps, true, - $_POST['recipient'], $_POST['emailList']); - endHTML(true); - } else { - header('HTTP/1.1 400 Bad Request'); - startHTML(); - echo "

Invalid mode.

\n"; - echo "

Please check your request and try again.

"; - endHTML(true); - } - } - } - - // Check for an invalid command. If so, display an error and exit. - if (!empty($_REQUEST['command'])) { - header('HTTP/1.1 400 Bad Request'); - startHTML(); - echo "

Invalid command.

\n"; - echo "

Please check your request and try again.

"; - endHTML(true); - } - - // If a menu parameter is available, display a submenu. - if (!empty($_REQUEST['menu'])) { - switch ($_REQUEST['menu']) { - case 'user': - startHTML(); - displayUserMenu(); - endHTML(); - case 'nickname': - startHTML(); - displayNicknameMenu(); - endHTML(); - case 'emailList': - startHTML(); - displayEmailListMenu(); - endHTML(); - case 'logout': - startHTML(false); - logout(); - endHTML(); - default: - header('HTTP/1.1 400 Bad Request'); - startHTML(); - echo "

Invalid menu selection.

\n"; - echo "

Please check your request and try again.

"; - endHTML(true); - } - } - - // If we get this far, that means there's nothing to do. Display - // the main menu. - // If no command was issued and no menu was selected, display the - // main menu. - startHTML(); - displayMenu(); - endHTML(); -} - -// ************************** PROGRAM ENTRY POINT ************************** - -if (!isset($_SERVER["HTTP_HOST"])) { - // running through command line - runCLIVersion($argv, $argc); -} else { - // running through web server - try { - runWWWVersion(); - } catch (Zend_Gdata_Gapps_ServiceException $e) { - // Try to recover gracefully from a service exception. - // The HTML prologue will have already been sent. - echo "

Service Error Encountered

\n"; - echo "
" . htmlspecialchars($e->__toString()) . "
"; - endHTML(true); - } -} diff --git a/demos/Zend/Gdata/InstallationChecker.php b/demos/Zend/Gdata/InstallationChecker.php deleted file mode 100644 index ab975a2b9ee..00000000000 --- a/demos/Zend/Gdata/InstallationChecker.php +++ /dev/null @@ -1,386 +0,0 @@ - array( - 'tested' => false, 'errors' => null), - self::ZEND_GDATA_INSTALL_ERRORS => array( - 'tested' => false, 'errors' => null), - self::SSL_CAPABILITIES_ERRORS => array( - 'tested' => false, 'errors' => null), - self::YOUTUBE_API_CONNECTIVITY_ERRORS => array( - 'tested' => false, 'errors' => null) - ); - - private $_sapiModeCLI = null; - - /** - * Create a new InstallationChecker object and run verifications. - * @return void - */ - public function __construct() - { - $this->determineIfInCLIMode(); - $this->runAllVerifications(); - $this->outputResults(); - } - - /** - * Set the sapiModeCLI variable to true if we are running CLI mode. - * - * @return void - */ - private function determineIfInCLIMode() - { - if (php_sapi_name() == 'cli') { - $this->_sapiModeCLI = true; - } - } - - /** - * Getter for sapiModeCLI variable. - * - * @return boolean True if we are running in CLI mode. - */ - public function runningInCLIMode() - { - if ($this->_sapiModeCLI) { - return true; - } else { - return false; - } - } - - /** - * Run verifications, stopping at each step if there is a failure. - * - * @return void - */ - public function runAllVerifications() - { - if (!$this->validatePHPExtensions()) { - return; - } - if (!$this->validateZendFrameworkInstallation()) { - return; - } - if (!$this->testSSLCapabilities()) { - return; - } - if (!$this->validateYouTubeAPIConnectivity()) { - return; - } - } - - /** - * Validate that the required PHP Extensions are installed and available. - * - * @return boolean False if there were errors. - */ - private function validatePHPExtensions() - { - $phpExtensionErrors = array(); - foreach (self::$REQUIRED_EXTENSIONS as $requiredExtension) { - if (!extension_loaded($requiredExtension)) { - $requiredExtensionError = $requiredExtension . - ' extension missing'; - $documentationLink = null; - if ($requiredExtension != 'standard') { - $documentationLink = self::PHP_MANUAL_LINK_FRAGMENT . - $requiredExtension . '.php'; - $documentationLink = - $this->checkAndAddHTMLLink($documentationLink); - } else { - $documentationLink = self::PHP_MANUAL_LINK_FRAGMENT . - 'spl.php'; - $documentationLink = - $this->checkAndAddHTMLLink($documentationLink); - } - - if ($documentationLink) { - $phpExtensionErrors[] = $requiredExtensionError . - ' - refer to ' . $documentationLink; - } - } - } - $this->_allErrors[self::PHP_EXTENSION_ERRORS]['tested'] = true; - if (count($phpExtensionErrors) > 0) { - $this->_allErrors[self::PHP_EXTENSION_ERRORS]['errors'] = - $phpExtensionErrors; - return false; - } - return true; - } - - /** - * Validate that the Gdata component of Zend Framework is installed - * properly. Also checks that the required YouTube API helper methods are - * found. - * - * @return boolean False if there were errors. - */ - private function validateZendFrameworkInstallation() - { - $zendFrameworkInstallationErrors = array(); - $zendLoaderPresent = false; - try { - $zendLoaderPresent = @fopen('Zend/Loader.php', 'r', true); - } catch (Exception $e) { - $zendFrameworkInstallationErrors[] = 'Exception thrown trying to ' . - 'access Zend/Loader.php using \'use_include_path\' = true ' . - 'Make sure you include the Zend Framework in your ' . - 'include_path which currently contains: "' . - ini_get('include_path') . '"'; - } - - if ($zendLoaderPresent) { - @fclose($zendLoaderPresent); - require_once('Zend/Loader.php'); - require_once('Zend/Version.php'); - Zend_Loader::loadClass('Zend_Gdata_YouTube'); - Zend_Loader::loadClass('Zend_Gdata_YouTube_VideoEntry'); - $yt = new Zend_Gdata_YouTube(); - $videoEntry = $yt->newVideoEntry(); - if (!method_exists($videoEntry, 'setVideoTitle')) { - $zendFrameworkMessage = 'Your version of the ' . - 'Zend Framework ' . Zend_Version::VERSION . ' is too old' . - ' to run the YouTube demo application and does not' . - ' contain the new helper methods. Please check out a' . - ' newer version from Zend\'s repository: ' . - checkAndAddHTMLLink(self::ZEND_SUBVERSION_URI); - $zendFrameworkInstallationErrors[] = $zendFrameworkMessage; - } - } else { - if (count($zendFrameworkInstallationErrors) < 1) { - $zendFrameworkInstallationErrors[] = 'Exception thrown trying' . - ' to access Zend/Loader.php using \'use_include_path\' =' . - ' true. Make sure you include Zend Framework in your' . - ' include_path which currently contains: ' . - ini_get('include_path'); - } - } - - $this->_allErrors[self::ZEND_GDATA_INSTALL_ERRORS]['tested'] = true; - - if (count($zendFrameworkInstallationErrors) > 0) { - $this->_allErrors[self::ZEND_GDATA_INSTALL_ERRORS]['errors'] = - $zendFrameworkInstallationErrors; - return false; - } - return true; - } - - /** - * Create HTML link from an input string if not in CLI mode. - * - * @param string The error message to be converted to a link. - * @return string Either the original error message or an HTML version. - */ - private function checkAndAddHTMLLink($inputString) { - if (!$this->runningInCLIMode()) { - return $this->makeHTMLLink($inputString); - } else { - return $inputString; - } - } - - /** - * Create an HTML link from a string. - * - * @param string The string to be made into link text and anchor target. - * @return string HTML link. - */ - private function makeHTMLLink($inputString) - { - return '' . - $inputString . ''; - } - - /** - * Validate that SSL Capabilities are available. - * - * @return boolean False if there were errors. - */ - private function testSSLCapabilities() - { - $sslCapabilitiesErrors = array(); - require_once 'Zend/Loader.php'; - Zend_Loader::loadClass('Zend_Http_Client'); - - $httpClient = new Zend_Http_Client( - 'https://www.google.com/accounts/AuthSubRequest'); - $response = $httpClient->request(); - $this->_allErrors[self::SSL_CAPABILITIES_ERRORS]['tested'] = true; - - if ($response->isError()) { - $sslCapabilitiesErrors[] = 'Response from trying to access' . - ' \'https://www.google.com/accounts/AuthSubRequest\' ' . - $response->getStatus() . ' - ' . $response->getMessage(); - } - - if (count($sslCapabilitiesErrors) > 0) { - $this->_allErrors[self::SSL_CAPABILITIES_ERRORS]['errors'] = - $sslCapabilitiesErrors; - return false; - } - return true; - } - - /** - * Validate that we can connect to the YouTube API. - * - * @return boolean False if there were errors. - */ - private function validateYouTubeAPIConnectivity() - { - $connectivityErrors = array(); - require_once 'Zend/Loader.php'; - Zend_Loader::loadClass('Zend_Gdata_YouTube'); - $yt = new Zend_Gdata_YouTube(); - $topRatedFeed = $yt->getTopRatedVideoFeed(); - if ($topRatedFeed instanceof Zend_Gdata_YouTube_VideoFeed) { - if ($topRatedFeed->getTotalResults()->getText() < 1) { - $connectivityErrors[] = 'There was less than 1 video entry' . - ' in the \'Top Rated Video Feed\''; - } - } else { - $connectivityErrors[] = 'The call to \'getTopRatedVideoFeed()\' ' . - 'did not result in a Zend_Gdata_YouTube_VideoFeed object'; - } - - $this->_allErrors[self::YOUTUBE_API_CONNECTIVITY_ERRORS]['tested'] = - true; - if (count($connectivityErrors) > 0) { - $this->_allErrors[self::YOUTUBE_API_CONNECTIVITY_ERRORS]['tested'] = - $connectivityErrors; - return false; - } - return true; - } - - /** - * Dispatch a call to outputResultsInHTML or outputResultsInText pending - * the current SAPI mode. - * - * @return void - */ - public function outputResults() - { - if ($this->_sapiModeCLI) { - print $this->getResultsInText(); - } else { - print $this->getResultsInHTML(); - } - } - - - /** - * Return a string representing the results of the verifications. - * - * @return string A string representing the results. - */ - private function getResultsInText() - { - $output = "== Ran PHP Installation Checker using CLI ==\n"; - - $error_count = 0; - foreach($this->_allErrors as $key => $value) { - $output .= $key . ' -- '; - if (($value['tested'] == true) && (count($value['errors']) == 0)) { - $output .= "No errors found\n"; - } elseif ($value['tested'] == true) { - $output .= "Tested\n"; - $error_count = 0; - foreach ($value['errors'] as $error) { - $output .= "Error number: " . $error_count . "\n--" . - $error . "\n"; - } - } else { - $output .= "Not tested\n"; - } - $error_count++; - } - return $output; - } - - /** - * Return an HTML table representing the results of the verifications. - * - * @return string An HTML string representing the results. - */ - private function getResultsInHTML() - { - $html = "\n". - "\nPHP Installation Checker\n" . - "\n" . - "\n" . - "\n"; - - $error_count = 0; - foreach($this->_allErrors as $key => $value) { - $html .= ""; - if (($value['tested'] == true) && (count($value['errors']) == 0)) { - $html .= "\n" . - "\n"; - } elseif ($value['tested'] == true) { - $html .= "\n"; - $error_count = 0; - foreach ($value['errors'] as $error) { - $html .= "" . - "\n"; - } - } else { - $html .= "\n"; - } - $error_count++; - } - $html .= ""; - return $html; - } -} - -$installationChecker = new InstallationChecker(); diff --git a/demos/Zend/Gdata/MyLibrary/demo.php b/demos/Zend/Gdata/MyLibrary/demo.php deleted file mode 100755 index 33045c59a2e..00000000000 --- a/demos/Zend/Gdata/MyLibrary/demo.php +++ /dev/null @@ -1,226 +0,0 @@ -getMessage() ."\nCredentials provided were ". - "email: [$email] and password [$password].\n"); - } - $this->gdClient = new Zend_Gdata_Books($client); - } - - /** - * Print the content of a feed - * - * @param Zend_Gdata_Gbase_Feed $feed - * @return void - */ - public function printFeed($feed) - { - $i = 0; - foreach($feed as $entry) { - $titles = $entry->getTitles(); - $rating = $entry->getRating(); - if (count($titles)) { - if (!is_object($rating)) { - $rating_str = "?"; - } else { - $rating_str = $rating->getAverage(); - } - print $i." ".$titles[0]->getText(). - ", Rating: ".$rating_str."\n"; - $i++; - } - } - } - - /** - * List books in the My library feed - * - * @return void - */ - public function listLibrary() - { - $feed = $this->gdClient->getUserLibraryFeed(); - print "== Books in my library ==\n"; - $this->printFeed($feed); - print "\n"; - } - - /** - * List books in the annotation feed. - * - * @return void - */ - public function listReviewed() - { - $feed = $this->gdClient->getUserLibraryFeed( - Zend_Gdata_Books::MY_ANNOTATION_FEED_URI); - print "== Books I annotated ==\n"; - $this->printFeed($feed); - print "\n"; - } - - /** - * Add an arbitrary book to the library feed. - * - * @param string $volumeId Volume to the library - * @return void - */ - public function addBookToLibrary($volumeId) - { - $entry = new Zend_Gdata_Books_VolumeEntry(); - $entry->setId( - new Zend_Gdata_App_Extension_Id($volumeId)); - print "Inserting ".$volumeId."\n\n"; - return $this->gdClient->insertVolume($entry); - } - - /** - * Add an arbitrary book to the library feed. - * - * @param string $volumeId Volume to add a rating to - * @param float $rating Numeric rating from 0 to 5 - * @return void - */ - public function addRating($volumeId, $rating) - { - $entry = new Zend_Gdata_Books_VolumeEntry(); - $entry->setId( - new Zend_Gdata_App_Extension_Id($volumeId)); - $entry->setRating( - new Zend_Gdata_Extension_Rating($rating, "0", 5, 1)); - print "Inserting a rating of ".$rating." for ".$volumeId."\n\n"; - return $this->gdClient->insertVolume($entry, - Zend_Gdata_Books::MY_ANNOTATION_FEED_URI); - } - - /** - * Remove an an arbitrary book from a feed (either remove - * from library feed or remove the annotations from annotation - * feed). - * - * @param Zend_Gdata_Books_VolumeEntry $entry - * @return void - */ - public function removeBook($entry) - { - print "Deleting ".$entry->getId()->getText()."\n\n"; - $this->gdClient->deleteVolume($entry); - } - - /** - * Main logic for the demo. - * - * @return void - */ - public function run() - { - $test_volume = "8YEAAAAAYAAJ"; - - // Playing with the library feed - $this->listLibrary(); - - $entry = $this->addBookToLibrary($test_volume); - $this->listLibrary(); - - $this->removeBook($entry); - $this->listLibrary(); - - // Playing with the annotation feed - $this->listReviewed(); - - $entry = $this->addRating($test_volume, 4.0); - $this->listReviewed(); - - $this->removeBook($entry); - $this->listReviewed(); - } -} - -/** - * getInput - * - * @param string $text - * @return string - */ -function getInput($text) -{ - echo $text.': '; - return trim(fgets(STDIN)); -} - -echo "Books Gdata API - my library demo\n\n"; -$email = null; -$pass = null; - -// process command line options -foreach ($argv as $argument) { - $argParts = explode('=', $argument); - if ($argParts[0] == '--email') { - $email = $argParts[1]; - } else if ($argParts[0] == '--pass') { - $pass = $argParts[1]; - } -} - -if (($email == null) || ($pass == null)) { - $email = getInput( - "Please enter your email address [example: username@gmail.com]"); - $pass = getInput( - "Please enter your password [example: mypassword]"); -} - -$demo = new SimpleDemo($email, $pass); -$demo->run(); diff --git a/demos/Zend/Gdata/Photos.php b/demos/Zend/Gdata/Photos.php deleted file mode 100755 index 013dded1cb4..00000000000 --- a/demos/Zend/Gdata/Photos.php +++ /dev/null @@ -1,904 +0,0 @@ -= 5.1.4 - * - * You can run this sample from a web browser. - * - * NOTE: You must ensure that Zend Framework is in your PHP include - * path. You can do this via php.ini settings, or by modifying the - * argument to set_include_path in the code below. - * - * NOTE: As this is sample code, not all of the functions do full error - * handling. - */ - -/** - * @see Zend_Loader - */ -require_once 'Zend/Loader.php'; - -/** - * @see Zend_Gdata - */ -Zend_Loader::loadClass('Zend_Gdata'); - -/** - * @see Zend_Gdata_AuthSub - */ -Zend_Loader::loadClass('Zend_Gdata_AuthSub'); - -/** - * @see Zend_Gdata_Photos - */ -Zend_Loader::loadClass('Zend_Gdata_Photos'); - -/** - * @see Zend_Gdata_Photos_UserQuery - */ -Zend_Loader::loadClass('Zend_Gdata_Photos_UserQuery'); - -/** - * @see Zend_Gdata_Photos_AlbumQuery - */ -Zend_Loader::loadClass('Zend_Gdata_Photos_AlbumQuery'); - -/** - * @see Zend_Gdata_Photos_PhotoQuery - */ -Zend_Loader::loadClass('Zend_Gdata_Photos_PhotoQuery'); - -/** - * @see Zend_Gdata_App_Extension_Category - */ -Zend_Loader::loadClass('Zend_Gdata_App_Extension_Category'); - -session_start(); - - -/** - * Adds a new photo to the specified album - * - * @param Zend_Http_Client $client The authenticated client - * @param string $user The user's account name - * @param integer $albumId The album's id - * @param array $photo The uploaded photo - * @return void - */ -function addPhoto($client, $user, $albumId, $photo) -{ - $photos = new Zend_Gdata_Photos($client); - - $fd = $photos->newMediaFileSource($photo["tmp_name"]); - $fd->setContentType($photo["type"]); - - $entry = new Zend_Gdata_Photos_PhotoEntry(); - $entry->setMediaSource($fd); - $entry->setTitle($photos->newTitle($photo["name"])); - - $albumQuery = new Zend_Gdata_Photos_AlbumQuery; - $albumQuery->setUser($user); - $albumQuery->setAlbumId($albumId); - - $albumEntry = $photos->getAlbumEntry($albumQuery); - - $result = $photos->insertPhotoEntry($entry, $albumEntry); - if ($result) { - outputAlbumFeed($client, $user, $albumId); - } else { - echo "There was an issue with the file upload."; - } -} - -/** - * Deletes the specified photo - * - * @param Zend_Http_Client $client The authenticated client - * @param string $user The user's account name - * @param integer $albumId The album's id - * @param integer $photoId The photo's id - * @return void - */ -function deletePhoto($client, $user, $albumId, $photoId) -{ - $photos = new Zend_Gdata_Photos($client); - - $photoQuery = new Zend_Gdata_Photos_PhotoQuery; - $photoQuery->setUser($user); - $photoQuery->setAlbumId($albumId); - $photoQuery->setPhotoId($photoId); - $photoQuery->setType('entry'); - - $entry = $photos->getPhotoEntry($photoQuery); - - $photos->deletePhotoEntry($entry, true); - - outputAlbumFeed($client, $user, $albumId); -} - -/** - * Adds a new album to the specified user's album - * - * @param Zend_Http_Client $client The authenticated client - * @param string $user The user's account name - * @param string $name The name of the new album - * @return void - */ -function addAlbum($client, $user, $name) -{ - $photos = new Zend_Gdata_Photos($client); - - $entry = new Zend_Gdata_Photos_AlbumEntry(); - $entry->setTitle($photos->newTitle($name)); - - $result = $photos->insertAlbumEntry($entry); - if ($result) { - outputUserFeed($client, $user); - } else { - echo "There was an issue with the album creation."; - } -} - -/** - * Deletes the specified album - * - * @param Zend_Http_Client $client The authenticated client - * @param string $user The user's account name - * @param integer $albumId The album's id - * @return void - */ -function deleteAlbum($client, $user, $albumId) -{ - $photos = new Zend_Gdata_Photos($client); - - $albumQuery = new Zend_Gdata_Photos_AlbumQuery; - $albumQuery->setUser($user); - $albumQuery->setAlbumId($albumId); - $albumQuery->setType('entry'); - - $entry = $photos->getAlbumEntry($albumQuery); - - $photos->deleteAlbumEntry($entry, true); - - outputUserFeed($client, $user); -} - -/** - * Adds a new comment to the specified photo - * - * @param Zend_Http_Client $client The authenticated client - * @param string $user The user's account name - * @param integer $albumId The album's id - * @param integer $photoId The photo's id - * @param string $comment The comment to add - * @return void - */ -function addComment($client, $user, $album, $photo, $comment) -{ - $photos = new Zend_Gdata_Photos($client); - - $entry = new Zend_Gdata_Photos_CommentEntry(); - $entry->setTitle($photos->newTitle($comment)); - $entry->setContent($photos->newContent($comment)); - - $photoQuery = new Zend_Gdata_Photos_PhotoQuery; - $photoQuery->setUser($user); - $photoQuery->setAlbumId($album); - $photoQuery->setPhotoId($photo); - $photoQuery->setType('entry'); - - $photoEntry = $photos->getPhotoEntry($photoQuery); - - $result = $photos->insertCommentEntry($entry, $photoEntry); - if ($result) { - outputPhotoFeed($client, $user, $album, $photo); - } else { - echo "There was an issue with the comment creation."; - } -} - -/** - * Deletes the specified comment - * - * @param Zend_Http_Client $client The authenticated client - * @param string $user The user's account name - * @param integer $albumId The album's id - * @param integer $photoId The photo's id - * @param integer $commentId The comment's id - * @return void - */ -function deleteComment($client, $user, $albumId, $photoId, $commentId) -{ - $photos = new Zend_Gdata_Photos($client); - - $photoQuery = new Zend_Gdata_Photos_PhotoQuery; - $photoQuery->setUser($user); - $photoQuery->setAlbumId($albumId); - $photoQuery->setPhotoId($photoId); - $photoQuery->setType('entry'); - - $path = $photoQuery->getQueryUrl() . '/commentid/' . $commentId; - - $entry = $photos->getCommentEntry($path); - - $photos->deleteCommentEntry($entry, true); - - outputPhotoFeed($client, $user, $albumId, $photoId); -} - -/** - * Adds a new tag to the specified photo - * - * @param Zend_Http_Client $client The authenticated client - * @param string $user The user's account name - * @param integer $album The album's id - * @param integer $photo The photo's id - * @param string $tag The tag to add to the photo - * @return void - */ -function addTag($client, $user, $album, $photo, $tag) -{ - $photos = new Zend_Gdata_Photos($client); - - $entry = new Zend_Gdata_Photos_TagEntry(); - $entry->setTitle($photos->newTitle($tag)); - - $photoQuery = new Zend_Gdata_Photos_PhotoQuery; - $photoQuery->setUser($user); - $photoQuery->setAlbumId($album); - $photoQuery->setPhotoId($photo); - $photoQuery->setType('entry'); - - $photoEntry = $photos->getPhotoEntry($photoQuery); - - $result = $photos->insertTagEntry($entry, $photoEntry); - if ($result) { - outputPhotoFeed($client, $user, $album, $photo); - } else { - echo "There was an issue with the tag creation."; - } -} - -/** - * Deletes the specified tag - * - * @param Zend_Http_Client $client The authenticated client - * @param string $user The user's account name - * @param integer $albumId The album's id - * @param integer $photoId The photo's id - * @param string $tagContent The name of the tag to be deleted - * @return void - */ -function deleteTag($client, $user, $albumId, $photoId, $tagContent) -{ - $photos = new Zend_Gdata_Photos($client); - - $photoQuery = new Zend_Gdata_Photos_PhotoQuery; - $photoQuery->setUser($user); - $photoQuery->setAlbumId($albumId); - $photoQuery->setPhotoId($photoId); - $query = $photoQuery->getQueryUrl() . "?kind=tag"; - - $photoFeed = $photos->getPhotoFeed($query); - - foreach ($photoFeed as $entry) { - if ($entry instanceof Zend_Gdata_Photos_TagEntry) { - if ($entry->getContent() == $tagContent) { - $tagEntry = $entry; - } - } - } - - $photos->deleteTagEntry($tagEntry, true); - - outputPhotoFeed($client, $user, $albumId, $photoId); -} - -/** - * Returns the path to the current script, without any query params - * - * Env variables used: - * $_SERVER['PHP_SELF'] - * - * @return string Current script path - */ -function getCurrentScript() -{ - global $_SERVER; - return $_SERVER["PHP_SELF"]; -} - -/** - * Returns the full URL of the current page, based upon env variables - * - * Env variables used: - * $_SERVER['HTTPS'] = (on|off|) - * $_SERVER['HTTP_HOST'] = value of the Host: header - * $_SERVER['SERVER_PORT'] = port number (only used if not http/80,https/443) - * $_SERVER['REQUEST_URI'] = the URI after the method of the HTTP request - * - * @return string Current URL - */ -function getCurrentUrl() -{ - global $_SERVER; - - /** - * Filter php_self to avoid a security vulnerability. - */ - $php_request_uri = htmlentities(substr($_SERVER['REQUEST_URI'], 0, - strcspn($_SERVER['REQUEST_URI'], "\n\r")), ENT_QUOTES); - - if (isset($_SERVER['HTTPS']) && strtolower($_SERVER['HTTPS']) == 'on') { - $protocol = 'https://'; - } else { - $protocol = 'http://'; - } - $host = $_SERVER['HTTP_HOST']; - if ($_SERVER['SERVER_PORT'] != '' && - (($protocol == 'http://' && $_SERVER['SERVER_PORT'] != '80') || - ($protocol == 'https://' && $_SERVER['SERVER_PORT'] != '443'))) { - $port = ':' . $_SERVER['SERVER_PORT']; - } else { - $port = ''; - } - return $protocol . $host . $port . $php_request_uri; -} - -/** - * Returns the AuthSub URL which the user must visit to authenticate requests - * from this application. - * - * Uses getCurrentUrl() to get the next URL which the user will be redirected - * to after successfully authenticating with the Google service. - * - * @return string AuthSub URL - */ -function getAuthSubUrl() -{ - $next = getCurrentUrl(); - $scope = 'http://picasaweb.google.com/data'; - $secure = false; - $session = true; - return Zend_Gdata_AuthSub::getAuthSubTokenUri($next, $scope, $secure, - $session); -} - -/** - * Outputs a request to the user to login to their Google account, including - * a link to the AuthSub URL. - * - * Uses getAuthSubUrl() to get the URL which the user must visit to authenticate - * - * @return void - */ -function requestUserLogin($linkText) -{ - $authSubUrl = getAuthSubUrl(); - echo "{$linkText}"; -} - -/** - * Returns a HTTP client object with the appropriate headers for communicating - * with Google using AuthSub authentication. - * - * Uses the $_SESSION['sessionToken'] to store the AuthSub session token after - * it is obtained. The single use token supplied in the URL when redirected - * after the user succesfully authenticated to Google is retrieved from the - * $_GET['token'] variable. - * - * @return Zend_Http_Client - */ -function getAuthSubHttpClient() -{ - global $_SESSION, $_GET; - if (!isset($_SESSION['sessionToken']) && isset($_GET['token'])) { - $_SESSION['sessionToken'] = - Zend_Gdata_AuthSub::getAuthSubSessionToken($_GET['token']); - } - $client = Zend_Gdata_AuthSub::getHttpClient($_SESSION['sessionToken']); - return $client; -} - -/** - * Processes loading of this sample code through a web browser. Uses AuthSub - * authentication and outputs a list of a user's albums if succesfully - * authenticated. - * - * @return void - */ -function processPageLoad() -{ - global $_SESSION, $_GET; - if (!isset($_SESSION['sessionToken']) && !isset($_GET['token'])) { - requestUserLogin('Please login to your Google Account.'); - } else { - $client = getAuthSubHttpClient(); - if (!empty($_REQUEST['command'])) { - switch ($_REQUEST['command']) { - case 'retrieveSelf': - outputUserFeed($client, "default"); - break; - case 'retrieveUser': - outputUserFeed($client, $_REQUEST['user']); - break; - case 'retrieveAlbumFeed': - outputAlbumFeed($client, $_REQUEST['user'], $_REQUEST['album']); - break; - case 'retrievePhotoFeed': - outputPhotoFeed($client, $_REQUEST['user'], $_REQUEST['album'], - $_REQUEST['photo']); - break; - } - } - - // Now we handle the potentially destructive commands, which have to - // be submitted by POST only. - if (!empty($_POST['command'])) { - switch ($_POST['command']) { - case 'addPhoto': - addPhoto($client, $_POST['user'], $_POST['album'], $_FILES['photo']); - break; - case 'deletePhoto': - deletePhoto($client, $_POST['user'], $_POST['album'], - $_POST['photo']); - break; - case 'addAlbum': - addAlbum($client, $_POST['user'], $_POST['name']); - break; - case 'deleteAlbum': - deleteAlbum($client, $_POST['user'], $_POST['album']); - break; - case 'addComment': - addComment($client, $_POST['user'], $_POST['album'], $_POST['photo'], - $_POST['comment']); - break; - case 'addTag': - addTag($client, $_POST['user'], $_POST['album'], $_POST['photo'], - $_POST['tag']); - break; - case 'deleteComment': - deleteComment($client, $_POST['user'], $_POST['album'], - $_POST['photo'], $_POST['comment']); - break; - case 'deleteTag': - deleteTag($client, $_POST['user'], $_POST['album'], $_POST['photo'], - $_POST['tag']); - break; - default: - break; - } - } - - // If a menu parameter is available, display a submenu. - if (!empty($_REQUEST['menu'])) { - switch ($_REQUEST['menu']) { - case 'user': - displayUserMenu(); - break; - case 'photo': - displayPhotoMenu(); - break; - case 'album': - displayAlbumMenu(); - break; - case 'logout': - logout(); - break; - default: - header('HTTP/1.1 400 Bad Request'); - echo "

Invalid menu selection.

\n"; - echo "

Please check your request and try again.

"; - } - } - - if (empty($_REQUEST['menu']) && empty($_REQUEST['command'])) { - displayMenu(); - } - } -} - -/** - * Displays the main menu, allowing the user to select from a list of actions. - * - * @return void - */ -function displayMenu() -{ -?> -

Main Menu

- -

Welcome to the Photos API demo page. Please select - from one of the following four options to fetch information.

- - -
"; - echo "<< Back"; -} - -/** - * Displays the user menu, allowing the user to request a specific user's feed. - * - * @return void - */ -function displayUserMenu() -{ -?> -

User Menu

- - - -

Photo Menu

- - - -

Album Menu

- - -setUser($user); - - $userFeed = $photos->getUserFeed(null, $query); - echo "

User Feed for: " . $userFeed->getTitle() . "

"; - echo "
\n"; - - echo "

Add an Album

"; -?> - - - - - - -setUser($user); - $query->setAlbumId($albumId); - - $albumFeed = $photos->getAlbumFeed($query); - echo "

Album Feed for: " . $albumFeed->getTitle() . "

"; - echo "
\n"; - - echo "

Add a Photo

"; -?> - - - - - - Please select a photo to upload:
- - -setUser($user); - $query->setAlbumId($albumId); - $query->setPhotoId($photoId); - $query = $query->getQueryUrl() . "?kind=comment,tag"; - - $photoFeed = $photos->getPhotoFeed($query); - echo "

Photo Feed for: " . $photoFeed->getTitle() . "

"; - $thumbs = $photoFeed->getMediaGroup()->getThumbnail(); - echo ""; - - echo "

Comments:

"; - echo "
    \n"; - foreach ($photoFeed as $entry) { - if ($entry instanceof Zend_Gdata_Photos_CommentEntry) { - echo "\t
  • " . $entry->getContent(); - echo "
    "; - echo ""; - echo ""; - echo ""; - echo ""; - echo ""; - echo ""; - echo "
  • \n"; - } - } - echo "
\n"; - echo "

Add a Comment

"; -?> - - - - - - - - -"; - echo "

Tags:

"; - echo "
    \n"; - foreach ($photoFeed as $entry) { - if ($entry instanceof Zend_Gdata_Photos_TagEntry) { - echo "\t
  • " . $entry->getTitle(); - echo "
    "; - echo ""; - echo ""; - echo ""; - echo ""; - echo ""; - echo ""; - echo "
  • \n"; - } - } - echo "
\n"; - echo "

Add a Tag

"; -?> - - - - - - - - - - -getMessage() ."\nCredentials provided were email: [$email] and password [$password].\n"); - } - - $this->gdClient = new Zend_Gdata_Spreadsheets($client); - $this->currKey = ''; - $this->currWkshtId = ''; - $this->listFeed = ''; - $this->rowCount = 0; - $this->columnCount = 0; - } - - /** - * promptForSpreadsheet - * - * @return void - */ - public function promptForSpreadsheet() - { - $feed = $this->gdClient->getSpreadsheetFeed(); - print "== Available Spreadsheets ==\n"; - $this->printFeed($feed); - $input = getInput("\nSelection"); - $currKey = explode('/', $feed->entries[$input]->id->text); - $this->currKey = $currKey[5]; - } - - /** - * promptForWorksheet - * - * @return void - */ - public function promptForWorksheet() - { - $query = new Zend_Gdata_Spreadsheets_DocumentQuery(); - $query->setSpreadsheetKey($this->currKey); - $feed = $this->gdClient->getWorksheetFeed($query); - print "== Available Worksheets ==\n"; - $this->printFeed($feed); - $input = getInput("\nSelection"); - $currWkshtId = explode('/', $feed->entries[$input]->id->text); - $this->currWkshtId = $currWkshtId[8]; - - } - - /** - * promptForCellsAction - * - * @return void - */ - public function promptForCellsAction() - { - echo "Pick a command:\n"; - echo "\ndump -- dump cell information\nupdate {row} {col} {input_value} -- update cell information\n"; - $input = getInput('Command'); - $command = explode(' ', $input); - if ($command[0] == 'dump') { - $this->cellsGetAction(); - } else if (($command[0] == 'update') && (count($command) > 2)) { - $this->getRowAndColumnCount(); - if (count($command) == 4) { - $this->cellsUpdateAction($command[1], $command[2], $command[3]); - } elseif (count($command) > 4) { - $newValue = implode(' ', array_slice($command,3)); - $this->cellsUpdateAction($command[1], $command[2], $newValue); - } else { - $this->cellsUpdateAction($command[1], $command[2], ''); - } - } else { - $this->invalidCommandError($input); - } - } - - /** - * promptToResize - * - * @param integer $newRowCount - * @param integer $newColumnCount - * @return boolean - */ - public function promptToResize($newRowCount, $newColumnCount) { - $input = getInput('Would you like to resize the worksheet? [yes | no]'); - if ($input == 'yes') { - return $this->resizeWorksheet($newRowCount, $newColumnCount); - } else { - return false; - } - } - - /** - * resizeWorksheet - * - * @param integer $newRowCount - * @param integer $newColumnCount - * @return boolean - */ - public function resizeWorksheet($newRowCount, $newColumnCount) { - $query = new Zend_Gdata_Spreadsheets_DocumentQuery(); - $query->setSpreadsheetKey($this->currKey); - $query->setWorksheetId($this->currWkshtId); - $currentWorksheet = $this->gdClient->getWorksheetEntry($query); - $currentWorksheet = $currentWorksheet->setRowCount(new Zend_Gdata_Spreadsheets_Extension_RowCount($newRowCount)); - $currentWorksheet = $currentWorksheet->setColumnCount(new Zend_Gdata_Spreadsheets_Extension_ColCount($newColumnCount)); - $currentWorksheet->save(); - $this->getRowAndColumnCount(); - print "Worksheet has been resized to $this->rowCount rows and $this->columnCount columns.\n"; - return true; - } - - /** - * promptForListAction - * - * @return void - */ - public function promptForListAction() - { - echo "\n== Options ==\n". - "dump -- dump row information\n". - "insert {row_data} -- insert data in the next available cell in a given column (example: insert column_header=content)\n". - "update {row_index} {row_data} -- update data in the row provided (example: update row-number column-header=newdata\n". - "delete {row_index} -- delete a row\n\n"; - - $input = getInput('Command'); - $command = explode(' ', $input); - if ($command[0] == 'dump') { - $this->listGetAction(); - } else if ($command[0] == 'insert') { - $this->listInsertAction(array_slice($command, 1)); - } else if ($command[0] == 'update') { - $this->listUpdateAction($command[1], array_slice($command, 2)); - } else if ($command[0] == 'delete') { - $this->listDeleteAction($command[1]); - } else { - $this->invalidCommandError($input); - } - } - - /** - * cellsGetAction - * - * @return void - */ - public function cellsGetAction() - { - $query = new Zend_Gdata_Spreadsheets_CellQuery(); - $query->setSpreadsheetKey($this->currKey); - $query->setWorksheetId($this->currWkshtId); - $feed = $this->gdClient->getCellFeed($query); - $this->printFeed($feed); - } - - /** - * cellsUpdateAction - * - * @param integer $row - * @param integer $col - * @param string $inputValue - * @return void - */ - public function cellsUpdateAction($row, $col, $inputValue) - { - if (($row > $this->rowCount) || ($col > $this->columnCount)) { - print "Current worksheet only has $this->rowCount rows and $this->columnCount columns.\n"; - if (!$this->promptToResize($row, $col)) { - return; - } - } - $entry = $this->gdClient->updateCell($row, $col, $inputValue, - $this->currKey, $this->currWkshtId); - if ($entry instanceof Zend_Gdata_Spreadsheets_CellEntry) { - echo "Success!\n"; - } - } - - /** - * listGetAction - * - * @return void - */ - public function listGetAction() - { - $query = new Zend_Gdata_Spreadsheets_ListQuery(); - $query->setSpreadsheetKey($this->currKey); - $query->setWorksheetId($this->currWkshtId); - $this->listFeed = $this->gdClient->getListFeed($query); - print "entry id | row-content in column A | column-header: cell-content\n". - "Please note: The 'dump' command on the list feed only dumps data until the first blank row is encountered.\n\n"; - - $this->printFeed($this->listFeed); - print "\n"; - } - - /** - * listInsertAction - * - * @param mixed $rowData - * @return void - */ - public function listInsertAction($rowData) - { - $rowArray = $this->stringToArray($rowData); - $entry = $this->gdClient->insertRow($rowArray, $this->currKey, $this->currWkshtId); - if ($entry instanceof Zend_Gdata_Spreadsheets_ListEntry) { - foreach ($rowArray as $column_header => $value) { - echo "Success! Inserted '$value' in column '$column_header' at row ". substr($entry->getTitle()->getText(), 5) ."\n"; - } - } - } - - /** - * listUpdateAction - * - * @param integer $index - * @param mixed $rowData - * @return void - */ - public function listUpdateAction($index, $rowData) - { - $query = new Zend_Gdata_Spreadsheets_ListQuery(); - $query->setSpreadsheetKey($this->currKey); - $query->setWorksheetId($this->currWkshtId); - $this->listFeed = $this->gdClient->getListFeed($query); - $rowArray = $this->stringToArray($rowData); - $entry = $this->gdClient->updateRow($this->listFeed->entries[$index], $rowArray); - if ($entry instanceof Zend_Gdata_Spreadsheets_ListEntry) { - echo "Success!\n"; $response = $entry->save(); - - } - } - - /** - * listDeleteAction - * - * @param integer $index - * @return void - */ - public function listDeleteAction($index) - { - $query = new Zend_Gdata_Spreadsheets_ListQuery(); - $query->setSpreadsheetKey($this->currKey); - $query->setWorksheetId($this->currWkshtId); - $this->listFeed = $this->gdClient->getListFeed($query); - $this->gdClient->deleteRow($this->listFeed->entries[$index]); - } - - /** - * stringToArray - * - * @param string $rowData - * @return array - */ - public function stringToArray($rowData) - { - $arr = array(); - foreach ($rowData as $row) { - $temp = explode('=', $row); - $arr[$temp[0]] = $temp[1]; - } - return $arr; - } - - /** - * printFeed - * - * @param Zend_Gdata_Gbase_Feed $feed - * @return void - */ - public function printFeed($feed) - { - $i = 0; - foreach($feed->entries as $entry) { - if ($entry instanceof Zend_Gdata_Spreadsheets_CellEntry) { - print $entry->title->text .' '. $entry->content->text . "\n"; - } else if ($entry instanceof Zend_Gdata_Spreadsheets_ListEntry) { - print $i .' '. $entry->title->text .' | '. $entry->content->text . "\n"; - } else { - print $i .' '. $entry->title->text . "\n"; - } - $i++; - } - } - - /** - * getRowAndColumnCount - * - * @return void - */ - public function getRowAndColumnCount() - { - $query = new Zend_Gdata_Spreadsheets_CellQuery(); - $query->setSpreadsheetKey($this->currKey); - $query->setWorksheetId($this->currWkshtId); - $feed = $this->gdClient->getCellFeed($query); - - if ($feed instanceOf Zend_Gdata_Spreadsheets_CellFeed) { - $this->rowCount = $feed->getRowCount(); - $this->columnCount = $feed->getColumnCount(); - } - } - - /** - * invalidCommandError - * - * @param string $input - * @return void - */ - public function invalidCommandError($input) - { - echo 'Invalid input: '.$input."\n"; - } - - /** - * promtForFeedtype - * - * @return void - */ - public function promptForFeedtype() { - - $input = getInput('Select to use either the cell or the list feed [cells or list]'); - - if ($input == 'cells') { - while(1) { - $this->promptForCellsAction(); - } - } else if ($input == 'list') { - while(1) { - $this->promptForListAction(); - } - } else { - print "Invalid input. Please try again.\n"; - $this->promptForFeedtype(); - } - } - - /** - * run - * - * @return void - */ - public function run() - { - $this->promptForSpreadsheet(); - $this->promptForWorksheet(); - $this->promptForFeedtype(); - } -} - -/** - * getInput - * - * @param string $text - * @return string - */ -function getInput($text) -{ - echo $text.': '; - return trim(fgets(STDIN)); -} - -$email = null; -$pass = null; - -// process command line options -foreach ($argv as $argument) { - $argParts = explode('=', $argument); - if ($argParts[0] == '--email') { - $email = $argParts[1]; - } else if ($argParts[0] == '--pass') { - $pass = $argParts[1]; - } -} - -if (($email == null) || ($pass == null)) { - $email = getInput("Please enter your email address [example: username@gmail.com]"); - $pass = getInput("Please enter your password [example: mypassword]"); -} - -$sample = new SimpleCRUD($email, $pass); -$sample->run(); diff --git a/demos/Zend/Gdata/YouTubeVideoApp/README.txt b/demos/Zend/Gdata/YouTubeVideoApp/README.txt deleted file mode 100644 index 50a117b1f33..00000000000 --- a/demos/Zend/Gdata/YouTubeVideoApp/README.txt +++ /dev/null @@ -1,44 +0,0 @@ -== YouTube data API Video App in PHP == - -PHP sample code for the YouTube data API. Utilizes the Zend Framework -Zend_Gdata component to communicate with the YouTube data API. - -Requires the Zend Framework Zend_Gdata component and PHP >= 5.1.4 -This sample is run from within a web browser. These files are required: - -session_details.php - a script to view log output and session variables -operations.php - the main logic, which interfaces with the YouTube API -index.php - the HTML to represent the web UI, contains some PHP -video_app.css - the CSS to define the interface style -video_app.js - the JavaScript used to provide the video list AJAX interface - --------------- - -NOTE: If using in production, some additional precautions with regards -to filtering the input data should be used. This code is designed only -for demonstration purposes. - --------------- - -Please be sure to obtain a Developer Key from YouTube prior to using -this application by visiting this site: - -http://code.google.com/apis/youtube/dashboard/ - -More information on the YouTube Data API and Tools is available here: - -http://code.google.com/apis/youtube - -For a video explaining the basics of how this application works, please -visit this link: - -http://www.youtube.com/watch?v=iIp7OnHXBlo - -To see this application running live, please visit: - -http://googlecodesamples.com - -== UPDATES == - -3/2009 - Removed functionality to set the Developer Key in a form. Instead, - it is now hard-coded in the index.php page. This reduces complexity. diff --git a/demos/Zend/Gdata/YouTubeVideoApp/index.php b/demos/Zend/Gdata/YouTubeVideoApp/index.php deleted file mode 100755 index 65fe59b187a..00000000000 --- a/demos/Zend/Gdata/YouTubeVideoApp/index.php +++ /dev/null @@ -1,193 +0,0 @@ -= 5.1.4 - * This sample is run from within a web browser. These files are required: - * session_details.php - a script to view log output and session variables - * operations.php - the main logic, which interfaces with the YouTube API - * index.php - the HTML to represent the web UI, contains some PHP - * video_app.css - the CSS to define the interface style - * video_app.js - the JavaScript used to provide the video list AJAX interface - * - * NOTE: If using in production, some additional precautions with regards - * to filtering the input data should be used. This code is designed only - * for demonstration purposes. - */ -session_start(); - -/** - * Set your developer key here. - * - * NOTE: In a production application you may want to store this information in - * an external file. - */ -$_SESSION['developerKey'] = ''; - -/** - * Convert HTTP status into normal text. - * - * @param number $status HTTP status received after posting syndicated upload - * @param string $code Alphanumeric description of error - * @param string $videoId (optional) Video id received back to which the status - * code refers to - */ -function uploadStatus($status, $code = null, $videoId = null) -{ - switch ($status) { - case $status < 400: - echo 'Success ! Entry created (id: '. $videoId . - ') (check details)'; - break; - default: - echo 'There seems to have been an error: '. $code . - '(check details)'; - } -} - -/** - * Helper function to check whether a session token has been set - * - * @return boolean Returns true if a session token has been set - */ -function authenticated() -{ - if (isset($_SESSION['sessionToken'])) { - return true; - } -} - -/** - * Helper function to print a list of authenticated actions for a user. - */ -function printAuthenticatedActions() -{ - print <<

Authenticated Actions

- -END; -} -?> - - - - - YouTube data API Video Browser in PHP - - - - - -
-
-

YouTube data API Video App in PHP

- click to examine session variables
- -
- -
-
- -
Authentication status: - -END; - } else { - print <<Click here to generate authentication link -
-END; - } - ?> -
- -
- ' . - uploadStatus($_GET['status'], $code, $id) . - '
'; - } - ?> - - - -
-
-
-
-
- - - - -
-
-
-
-
-
- - - \ No newline at end of file diff --git a/demos/Zend/Gdata/YouTubeVideoApp/notfound.jpg b/demos/Zend/Gdata/YouTubeVideoApp/notfound.jpg deleted file mode 100755 index 76ec81c45f2..00000000000 Binary files a/demos/Zend/Gdata/YouTubeVideoApp/notfound.jpg and /dev/null differ diff --git a/demos/Zend/Gdata/YouTubeVideoApp/operations.php b/demos/Zend/Gdata/YouTubeVideoApp/operations.php deleted file mode 100755 index fdb1ffd2072..00000000000 --- a/demos/Zend/Gdata/YouTubeVideoApp/operations.php +++ /dev/null @@ -1,1097 +0,0 @@ -= 5.1.4 - * This sample is run from within a web browser. These files are required: - * session_details.php - a script to view log output and session variables - * operations.php - the main logic, which interfaces with the YouTube API - * index.php - the HTML to represent the web UI, contains some PHP - * video_app.css - the CSS to define the interface style - * video_app.js - the JavaScript used to provide the video list AJAX interface - * - * NOTE: If using in production, some additional precautions with regards - * to filtering the input data should be used. This code is designed only - * for demonstration purposes. - */ -require_once 'Zend/Loader.php'; -Zend_Loader::loadClass('Zend_Gdata_YouTube'); -Zend_Loader::loadClass('Zend_Gdata_AuthSub'); -Zend_Loader::loadClass('Zend_Gdata_App_Exception'); - -/* - * The main controller logic. - * - * POST used for all authenticated requests - * otherwise use GET for retrieve and supplementary values - */ -session_start(); -setLogging('on'); -generateUrlInformation(); - -if (!isset($_POST['operation'])) { - // if a GET variable is set then process the token upgrade - if (isset($_GET['token'])) { - updateAuthSubToken($_GET['token']); - } else { - if (loggingEnabled()) { - logMessage('reached operations.php without $_POST or $_GET variables set', 'error'); - header('Location: index.php'); - } - } -} - -$operation = $_POST['operation']; - -switch ($operation) { - - case 'create_upload_form': - createUploadForm($_POST['videoTitle'], - $_POST['videoDescription'], - $_POST['videoCategory'], - $_POST['videoTags']); - break; - - case 'edit_meta_data': - editVideoData($_POST['newVideoTitle'], - $_POST['newVideoDescription'], - $_POST['newVideoCategory'], - $_POST['newVideoTags'], - $_POST['videoId']); - break; - - case 'check_upload_status': - checkUpload($_POST['videoId']); - break; - - case 'delete_video': - deleteVideo($_POST['videoId']); - break; - - case 'auth_sub_request': - generateAuthSubRequestLink(); - break; - - case 'auth_sub_token_upgrade': - updateAuthSubToken($_GET['token']); - break; - - case 'clear_session_var': - clearSessionVar($_POST['name']); - break; - - case 'retrieve_playlists': - retrievePlaylists(); - break; - - case 'create_playlist': - createPlaylist($_POST['playlistTitle'], $_POST['playlistDescription']); - break; - - case 'delete_playlist': - deletePlaylist($_POST['playlistTitle']); - break; - - case 'update_playlist': - updatePlaylist($_POST['newPlaylistTitle'], - $_POST['newPlaylistDescription'], - $_POST['oldPlaylistTitle']); - break; - - case (strcmp(substr($operation, 0, 7), 'search_') == 0): - // initialize search specific information - $searchType = substr($operation, 7); - searchVideos($searchType, $_POST['searchTerm'], $_POST['startIndex'], - $_POST['maxResults']); - break; - - case 'show_video': - echoVideoPlayer($_POST['videoId']); - break; - - default: - unsupportedOperation($_POST); - break; -} - -/** - * Perform a search on youtube. Passes the result feed to echoVideoList. - * - * @param string $searchType The type of search to perform. - * If set to 'owner' then attempt to authenticate. - * @param string $searchTerm The term to search on. - * @param string $startIndex Start retrieving search results from this index. - * @param string $maxResults The number of results to retrieve. - * @return void - */ -function searchVideos($searchType, $searchTerm, $startIndex, $maxResults) -{ - // create an unauthenticated service object - $youTubeService = new Zend_Gdata_YouTube(); - $query = $youTubeService->newVideoQuery(); - $query->setQuery($searchTerm); - $query->setStartIndex($startIndex); - $query->setMaxResults($maxResults); - - switch ($searchType) { - case 'most_viewed': - $query->setFeedType('most viewed'); - $query->setTime('this_week'); - $feed = $youTubeService->getVideoFeed($query); - break; - case 'most_recent': - $query->setFeedType('most recent'); - $query->setTime('this_week'); - $feed = $youTubeService->getVideoFeed($query); - break; - case 'recently_featured': - $query->setFeedType('recently featured'); - $feed = $youTubeService->getVideoFeed($query); - break; - case 'top_rated': - $query->setFeedType('top rated'); - $query->setTime('this_week'); - $feed = $youTubeService->getVideoFeed($query); - break; - case 'username': - $feed = $youTubeService->getUserUploads($searchTerm); - break; - case 'all': - $feed = $youTubeService->getVideoFeed($query); - break; - case 'owner': - $httpClient = getAuthSubHttpClient(); - $youTubeService = new Zend_Gdata_YouTube($httpClient); - try { - $feed = $youTubeService->getUserUploads('default'); - if (loggingEnabled()) { - logMessage($httpClient->getLastRequest(), 'request'); - logMessage($httpClient->getLastResponse()->getBody(), - 'response'); - } - } catch (Zend_Gdata_App_HttpException $httpException) { - print 'ERROR ' . $httpException->getMessage() - . ' HTTP details

' - . '' - . 'click here to view details of last request
'; - return; - } catch (Zend_Gdata_App_Exception $e) { - print 'ERROR - Could not retrieve users video feed: ' - . $e->getMessage() . '
'; - return; - } - echoVideoList($feed, true); - return; - - default: - echo 'ERROR - Unknown search type - \'' . $searchType . '\''; - return; - } - - if (loggingEnabled()) { - $httpClient = $youTubeService->getHttpClient(); - logMessage($httpClient->getLastRequest(), 'request'); - logMessage($httpClient->getLastResponse()->getBody(), 'response'); - } - echoVideoList($feed); -} - -/** - * Finds the URL for the flash representation of the specified video. - * - * @param Zend_Gdata_YouTube_VideoEntry $entry The video entry - * @return (string|null) The URL or null, if the URL is not found - */ -function findFlashUrl($entry) -{ - foreach ($entry->mediaGroup->content as $content) { - if ($content->type === 'application/x-shockwave-flash') { - return $content->url; - } - } - return null; -} - -/** - * Check the upload status of a video - * - * @param string $videoId The video to check. - * @return string A message about the video's status. - */ -function checkUpload($videoId) -{ - $httpClient = getAuthSubHttpClient(); - $youTubeService = new Zend_Gdata_YouTube($httpClient); - - $feed = $youTubeService->getuserUploads('default'); - $message = 'No further status information available yet.'; - - foreach($feed as $videoEntry) { - if ($videoEntry->getVideoId() == $videoId) { - // check if video is in draft status - try { - $control = $videoEntry->getControl(); - } catch (Zend_Gdata_App_Exception $e) { - print 'ERROR - not able to retrieve control element ' - . $e->getMessage(); - return; - } - - if ($control instanceof Zend_Gdata_App_Extension_Control) { - if (($control->getDraft() != null) && - ($control->getDraft()->getText() == 'yes')) { - $state = $videoEntry->getVideoState(); - if ($state instanceof Zend_Gdata_YouTube_Extension_State) { - $message = 'Upload status: ' . $state->getName() . ' ' - . $state->getText(); - } else { - print $message; - } - } - } - } - } - print $message; -} - -/** - * Store location of the demo application into session variables. - * - * @return void - */ -function generateUrlInformation() -{ - if (!isset($_SESSION['operationsUrl']) || !isset($_SESSION['homeUrl'])) { - $_SESSION['operationsUrl'] = 'http://'. $_SERVER['HTTP_HOST'] - . $_SERVER['PHP_SELF']; - $path = explode('/', $_SERVER['PHP_SELF']); - $path[count($path)-1] = 'index.php'; - $_SESSION['homeUrl'] = 'http://'. $_SERVER['HTTP_HOST'] - . implode('/', $path); - } -} - -/** - * Log a message to the session variable array. - * - * @param string $message The message to log. - * @param string $messageType The type of message to log. - * @return void - */ -function logMessage($message, $messageType) -{ - if (!isset($_SESSION['log_maxLogEntries'])) { - $_SESSION['log_maxLogEntries'] = 20; - } - - if (!isset($_SESSION['log_currentCounter'])) { - $_SESSION['log_currentCounter'] = 0; - } - - $currentCounter = $_SESSION['log_currentCounter']; - $currentCounter++; - - if ($currentCounter > $_SESSION['log_maxLogEntries']) { - $_SESSION['log_currentCounter'] = 0; - } - - $logLocation = 'log_entry_'. $currentCounter . '_' . $messageType; - $_SESSION[$logLocation] = $message; - $_SESSION['log_currentCounter'] = $currentCounter; -} - -/** - * Update an existing video's meta-data. - * - * @param string $newVideoTitle The new title for the video entry. - * @param string $newVideoDescription The new description for the video entry. - * @param string $newVideoCategory The new category for the video entry. - * @param string $newVideoTags The new set of tags for the video entry (whitespace separated). - * @param string $videoId The video id for the video to be edited. - * @return void - */ -function editVideoData($newVideoTitle, $newVideoDescription, $newVideoCategory, $newVideoTags, $videoId) -{ - $httpClient = getAuthSubHttpClient(); - $youTubeService = new Zend_Gdata_YouTube($httpClient); - $feed = $youTubeService->getVideoFeed('http://gdata.youtube.com/feeds/users/default/uploads'); - $videoEntryToUpdate = null; - - foreach($feed as $entry) { - if ($entry->getVideoId() == $videoId) { - $videoEntryToUpdate = $entry; - break; - } - } - - if (!$videoEntryToUpdate instanceof Zend_Gdata_YouTube_VideoEntry) { - print 'ERROR - Could not find a video entry with id ' . $videoId - . '
' . printCacheWarning(); - return; - } - - try { - $putUrl = $videoEntryToUpdate->getEditLink()->getHref(); - } catch (Zend_Gdata_App_Exception $e) { - print 'ERROR - Could not obtain video entry\'s edit link: ' - . $e->getMessage() . '
'; - return; - } - - $videoEntryToUpdate->setVideoTitle($newVideoTitle); - $videoEntryToUpdate->setVideoDescription($newVideoDescription); - $videoEntryToUpdate->setVideoCategory($newVideoCategory); - - // convert tags from space separated to comma separated - $videoTagsArray = explode(' ', trim($newVideoTags)); - - // strip out empty array elements - foreach($videoTagsArray as $key => $value) { - if (strlen($value) < 2) { - unset($videoTagsArray[$key]); - } - } - - $videoEntryToUpdate->setVideoTags(implode(', ', $videoTagsArray)); - - try { - $updatedEntry = $youTubeService->updateEntry($videoEntryToUpdate, $putUrl); - if (loggingEnabled()) { - logMessage($httpClient->getLastRequest(), 'request'); - logMessage($httpClient->getLastResponse()->getBody(), 'response'); - } - } catch (Zend_Gdata_App_HttpException $httpException) { - print 'ERROR ' . $httpException->getMessage() - . ' HTTP details

' - . '' - . 'click here to view details of last request
'; - return; - } catch (Zend_Gdata_App_Exception $e) { - print 'ERROR - Could not post video meta-data: ' . $e->getMessage(); - return; - } - print 'Entry updated successfully.
' - . '(refresh your video listing)
' - . printCacheWarning(); -} - -/** - * Create upload form by sending the incoming video meta-data to youtube and - * retrieving a new entry. Prints form HTML to page. - * - * @param string $VideoTitle The title for the video entry. - * @param string $VideoDescription The description for the video entry. - * @param string $VideoCategory The category for the video entry. - * @param string $VideoTags The set of tags for the video entry (whitespace separated). - * @param string $nextUrl (optional) The URL to redirect back to after form upload has completed. - * @return void - */ -function createUploadForm($videoTitle, $videoDescription, $videoCategory, $videoTags, $nextUrl = null) -{ - $httpClient = getAuthSubHttpClient(); - $youTubeService = new Zend_Gdata_YouTube($httpClient); - $newVideoEntry = new Zend_Gdata_YouTube_VideoEntry(); - - $newVideoEntry->setVideoTitle($videoTitle); - $newVideoEntry->setVideoDescription($videoDescription); - - //make sure first character in category is capitalized - $videoCategory = strtoupper(substr($videoCategory, 0, 1)) - . substr($videoCategory, 1); - $newVideoEntry->setVideoCategory($videoCategory); - - // convert videoTags from whitespace separated into comma separated - $videoTagsArray = explode(' ', trim($videoTags)); - $newVideoEntry->setVideoTags(implode(', ', $videoTagsArray)); - - $tokenHandlerUrl = 'http://gdata.youtube.com/action/GetUploadToken'; - try { - $tokenArray = $youTubeService->getFormUploadToken($newVideoEntry, $tokenHandlerUrl); - if (loggingEnabled()) { - logMessage($httpClient->getLastRequest(), 'request'); - logMessage($httpClient->getLastResponse()->getBody(), 'response'); - } - } catch (Zend_Gdata_App_HttpException $httpException) { - print 'ERROR ' . $httpException->getMessage() - . ' HTTP details

' - . '' - . 'click here to view details of last request
'; - return; - } catch (Zend_Gdata_App_Exception $e) { - print 'ERROR - Could not retrieve token for syndicated upload. ' - . $e->getMessage() - . '
' - . 'click here to view details of last request
'; - return; - } - - $tokenValue = $tokenArray['token']; - $postUrl = $tokenArray['url']; - - // place to redirect user after upload - if (!$nextUrl) { - $nextUrl = $_SESSION['homeUrl']; - } - - print <<< END -
- - - - -END; -} - -/** - * Deletes a Video. - * - * @param string $videoId Id of the video to be deleted. - * @return void - */ -function deleteVideo($videoId) -{ - $httpClient = getAuthSubHttpClient(); - $youTubeService = new Zend_Gdata_YouTube($httpClient); - $feed = $youTubeService->getVideoFeed('http://gdata.youtube.com/feeds/users/default/uploads'); - $videoEntryToDelete = null; - - foreach($feed as $entry) { - if ($entry->getVideoId() == $videoId) { - $videoEntryToDelete = $entry; - break; - } - } - - // check if videoEntryToUpdate was found - if (!$videoEntryToDelete instanceof Zend_Gdata_YouTube_VideoEntry) { - print 'ERROR - Could not find a video entry with id ' . $videoId . '
'; - return; - } - - try { - $httpResponse = $youTubeService->delete($videoEntryToDelete); - if (loggingEnabled()) { - logMessage($httpClient->getLastRequest(), 'request'); - logMessage($httpClient->getLastResponse()->getBody(), 'response'); - } - - } catch (Zend_Gdata_App_HttpException $httpException) { - print 'ERROR ' . $httpException->getMessage() - . ' HTTP details

' - . '' - . 'click here to view details of last request
'; - return; - } catch (Zend_Gdata_App_Exception $e) { - print 'ERROR - Could not delete video: '. $e->getMessage(); - return; - } - - print 'Entry deleted succesfully.
' . $httpResponse->getBody() - . '
(refresh your video listing)
' - . printCacheWarning(); -} - -/** - * Enables logging. - * - * @param string $loggingOption 'on' to turn logging on, 'off' to turn logging off. - * @param integer|null $maxLogItems Maximum items to log, default is 10. - * @return void - */ -function setLogging($loggingOption, $maxLogItems = 10) -{ - switch ($loggingOption) { - case 'on' : - $_SESSION['logging'] = 'on'; - $_SESSION['log_currentCounter'] = 0; - $_SESSION['log_maxLogEntries'] = $maxLogItems; - break; - - case 'off': - $_SESSION['logging'] = 'off'; - break; - } -} - -/** - * Check whether logging is enabled. - * - * @return boolean Return true if session variable for logging is set to 'on'. - */ -function loggingEnabled() -{ - if ($_SESSION['logging'] == 'on') { - return true; - } -} - -/** - * Unset a specific session variable. - * - * @param string $name Name of the session variable to delete. - * @return void - */ -function clearSessionVar($name) -{ - if (isset($_SESSION[$name])) { - unset($_SESSION[$name]); - } - header('Location: session_details.php'); -} - -/** - * Generate an AuthSub request Link and print it to the page. - * - * @param string $nextUrl URL to redirect to after performing the authentication. - * @return void - */ -function generateAuthSubRequestLink($nextUrl = null) -{ - $scope = 'http://gdata.youtube.com'; - $secure = false; - $session = true; - - if (!$nextUrl) { - generateUrlInformation(); - $nextUrl = $_SESSION['operationsUrl']; - } - - $url = Zend_Gdata_AuthSub::getAuthSubTokenUri($nextUrl, $scope, $secure, $session); - echo 'Click here to authenticate with YouTube'; -} - -/** - * Upgrade the single-use token to a session token. - * - * @param string $singleUseToken A valid single use token that is upgradable to a session token. - * @return void - */ -function updateAuthSubToken($singleUseToken) -{ - try { - $sessionToken = Zend_Gdata_AuthSub::getAuthSubSessionToken($singleUseToken); - } catch (Zend_Gdata_App_Exception $e) { - print 'ERROR - Token upgrade for ' . $singleUseToken - . ' failed : ' . $e->getMessage(); - return; - } - - $_SESSION['sessionToken'] = $sessionToken; - generateUrlInformation(); - header('Location: ' . $_SESSION['homeUrl']); -} - -/** - * Convenience method to obtain an authenticted Zend_Http_Client object. - * - * @return Zend_Http_Client An authenticated client. - */ -function getAuthSubHttpClient() -{ - try { - $httpClient = Zend_Gdata_AuthSub::getHttpClient($_SESSION['sessionToken']); - } catch (Zend_Gdata_App_Exception $e) { - print 'ERROR - Could not obtain authenticated Http client object. ' - . $e->getMessage(); - return; - } - $httpClient->setHeaders('X-GData-Key', 'key='. $_SESSION['developerKey']); - return $httpClient; -} - -/** - * Echo img tags for the first thumbnail representing each video in the - * specified video feed. Upon clicking the thumbnails, the video should - * be presented. - * - * @param Zend_Gdata_YouTube_VideoFeed $feed The video feed - * @return void - */ -function echoThumbnails($feed) -{ - foreach ($feed as $entry) { - $videoId = $entry->getVideoId(); - $firstThumbnail = htmlspecialchars( - $entry->mediaGroup->thumbnail[0]->url); - echo ''; - } -} - -/** - * Echo the list of videos in the specified feed. - * - * @param Zend_Gdata_YouTube_VideoFeed $feed The video feed. - * @param boolean|null $authenticated If true then the videoList will - * attempt to create additional forms to edit video meta-data. - * @return void - */ -function echoVideoList($feed, $authenticated = false) -{ - $table = '
Ran PHP Installation Checker on " . - gmdate('c') . "
" . $key . "Tested
No errors found
Tested
" . $error_count . "" . $error . "
Not tested
'; - $results = 0; - - foreach ($feed as $entry) { - $videoId = $entry->getVideoId(); - $thumbnailUrl = 'notfound.jpg'; - if (count($entry->mediaGroup->thumbnail) > 0) { - $thumbnailUrl = htmlspecialchars( - $entry->mediaGroup->thumbnail[0]->url); - } - - $videoTitle = htmlspecialchars($entry->getVideoTitle()); - $videoDescription = htmlspecialchars($entry->getVideoDescription()); - $videoCategory = htmlspecialchars($entry->getVideoCategory()); - $videoTags = $entry->getVideoTags(); - - $table .= '' - . '' - . ''; - $results++; - } - - if ($results < 1) { - echo '
No results found

'; - } else { - echo $table .'
'. stripslashes($videoTitle) . '' - . '

' - . stripslashes($videoDescription) . '

' - . '

category: ' . $videoCategory - . '

tagged: ' - . htmlspecialchars(implode(', ', $videoTags)) . '

'; - - if ($authenticated) { - $table .= '

' - . 'edit video data | ' - . 'delete this video


'; - } - - $table .= '

'; - } -} - -/** - * Echo the video embed code, related videos and videos owned by the same user - * as the specified videoId. - * - * @param string $videoId The video - * @return void - */ -function echoVideoPlayer($videoId) -{ - $youTubeService = new Zend_Gdata_YouTube(); - - try { - $entry = $youTubeService->getVideoEntry($videoId); - } catch (Zend_Gdata_App_HttpException $httpException) { - print 'ERROR ' . $httpException->getMessage() - . ' HTTP details

' - . '' - . 'click here to view details of last request
'; - return; - } - - $videoTitle = htmlspecialchars($entry->getVideoTitle()); - $videoUrl = htmlspecialchars(findFlashUrl($entry)); - $relatedVideoFeed = getRelatedVideos($entry->getVideoId()); - $topRatedFeed = getTopRatedVideosByUser($entry->author[0]->name); - - print <<$videoTitle
- - - - - -END; - - echo '
'; - echoVideoMetadata($entry); - echo '
Related:
'; - echoThumbnails($relatedVideoFeed); - echo '
Top rated videos by user:
'; - echoThumbnails($topRatedFeed); -} - -/** - * Returns a feed of videos related to the specified video - * - * @param string $videoId The video - * @return Zend_Gdata_YouTube_VideoFeed The feed of related videos - */ -function getRelatedVideos($videoId) -{ - $youTubeService = new Zend_Gdata_YouTube(); - $ytQuery = $youTubeService->newVideoQuery(); - // show videos related to the specified video - $ytQuery->setFeedType('related', $videoId); - // order videos by rating - $ytQuery->setOrderBy('rating'); - // retrieve a maximum of 5 videos - $ytQuery->setMaxResults(5); - // retrieve only embeddable videos - $ytQuery->setFormat(5); - return $youTubeService->getVideoFeed($ytQuery); -} - -/** - * Returns a feed of top rated videos for the specified user - * - * @param string $user The username - * @return Zend_Gdata_YouTube_VideoFeed The feed of top rated videos - */ -function getTopRatedVideosByUser($user) -{ - $userVideosUrl = 'http://gdata.youtube.com/feeds/users/' . - $user . '/uploads'; - $youTubeService = new Zend_Gdata_YouTube(); - $ytQuery = $youTubeService->newVideoQuery($userVideosUrl); - // order by the rating of the videos - $ytQuery->setOrderBy('rating'); - // retrieve a maximum of 5 videos - $ytQuery->setMaxResults(5); - // retrieve only embeddable videos - $ytQuery->setFormat(5); - return $youTubeService->getVideoFeed($ytQuery); -} - -/** - * Echo video metadata - * - * @param Zend_Gdata_YouTube_VideoEntry $entry The video entry - * @return void - */ -function echoVideoMetadata($entry) -{ - $title = htmlspecialchars($entry->getVideoTitle()); - $description = htmlspecialchars($entry->getVideoDescription()); - $authorUsername = htmlspecialchars($entry->author[0]->name); - $authorUrl = 'http://www.youtube.com/profile?user=' . - $authorUsername; - $tags = htmlspecialchars(implode(', ', $entry->getVideoTags())); - $duration = htmlspecialchars($entry->getVideoDuration()); - $watchPage = htmlspecialchars($entry->getVideoWatchPageUrl()); - $viewCount = htmlspecialchars($entry->getVideoViewCount()); - $rating = 0; - if (isset($entry->rating->average)) { - $rating = $entry->rating->average; - } - $numRaters = 0; - if (isset($entry->rating->numRaters)) { - $numRaters = $entry->rating->numRaters; - } - $flashUrl = htmlspecialchars(findFlashUrl($entry)); - print <<Title: ${title}
- Description: ${description}
- Author: ${authorUsername}
- Tags: ${tags}
- Duration: ${duration} seconds
- View count: ${viewCount}
- Rating: ${rating} (${numRaters} ratings)
- Flash: ${flashUrl}
- Watch page: ${watchPage}
-END; -} - -/** - * Print message about YouTube caching. - * - * @return string A message - */ -function printCacheWarning() -{ - return '

' - . 'Please note that the change may not be reflected in the API ' - . 'immediately due to caching.
' - . 'Please refer to the API documentation for more details.

'; -} - -/** - * Retrieve playlists for the currently authenticated user and print. - * @return void - */ -function retrievePlaylists() -{ - $httpClient = getAuthSubHttpClient(); - $youTubeService = new Zend_Gdata_YouTube($httpClient); - $feed = $youTubeService->getPlaylistListFeed('default'); - - if (loggingEnabled()) { - logMessage($httpClient->getLastRequest(), 'request'); - logMessage($httpClient->getLastResponse()->getBody(), 'response'); - } - - if (!$feed instanceof Zend_Gdata_YouTube_PlaylistListFeed) { - print 'ERROR - Could not retrieve playlists
'. - printCacheWarning(); - return; - } - - $playlistEntries = '
    '; - $entriesFound = 0; - foreach($feed as $entry) { - $playlistTitle = $entry->getTitleValue(); - $playlistDescription = $entry->getDescription()->getText(); - $playlistEntries .= '
  • ' . $playlistTitle - . '

    ' . $playlistDescription . ' | ' - . 'update | ' - . 'delete
  • '; - $entriesFound++; - } - - $playlistEntries .= '

' - . 'Add new playlist
' - . '
'; - - if (loggingEnabled()) { - logMessage($httpClient->getLastRequest(), 'request'); - logMessage($httpClient->getLastResponse()->getBody(), 'response'); - } - if ($entriesFound > 0) { - print $playlistEntries; - } else { - print 'No playlists found'; - } -} - -/** - * Create a new playlist for the currently authenticated user - * - * @param string $playlistTitle Title of the new playlist - * @param string $playlistDescription Description for the new playlist - * @return void - */ -function createPlaylist($playlistTitle, $playlistDescription) -{ - $httpClient = getAuthSubHttpClient(); - $youTubeService = new Zend_Gdata_YouTube($httpClient); - $feed = $youTubeService->getPlaylistListFeed('default'); - if (loggingEnabled()) { - logMessage($httpClient->getLastRequest(), 'request'); - logMessage($httpClient->getLastResponse()->getBody(), 'response'); - } - - $newPlaylist = $youTubeService->newPlaylistListEntry(); - $newPlaylist->description = $youTubeService->newDescription()->setText($playlistDescription); - $newPlaylist->title = $youTubeService->newTitle()->setText($playlistDescription); - - if (!$feed instanceof Zend_Gdata_YouTube_PlaylistListFeed) { - print 'ERROR - Could not retrieve playlists
' - . printCacheWarning(); - return; - } - - $playlistFeedUrl = 'http://gdata.youtube.com/feeds/users/default/playlists'; - - try { - $updatedEntry = $youTubeService->insertEntry($newPlaylist, $playlistFeedUrl); - if (loggingEnabled()) { - logMessage($httpClient->getLastRequest(), 'request'); - logMessage($httpClient->getLastResponse()->getBody(), 'response'); - } - } catch (Zend_Gdata_App_HttpException $httpException) { - print 'ERROR ' . $httpException->getMessage() - . ' HTTP details

' - . '' - . 'click here to view details of last request
'; - return; - } catch (Zend_Gdata_App_Exception $e) { - print 'ERROR - Could not create new playlist: ' . $e->getMessage(); - return; - } - - print 'Playlist added succesfully.
(refresh your playlist listing)
' - . printCacheWarning(); -} - -/** - * Delete a playlist - * - * @param string $playlistTitle Title of the playlist to be deleted - * @return void - */ -function deletePlaylist($playlistTitle) -{ - $httpClient = getAuthSubHttpClient(); - $youTubeService = new Zend_Gdata_YouTube($httpClient); - $feed = $youTubeService->getPlaylistListFeed('default'); - if (loggingEnabled()) { - logMessage($httpClient->getLastRequest(), 'request'); - logMessage($httpClient->getLastResponse()->getBody(), 'response'); - } - - $playlistEntryToDelete = null; - - foreach($feed as $playlistEntry) { - if ($playlistEntry->getTitleValue() == $playlistTitle) { - $playlistEntryToDelete = $playlistEntry; - break; - } - } - - if (!$playlistEntryToDelete instanceof Zend_Gdata_YouTube_PlaylistListEntry) { - print 'ERROR - Could not retrieve playlist to be deleted
' - . printCacheWarning(); - return; - } - - try { - $response = $playlistEntryToDelete->delete(); - if (loggingEnabled()) { - logMessage($httpClient->getLastRequest(), 'request'); - logMessage($httpClient->getLastResponse()->getBody(), 'response'); - } - } catch (Zend_Gdata_App_HttpException $httpException) { - print 'ERROR ' . $httpException->getMessage() - . ' HTTP details

' - . '' - . 'click here to view details of last request
'; - return; - } catch (Zend_Gdata_App_Exception $e) { - print 'ERROR - Could not delete the playlist: ' . $e->getMessage(); - return; - } - - print 'Playlist deleted succesfully.
' - . '' - . '(refresh your playlist listing)
' . printCacheWarning(); -} - -/** - * Delete a playlist - * - * @param string $newplaylistTitle New title for the playlist to be updated - * @param string $newPlaylistDescription New description for the playlist to be updated - * @param string $oldPlaylistTitle Title of the playlist to be updated - * @return void - */ -function updatePlaylist($newPlaylistTitle, $newPlaylistDescription, $oldPlaylistTitle) -{ - $httpClient = getAuthSubHttpClient(); - $youTubeService = new Zend_Gdata_YouTube($httpClient); - $feed = $youTubeService->getPlaylistListFeed('default'); - - if (loggingEnabled()) { - logMessage($httpClient->getLastRequest(), 'request'); - logMessage($httpClient->getLastResponse()->getBody(), 'response'); - } - - $playlistEntryToDelete = null; - - foreach($feed as $playlistEntry) { - if ($playlistEntry->getTitleValue() == $oldplaylistTitle) { - $playlistEntryToDelete = $playlistEntry; - break; - } - } - - if (!$playlistEntryToDelete instanceof Zend_Gdata_YouTube_PlaylistListEntry) { - print 'ERROR - Could not retrieve playlist to be updated
' - . printCacheWarning(); - return; - } - - try { - $response = $playlistEntryToDelete->delete(); - if (loggingEnabled()) { - logMessage($httpClient->getLastRequest(), 'request'); - logMessage($httpClient->getLastResponse()->getBody(), 'response'); - } - } catch (Zend_Gdata_App_HttpException $httpException) { - print 'ERROR ' . $httpException->getMessage() - . ' HTTP details

' - . '' - . 'click here to view details of last request
'; - return; - } catch (Zend_Gdata_App_Exception $e) { - print 'ERROR - Could not delete the playlist: ' . $e->getMessage(); - return; - } - - print 'Playlist deleted succesfully.
(refresh your playlist listing)
'. - printCacheWarning(); -} - -/** - * Helper function if an unsupported operation is passed into this files main loop. - * - * @param array $post (Optional) The post variables that accompanied the operation, if available. - * @return void - */ -function unsupportedOperation($_POST) -{ - $message = 'ERROR An unsupported operation has been called - post variables received ' - . print_r($_POST, true); - - if (loggingEnabled()) { - logMessage($message, 'error'); - } - print $message; -} - -?> diff --git a/demos/Zend/Gdata/YouTubeVideoApp/session_details.php b/demos/Zend/Gdata/YouTubeVideoApp/session_details.php deleted file mode 100755 index 40cd1f475df..00000000000 --- a/demos/Zend/Gdata/YouTubeVideoApp/session_details.php +++ /dev/null @@ -1,66 +0,0 @@ -= 5.1.4 - * This sample is run from within a web browser. These files are required: - * session_details.php - a script to view log output and session variables - * operations.php - the main logic, which interfaces with the YouTube API - * index.php - the HTML to represent the web UI, contains some PHP - * video_app.css - the CSS to define the interface style - * video_app.js - the JavaScript used to provide the video list AJAX interface - * - * NOTE: If using in production, some additional precautions with regards - * to filtering the input data should be used. This code is designed only - * for demonstration purposes. - */ -session_start(); -?> - - - YouTube data API Video Browser in PHP - Session Viewer - - - - -
-
-

Session variables


-
- $value) { - - print '

'. $key . '

'. $value .'

'. - '
' . - ''. - ''. - '

'; -} -?> -
-back -
\ No newline at end of file diff --git a/demos/Zend/Gdata/YouTubeVideoApp/video_app.css b/demos/Zend/Gdata/YouTubeVideoApp/video_app.css deleted file mode 100755 index 0e4a743e059..00000000000 --- a/demos/Zend/Gdata/YouTubeVideoApp/video_app.css +++ /dev/null @@ -1,236 +0,0 @@ -body { - background-color: #fff; - color: #232323; - font-family: Arial, sans-serif; - font-size: small; - margin: 8px; - margin-top: 3px; -} - -/* TODO jhartman --> swap out with css from app engine apps -*/ - - -img { - border: 0; -} - -table { - border-collapse: collapse; -} - -th, td { - padding: 0; - vertical-align: top; - text-align: left; -} - -a:link { - color: #0000cc; -} - -a:active { - color: #cc0000; -} - -a:visited { - color: #551a8b; -} - -h1 { - font-size: x-large; - margin-top: 0px; - margin-bottom: 5px; -} - -h2 { - font-size: large; -} - -h3 { - font-size: medium; -} - -h4 { - font-size: small; -} - -form { - display: inline; - margin: 0; - padding: 0; -} - -li { - margin-bottom: 0.25em; -} - -pre, code { - color: #007000; - font-family: "bogus font here", monospace; - font-size: 100%; -} - -pre { - border: 1px solid silver; - background-color: #f5f5f5; - padding: 0.5em; - overflow: auto; - margin: 2em; -} - -pre ins { - color: #cc0000; - font-weight: bold; - text-decoration: none; -} - -/* forms */ -textarea { - width: 600px; - border: 1px solid #ddd; - padding: 5px; -} - -.submit { - border: 1px solid #ddd; -} - -input, select{ - border: 1px solid #ddd; - margin-bottom: 2px; -} - -hr { - border: none; - border-bottom: 1px solid #ddd; -} - -/* "Selected" links */ -a.selected, .selected a, .selected { - color: black; - font-weight: bold; - text-decoration: none; -} - -a.selected:visited, .selected a:visited { - color: black; -} - -p.videoDescription { - margin: 0; - padding: 0; - overflow: scroll; - font-size: small; -} - -p.videoCategory { - margin: 0; - padding: 0; - /* overflow: scroll; */ - font-size: x-small; -} - -p.videoTags { - margin: 0; - padding: 0; - /* overflow: scroll; */ - font-size: x-small; -} - -p.edit { - font-size: small; -} - -.note { - padding: 2px; - background-color: yellow; - color: #000; -} - -#editForm { - font-size: small; -} - -table.videoList { - width: 100%; -} - -.videoList td { - padding: 10px 0px 5px 5px; - border-bottom: 1px solid silver; -} - -#titleBar { - border: 1px solid silver; - background-color: #e5ecf9; - margin: 0; - padding: 0; - padding-top: 5px; - padding-bottom: 10px; - padding-left: 10px; - padding-right: 10px; - margin-top: 5px; - margin-bottom: 15px; -} - -#titleText { - float: left; -} - -#searchBox { - float: right; -} - -#authStatus { - border-bottom: 1px solid #ddd; - padding: 2px; - margin-bottom: 10px; - -} - -#main { - margin: 10px; -} - -#mainSessions { - background-color: #ddd; - padding: 10px; -} - -#searchResults { - width: 100%; - background-color: silver; -} - -#searchResultsListColumn { - float: left; - width: 47%; - margin-bottom: 20px; - padding-right: 2px; -} - -#searchResultsVideoColumn { - float: right; - width: 47%; - padding-left: 5px; - border-left: 1px solid #ddd; - -} - -#sessionVariable { - font-family: Courier, monospace; - background-color: #fff; - padding: 10px; - width: 80%; - overflow: scroll; -} - -.thumbnail { - padding: 0px 0px 0px 2px; -} - -#imageLoadThumbnail { - padding: 4px; - background-color: #333; -} diff --git a/demos/Zend/Gdata/YouTubeVideoApp/video_app.js b/demos/Zend/Gdata/YouTubeVideoApp/video_app.js deleted file mode 100755 index db46ac19127..00000000000 --- a/demos/Zend/Gdata/YouTubeVideoApp/video_app.js +++ /dev/null @@ -1,582 +0,0 @@ -/** - * Zend Framework - * - * LICENSE - * - * This source file is subject to the new BSD license that is bundled - * with this package in the file LICENSE.txt. - * It is also available through the world-wide-web at this URL: - * http://framework.zend.com/license/new-bsd - * If you did not receive a copy of the license and are unable to - * obtain it through the world-wide-web, please send an email - * to license@zend.com so we can send you a copy immediately. - * - * @category Zend - * @package Zend_Gdata - * @copyright Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com) - * @license http://framework.zend.com/license/new-bsd New BSD License - */ - -/** - * @fileoverview Provides functions for browsing and searching YouTube - * data API feeds, as well as performing authentication, syndicated uploads - * and playlist management using a PHP backend powered by the Zend_Gdata component - * of Zend Framework. - */ - -/** - * provides namespacing for the YouTube Video Application PHP version (ytVideoApp) - */ -var ytVideoApp = {}; - -/** - * maximum number of results to return for list of videos - * @type Number - */ -ytVideoApp.MAX_RESULTS_LIST = 5; - -/** - * navigation button id used to page to the previous page of - * results in the list of videos - * @type String - */ -ytVideoApp.PREVIOUS_PAGE_BUTTON = 'previousPageButton'; - -/** - * navigation button id used to page to the next page of - * results in the list of videos - * @type String - */ -ytVideoApp.NEXT_PAGE_BUTTON = 'nextPageButton'; - -/** - * container div for navigation elements - * @type String - */ -ytVideoApp.NAVIGATION_DIV = 'navigationForm'; - -/** - * container div id used to hold list of videos - * @type String - */ -ytVideoApp.VIDEO_LIST_CONTAINER_DIV = 'searchResultsVideoList'; - -/** - * container div id used to hold video search results - * @type String - */ -ytVideoApp.VIDEO_SEARCH_RESULTS_DIV = 'searchResultsVideoColumn'; - -/** - * container div id used to hold the video player - * @type String - */ -ytVideoApp.VIDEO_PLAYER_DIV = 'videoPlayer'; - -/** - * container div id used to hold the search box displayed at the top of - * the browser after one search has already been performed - * @type String - */ -ytVideoApp.TOP_SEARCH_CONTAINER_DIV = 'searchBox'; - -/** container div to show detailed upload status - * @type String - */ -ytVideoApp.VIDEO_UPLOAD_STATUS = 'detailedUploadStatus'; - -/** - * container div to hold the form for syndicated upload - * @type String - */ -ytVideoApp.SYNDICATED_UPLOAD_DIV = 'syndicatedUploadDiv'; - -/** - * container div to hold the form to edit video meta-data - * @type String - */ -ytVideoApp.VIDEO_DATA_EDIT_DIV = 'editForm'; - -/** - * containder div to hold authentication link in special cases where auth gets - * set prior to developer key - * @type String - */ -ytVideoApp.AUTHSUB_REQUEST_DIV = 'generateAuthSubLink'; - -/** - * container div to hold the form for editing video meta-data - * @type String - */ -ytVideoApp.VIDEO_META_DATA_EDIT_DIV = 'editVideoMetaDataDiv'; - -/** - * container div to hold the form for adding a new playlist - * @type String - */ -ytVideoApp.PLAYLIST_ADD_DIV = 'addNewPlaylist'; - -/** - * the page number to use for the next page navigation button - * @type Number - */ -ytVideoApp.nextPage = 2; - -/** - * the page number to use for the previous page navigation button - * @type Number - */ -ytVideoApp.previousPage = 0; - -/** - * the last search term used to query - allows for the navigation - * buttons to know what string query to perform when clicked - * @type String - */ -ytVideoApp.previousSearchTerm = ''; - -/** - * the last query type used for querying - allows for the navigation - * buttons to know what type of query to perform when clicked - * @type String - */ -ytVideoApp.previousQueryType = 'all'; - -/** - * Retrieves a list of videos matching the provided criteria. The list of - * videos can be restricted to a particular standard feed or search criteria. - * @param {String} op The type of action to be done. - * for querying all videos, or the name of a standard feed. - * @param {String} searchTerm The search term(s) to use for querying as the - * 'vq' query parameter value - * @param {Number} page The 1-based page of results to return. - */ -ytVideoApp.listVideos = function(op, searchTerm, page) { - ytVideoApp.previousSearchTerm = searchTerm; - ytVideoApp.previousQueryType = op; - var maxResults = ytVideoApp.MAX_RESULTS_LIST; - var startIndex = (((page - 1) * ytVideoApp.MAX_RESULTS_LIST) + 1); - ytVideoApp.presentFeed(op, maxResults, startIndex, searchTerm); - ytVideoApp.updateNavigation(page); -}; - -/** - * Sends an AJAX request to the server to retrieve a list of videos or - * the video player/metadata. Sends the request to the specified filePath - * on the same host, passing the specified params, and filling the specified - * resultDivName with the resutls upon success. - * @param {String} filePath The path to which the request should be sent - * @param {String} params The URL encoded POST params - * @param {String} resultDivName The name of the DIV used to hold the results - */ -ytVideoApp.sendRequest = function(filePath, params, resultDivName) { - if (window.XMLHttpRequest) { - var xmlhr = new XMLHttpRequest(); - } else { - var xmlhr = new ActiveXObject('MSXML2.XMLHTTP.3.0'); - } - - xmlhr.open('POST', filePath); - xmlhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded'); - - xmlhr.onreadystatechange = function() { - var resultDiv = document.getElementById(resultDivName); - if (xmlhr.readyState == 1) { - resultDiv.innerHTML = 'Loading...'; - } else if (xmlhr.readyState == 4 && xmlhr.status == 200) { - if (xmlhr.responseText) { - resultDiv.innerHTML = xmlhr.responseText; - } - } else if (xmlhr.readyState == 4) { - alert('Invalid response received - Status: ' + xmlhr.status); - } - } - xmlhr.send(params); -} - -/** - * Uses ytVideoApp.sendRequest to display a YT video player and metadata for the - * specified video ID. - * @param {String} videoId The ID of the YouTube video to show - */ -ytVideoApp.presentVideo = function(videoId, updateThumbnail) { - var params = 'operation=show_video&videoId=' + videoId; - var filePath = 'operations.php'; - ytVideoApp.sendRequest(filePath, params, ytVideoApp.VIDEO_PLAYER_DIV); -} - -/** - * Creates a form to enter video meta-data in preparation for syndicated upload. - */ -ytVideoApp.prepareUploadForm = function() { - var metaDataForm = ['
', - 'Enter video title:

', - 'Enter video description:

', - 'Select a category:
', - 'Enter some tags to describe your video ', - '(separated by spaces):
', - '
', - '', - '
'].join(''); - - document.getElementById(ytVideoApp.SYNDICATED_UPLOAD_DIV).innerHTML = metaDataForm; -} - -/** - * Uses ytVideoApp.sendRequest to prepare a syndicated upload. - * - * @param {String} videoTitle The title for new video - * @param {String} videoDescription The video's description - * @param {String} videoCategory The category for the video - * @param {String} videoTags A white-space separated string of Tags - */ -ytVideoApp.prepareSyndicatedUpload = function(videoTitle, videoDescription, videoCategory, videoTags) { - var filePath = 'operations.php'; - var params = 'operation=create_upload_form' + - '&videoTitle=' + videoTitle + - '&videoDescription=' + videoDescription + - '&videoCategory=' + videoCategory + - '&videoTags=' + videoTags; - ytVideoApp.sendRequest(filePath, params, ytVideoApp.SYNDICATED_UPLOAD_DIV); -} - -/** - * Uses ytVideoApp.sendRequest to create the authSub link. - */ -ytVideoApp.presentAuthLink = function() { - var filePath = 'operations.php'; - var params = 'operation=auth_sub_request'; - ytVideoApp.sendRequest(filePath, params, ytVideoApp.AUTHSUB_REQUEST_DIV); -} - - -/** - * Uses ytVideoApp.sendRequest to check a videos upload status. - * - * @param {String} videoId The id of the video to check - */ -ytVideoApp.checkUploadDetails = function(videoId) { - var filePath = 'operations.php'; - var params = 'operation=check_upload_status' + - '&videoId=' + videoId; - ytVideoApp.sendRequest(filePath, params, ytVideoApp.VIDEO_UPLOAD_STATUS); -} - - -/** - * Creates an HTML form to edit a video's meta-data, populated with the - * videos current meta-data. - * - * @param {String} oldVideoTitle The old title of the video - * @param {String} oldVideoDescription The old description of the video - * @param {String} oldVideoCategory The old category of the video - * @param {String} oldVideoTags The old tags for the video (separated by white-space) - * @param {String} videoId The id of the video to be edited - */ -ytVideoApp.presentMetaDataEditForm = function(oldVideoTitle, oldVideoDescription, oldVideoCategory, oldVideoTags, videoId) { - // split oldVideoTags by comma and present as whitespace separated - var oldVideoTagsArray = oldVideoTags.split(','); - oldVideoTags = oldVideoTagsArray.join(' '); - var editMetaDataForm = ['
', - 'Enter a new video title:
', - '
', - 'Enter a new video description:
', - '
', - 'Select a new category:
', - 'Enter some new tags to describe your video ', - '(separated by spaces):
', - '
', - '
', - '', - '
'].join(''); - - document.getElementById(ytVideoApp.VIDEO_SEARCH_RESULTS_DIV).innerHTML = editMetaDataForm; -} - -/** - * Uses ytVideoApp.sendRequest to submit updated video meta-data. - * - * @param {String} newVideoTitle The new title of the video - * @param {String} newVideoDescription The new description of the video - * @param {String} newVideoCategory The new category of the video - * @param {String} newVideoTags The new tags for the video (separated by white-space) - * @param {String} videoId The id of the video to be edited - */ -ytVideoApp.editMetaData = function(newVideoTitle, newVideoDescription, newVideoCategory, newVideoTags, videoId) { - var filePath = 'operations.php'; - var params = 'operation=edit_meta_data' + - '&newVideoTitle=' + newVideoTitle + - '&newVideoDescription=' + newVideoDescription + - '&newVideoCategory=' + newVideoCategory + - '&newVideoTags=' + newVideoTags + - '&videoId=' + videoId; - ytVideoApp.sendRequest(filePath, params, ytVideoApp.VIDEO_SEARCH_RESULTS_DIV); -}; - - -/** - * Confirms whether user wants to delete a video. - * @param {String} videoId The video Id to be deleted - */ -ytVideoApp.confirmDeletion = function(videoId) { - var answer = confirm('Do you really want to delete the video with id: ' + videoId + ' ?'); - if (answer) { - ytVideoApp.prepareDeletion(videoId); - } -} - -/** - * Uses ytVideoApp.sendRequest to request a video to be deleted. - * @param {String} videoId The video Id to be deleted - */ -ytVideoApp.prepareDeletion = function(videoId) { - var filePath = 'operations.php'; - var params = 'operation=delete_video' + - '&videoId=' + videoId; - - var table = document.getElementById('videoResultList'); - var indexOfRowToBeDeleted = -1; - var tableRows = document.getElementsByTagName('TR'); - for (var i = 0, tableRow; tableRow = tableRows[i]; i++) { - if (tableRow.id == videoId) { - indexOfRowToBeDeleted = i; - } - } - if (indexOfRowToBeDeleted > -1) { - table.deleteRow(indexOfRowToBeDeleted); - } - ytVideoApp.sendRequest(filePath, params, ytVideoApp.VIDEO_SEARCH_RESULTS_DIV); -} - -/** - * Uses ytVideoApp.sendRequest to display a list of of YT videos. - * @param {String} op The operation to perform to retrieve a feed - * @param {Number} maxResults The maximum number of videos to list - * @param {Number} startIndex The first video to include in the list - * @param {String} searchTerm The search terms to pass to the specified feed - */ -ytVideoApp.presentFeed = function(op, maxResults, startIndex, searchTerm){ - var params = 'operation=' + op + - '&maxResults=' + maxResults + - '&startIndex=' + startIndex + - '&searchTerm=' + searchTerm; - var filePath = 'operations.php'; - ytVideoApp.sendRequest(filePath, params, ytVideoApp.VIDEO_LIST_CONTAINER_DIV); -}; - -/** - * Updates the variables used by the navigation buttons and the 'enabled' - * status of the buttons based upon the current page number passed in. - * @param {Number} page The current page number - */ -ytVideoApp.updateNavigation = function(page) { - ytVideoApp.nextPage = page + 1; - ytVideoApp.previousPage = page - 1; - document.getElementById(ytVideoApp.NEXT_PAGE_BUTTON).style.display = 'inline'; - document.getElementById(ytVideoApp.PREVIOUS_PAGE_BUTTON).style.display = 'inline'; - if (ytVideoApp.previousPage < 1) { - document.getElementById(ytVideoApp.PREVIOUS_PAGE_BUTTON).disabled = true; - } else { - document.getElementById(ytVideoApp.PREVIOUS_PAGE_BUTTON).disabled = false; - } - document.getElementById(ytVideoApp.NEXT_PAGE_BUTTON).disabled = false; -}; - -/** - * Hides the navigation. - */ -ytVideoApp.hideNavigation = function() { - document.getElementById(ytVideoApp.NAVIGATION_DIV).style.display = 'none'; -}; - -/** - * Update video results div - */ -ytVideoApp.refreshSearchResults = function() { - document.getElementById(ytVideoApp.VIDEO_SEARCH_RESULTS_DIV).innerHTML = ''; -} - -/** - * Method called when the query type has been changed. Clears out the - * value of the search term input box by default if one of the standard - * feeds is selected. This is to improve usability, as many of the standard - * feeds may not include results for even fairly popular search terms. - * @param {String} op The operation to perform. - * for querying all videos, or the name of one of the standard feeds. - * @param {Node} searchTermInputElement The HTML input element for the input - * element. - */ -ytVideoApp.queryTypeChanged = function(op, searchTermInputElement) { - if (op == 'search_username') { - searchTermInputElement.value = '-- enter username --'; - } else if (op != 'search_all') { - searchTermInputElement.value = ''; - } -}; - -/** - * Create a basic HTML form to use for creating a new playlist. - */ -ytVideoApp.prepareCreatePlaylistForm = function() { - var newPlaylistForm = ['
', - 'Enter a title for the new playlist:
', - '
', - 'Enter a description:
', - '
', - '', - '
'].join(''); - - document.getElementById(ytVideoApp.PLAYLIST_ADD_DIV).innerHTML = newPlaylistForm; -} - -/** -* Uses ytVideoApp.sendRequest to create a new playlist. -* -* @param {String} playlistTitle The title of the new playlist -* @param {String} playlistDescription A description of the new playlist -*/ -ytVideoApp.createNewPlaylist = function(playlistTitle, playlistDescription) { - var filePath = 'operations.php'; - var params = 'operation=create_playlist' + - '&playlistTitle=' + playlistTitle + - '&playlistDescription=' + playlistDescription; - ytVideoApp.hideNavigation(); - ytVideoApp.sendRequest(filePath, params, ytVideoApp.VIDEO_SEARCH_RESULTS_DIV); -} - -/** - * Confirm user wants to delete a playlist - * - * @param {String} playlistTitle The title of the playlist to be deleted - */ -ytVideoApp.confirmPlaylistDeletion = function(playlistTitle) { - var answer = confirm('Do you really want to delete the playlist titled : ' + - playlistTitle + ' ?'); - if (answer) { - ytVideoApp.deletePlaylist(playlistTitle); - } -} - -/** -* Uses ytVideoApp.sendRequest to delete a playlist. -* -* @param {String} playlistTitle The title of the new playlist -*/ -ytVideoApp.deletePlaylist = function(playlistTitle) { - var filePath = 'operations.php'; - var params = 'operation=delete_playlist' + - '&playlistTitle=' + playlistTitle; - ytVideoApp.sendRequest(filePath, params, ytVideoApp.VIDEO_SEARCH_RESULTS_DIV); -} - -/** - * Create a basic HTML form to use for modifying a playlist. - * - * @param {String} oldPlaylistTitle The old title of the playlist - * @param {String} oldPlaylistDescription The old description of the playlist - */ -ytVideoApp.prepareUpdatePlaylistForm = function(oldPlaylistTitle, oldPlaylistDescription) { - var playlistUpdateForm = ['
', - 'Enter a title for the new playlist:
', - '
', - 'Enter a description:
', - '
', - '', - '', - '
'].join(''); - - document.getElementById(ytVideoApp.VIDEO_SEARCH_RESULTS_DIV).innerHTML = playlistUpdateForm; -} - -/** -* Uses ytVideoApp.sendRequest to update a playlist. -* -* @param {String} newPlaylistTitle The new title of the playlist -* @param {String} newPlaylistDescription A new description of the playlist -*/ -ytVideoApp.updatePlaylist = function(newPlaylistTitle, newPlaylistDescription, oldPlaylistTitle) { - var filePath = 'operations.php'; - var params = 'operation=update_playlist' + - '&newPlaylistTitle=' + newPlaylistTitle + - '&newPlaylistDescription=' + newPlaylistDescription + - '&oldPlaylistTitle=' + oldPlaylistTitle; - ytVideoApp.sendRequest(filePath, params, ytVideoApp.VIDEO_LIST_CONTAINER_DIV); -} - -/** -* Uses ytVideoApp.sendRequest to retrieve a users playlist. -* -*/ -ytVideoApp.retrievePlaylists = function() { - var filePath = 'operations.php'; - var params = 'operation=retrieve_playlists'; - ytVideoApp.hideNavigation(); - ytVideoApp.sendRequest(filePath, params, ytVideoApp.VIDEO_LIST_CONTAINER_DIV); -} diff --git a/demos/Zend/Gdata/YouTubeVideoBrowser/index.php b/demos/Zend/Gdata/YouTubeVideoBrowser/index.php deleted file mode 100755 index 370afeb0990..00000000000 --- a/demos/Zend/Gdata/YouTubeVideoBrowser/index.php +++ /dev/null @@ -1,278 +0,0 @@ -= 5.1.4 - * - * This sample is run from within a web browser. These files are required: - * index.php - the main logic, which interfaces with the YouTube API - * interface.html - the HTML to represent the web UI - * web_browser.css - the CSS to define the interface style - * web_browser.js - the JavaScript used to provide the video list AJAX interface - * - * NOTE: If using in production, some additional precautions with regards - * to filtering the input data should be used. This code is designed only - * for demonstration purposes. - */ - -/** - * @see Zend_Loader - */ -require_once 'Zend/Loader.php'; - -/** - * @see Zend_Gdata_YouTube - */ -Zend_Loader::loadClass('Zend_Gdata_YouTube'); - -/** - * Finds the URL for the flash representation of the specified video - * - * @param Zend_Gdata_YouTube_VideoEntry $entry The video entry - * @return string|null The URL or null, if the URL is not found - */ -function findFlashUrl($entry) -{ - foreach ($entry->mediaGroup->content as $content) { - if ($content->type === 'application/x-shockwave-flash') { - return $content->url; - } - } - return null; -} - -/** - * Returns a feed of top rated videos for the specified user - * - * @param string $user The username - * @return Zend_Gdata_YouTube_VideoFeed The feed of top rated videos - */ -function getTopRatedVideosByUser($user) -{ - $userVideosUrl = 'http://gdata.youtube.com/feeds/users/' . - $user . '/uploads'; - $yt = new Zend_Gdata_YouTube(); - $ytQuery = $yt->newVideoQuery($userVideosUrl); - // order by the rating of the videos - $ytQuery->setOrderBy('rating'); - // retrieve a maximum of 5 videos - $ytQuery->setMaxResults(5); - // retrieve only embeddable videos - $ytQuery->setFormat(5); - return $yt->getVideoFeed($ytQuery); -} - -/** - * Returns a feed of videos related to the specified video - * - * @param string $videoId The video - * @return Zend_Gdata_YouTube_VideoFeed The feed of related videos - */ -function getRelatedVideos($videoId) -{ - $yt = new Zend_Gdata_YouTube(); - $ytQuery = $yt->newVideoQuery(); - // show videos related to the specified video - $ytQuery->setFeedType('related', $videoId); - // order videos by rating - $ytQuery->setOrderBy('rating'); - // retrieve a maximum of 5 videos - $ytQuery->setMaxResults(5); - // retrieve only embeddable videos - $ytQuery->setFormat(5); - return $yt->getVideoFeed($ytQuery); -} - -/** - * Echo img tags for the first thumbnail representing each video in the - * specified video feed. Upon clicking the thumbnails, the video should - * be presented. - * - * @param Zend_Gdata_YouTube_VideoFeed $feed The video feed - * @return void - */ -function echoThumbnails($feed) -{ - foreach ($feed as $entry) { - $videoId = $entry->getVideoId(); - echo ''; - } -} - -/** - * Echo the video embed code, related videos and videos owned by the same user - * as the specified videoId. - * - * @param string $videoId The video - * @return void - */ -function echoVideoPlayer($videoId) -{ - $yt = new Zend_Gdata_YouTube(); - - $entry = $yt->getVideoEntry($videoId); - $videoTitle = $entry->mediaGroup->title; - $videoUrl = findFlashUrl($entry); - $relatedVideoFeed = getRelatedVideos($entry->getVideoId()); - $topRatedFeed = getTopRatedVideosByUser($entry->author[0]->name); - - print <<$videoTitle
- - - - - -END; - echo '
'; - echoVideoMetadata($entry); - echo '
Related:
'; - echoThumbnails($relatedVideoFeed); - echo '
Top rated videos by user:
'; - echoThumbnails($topRatedFeed); -} - -/** - * Echo video metadata - * - * @param Zend_Gdata_YouTube_VideoEntry $entry The video entry - * @return void - */ -function echoVideoMetadata($entry) -{ - $title = $entry->mediaGroup->title; - $description = $entry->mediaGroup->description; - $authorUsername = $entry->author[0]->name; - $authorUrl = 'http://www.youtube.com/profile?user=' . $authorUsername; - $tags = $entry->mediaGroup->keywords; - $duration = $entry->mediaGroup->duration->seconds; - $watchPage = $entry->mediaGroup->player[0]->url; - $viewCount = $entry->statistics->viewCount; - $rating = $entry->rating->average; - $numRaters = $entry->rating->numRaters; - $flashUrl = findFlashUrl($entry); - print <<Title: ${title}
- Description: ${description}
- Author: ${authorUsername}
- Tags: ${tags}
- Duration: ${duration} seconds
- View count: ${viewCount}
- Rating: ${rating} (${numRaters} ratings)
- Flash: ${flashUrl}
- Watch page: ${watchPage}
-END; -} - -/** - * Echo the list of videos in the specified feed. - * - * @param Zend_Gdata_YouTube_VideoFeed $feed The video feed - * @return void - */ -function echoVideoList($feed) -{ - echo ''; - echo ''; - foreach ($feed as $entry) { - $videoId = $entry->getVideoId(); - $thumbnailUrl = $entry->mediaGroup->thumbnail[0]->url; - $videoTitle = $entry->mediaGroup->title; - $videoDescription = $entry->mediaGroup->description; - print << - - - -END; - } - echo '
- ${videoTitle} -

${videoDescription}

-
'; -} - -/* - * The main controller logic of the YouTube video browser demonstration app. - */ -$queryType = isset($_POST['queryType']) ? $_POST['queryType'] : null; - -if ($queryType === null) { - /* display the entire interface */ - include 'interface.html'; -} else if ($queryType == 'show_video') { - /* display an individual video */ - if (array_key_exists('videoId', $_POST)) { - $videoId = $_POST['videoId']; - echoVideoPlayer($videoId); - } else if (array_key_exists('videoId', $_GET)) { - $videoId = $_GET['videoId']; - echoVideoPlayer($videoId); - } else { - echo 'No videoId found.'; - exit; - } -} else { - /* display a list of videos */ - $searchTerm = $_POST['searchTerm']; - $startIndex = $_POST['startIndex']; - $maxResults = $_POST['maxResults']; - - $yt = new Zend_Gdata_YouTube(); - $query = $yt->newVideoQuery(); - $query->setQuery($searchTerm); - $query->setStartIndex($startIndex); - $query->setMaxResults($maxResults); - - /* check for one of the standard feeds, or list from 'all' videos */ - switch ($queryType) { - case 'most_viewed': - $query->setFeedType('most viewed'); - $query->setTime('this_week'); - $feed = $yt->getVideoFeed($query); - break; - case 'most_recent': - $query->setFeedType('most recent'); - $feed = $yt->getVideoFeed($query); - break; - case 'recently_featured': - $query->setFeedType('recently featured'); - $feed = $yt->getVideoFeed($query); - break; - case 'top_rated': - $query->setFeedType('top rated'); - $query->setTime('this_week'); - $feed = $yt->getVideoFeed($query); - break; - case 'all': - $feed = $yt->getVideoFeed($query); - break; - default: - echo 'ERROR - unknown queryType - "' . $queryType . '"'; - break; - } - echoVideoList($feed); -} diff --git a/demos/Zend/Gdata/YouTubeVideoBrowser/interface.html b/demos/Zend/Gdata/YouTubeVideoBrowser/interface.html deleted file mode 100644 index bff0dfa4d7d..00000000000 --- a/demos/Zend/Gdata/YouTubeVideoBrowser/interface.html +++ /dev/null @@ -1,79 +0,0 @@ - - - - YouTube data API Video Browser in PHP - - - - -
-
-

YouTube data API Video Browser in PHP

- -
-
-
-
-

Search YouTube:

-
- - - -
-
-
-
-
-
-
- -
-
-
-
-
-
-
- - diff --git a/demos/Zend/Gdata/YouTubeVideoBrowser/video_browser.css b/demos/Zend/Gdata/YouTubeVideoBrowser/video_browser.css deleted file mode 100644 index 1984ed996b1..00000000000 --- a/demos/Zend/Gdata/YouTubeVideoBrowser/video_browser.css +++ /dev/null @@ -1,152 +0,0 @@ -body { - background-color: white; - color: black; - font-family: Arial, sans-serif; - font-size: small; - margin: 8px; - margin-top: 3px; -} - -img { - border: 0; -} - -table { - border-collapse: collapse; -} - -th, td { - padding: 0; - vertical-align: top; - text-align: left; -} - -a:link { - color: #0000cc; -} - -a:active { - color: #cc0000; -} - -a:visited { - color: #551a8b; -} - -h1 { - font-size: x-large; - margin-top: 0px; - margin-bottom: 5px; -} - -h2 { - font-size: large; -} - -h3 { - font-size: medium; -} - -h4 { - font-size: small; -} - -form { - display: inline; - margin: 0; - padding: 0; -} - -li { - margin-bottom: 0.25em; -} - -pre, code { - color: #007000; - font-family: "bogus font here", monospace; - font-size: 100%; -} - -pre { - border: 1px solid silver; - background-color: #f5f5f5; - padding: 0.5em; - overflow: auto; - margin: 2em; -} - -pre ins { - color: #cc0000; - font-weight: bold; - text-decoration: none; -} - -/* "Selected" links */ - -a.selected, .selected a, .selected { - color: black; - font-weight: bold; - text-decoration: none; -} - -a.selected:visited, .selected a:visited { - color: black; -} - -p.videoDescription { - font-size: small; - margin: 0; - padding: 0; -} - -.videoList td { - padding-bottom: 5px; - padding-right: 5px; -} - -#titleBar { - border: 1px solid silver; - background-color: #e5ecf9; - font-size: large; - font-weight: bold; - margin: 0; - padding: 0; - padding-top: 5px; - padding-bottom: 10px; - padding-left: 10px; - padding-right: 10px; - margin-top: 5px; - margin-bottom: 15px; -} - -#titleText { - float: left; -} - -#searchBox { - float: right; -} - -#mainSearchBox { - background-color: #e5ecf9; - border: 1px solid silver; - width: 250; - padding-top: 5px; - padding-bottom: 5px; - padding-left: 10px; - padding-right: 10px; -} - -#searchResults { - width: 100%; -} - -#searchResultsListColumn { - float: left; - width: 47%; -} - -#searchResultsVideoColumn { - float: right; - width: 47%; -} diff --git a/demos/Zend/Gdata/YouTubeVideoBrowser/video_browser.js b/demos/Zend/Gdata/YouTubeVideoBrowser/video_browser.js deleted file mode 100644 index 71a840f617e..00000000000 --- a/demos/Zend/Gdata/YouTubeVideoBrowser/video_browser.js +++ /dev/null @@ -1,228 +0,0 @@ -/** - * Zend Framework - * - * LICENSE - * - * This source file is subject to the new BSD license that is bundled - * with this package in the file LICENSE.txt. - * It is also available through the world-wide-web at this URL: - * http://framework.zend.com/license/new-bsd - * If you did not receive a copy of the license and are unable to - * obtain it through the world-wide-web, please send an email - * to license@zend.com so we can send you a copy immediately. - * - * @category Zend - * @package Zend_Gdata - * @subpackage Demos - * @copyright Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com) - * @license http://framework.zend.com/license/new-bsd New BSD License - */ - -/** - * @fileoverview Provides functions for browsing and searching YouTube - * data API feeds using a PHP backend powered by the Zend_Gdata component - * of the Zend Framework. - */ - -/** - * provides namespacing for the YouTube Video Browser PHP version (ytvbp) - */ -var ytvbp = {}; - -/** - * maximum number of results to return for list of videos - * @type Number - */ -ytvbp.MAX_RESULTS_LIST = 5; - -/** - * navigation button id used to page to the previous page of - * results in the list of videos - * @type String - */ -ytvbp.PREVIOUS_PAGE_BUTTON = 'previousPageButton'; - -/** - * navigation button id used to page to the next page of - * results in the list of videos - * @type String - */ -ytvbp.NEXT_PAGE_BUTTON = 'nextPageButton'; - -/** - * container div id used to hold list of videos - * @type String - */ -ytvbp.VIDEO_LIST_CONTAINER_DIV = 'searchResultsVideoList'; - -/** - * container div id used to hold the video player - * @type String - */ -ytvbp.VIDEO_PLAYER_DIV = 'videoPlayer'; - -/** - * container div id used to hold the search box which displays when the page - * first loads - * @type String - */ -ytvbp.MAIN_SEARCH_CONTAINER_DIV = 'mainSearchBox'; - -/** - * container div id used to hold the search box displayed at the top of - * the browser after one search has already been performed - * @type String - */ -ytvbp.TOP_SEARCH_CONTAINER_DIV = 'searchBox'; - -/** - * the page number to use for the next page navigation button - * @type Number - */ -ytvbp.nextPage = 2; - -/** - * the page number to use for the previous page navigation button - * @type Number - */ -ytvbp.previousPage = 0; - -/** - * the last search term used to query - allows for the navigation - * buttons to know what string query to perform when clicked - * @type String - */ -ytvbp.previousSearchTerm = ''; - -/** - * the last query type used for querying - allows for the navigation - * buttons to know what type of query to perform when clicked - * @type String - */ -ytvbp.previousQueryType = 'all'; - -/** - * Retrieves a list of videos matching the provided criteria. The list of - * videos can be restricted to a particular standard feed or search criteria. - * @param {String} queryType The type of query to be done - either 'all' - * for querying all videos, or the name of a standard feed. - * @param {String} searchTerm The search term(s) to use for querying as the - * 'vq' query parameter value - * @param {Number} page The 1-based page of results to return. - */ -ytvbp.listVideos = function(queryType, searchTerm, page) { - ytvbp.previousSearchTerm = searchTerm; - ytvbp.previousQueryType = queryType; - var maxResults = ytvbp.MAX_RESULTS_LIST; - var startIndex = (((page - 1) * ytvbp.MAX_RESULTS_LIST) + 1); - ytvbp.presentFeed(queryType, maxResults, startIndex, searchTerm); - ytvbp.updateNavigation(page); -}; - -/** - * Sends an AJAX request to the server to retrieve a list of videos or - * the video player/metadata. Sends the request to the specified filePath - * on the same host, passing the specified params, and filling the specified - * resultDivName with the resutls upon success. - * @param {String} filePath The path to which the request should be sent - * @param {String} params The URL encoded POST params - * @param {String} resultDivName The name of the DIV used to hold the results - */ -ytvbp.sendRequest = function(filePath, params, resultDivName) { - if (window.XMLHttpRequest) { - var xmlhr = new XMLHttpRequest(); - } else { - var xmlhr = new ActiveXObject('MSXML2.XMLHTTP.3.0'); - } - - xmlhr.open('POST', filePath, true); - xmlhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded'); - - xmlhr.onreadystatechange = function() { - var resultDiv = document.getElementById(resultDivName); - if (xmlhr.readyState == 1) { - resultDiv.innerHTML = 'Loading...'; - } else if (xmlhr.readyState == 4 && xmlhr.status == 200) { - if (xmlhr.responseText) { - resultDiv.innerHTML = xmlhr.responseText; - } - } else if (xmlhr.readyState == 4) { - alert('Invalid response received - Status: ' + xmlhr.status); - } - } - xmlhr.send(params); -} - -/** - * Uses ytvbp.sendRequest to display a YT video player and metadata for the - * specified video ID. - * @param {String} videoId The ID of the YouTube video to show - */ -ytvbp.presentVideo = function(videoId) { - var params = 'queryType=show_video&videoId=' + videoId; - var filePath = 'index.php'; - ytvbp.sendRequest(filePath, params, ytvbp.VIDEO_PLAYER_DIV); -} - -/** - * Uses ytvbp.sendRequest to display a list of of YT videos. - * @param {String} queryType The name of a standard video feed or 'all' - * @param {Number} maxResults The maximum number of videos to list - * @param {Number} startIndex The first video to include in the list - * @param {String} searchTerm The search terms to pass to the specified feed - */ -ytvbp.presentFeed = function(queryType, maxResults, startIndex, searchTerm){ - var params = 'queryType=' + queryType + - '&maxResults=' + maxResults + - '&startIndex=' + startIndex + - '&searchTerm=' + searchTerm; - var filePath = 'index.php'; - ytvbp.sendRequest(filePath, params, ytvbp.VIDEO_LIST_CONTAINER_DIV); -} - -/** - * Updates the variables used by the navigation buttons and the 'enabled' - * status of the buttons based upon the current page number passed in. - * @param {Number} page The current page number - */ -ytvbp.updateNavigation = function(page) { - ytvbp.nextPage = page + 1; - ytvbp.previousPage = page - 1; - document.getElementById(ytvbp.NEXT_PAGE_BUTTON).style.display = 'inline'; - document.getElementById(ytvbp.PREVIOUS_PAGE_BUTTON).style.display = 'inline'; - if (ytvbp.previousPage < 1) { - document.getElementById(ytvbp.PREVIOUS_PAGE_BUTTON).disabled = true; - } else { - document.getElementById(ytvbp.PREVIOUS_PAGE_BUTTON).disabled = false; - } - document.getElementById(ytvbp.NEXT_PAGE_BUTTON).disabled = false; -}; - -/** - * Hides the main (large) search form and enables one that's in the - * title bar of the application. The main search form is only used - * for the first load. Subsequent searches should use the version in - * the title bar. - */ -ytvbp.hideMainSearch = function() { - document.getElementById(ytvbp.MAIN_SEARCH_CONTAINER_DIV).style.display = - 'none'; - document.getElementById(ytvbp.TOP_SEARCH_CONTAINER_DIV).style.display = - 'inline'; -}; - -/** - * Method called when the query type has been changed. Clears out the - * value of the search term input box by default if one of the standard - * feeds is selected. This is to improve usability, as many of the standard - * feeds may not include results for even fairly popular search terms. - * @param {String} queryType The type of query being done - either 'all' - * for querying all videos, or the name of one of the standard feeds. - * @param {Node} searchTermInputElement The HTML input element for the input - * element. - */ -ytvbp.queryTypeChanged = function(queryType, searchTermInputElement) { - if (queryType != 'all') { - searchTermInputElement.value = ''; - } -}; diff --git a/demos/Zend/Locale/AllLanguages.php b/demos/Zend/Locale/AllLanguages.php deleted file mode 100644 index 2227d2931b3..00000000000 --- a/demos/Zend/Locale/AllLanguages.php +++ /dev/null @@ -1,43 +0,0 @@ - $content) { - try { - $lang = Zend_Locale::getTranslation($language, 'language', $language); - print "\n
[".$language."] ".$lang; - } catch (Exception $e) { - // no output - } -} diff --git a/demos/Zend/Mail/SimpleMailer.php b/demos/Zend/Mail/SimpleMailer.php deleted file mode 100644 index 4b960ba561b..00000000000 --- a/demos/Zend/Mail/SimpleMailer.php +++ /dev/null @@ -1,449 +0,0 @@ - 'SSL' - * or - * 'ssl' => 'TLS' - * if you want to use ssl support. - * - * Because of problems with Windows filenames (maildir needs : in filenames) the maildir folder is in a tar. - * Untar maildir.tar in maildir/ to test maildir support (won't work on Windows). - * - * The structure of the class is very simple. Every method named show...() output HTML, run() inits mail storage - * after login and calls a show method, everything else inits and checks variables and mail storage handler. - * - * @category Zend - * @package Zend_Mail - * @subpackage Demos - * @copyright Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com) - * @license http://framework.zend.com/license/new-bsd New BSD License - */ -class Demo_Zend_Mail_SimpleMailer -{ - /** - * Mail storage type (mbox, mbox-folder, maildir, maildir-folder, pop3, imap) - * - * @var string - */ - private $type; - - /** - * Filename, dirname or hostname for current mailstorage - * - * @var string - */ - private $param; - - /** - * Selected mail message or null if none - * - * @var integer - */ - private $messageNum; - - /** - * Mail storage handler - * - * @var Zend_Mail_Storage - */ - private $mail; - - /** - * Query string with current selection for output - * - * @var string - */ - private $queryString; - - /** - * Don't run run(), needed for auth - * - * @var boolean - */ - private $noRun = false; - - /** - * Init class for run() and output - * - * @return void - */ - function __construct() - { - $this->initVars(); - $this->loadClasses(); - $this->whitelistParam(); - - // we use http auth for username and password or mail storage - if (($this->type == 'pop3' || $this->type == 'imap') && !isset($_SERVER['PHP_AUTH_USER'])) { - $this->needAuth(); - return; - } - - switch ($this->type) { - case 'mbox': - $this->mail = new Zend_Mail_Storage_Mbox(array('filename' => $this->param)); - break; - case 'mbox-folder': - $this->mail = new Zend_Mail_Storage_Folder_Mbox(array('dirname' => $this->param)); - break; - case 'maildir': - $this->mail = new Zend_Mail_Storage_Maildir(array('dirname' => $this->param)); - break; - case 'maildir-folder': - $this->mail = new Zend_Mail_Storage_Folder_Maildir(array('dirname' => $this->param)); - break; - case 'pop3': - $this->mail = new Zend_Mail_Storage_Pop3(array('host' => $this->param, - 'user' => $_SERVER['PHP_AUTH_USER'], - 'password' => $_SERVER['PHP_AUTH_PW'])); - break; - case 'imap': - $this->mail = new Zend_Mail_Storage_Imap(array('host' => $this->param, - 'user' => $_SERVER['PHP_AUTH_USER'], - 'password' => $_SERVER['PHP_AUTH_PW'])); - break; - default: - $this->mail = null; - break; - } - } - - /** - * Check parameter and type - * - * @return void - */ - function whitelistParam() - { - $whitelist = array('mbox' => array('mbox/INBOX', 'mbox/subfolder/test'), - 'mbox-folder' => array('mbox'), - 'maildir' => array('maildir', 'maildir/.subfolder', 'maildir/.subfolder.test'), - 'maildir-folder' => array('maildir', 'maildir/.subfolder', 'maildir/.subfolder.test'), - 'pop3' => array(), - 'imap' => array()); - - if ($this->type === null || @$whitelist[$this->type] === array() || @in_array($this->param, $whitelist[$this->type])) { - return; - } - - throw new Exception('Unknown type or param not in whitelist'); - } - - /** - * Load needed classes - * - * @return void - */ - function loadClasses() - { - $classname = array('mbox' => 'Zend_Mail_Storage_Mbox', - 'mbox-folder' => 'Zend_Mail_Storage_Folder_Mbox', - 'maildir' => 'Zend_Mail_Storage_Maildir', - 'maildir-folder' => 'Zend_Mail_Storage_Folder_Maildir', - 'pop3' => 'Zend_Mail_Storage_Pop3', - 'imap' => 'Zend_Mail_Storage_Imap'); - - if (isset($classname[$this->type])) { - Zend_Loader::loadClass($classname[$this->type]); - } - - Zend_Loader::loadClass('Zend_Mail_Storage'); - } - - /** - * Init variables - * - * @return void - */ - function initVars() - { - $this->type = isset($_GET['type']) ? $_GET['type'] : null; - $this->param = isset($_GET['param']) ? $_GET['param'] : null; - $this->folder = isset($_GET['folder']) ? $_GET['folder'] : null; - $this->messageNum = isset($_GET['message']) && is_numeric($_GET['message']) ? $_GET['message'] : null; - $this->queryString = http_build_query(array('type' => $this->type, - 'param' => $this->param, - 'folder' => $this->folder)); - } - - /** - * Send http auth headers, for username and password in pop3 and imap - * - * @return void - */ - function needAuth() - { - header("WWW-Authenticate: Basic realm='{$this->type} credentials'"); - header('HTTP/1.0 401 Please enter credentials'); - $this->noRun = true; - } - - /** - * Get data from mail storage and output html - * - * @return void - */ - function run() - { - if ($this->noRun) { - return; - } - - if ($this->mail instanceof Zend_Mail_Storage_Folder_Interface && $this->folder) { - // could also be done in constructor of $this->mail with parameter 'folder' => '...' - $this->mail->selectFolder($this->folder); - } - - $message = null; - try { - if ($this->messageNum) { - $message = $this->mail->getMessage($this->messageNum); - } - } catch(Zend_Mail_Exception $e) { - // ignored, $message is still null and we display the list - } - - if (!$this->mail) { - $this->showChooseType(); - } else if ($message) { - $this->showMessage($message); - } else { - $this->showList(); - } - } - - /** - * Output html header - * - * @param string $title page title - * @return void - */ - function showHeader($title) - { - echo " - {$title} - -

{$title}

"; - } - - /** - * Output html footer - * - * @return void - */ - function showFooter() - { - echo ''; - } - - /** - * Output type selection AKA "login-form" - * - * @return void - */ - function showChooseType() - { - $this->showHeader('Choose Type'); - - echo '
-
- -
-
- -
-
- -
-
- -
-
- -
-
'; - - $this->showFooter(); - } - - /** - * Output mail message - * - * @return void - */ - function showMessage($message) - { - try { - $from = $message->from; - } catch(Zend_Mail_Exception $e) { - $from = '(unknown)'; - } - - try { - $to = $message->to; - } catch(Zend_Mail_Exception $e) { - $to = '(unknown)'; - } - - try { - $subject = $message->subject; - } catch(Zend_Mail_Exception $e) { - $subject = '(unknown)'; - } - - $this->showHeader($subject); - - echo " - - -
From:$from
Subject:$subject
To:$to
"; - - if ($message->isMultipart()) { - echo '
'; - foreach (new RecursiveIteratorIterator($message) as $part) { - echo "
Part with type {$part->contentType}:
"; - echo htmlentities($part); - echo '
'; - } - echo '
'; - } else { - echo htmlentities($message->getContent()); - } - - echo "
back to list"; - - if ($this->messageNum > 1) { - echo " - queryString}&message=", $this->messageNum - 1, '">prev'; - } - - if ($this->messageNum < $this->mail->countMessages()) { - echo " - queryString}&message=", $this->messageNum + 1, '">next'; - } - - $this->showFooter(); - } - - /** - * Output message list - * - * @return void - */ - function showList() - { - $this->showHeader('Overview'); - - echo ''; - - foreach ($this->mail as $num => $message) { - if ($this->mail->hasFlags) { - $class = array(); - - if ($message->hasFlag(Zend_Mail_Storage::FLAG_RECENT)) { - $class['unread'] = 'unread'; - $class['new'] = 'new'; - } - if (!$message->hasFlag(Zend_Mail_Storage::FLAG_SEEN)) { - $class['unread'] = 'unread'; - } - if ($message->hasFlag(Zend_Mail_Storage::FLAG_FLAGGED)) { - $class['flagged'] = 'flagged'; - } - - $class = implode(' ', $class); - echo ""; - } else { - echo ''; - } - - echo ""; - - try { - echo ""; - } catch(Zend_Mail_Exception $e){ - echo ''; - } - - echo ''; - } - - echo '
FromToSubject
read{$message->from}{$message->to}{$message->subject}error
'; - - if ($this->mail instanceof Zend_Mail_Storage_Folder_Interface) { - $this->showFolders(); - } - - $this->showFooter(); - } - - /** - * Output folder list - * - * @return void - */ - function showFolders() - { - echo "
- -
"; - } -} - -// init and run mailer -$SimpleMailer = new Demo_Zend_Mail_SimpleMailer(); -$SimpleMailer->run(); diff --git a/demos/Zend/Mail/maildir/maildir.tar b/demos/Zend/Mail/maildir/maildir.tar deleted file mode 100644 index 4084bd88043..00000000000 Binary files a/demos/Zend/Mail/maildir/maildir.tar and /dev/null differ diff --git a/demos/Zend/Mail/mbox/INBOX b/demos/Zend/Mail/mbox/INBOX deleted file mode 100644 index 03c81a4d95d..00000000000 --- a/demos/Zend/Mail/mbox/INBOX +++ /dev/null @@ -1,100 +0,0 @@ -From next-message@example.com Mon Jan 00 00:00:00 0000 -Return-Path: -Delivered-To: to@example.com -Received: by example.com - id 1; Sun, 30 Apr 2006 19:00:00 +0200 (CEST) -Received: by localhost - id 1; Sun, 30 Apr 2006 19:10:00 +0200 (CEST) -To: to@example.com -Subject: Simple Message -Message-Id: <20060430185000.1@example.com> -Date: Sun, 30 Apr 2006 18:50:00 +0200 (CEST) -From: from@example.com - -This is a simple test message -From next-message@example.com Mon Jan 00 00:00:00 0000 -To: bar@example.com -Subject: A Really Simple Message -From: foo@example.com - -Message - -From next-message@example.com Mon Jan 00 00:00:00 0000 -To: river@example.com -Subject: To the River -Date: Sun, 01 Jan 1829 00:00:00 +0000 -From: poe@example.com -Message-Id: <18290101000000.0000@example.com> -Content-type: text/plain -MIME-version: 1.0 -X-Twin: the good -X-Twin: the evil - -Fair river! in thy bright, clear flow -Of crystal, wandering water, -Thou art an emblem of the glow -Of beautythe unhidden heart -The playful maziness of art -In old Alberto's daughter; - -But when within thy wave she looks -Which glistens then, and trembles -Why, then, the prettiest of brooks -Her worshipper resembles; -For in his heart, as in thy stream, -Her image deeply lies -His heart which trembles at the beam -Of her soul-searching eyes. - -From next-message@example.com Mon Jan 00 00:00:00 0000 -To: foo@example.com -Subject: multipart -Date: Sun, 01 Jan 2000 00:00:00 +0000 -From: crazy@example.com -Content-type: multipart/alternative; boundary="crazy-multipart" -MIME-version: 1.0 - -multipart message ---crazy-multipart -Content-type: text/plain - -The first part -is horizontal - ---crazy-multipart -Content-type: text/x-vertical - -T s p i v -h e a s e -e c r r - o t t - n i - d c - a - l ---crazy-multipart-- - -From next-message@example.com Mon Jan 00 00:00:00 0000 -To: foo@example.com -Subject: multipart -Date: Sun, 01 Jan 2000 01:00:00 +0000 -From: normal@example.com -Content-type: multipart/alternative; boundary="normal-multipart" -MIME-version: 1.0 - -multipart message ---normal-multipart -Content-type: text/html - - - -Again a simple message - ---normal-multipart -Content-type: text/plain - -Again a simple message ---normal-multipart-- \ No newline at end of file diff --git a/demos/Zend/Mail/mbox/subfolder/test b/demos/Zend/Mail/mbox/subfolder/test deleted file mode 100644 index c59490e4521..00000000000 --- a/demos/Zend/Mail/mbox/subfolder/test +++ /dev/null @@ -1,14 +0,0 @@ -From next-message@example.com Mon Jan 00 00:00:00 0000 -Return-Path: -Delivered-To: to@example.com -Received: by example.com - id 1; Sun, 30 May 2006 19:00:00 +0200 (CEST) -Received: by localhost - id 1; Sun, 30 May 2006 19:10:00 +0200 (CEST) -To: to@example.com -Subject: Message in subfolder -Message-Id: <20060530185000.1@example.com> -Date: Sun, 30 May 2006 18:50:00 +0200 (CEST) -From: from@example.com - -This is the message in the subfolder \ No newline at end of file diff --git a/demos/Zend/OpenId/login-bg.gif b/demos/Zend/OpenId/login-bg.gif deleted file mode 100644 index cde836c893f..00000000000 Binary files a/demos/Zend/OpenId/login-bg.gif and /dev/null differ diff --git a/demos/Zend/OpenId/mvc_auth/application/controllers/ErrorController.php b/demos/Zend/OpenId/mvc_auth/application/controllers/ErrorController.php deleted file mode 100644 index daf4aaec42d..00000000000 --- a/demos/Zend/OpenId/mvc_auth/application/controllers/ErrorController.php +++ /dev/null @@ -1,64 +0,0 @@ -_getParam('error_handler', false); - if (!$errors) { - // Unknown application error - return $this->render('500'); - } - - switch ($errors->type) { - case Zend_Controller_Plugin_ErrorHandler::EXCEPTION_NO_CONTROLLER: - case Zend_Controller_Plugin_ErrorHandler::EXCEPTION_NO_ACTION: - // Page not found (404) error - $this->render('404'); - break; - default: - // Application (500) error - $this->render('500'); - break; - } - } -} diff --git a/demos/Zend/OpenId/mvc_auth/application/controllers/IndexController.php b/demos/Zend/OpenId/mvc_auth/application/controllers/IndexController.php deleted file mode 100644 index b58691f0ceb..00000000000 --- a/demos/Zend/OpenId/mvc_auth/application/controllers/IndexController.php +++ /dev/null @@ -1,112 +0,0 @@ -hasIdentity()) { - $this->_redirect('/index/login'); - } else { - $this->_redirect('/index/welcome'); - } - } - - /** - * welcomeAction - * - * @return void - */ - public function welcomeAction() - { - $auth = Zend_Auth::getInstance(); - if (!$auth->hasIdentity()) { - $this->_redirect('index/login'); - } - $this->view->user = $auth->getIdentity(); - } - - /** - * loginAction - * - * @return void - */ - public function loginAction() - { - $this->view->status = ""; - if (($this->_request->isPost() && - $this->_request->getPost('openid_action') == 'login' && - $this->_request->getPost('openid_identifier', '') !== '') || - ($this->_request->isPost() && - $this->_request->getPost('openid_mode') !== null) || - (!$this->_request->isPost() && - $this->_request->getQuery('openid_mode') != null)) { - Zend_Loader::loadClass('Zend_Auth_Adapter_OpenId'); - $auth = Zend_Auth::getInstance(); - $result = $auth->authenticate( - new Zend_Auth_Adapter_OpenId($this->_request->getPost('openid_identifier'))); - if ($result->isValid()) { - $this->_redirect('/index/welcome'); - } else { - $auth->clearIdentity(); - foreach ($result->getMessages() as $message) { - $this->view->status .= "$message
\n"; - } - } - } - $this->render(); - } - - /** - * logoutAction - * - * @return void - */ - public function logoutAction() - { - Zend_Auth::getInstance()->clearIdentity(); - $this->_redirect('/index/index'); - } -} diff --git a/demos/Zend/OpenId/mvc_auth/application/views/scripts/error/404.phtml b/demos/Zend/OpenId/mvc_auth/application/views/scripts/error/404.phtml deleted file mode 100644 index d4aa37821a2..00000000000 --- a/demos/Zend/OpenId/mvc_auth/application/views/scripts/error/404.phtml +++ /dev/null @@ -1,12 +0,0 @@ - - - - - ZF OpenId Auth Application - - -Page not found! - - diff --git a/demos/Zend/OpenId/mvc_auth/application/views/scripts/error/500.phtml b/demos/Zend/OpenId/mvc_auth/application/views/scripts/error/500.phtml deleted file mode 100644 index c7c48d19465..00000000000 --- a/demos/Zend/OpenId/mvc_auth/application/views/scripts/error/500.phtml +++ /dev/null @@ -1,12 +0,0 @@ - - - - - ZF OpenId Auth Application - - -An error occurred in this application! - - diff --git a/demos/Zend/OpenId/mvc_auth/application/views/scripts/index/login.phtml b/demos/Zend/OpenId/mvc_auth/application/views/scripts/index/login.phtml deleted file mode 100644 index ddb5f0b9e65..00000000000 --- a/demos/Zend/OpenId/mvc_auth/application/views/scripts/index/login.phtml +++ /dev/null @@ -1,17 +0,0 @@ - - - - - ZF OpenId Auth Application - - -status; ?> -
-OpenID Login - - -
- - \ No newline at end of file diff --git a/demos/Zend/OpenId/mvc_auth/application/views/scripts/index/welcome.phtml b/demos/Zend/OpenId/mvc_auth/application/views/scripts/index/welcome.phtml deleted file mode 100644 index df7f628d26b..00000000000 --- a/demos/Zend/OpenId/mvc_auth/application/views/scripts/index/welcome.phtml +++ /dev/null @@ -1,14 +0,0 @@ - - - - - ZF OpenId Auth Application - - -Hello user; ?>! -
-logout - - diff --git a/demos/Zend/OpenId/mvc_auth/html/.htaccess b/demos/Zend/OpenId/mvc_auth/html/.htaccess deleted file mode 100644 index 06cc9adafcd..00000000000 --- a/demos/Zend/OpenId/mvc_auth/html/.htaccess +++ /dev/null @@ -1,2 +0,0 @@ -RewriteEngine on -RewriteRule !\.(js|ico|gif|jpg|png|css|php)$ index.php diff --git a/demos/Zend/OpenId/mvc_auth/html/config.ini b/demos/Zend/OpenId/mvc_auth/html/config.ini deleted file mode 100644 index de05220d657..00000000000 --- a/demos/Zend/OpenId/mvc_auth/html/config.ini +++ /dev/null @@ -1 +0,0 @@ -baseUrl=/demos/Zend/OpenId/mvc_auth/html \ No newline at end of file diff --git a/demos/Zend/OpenId/mvc_auth/html/index.php b/demos/Zend/OpenId/mvc_auth/html/index.php deleted file mode 100644 index 4a66a3772fc..00000000000 --- a/demos/Zend/OpenId/mvc_auth/html/index.php +++ /dev/null @@ -1,36 +0,0 @@ -setControllerDirectory(dirname(__DIR__) . '/application/controllers') - ->setBaseUrl($config->baseUrl); -$front->dispatch(); diff --git a/demos/Zend/OpenId/templates/identity.phtml b/demos/Zend/OpenId/templates/identity.phtml deleted file mode 100644 index a1f3eea2393..00000000000 --- a/demos/Zend/OpenId/templates/identity.phtml +++ /dev/null @@ -1,9 +0,0 @@ - - -Zend OpenID Server Example - - - -server . '?openid=' . $this->name;?> - - diff --git a/demos/Zend/OpenId/templates/identity2.phtml b/demos/Zend/OpenId/templates/identity2.phtml deleted file mode 100644 index 3cd7cd412a6..00000000000 --- a/demos/Zend/OpenId/templates/identity2.phtml +++ /dev/null @@ -1,10 +0,0 @@ - - -Zend OpenID Server Example - - - - -server . '?openid2=' . $this->name;?> - - diff --git a/demos/Zend/OpenId/templates/login.phtml b/demos/Zend/OpenId/templates/login.phtml deleted file mode 100644 index 28288a1da13..00000000000 --- a/demos/Zend/OpenId/templates/login.phtml +++ /dev/null @@ -1,83 +0,0 @@ - - - -Zend OpenID Server Example - - - - -error)) { - echo ''; -} -?> -
-
-
-OpenID Login - -
- - -id)) { - echo ' value="' . $this->id . '"'; - } - if (isset($this->ro)) { - echo ' readonly="1" disabled="1">'."\n"; - echo '> -
- - - -
  - -
-ro)) { - echo '
'; - echo 'register'; - } - -?> -
-
-
- - diff --git a/demos/Zend/OpenId/templates/profile.phtml b/demos/Zend/OpenId/templates/profile.phtml deleted file mode 100644 index 36f9d295fa2..00000000000 --- a/demos/Zend/OpenId/templates/profile.phtml +++ /dev/null @@ -1,14 +0,0 @@ - - - -Zend OpenID Server Example - - -

Your are logged in as url;?>

-
-LogOut -

Trusted Sites:

- -sites;?> -
- diff --git a/demos/Zend/OpenId/templates/register.phtml b/demos/Zend/OpenId/templates/register.phtml deleted file mode 100644 index 0b6157af5e6..00000000000 --- a/demos/Zend/OpenId/templates/register.phtml +++ /dev/null @@ -1,69 +0,0 @@ - - - -Zend OpenID Server Example - - - - -error)) { - echo ''; -} -?> -
-
-
-Register OpenID Account - -
- - -name)) {echo ' value="' . $this->name . '"';} ?>> -
- - - -
- - - -
  - -
-
-
-
- - diff --git a/demos/Zend/OpenId/templates/registration_complete.phtml b/demos/Zend/OpenId/templates/registration_complete.phtml deleted file mode 100644 index 15661e15890..00000000000 --- a/demos/Zend/OpenId/templates/registration_complete.phtml +++ /dev/null @@ -1,11 +0,0 @@ - - - -Zend OpenID Server Example - - -

Than you for registration!

-

Your OpenID identity url;?>

-

You also can use OpenID 2.0 identity url2;?>

- - \ No newline at end of file diff --git a/demos/Zend/OpenId/templates/trust.phtml b/demos/Zend/OpenId/templates/trust.phtml deleted file mode 100644 index 0c7a3645f24..00000000000 --- a/demos/Zend/OpenId/templates/trust.phtml +++ /dev/null @@ -1,18 +0,0 @@ - - - -Zend OpenID Server Example - - -

A site identifying as site;?> has asked us for confirmation that url;?> is your identity URL.

-
-sreg;?> - -
- -
- - -
- - diff --git a/demos/Zend/OpenId/test_auth.php b/demos/Zend/OpenId/test_auth.php deleted file mode 100644 index 5e872ac693c..00000000000 --- a/demos/Zend/OpenId/test_auth.php +++ /dev/null @@ -1,68 +0,0 @@ -authenticate( - new Zend_Auth_Adapter_OpenId(@$_POST['openid_identifier'])); - if ($result->isValid()) { - Zend_OpenId::redirect(Zend_OpenId::selfURL()); - } else { - $auth->clearIdentity(); - foreach ($result->getMessages() as $message) { - $status .= "$message
\n"; - } - } -} else if ($auth->hasIdentity()) { - if (isset($_POST['openid_action']) && - $_POST['openid_action'] == "logout") { - $auth->clearIdentity(); - } else { - $status = "You are logged-in as " . $auth->getIdentity() . "
\n"; - } -} -?> - - -
-OpenID Login - - - -
diff --git a/demos/Zend/OpenId/test_consumer.php b/demos/Zend/OpenId/test_consumer.php deleted file mode 100644 index 30048258e99..00000000000 --- a/demos/Zend/OpenId/test_consumer.php +++ /dev/null @@ -1,128 +0,0 @@ -login($id, null, null, $sreg)) { - $status = "OpenID login failed (".$consumer->getError().")"; - } -} else if (isset($_GET['openid_mode'])) { - if ($_GET['openid_mode'] == "id_res") { - $sreg = new Zend_OpenId_Extension_Sreg(); - $consumer = new Zend_OpenId_Consumer(); - if ($consumer->verify($_GET, $id, $sreg)) { - $status = "VALID $id"; - $data = $sreg->getProperties(); - } else { - $status = "INVALID $id (".$consumer->getError().")"; - } - } else if ($_GET['openid_mode'] == "cancel") { - $status = "CANCELED"; - } -} -$sreg_html = ""; -$sreg = new Zend_OpenId_Extension_Sreg(); -foreach (Zend_OpenId_Extension_Sreg::getSregProperties() as $prop) { - $val = isset($data[$prop]) ? $data[$prop] : ""; - $sreg_html .= <<$prop - - - - - - - - $val - -EOF; -} -?> - - - -Zend OpenID Consumer Example - - - -\n";?> -
-
-
-OpenID Login - -
- - - - -\n";?> -
 requirdoptionalnone 
-
-register -
-
-
-
- - diff --git a/demos/Zend/OpenId/test_server.php b/demos/Zend/OpenId/test_server.php deleted file mode 100644 index 27a6563e95c..00000000000 --- a/demos/Zend/OpenId/test_server.php +++ /dev/null @@ -1,268 +0,0 @@ - $val) { - $str .= "$key:\"$val\";"; - } - } - $trusted = true; - } - $s = '
' - . '' - . '' - . '' - . $site -// . '' -// . ($trusted ? 'allowed' : 'denied') - . '' - . ($trusted ? - '' : - '') - . '' - . '' - . ''.$str.'' - . '
'; - return $s; -} - -/** - * sreg_form - * - * @param Zend_OpenId_Extension_Sreg $sreg - * @return string - */ -function sreg_form(Zend_OpenId_Extension_Sreg $sreg) -{ - $s = ""; - $props = $sreg->getProperties(); - if (is_array($props) && count($props) > 0) { - $s = 'It also requests additinal information about you'; - $s .= ' (fields marked by * are required)
'; - $s .= ''; - foreach ($props as $prop => $val) { - if ($val) { - $s .= ''; - } else { - $s .= ''; - } - $value = ""; - $s .= ''; - } - $s .= '
'.$prop.':*
'.$prop.':

'; - $policy = $sreg->getPolicyUrl(); - if (!empty($policy)) { - $s .= 'The private policy can be found at '.$policy.'.
'; - } - } - return $s; -} - -$session = new Zend_Session_Namespace("opeinid.server"); -Zend_Session::start(); - -$ret = false; -if ($_SERVER["REQUEST_METHOD"] == "GET") { - if (!isset($_GET['openid_action']) && isset($_GET['openid_mode'])) { - $ret = $server->handle($_GET, new Zend_OpenId_Extension_Sreg()); - } else { - require_once 'Zend/View.php'; - - $view = new Zend_View(); - $view->setScriptPath(__DIR__ . '/templates'); - $view->strictVars(true); - - if (isset($session->id)) { - $view->id = $session->id; - } - if (isset($session->error)) { - $view->error = $session->error; - unset($session->error); - } - if (isset($_GET['openid_action'])) { - if ($_GET['openid_action'] == 'register') { - $ret = $view->render('register.phtml'); - } else if ($_GET['openid_action'] == 'registration_complete' && - isset($_GET['openid_name'])) { - $view->name = $_GET['openid_name']; - $view->url = Zend_OpenId::selfURL() . '?openid=' . $view->name; - if ($server->hasUser($view->url)) { - $view->url2 = Zend_OpenId::selfURL() . '?openid2=' . $view->name; - $ret = $view->render('registration_complete.phtml'); - } - } else if ($_GET['openid_action'] == 'logout') { - $server->logout(); - header('Location: ' . $_SERVER['PHP_SELF']); - exit; - } else if ($_GET['openid_action'] == 'login') { - if (isset($_GET['openid_identity'])) { - $view->id = $_GET['openid_identity']; - $view->ro = true; - } - $ret = $view->render('login.phtml'); - } else if ($_GET['openid_action'] == 'trust') { - if ($server->getLoggedInUser() !== false) { - $view->site = $server->getSiteRoot($_GET); - $view->url = $server->getLoggedInUser(); - $sreg = new Zend_OpenId_Extension_Sreg(); - $sreg->parseRequest($_GET); - $view->sreg = sreg_form($sreg); - if ($server->hasUser($view->url)) { - $ret = $view->render('trust.phtml'); - } - } - } - } else if (isset($_GET['openid'])) { - $url = Zend_OpenId::selfURL() . '?openid=' . $_GET['openid']; - if ($server->hasUser($url)) { - $view->server = Zend_OpenId::selfURL(); - $view->name = $_GET['openid']; - $ret = $view->render('identity.phtml'); - } - } else if (isset($_GET['openid2'])) { - $url = Zend_OpenId::selfURL() . '?openid=' . $_GET['openid2']; - if ($server->hasUser($url)) { - $view->server = Zend_OpenId::selfURL(); - $view->name = $_GET['openid2']; - $ret = $view->render('identity2.phtml'); - } - } else { - if ($server->getLoggedInUser() !== false) { - $view->url = $server->getLoggedInUser(); - if ($server->hasUser($view->url)) { - $sites = $server->getTrustedSites(); - $s = ""; - foreach ($sites as $site => $trusted) { - if (is_bool($trusted) || is_array($trusted)) { - $s .= trust_form($site, $trusted); - } - } - if (empty($s)) { - $s = "None"; - } - $view->sites = $s; - $ret = $view->render('profile.phtml'); - } - } else { - $ret = $view->render('login.phtml'); - } - } - } -} else if ($_SERVER["REQUEST_METHOD"] == "POST") { - if (!isset($_POST['openid_action']) && isset($_POST['openid_mode'])) { - $ret = $server->handle($_POST, new Zend_OpenId_Extension_Sreg()); - } else if (isset($_POST['openid_action'])) { - if ($_POST['openid_action'] == 'login' && - isset($_POST['openid_url']) && - isset($_POST['openid_password'])) { - if (!$server->login($_POST['openid_url'], - $_POST['openid_password'])) { - $session->error = 'Wrong identity/password!'; - $session->id = $_POST['openid_url']; - } - unset($_GET['openid_action']); - Zend_OpenId::redirect($_SERVER['PHP_SELF'], $_GET); - } else if ($_POST['openid_action'] == 'register' && - isset($_POST['openid_name']) && - isset($_POST['openid_password']) && - isset($_POST['openid_password2'])) { - - $url = Zend_OpenId::selfURL() . '?openid=' . $_POST['openid_name']; - if ($_POST['openid_password'] != $_POST['openid_password2']) { - $session->name = $_POST['openid_name']; - $session->error = 'Password mismatch.'; - header('Location: ' . $_SERVER['PHP_SELF'] . '?openid.action=register'); - } else if ($server->register($url, $_POST['openid_password'])) { - header('Location: ' . $_SERVER['PHP_SELF'] . '?openid.action=registration_complete&openid.name=' . $_POST['openid_name']); - } else { - $session->error = 'Registration failed. Try another name.'; - header('Location: ' . $_SERVER['PHP_SELF'] . '?openid.action=register'); - } - exit; - } else if ($_POST['openid_action'] == 'trust') { - if (isset($_GET['openid_return_to'])) { - $sreg = new Zend_OpenId_Extension_Sreg(); - $sreg->parseResponse($_POST); - if (isset($_POST['allow'])) { - if (isset($_POST['forever'])) { - $server->allowSite($server->getSiteRoot($_GET), $sreg); - } - unset($_GET['openid_action']); - $server->respondToConsumer($_GET, $sreg); - } else if (isset($_POST['deny'])) { - if (isset($_POST['forever'])) { - $server->denySite($server->getSiteRoot($_GET)); - } - Zend_OpenId::redirect($_GET['openid_return_to'], array('openid.mode'=>'cancel')); - } - } else if (isset($_POST['allow'])) { - $server->allowSite($_POST['site']); - header('Location: ' . $_SERVER['PHP_SELF']); - exit; - } else if (isset($_POST['deny'])) { - $server->denySite($_POST['site']); - header('Location: ' . $_SERVER['PHP_SELF']); - exit; - } else if (isset($_POST['del'])) { - $server->delSite($_POST['site']); - header('Location: ' . $_SERVER['PHP_SELF']); - exit; - } - } - } -} -if (is_string($ret)) { - echo $ret; -} else if ($ret !== true) { - header('HTTP/1.0 403 Forbidden'); - echo 'Forbidden'; -} diff --git a/demos/Zend/Pdf/demo.php b/demos/Zend/Pdf/demo.php deleted file mode 100644 index 6acc4c0cead..00000000000 --- a/demos/Zend/Pdf/demo.php +++ /dev/null @@ -1,268 +0,0 @@ - []\n"; - exit; -} - -try { - $pdf = Zend_Pdf::load($argv[1]); -} catch (Zend_Pdf_Exception $e) { - if ($e->getMessage() == 'Can not open \'' . $argv[1] . '\' file for reading.') { - // Create new PDF if file doesn't exist - $pdf = new Zend_Pdf(); - - if (!isset($argv[2])) { - // force complete file rewriting (instead of updating) - $argv[2] = $argv[1]; - } - } else { - // Throw an exception if it's not the "Can't open file" exception - throw $e; - } -} - -//------------------------------------------------------------------------------------ -// Reverse page order -$pdf->pages = array_reverse($pdf->pages); - -// Create new Style -$style = new Zend_Pdf_Style(); -$style->setFillColor(new Zend_Pdf_Color_Rgb(0, 0, 0.9)); -$style->setLineColor(new Zend_Pdf_Color_GrayScale(0.2)); -$style->setLineWidth(3); -$style->setLineDashingPattern(array(3, 2, 3, 4), 1.6); -$style->setFont(Zend_Pdf_Font::fontWithName(Zend_Pdf_Font::FONT_HELVETICA_BOLD), 32); - -try { - // Create new image object - require_once 'Zend/Pdf/Image.php'; - $stampImage = Zend_Pdf_Image::imageWithPath(__DIR__ . '/stamp.jpg'); -} catch (Zend_Pdf_Exception $e) { - // Example of operating with image loading exceptions. - if ($e->getMessage() != 'Image extension is not installed.' && - $e->getMessage() != 'JPG support is not configured properly.') { - throw $e; - } - $stampImage = null; -} - -// Mark page as modified -foreach ($pdf->pages as $page){ - $page->saveGS() - ->setAlpha(0.25) - ->setStyle($style) - ->rotate(0, 0, M_PI_2/3); - - $page->saveGS(); - $page->clipCircle(550, -10, 50); - if ($stampImage != null) { - $page->drawImage($stampImage, 500, -60, 600, 40); - } - $page->restoreGS(); - - $page->drawText('Modified by Zend Framework!', 150, 0) - ->restoreGS(); -} - -// Add new page generated by Zend_Pdf object (page is attached to the specified the document) -$pdf->pages[] = ($page1 = $pdf->newPage('A4')); - -// Add new page generated by Zend_Pdf_Page object (page is not attached to the document) -$pdf->pages[] = ($page2 = new Zend_Pdf_Page(Zend_Pdf_Page::SIZE_LETTER_LANDSCAPE)); - -// Create new font -$font = Zend_Pdf_Font::fontWithName(Zend_Pdf_Font::FONT_HELVETICA); - -// Apply font and draw text -$page1->setFont($font, 36) - ->setFillColor(Zend_Pdf_Color_Html::color('#9999cc')) - ->drawText('Helvetica 36 text string', 60, 500); - -// Use font object for another page -$page2->setFont($font, 24) - ->drawText('Helvetica 24 text string', 60, 500); - -// Use another font -$page2->setFont(Zend_Pdf_Font::fontWithName(Zend_Pdf_Font::FONT_TIMES), 32) - ->drawText('Times-Roman 32 text string', 60, 450); - -// Draw rectangle -$page2->setFillColor(new Zend_Pdf_Color_GrayScale(0.8)) - ->setLineColor(new Zend_Pdf_Color_GrayScale(0.2)) - ->setLineDashingPattern(array(3, 2, 3, 4), 1.6) - ->drawRectangle(60, 400, 400, 350); - -// Draw circle -$page2->setLineDashingPattern(Zend_Pdf_Page::LINE_DASHING_SOLID) - ->setFillColor(new Zend_Pdf_Color_Rgb(1, 0, 0)) - ->drawCircle(85, 375, 25); - -// Draw sectors -$page2->drawCircle(200, 375, 25, 2*M_PI/3, -M_PI/6) - ->setFillColor(new Zend_Pdf_Color_Cmyk(1, 0, 0, 0)) - ->drawCircle(200, 375, 25, M_PI/6, 2*M_PI/3) - ->setFillColor(new Zend_Pdf_Color_Rgb(1, 1, 0)) - ->drawCircle(200, 375, 25, -M_PI/6, M_PI/6); - -// Draw ellipse -$page2->setFillColor(new Zend_Pdf_Color_Rgb(1, 0, 0)) - ->drawEllipse(250, 400, 400, 350) - ->setFillColor(new Zend_Pdf_Color_Cmyk(1, 0, 0, 0)) - ->drawEllipse(250, 400, 400, 350, M_PI/6, 2*M_PI/3) - ->setFillColor(new Zend_Pdf_Color_Rgb(1, 1, 0)) - ->drawEllipse(250, 400, 400, 350, -M_PI/6, M_PI/6); - -// Draw and fill polygon -$page2->setFillColor(new Zend_Pdf_Color_Rgb(1, 0, 1)); -$x = array(); -$y = array(); -for ($count = 0; $count < 8; $count++) { - $x[] = 140 + 25*cos(3*M_PI_4*$count); - $y[] = 375 + 25*sin(3*M_PI_4*$count); -} -$page2->drawPolygon($x, $y, - Zend_Pdf_Page::SHAPE_DRAW_FILL_AND_STROKE, - Zend_Pdf_Page::FILL_METHOD_EVEN_ODD); - -// ---------- Draw figures in modified coordination system ----------------------------------- - -// Coordination system movement -$page2->saveGS(); -$page2->translate(60, 250); // Shift coordination system - -// Draw rectangle -$page2->setFillColor(new Zend_Pdf_Color_GrayScale(0.8)) - ->setLineColor(new Zend_Pdf_Color_GrayScale(0.2)) - ->setLineDashingPattern(array(3, 2, 3, 4), 1.6) - ->drawRectangle(0, 50, 340, 0); - -// Draw circle -$page2->setLineDashingPattern(Zend_Pdf_Page::LINE_DASHING_SOLID) - ->setFillColor(new Zend_Pdf_Color_Rgb(1, 0, 0)) - ->drawCircle(25, 25, 25); - -// Draw sectors -$page2->drawCircle(140, 25, 25, 2*M_PI/3, -M_PI/6) - ->setFillColor(new Zend_Pdf_Color_Cmyk(1, 0, 0, 0)) - ->drawCircle(140, 25, 25, M_PI/6, 2*M_PI/3) - ->setFillColor(new Zend_Pdf_Color_Rgb(1, 1, 0)) - ->drawCircle(140, 25, 25, -M_PI/6, M_PI/6); - -// Draw ellipse -$page2->setFillColor(new Zend_Pdf_Color_Rgb(1, 0, 0)) - ->drawEllipse(190, 50, 340, 0) - ->setFillColor(new Zend_Pdf_Color_Cmyk(1, 0, 0, 0)) - ->drawEllipse(190, 50, 340, 0, M_PI/6, 2*M_PI/3) - ->setFillColor(new Zend_Pdf_Color_Rgb(1, 1, 0)) - ->drawEllipse(190, 50, 340, 0, -M_PI/6, M_PI/6); - -// Draw and fill polygon -$page2->setFillColor(new Zend_Pdf_Color_Rgb(1, 0, 1)); -$x = array(); -$y = array(); -for ($count = 0; $count < 8; $count++) { - $x[] = 80 + 25*cos(3*M_PI_4*$count); - $y[] = 25 + 25*sin(3*M_PI_4*$count); -} -$page2->drawPolygon($x, $y, - Zend_Pdf_Page::SHAPE_DRAW_FILL_AND_STROKE, - Zend_Pdf_Page::FILL_METHOD_EVEN_ODD); - -// Draw line -$page2->setLineWidth(0.5) - ->drawLine(0, 25, 340, 25); - -$page2->restoreGS(); - - -// Coordination system movement, skewing and scaling -$page2->saveGS(); -$page2->translate(60, 150) // Shift coordination system - ->skew(0, 0, 0, -M_PI/9) // Skew coordination system - ->scale(0.9, 0.9); // Scale coordination system - -// Draw rectangle -$page2->setFillColor(new Zend_Pdf_Color_GrayScale(0.8)) - ->setLineColor(new Zend_Pdf_Color_GrayScale(0.2)) - ->setLineDashingPattern(array(3, 2, 3, 4), 1.6) - ->drawRectangle(0, 50, 340, 0); - -// Draw circle -$page2->setLineDashingPattern(Zend_Pdf_Page::LINE_DASHING_SOLID) - ->setFillColor(new Zend_Pdf_Color_Rgb(1, 0, 0)) - ->drawCircle(25, 25, 25); - -// Draw sectors -$page2->drawCircle(140, 25, 25, 2*M_PI/3, -M_PI/6) - ->setFillColor(new Zend_Pdf_Color_Cmyk(1, 0, 0, 0)) - ->drawCircle(140, 25, 25, M_PI/6, 2*M_PI/3) - ->setFillColor(new Zend_Pdf_Color_Rgb(1, 1, 0)) - ->drawCircle(140, 25, 25, -M_PI/6, M_PI/6); - -// Draw ellipse -$page2->setFillColor(new Zend_Pdf_Color_Rgb(1, 0, 0)) - ->drawEllipse(190, 50, 340, 0) - ->setFillColor(new Zend_Pdf_Color_Cmyk(1, 0, 0, 0)) - ->drawEllipse(190, 50, 340, 0, M_PI/6, 2*M_PI/3) - ->setFillColor(new Zend_Pdf_Color_Rgb(1, 1, 0)) - ->drawEllipse(190, 50, 340, 0, -M_PI/6, M_PI/6); - -// Draw and fill polygon -$page2->setFillColor(new Zend_Pdf_Color_Rgb(1, 0, 1)); -$x = array(); -$y = array(); -for ($count = 0; $count < 8; $count++) { - $x[] = 80 + 25*cos(3*M_PI_4*$count); - $y[] = 25 + 25*sin(3*M_PI_4*$count); -} -$page2->drawPolygon($x, $y, - Zend_Pdf_Page::SHAPE_DRAW_FILL_AND_STROKE, - Zend_Pdf_Page::FILL_METHOD_EVEN_ODD); - -// Draw line -$page2->setLineWidth(0.5) - ->drawLine(0, 25, 340, 25); - -$page2->restoreGS(); - -//------------------------------------------------------------------------------------ - -if (isset($argv[2])) { - $pdf->save($argv[2]); -} else { - $pdf->save($argv[1], true /* update */); -} diff --git a/demos/Zend/Pdf/stamp.jpg b/demos/Zend/Pdf/stamp.jpg deleted file mode 100644 index 1c3f56ae8a4..00000000000 Binary files a/demos/Zend/Pdf/stamp.jpg and /dev/null differ diff --git a/demos/Zend/Pdf/test.pdf b/demos/Zend/Pdf/test.pdf deleted file mode 100644 index 7bc8e7ba600..00000000000 Binary files a/demos/Zend/Pdf/test.pdf and /dev/null differ diff --git a/demos/Zend/ProgressBar/JsPush.php b/demos/Zend/ProgressBar/JsPush.php index 836d38d42ea..fdb027a7664 100644 --- a/demos/Zend/ProgressBar/JsPush.php +++ b/demos/Zend/ProgressBar/JsPush.php @@ -1,45 +1,36 @@ true)); + $loader->register(); - require_once 'Zend/ProgressBar.php'; - require_once 'Zend/ProgressBar/Adapter/JsPush.php'; - - $adapter = new Zend_ProgressBar_Adapter_JsPush(array('updateMethodName' => 'Zend_ProgressBar_Update', - 'finishMethodName' => 'Zend_ProgressBar_Finish')); - $progressBar = new Zend_ProgressBar($adapter, 0, 100); + $adapter = new JsPush(array('updateMethodName' => 'Zend_ProgressBar_Update', + 'finishMethodName' => 'Zend_ProgressBar_Finish')); + $progressBar = new ProgressBar($adapter, 0, 100); for ($i = 1; $i <= 100; $i++) { if ($i < 20) { $text = 'Just beginning'; - } else if ($i < 50) { + } elseif ($i < 50) { $text = 'A bit done'; - } else if ($i < 80) { + } elseif ($i < 80) { $text = 'Getting closer'; } else { $text = 'Nearly done'; @@ -126,23 +117,20 @@ } -
- - - + + + +
@@ -213,6 +201,8 @@ function finish()
-
+
+
+
diff --git a/demos/Zend/ProgressBar/ZendForm.php b/demos/Zend/ProgressBar/ZendForm.php index ca0cd9e1e48..5e5a58fa291 100644 --- a/demos/Zend/ProgressBar/ZendForm.php +++ b/demos/Zend/ProgressBar/ZendForm.php @@ -1,39 +1,30 @@ true)); +$loader->register(); if (isset($_GET['progress_key'])) { - require_once 'Zend/File/Transfer/Adapter/Http.php'; - require_once 'Zend/ProgressBar.php'; - require_once 'Zend/ProgressBar/Adapter/JsPull.php'; - - $adapter = new Zend_ProgressBar_Adapter_JsPull(); - Zend_File_Transfer_Adapter_Http::getProgress(array('progress' => $adapter)); + $adapter = new JsPull(); + Http::getProgress(array('progress' => $adapter)); die; } ?> @@ -109,8 +100,7 @@ } - 'multipart/form-data', 'action' => 'ZendForm.php', 'target' => 'uploadTarget', @@ -202,24 +188,26 @@ function finish() 'file' => array('file', array('label' => 'File')), 'submit' => array('submit', array('label' => 'Upload!')) ) - )); + ) +); +$form->prepare(); - $form->setView(new Zend_View()); - - echo $form; - ?> - +echo $form; +?> + -
-
-
-
-
-
-
+
+
+
+
+
+
-
+
+
+
+
diff --git a/demos/Zend/Search/Lucene/feed-search/create-index.php b/demos/Zend/Search/Lucene/feed-search/create-index.php deleted file mode 100644 index 36c37af49cc..00000000000 --- a/demos/Zend/Search/Lucene/feed-search/create-index.php +++ /dev/null @@ -1,57 +0,0 @@ -items as $item) { - $doc = new Zend_Search_Lucene_Document(); - - if ($item->link && $item->title && $item->description) { - - $link = htmlentities(strip_tags( $item->link() )); - $doc->addField(Zend_Search_Lucene_Field::UnIndexed('link', $link)); - - $title = htmlentities(strip_tags( $item->title() )); - $doc->addField(Zend_Search_Lucene_Field::Text('title', $title)); - - $contents = htmlentities(strip_tags( $item->description() )); - $doc->addField(Zend_Search_Lucene_Field::Text('contents', $contents)); - - echo "Adding {$item->title()}...\n"; - $index->addDocument($doc); - } -} - -$index->commit(); diff --git a/demos/Zend/Search/Lucene/feed-search/search-index.php b/demos/Zend/Search/Lucene/feed-search/search-index.php deleted file mode 100644 index 3e5675b91dd..00000000000 --- a/demos/Zend/Search/Lucene/feed-search/search-index.php +++ /dev/null @@ -1,43 +0,0 @@ -count()} documents.\n"; - -$search = 'php'; -$hits = $index->find(strtolower($search)); -echo "Search for \"$search\" returned " .count($hits). " hits.\n\n"; - -foreach ($hits as $hit) { - echo str_repeat('-', 80) . "\n"; - echo 'ID: ' . $hit->id ."\n"; - echo 'Score: ' . sprintf('%.2f', $hit->score) ."\n\n"; - - foreach ($hit->getDocument()->getFieldNames() as $field) { - echo "$field: \n"; - echo ' ' . trim(substr($hit->$field,0,76)) . "\n"; - } -} diff --git a/demos/Zend/Search/Lucene/indexing/CreateIndex.php b/demos/Zend/Search/Lucene/indexing/CreateIndex.php deleted file mode 100644 index 733e86e6ceb..00000000000 --- a/demos/Zend/Search/Lucene/indexing/CreateIndex.php +++ /dev/null @@ -1,97 +0,0 @@ -addField(Zend_Search_Lucene_Field::Text('path', $fileName)); - $this->addField(Zend_Search_Lucene_Field::Keyword( 'modified', filemtime($fileName) )); - - $f = fopen($fileName,'rb'); - $byteCount = filesize($fileName); - - $data = ''; - while ( $byteCount > 0 && ($nextBlock = fread($f, $byteCount)) != false ) { - $data .= $nextBlock; - $byteCount -= strlen($nextBlock); - } - fclose($f); - - if ($storeContent) { - $this->addField(Zend_Search_Lucene_Field::Text('contents', $data, 'ISO8859-1')); - } else { - $this->addField(Zend_Search_Lucene_Field::UnStored('contents', $data, 'ISO8859-1')); - } - } -} - - -// Create index -$index = new Zend_Search_Lucene('index', true); -// Uncomment next line if you want to have case sensitive index -// ZSearchAnalyzer::setDefault(new ZSearchTextAnalyzer()); - -setlocale(LC_CTYPE, 'en_US'); - -$indexSourceDir = 'IndexSource'; -$dir = opendir($indexSourceDir); -while (($file = readdir($dir)) !== false) { - if (is_dir($indexSourceDir . '/' . $file)) { - continue; - } - if (strcasecmp(substr($file, strlen($file)-5), '.html') != 0) { - continue; - } - - // Create new Document from a file - $doc = new FileDocument($indexSourceDir . '/' . $file, true); - // Add document to the index - $index->addDocument($doc); - - echo $file . "...\n"; - flush(); -} -closedir($dir); diff --git a/demos/Zend/Search/Lucene/indexing/IndexSource/about-pear.html b/demos/Zend/Search/Lucene/indexing/IndexSource/about-pear.html deleted file mode 100644 index 8a75445e756..00000000000 --- a/demos/Zend/Search/Lucene/indexing/IndexSource/about-pear.html +++ /dev/null @@ -1,179 +0,0 @@ -About PEAR
PEAR Manual
PrevNext


PrevHomeNext
Authors and Contributors Introduction
\ No newline at end of file diff --git a/demos/Zend/Search/Lucene/indexing/IndexSource/authors.html b/demos/Zend/Search/Lucene/indexing/IndexSource/authors.html deleted file mode 100644 index cac8abe9569..00000000000 --- a/demos/Zend/Search/Lucene/indexing/IndexSource/authors.html +++ /dev/null @@ -1,235 +0,0 @@ -Authors and Contributors
PEAR Manual
PrevPrefaceNext

Authors and Contributors

The following is a list of people that are helping to maintain this - documentation. If you would like to contact one of them, please - write to pear-doc@lists.php.net. -

  • Lorenzo Alberton -

  • Gregory Beaver -

  • Daniel Convissor -

  • David Costa -

  • Thomas V.V. Cox -

  • Martin Jansen -

  • Alan Knowles -

  • Clay Loveless -

  • Alexander Merz -

  • Stefan Neufeind -

  • Jon Parise -

  • Tobias Schlitt -

  • Stephan Schmidt -

  • Mika Tuupola -

  • Michael Wallner -

(In alphabetic order.) -


PrevHomeNext
The structure of the ManualUpAbout PEAR
\ No newline at end of file diff --git a/demos/Zend/Search/Lucene/indexing/IndexSource/contributing.bugs.html b/demos/Zend/Search/Lucene/indexing/IndexSource/contributing.bugs.html deleted file mode 100644 index 70035c2bb3e..00000000000 --- a/demos/Zend/Search/Lucene/indexing/IndexSource/contributing.bugs.html +++ /dev/null @@ -1,185 +0,0 @@ -Reporting Bugs
PEAR Manual
PrevChapter 5. ContributingNext

Reporting Bugs

If you think that you have found a bug in a PEAR package, please - take care that you are using the latest version of the package and - that your system does meet the packages' requirements. -

If the bug still persists with the latest version of the package, - don't hesitate to fill out a bug report. The easiest way is to click - to link "Package Bugs" on the package information page - for the package on the PEAR - Homepage, which you think contains a bug. This will take you - to a list of existing bugs of the package. Please double check if - the bug hasn't already been reported! If you are unable to find it - in the list, you can click on "Report a new bug" to - fill out the bug form. -

More information and tips on how to report bugs in a proper way - can be found at http://bugs.php.net/how-to-report.php. -

If you have already fixed a bug that you have found in a package, please - read this. -


PrevHomeNext
Submitting PatchesUpWriting & Translating Documentation
\ No newline at end of file diff --git a/demos/Zend/Search/Lucene/indexing/IndexSource/contributing.documentation.html b/demos/Zend/Search/Lucene/indexing/IndexSource/contributing.documentation.html deleted file mode 100644 index c9ba9c132e1..00000000000 --- a/demos/Zend/Search/Lucene/indexing/IndexSource/contributing.documentation.html +++ /dev/null @@ -1,165 +0,0 @@ -Writing & Translating Documentation
PEAR Manual
PrevChapter 5. ContributingNext

Writing & Translating Documentation

Good documentation is essential for users to fully understand any - software. Several PEAR packages lack documentation or have docs which - need improvement. Writing documentation - provides more information about helping out on this front. -

Translating documentation is another important task. - Not only does new documentation need to be translated - into the existing languages, additional languages are - welcome. Also, existing translations need to be brought - up to date because the English versions have been changed. - Help on how to perform the translation process is in the Revision Tracking - section of the manual. -


PrevHomeNext
Reporting BugsUpWishlists
\ No newline at end of file diff --git a/demos/Zend/Search/Lucene/indexing/IndexSource/contributing.html b/demos/Zend/Search/Lucene/indexing/IndexSource/contributing.html deleted file mode 100644 index e5e672a1f03..00000000000 --- a/demos/Zend/Search/Lucene/indexing/IndexSource/contributing.html +++ /dev/null @@ -1,201 +0,0 @@ -Contributing
PEAR Manual
PrevNext


PrevHomeNext
Sample File (including Docblock Comment standards)UpWriting New Packages
\ No newline at end of file diff --git a/demos/Zend/Search/Lucene/indexing/IndexSource/contributing.newpackage.html b/demos/Zend/Search/Lucene/indexing/IndexSource/contributing.newpackage.html deleted file mode 100644 index 8ad9c4f0917..00000000000 --- a/demos/Zend/Search/Lucene/indexing/IndexSource/contributing.newpackage.html +++ /dev/null @@ -1,151 +0,0 @@ -Writing New Packages
PEAR Manual
PrevChapter 5. ContributingNext


PrevHomeNext
ContributingUpSubmitting Patches
\ No newline at end of file diff --git a/demos/Zend/Search/Lucene/indexing/IndexSource/contributing.patches.html b/demos/Zend/Search/Lucene/indexing/IndexSource/contributing.patches.html deleted file mode 100644 index d7d73f80f24..00000000000 --- a/demos/Zend/Search/Lucene/indexing/IndexSource/contributing.patches.html +++ /dev/null @@ -1,274 +0,0 @@ -Submitting Patches
PEAR Manual
PrevChapter 5. ContributingNext

Submitting Patches

If you have modified a package to expand its functionality or to fix a - bug, you should contribute your changes back to the community (some - licenses force you to do so, and it is generally considered immoral not to). -

Before creating the patch, you must first obtain the latest sources of the - package you wish to patch from CVS by running the commands (the package - in this example is Foo_Bar): -

cvs -d:pserver:cvsread@cvs.php.net:/repository login
-
-password is phpfi
-
cvs -d:pserver:cvsread@cvs.php.net:/repository co pear/Foo_Bar
-
- Now that you have the latest sources, you can edit the relevant file(s). - Make sure that your patch is fully compatible with the PEAR
coding -standards.. -

After you have finished adding/changing the code, TEST it: We will not - accept code that hasn't been carefully tested. - When you are absolutely sure the new code doesn't introduce bugs, create a - unified diff by running: -
cd pear/Foo_Bar
-cvs diff -u >Foo_Bar.diff
- The resulting .diff file contains your patch. This diff makes it easy - for us to see what has been changed. -

Next step is to submit the patch. Send a mail to pear-dev@lists.php.net and - Cc the maintainer(s) of the package. The subject of the mail should be - prefixed with '[Patch]' to make it clear you are submitting a patch. Also - include a verbose explanation of what the patch does. - Don't forget to attach the .diff file to the mail. The maintainers of - the package are usually listed in the header of each source file. Apart - from that their email adresses are available on the package information - page on http://pear.php.net/. -

Note: - If you are using Outlook or Outlook Express, please change the file - extension of the diff file to .txt, because Outlook's MIME-Type - detection depends on the file extension and attachments with a - MIME-Type not equal to text/plain will be rejected - by our mailinglist software. -

Note: - If your patch does break backwards compatibility, the chances are fairly - good that the maintainers won't be happy about it. Thus you should always - try to fix a bug in a way that does not seriously change the public API. - But if there is absolutely no way to keep backwards compatibility and/or - if your patch contains a groundbraking improvement, even API changes are - fine. -


PrevHomeNext
Writing New PackagesUpReporting Bugs
\ No newline at end of file diff --git a/demos/Zend/Search/Lucene/indexing/IndexSource/contributing.wishlist.html b/demos/Zend/Search/Lucene/indexing/IndexSource/contributing.wishlist.html deleted file mode 100644 index f5d13cecb5f..00000000000 --- a/demos/Zend/Search/Lucene/indexing/IndexSource/contributing.wishlist.html +++ /dev/null @@ -1,158 +0,0 @@ -Wishlists
PEAR Manual
PrevChapter 5. ContributingNext

Wishlists

Some of the PEAR developers have wishlists at Amazon or a similar - service. If you appreciate the work of a certain developer, feel - free to buy something for her from her wishlist. To find out if - a developer has one of those wishlists, go to the - account browser, - look for the details of the developer and there you'll see if she - has a wishlist. Buying something from people's wishlists may even - speed up the time in which annoying bugs are fixed ;-). -


PrevHomeNext
Writing & Translating DocumentationUpFAQ - Frequently Asked Questions
\ No newline at end of file diff --git a/demos/Zend/Search/Lucene/indexing/IndexSource/copyright.html b/demos/Zend/Search/Lucene/indexing/IndexSource/copyright.html deleted file mode 100644 index d4e082bd837..00000000000 --- a/demos/Zend/Search/Lucene/indexing/IndexSource/copyright.html +++ /dev/null @@ -1,196 +0,0 @@ -
PEAR Manual

Copyright

Copyright © 2001 - 2006 by the PEAR Documentation Group. - This material may be distributed only subject to the terms and - conditions set forth in the Open Publication License, v1.0 or - later (the latest version is presently available at - http://www.opencontent.org/openpub/). -

Distribution of substantively modified versions of this document - is prohibited without the explicit permission of the copyright - holder. -

Distribution of the work or derivative of the work in any - standard (paper) book form is prohibited unless prior permission - is obtained from the copyright holder. -

The PEAR Documentation Group consists of all the people that - have contributed documentation to the PEAR manual. - Representatives are listed on the front page of this manual. - In case you would like to contact the group, please write to - pear-doc@lists.php.net. -

Copyright for the XML_RPC documentation -

The documentation - of the XML_RPC package has originally been written by Edd Dumbill as an independent - document on his - homepage and is published as part of the PEAR Manual under - the following license restrictions: -

Copyright © 1999,2000,2001 by Edd Dumbill, Useful Information Company -

All rights reserved. -

Redistribution and use in source and binary forms, with or without - modification, are permitted provided that the following conditions - are met: -

  • Redistributions of source code must retain the above copyright - notice, this list of conditions and the following disclaimer. -

  • Redistributions in binary form must reproduce the above - copyright notice, this list of conditions and the following - disclaimer in the documentation and/or other materials provided - with the distribution. -

  • Neither the name of the "XML-RPC for PHP" nor the names of its - contributors may be used to endorse or promote products derived - from this software without specific prior written permission. -

-

- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND - CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, - INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF - MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE - LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, - OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY - THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR - TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT - OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY - OF SUCH DAMAGE. -


 Home 
\ No newline at end of file diff --git a/demos/Zend/Search/Lucene/indexing/IndexSource/core.html b/demos/Zend/Search/Lucene/indexing/IndexSource/core.html deleted file mode 100644 index cf811503a24..00000000000 --- a/demos/Zend/Search/Lucene/indexing/IndexSource/core.html +++ /dev/null @@ -1,159 +0,0 @@ -Core components
PEAR Manual
PrevNext


PrevHomeNext
Structure of a post-install script PEAR base classes
\ No newline at end of file diff --git a/demos/Zend/WebServices/Amazon/amazon-search.php b/demos/Zend/Service/Amazon/amazon-search.php similarity index 86% rename from demos/Zend/WebServices/Amazon/amazon-search.php rename to demos/Zend/Service/Amazon/amazon-search.php index 93a2671e86e..c41b60dae11 100644 --- a/demos/Zend/WebServices/Amazon/amazon-search.php +++ b/demos/Zend/Service/Amazon/amazon-search.php @@ -1,32 +1,26 @@ true)); +$loader->register(); $keywords = ''; $searchFor = ''; @@ -166,7 +160,7 @@ category($searchFor)->ResponseGroup('Large')->Keywords($keywords); @@ -204,7 +198,7 @@ echo '
'; } } - catch (Zend_Service_Exception $e) { + catch (AmazonException $e) { echo '

An error occured, please try again later. (' .$e->getMessage(). ')

'; } } diff --git a/demos/Zend/WebServices/Flickr/flickr-composite.php b/demos/Zend/Service/Flickr/flickr-composite.php similarity index 81% rename from demos/Zend/WebServices/Flickr/flickr-composite.php rename to demos/Zend/Service/Flickr/flickr-composite.php index 74f27844cca..9cebaad860f 100644 --- a/demos/Zend/WebServices/Flickr/flickr-composite.php +++ b/demos/Zend/Service/Flickr/flickr-composite.php @@ -1,32 +1,24 @@ true)); +$loader->register(); if (isset($_POST) && strtolower($_SERVER['REQUEST_METHOD']) == 'post') { $keywords = strip_tags($_POST['search_term']); @@ -95,7 +87,7 @@ tagSearch($keywords, array('per_page' => 50, 'tag_mode' => 'all')); @@ -152,8 +144,8 @@ echo '

No Results Found

'; } } - catch (Zend_Service_Exception $e) { - echo '

An error occured, please try again later. (' .$e->getMessage(). ')

'; + catch (FlickrException $e) { + echo '

An error occurred, please try again later. (' .$e->getMessage(). ')

'; } } ?> diff --git a/demos/Zend/Service/Flickr/flickr-search.php b/demos/Zend/Service/Flickr/flickr-search.php new file mode 100644 index 00000000000..f629fe95879 --- /dev/null +++ b/demos/Zend/Service/Flickr/flickr-search.php @@ -0,0 +1,33 @@ + true)); +$loader->register(); + +$flickr = new Flickr('your api key here'); + +$photos = $flickr->tagSearch('php'); + +foreach ($photos as $photo) { + echo '
'; + echo $photo->title . "
\n"; +} diff --git a/demos/Zend/Service/LiveDocx/.gitignore b/demos/Zend/Service/LiveDocx/.gitignore new file mode 100644 index 00000000000..d61d33b122f --- /dev/null +++ b/demos/Zend/Service/LiveDocx/.gitignore @@ -0,0 +1 @@ +DemoConfiguration.php diff --git a/demos/Zend/Service/LiveDocx/Bootstrap.php b/demos/Zend/Service/LiveDocx/Bootstrap.php index a25cc8e012e..96e8d006898 100755 --- a/demos/Zend/Service/LiveDocx/Bootstrap.php +++ b/demos/Zend/Service/LiveDocx/Bootstrap.php @@ -1,9 +1,8 @@ setLocalTemplate('template.docx'); +$date = new DateTime(); + $mailMerge->assign('software', 'Magic Graphical Compression Suite v1.9') ->assign('licensee', 'DaĆÆ Lemaitre') ->assign('company', 'Megasoft Co-operation') - ->assign('date', Date::now()->toString(Date::DATE_LONG)) - ->assign('time', Date::now()->toString(Date::TIME_LONG)) + ->assign('date', $date->format('Y-m-d')) + ->assign('time', $date->format('H:i:s')) ->assign('city', 'Lyon') ->assign('country', 'France'); diff --git a/demos/Zend/Service/LiveDocx/MailMerge/conference-pass/generate-document.php b/demos/Zend/Service/LiveDocx/MailMerge/conference-pass/generate-document.php index 73450d44833..ae414bbeaae 100755 --- a/demos/Zend/Service/LiveDocx/MailMerge/conference-pass/generate-document.php +++ b/demos/Zend/Service/LiveDocx/MailMerge/conference-pass/generate-document.php @@ -2,8 +2,7 @@ require_once dirname(dirname(__DIR__)) . DIRECTORY_SEPARATOR . 'Bootstrap.php'; - -use Zend\Date\Date; +use DateTime; use Zend\Service\LiveDocx\MailMerge; $mailMerge = new MailMerge(); @@ -23,9 +22,11 @@ $mailMerge->setLocalTemplate('template.docx'); +$date = new DateTime(); + $mailMerge->assign('name', 'DaĆÆ Lemaitre') ->assign('company', 'Megasoft Co-operation') - ->assign('date', Date::now()->toString(Date::DATE_LONG)) + ->assign('date', $date->format('Y-m-d')) ->assign('image:photo', $photoFilename); $mailMerge->createDocument(); diff --git a/demos/Zend/Service/LiveDocx/MailMerge/license-agreement/generate-document-concat.php b/demos/Zend/Service/LiveDocx/MailMerge/license-agreement/generate-document-concat.php index 54428eac590..cfd4db1b650 100755 --- a/demos/Zend/Service/LiveDocx/MailMerge/license-agreement/generate-document-concat.php +++ b/demos/Zend/Service/LiveDocx/MailMerge/license-agreement/generate-document-concat.php @@ -32,10 +32,9 @@ * location. The specified paths are correct for Debian 5.0.3. */ -use Zend\Date\Date; +use DateTime; use Zend\Log\Logger; use Zend\Log\Writer\Stream as Writer; -use Zend\Registry; use Zend\Service\LiveDocx\Helper; use Zend\Service\LiveDocx\MailMerge; @@ -75,8 +74,6 @@ $logger = new Logger(new Writer('php://stdout')); -Registry::set('logger', $logger); - // ----------------------------------------------------------------------------- // Create temporary directory @@ -104,6 +101,8 @@ $mailMerge->setLocalTemplate('template.docx'); +$date = new DateTime(); + for ($iteration = 1; $iteration <= $iterations; $iteration ++) { $tempFilename = sprintf('%s%s%010s.pdf', $tempDirectory, DIRECTORY_SEPARATOR, $iteration); @@ -112,8 +111,8 @@ $mailMerge->assign('software', randomString()) ->assign('licensee', randomString()) ->assign('company', randomString()) - ->assign('date', Date::now()->toString(Date::DATE_LONG)) - ->assign('time', Date::now()->toString(Date::TIME_LONG)) + ->assign('date', $date->format('Y-m-d')) + ->assign('time', $date->format('H:i:s')) ->assign('city', randomString()) ->assign('country', randomString()); @@ -156,8 +155,7 @@ /** * Create a random string - * - * @param $length + * * @return string */ function randomString() @@ -213,9 +211,9 @@ function recursiveRemoveDirectory($dir) function concatenatePdfFilenames($inputFilenames, $outputFilename, $processor = EXEC_PDFTK) { $ret = false; - - $logger = Registry::get('logger'); - + + $logger = new Logger(new Writer('php://stdout')); + if (! (is_file(EXEC_PDFTK) || is_file(EXEC_GHOSTSCRIPT))) { $logger->log('Either pdftk or ghostscript are required for this sample application.', Logger::CRIT); exit(); diff --git a/demos/Zend/Service/LiveDocx/MailMerge/license-agreement/generate-document.php b/demos/Zend/Service/LiveDocx/MailMerge/license-agreement/generate-document.php index c03486b6e06..4af81f73ba3 100755 --- a/demos/Zend/Service/LiveDocx/MailMerge/license-agreement/generate-document.php +++ b/demos/Zend/Service/LiveDocx/MailMerge/license-agreement/generate-document.php @@ -2,8 +2,7 @@ require_once dirname(dirname(__DIR__)) . DIRECTORY_SEPARATOR . 'Bootstrap.php'; - -use Zend\Date\Date; +use DateTime; use Zend\Service\LiveDocx\MailMerge; $mailMerge = new MailMerge(); @@ -13,11 +12,13 @@ $mailMerge->setLocalTemplate('template.docx'); +$date = new DateTime(); + $mailMerge->assign('software', 'Magic Graphical Compression Suite v1.9') ->assign('licensee', 'Henry Dƶner-Meyer') ->assign('company', 'Co-Operation') - ->assign('date', Date::now()->toString(Date::DATE_LONG)) - ->assign('time', Date::now()->toString(Date::TIME_LONG)) + ->assign('date', $date->format('Y-m-d')) + ->assign('time', $date->format('H:i:s')) ->assign('city', 'Berlin') ->assign('country', 'Germany'); diff --git a/demos/Zend/Service/LiveDocx/MailMerge/metafiles/generate-metafiles.php b/demos/Zend/Service/LiveDocx/MailMerge/metafiles/generate-metafiles.php index 1fa6d6d9910..fc7ed3793f1 100755 --- a/demos/Zend/Service/LiveDocx/MailMerge/metafiles/generate-metafiles.php +++ b/demos/Zend/Service/LiveDocx/MailMerge/metafiles/generate-metafiles.php @@ -2,8 +2,7 @@ require_once dirname(dirname(__DIR__)) . DIRECTORY_SEPARATOR . 'Bootstrap.php'; - -use Zend\Date\Date; +use DateTime; use Zend\Service\LiveDocx\MailMerge; $mailMerge = new MailMerge(); @@ -12,12 +11,14 @@ ->setPassword(DEMOS_ZEND_SERVICE_LIVEDOCX_PASSWORD); $mailMerge->setLocalTemplate('template.docx'); - + +$date = new DateTime(); + $mailMerge->setFieldValue('software', 'Magic Graphical Compression Suite v1.9') ->setFieldValue('licensee', 'Henry Dƶner-Meyer') ->setFieldValue('company', 'Megasoft Co-operation') - ->setFieldValue('date', Date::now()->toString(Date::DATE_LONG)) - ->setFieldValue('time', Date::now()->toString(Date::TIME_LONG)) + ->setFieldValue('date', $date->format('Y-m-d')) + ->setFieldValue('time', $date->format('H:i:s')) ->setFieldValue('city', 'Bremen') ->setFieldValue('country', 'Germany'); diff --git a/demos/Zend/Service/LiveDocx/MailMerge/pdf-security/generate-document.php b/demos/Zend/Service/LiveDocx/MailMerge/pdf-security/generate-document.php index 3820f117840..60a932cbede 100755 --- a/demos/Zend/Service/LiveDocx/MailMerge/pdf-security/generate-document.php +++ b/demos/Zend/Service/LiveDocx/MailMerge/pdf-security/generate-document.php @@ -2,8 +2,7 @@ require_once dirname(dirname(__DIR__)) . DIRECTORY_SEPARATOR . 'Bootstrap.php'; - -use Zend\Date\Date; +use DateTime; use Zend\Service\LiveDocx\MailMerge; $mailMerge = new MailMerge(); @@ -17,11 +16,13 @@ $mailMerge->setLocalTemplate('template.docx'); +$date = new DateTime(); + $mailMerge->assign('software', 'Magic Graphical Compression Suite v1.9') ->assign('licensee', 'Henry Dƶner-Meyer') ->assign('company', 'Co-Operation') - ->assign('date', Date::now()->toString(Date::DATE_LONG)) - ->assign('time', Date::now()->toString(Date::TIME_LONG)) + ->assign('date', $date->format('Y-m-d')) + ->assign('time', $date->format('H:i:s')) ->assign('city', 'Berlin') ->assign('country', 'Germany'); diff --git a/demos/Zend/Service/LiveDocx/MailMerge/supported-fonts/show-supported-fonts-cached.php b/demos/Zend/Service/LiveDocx/MailMerge/supported-fonts/show-supported-fonts-cached.php index 05f6b4209a0..ef0965b2e5f 100755 --- a/demos/Zend/Service/LiveDocx/MailMerge/supported-fonts/show-supported-fonts-cached.php +++ b/demos/Zend/Service/LiveDocx/MailMerge/supported-fonts/show-supported-fonts-cached.php @@ -2,29 +2,26 @@ require_once dirname(dirname(__DIR__)) . DIRECTORY_SEPARATOR . 'Bootstrap.php'; - -use Zend\Cache\Cache; +use Zend\Cache\StorageFactory; use Zend\Service\LiveDocx\Helper; use Zend\Service\LiveDocx\MailMerge; $cacheId = md5(__FILE__); -$cacheFrontendOptions = array( - 'lifetime' => 2592000, // 30 days - 'automatic_serialization' => true -); - -$cacheBackendOptions = array( - 'cache_dir' => __DIR__ . '/cache' +$cache = array( + 'adapter' => 'FileSystem', + 'options' => array( + 'cache_dir' => __DIR__ . '/cache', + ), ); -if (!is_dir($cacheBackendOptions['cache_dir'])) { - mkdir($cacheBackendOptions['cache_dir']); +if (!is_dir($cache['options']['cache_dir'])) { + mkdir($cache['options']['cache_dir']); } -$cache = Cache::factory('Core', 'File', $cacheFrontendOptions, $cacheBackendOptions); +$cache = StorageFactory::factory($cache); -if (! $fonts = $cache->load($cacheId)) { +if (! $fonts = $cache->getItem($cacheId)) { // Cache miss. Connect to backend service (expensive). @@ -35,7 +32,7 @@ $fonts = $mailMerge->getFontNames(); - $cache->save($fonts, $cacheId); + $cache->addItem($fonts, $cacheId); unset($mailMerge); diff --git a/demos/Zend/Service/LiveDocx/MailMerge/supported-formats/show-supported-formats-cached.php b/demos/Zend/Service/LiveDocx/MailMerge/supported-formats/show-supported-formats-cached.php index 95bfaa713b7..eef99aae27b 100755 --- a/demos/Zend/Service/LiveDocx/MailMerge/supported-formats/show-supported-formats-cached.php +++ b/demos/Zend/Service/LiveDocx/MailMerge/supported-formats/show-supported-formats-cached.php @@ -2,8 +2,7 @@ require_once dirname(dirname(__DIR__)) . DIRECTORY_SEPARATOR . 'Bootstrap.php'; - -use Zend\Cache\Cache; +use Zend\Cache\StorageFactory; use Zend\Service\LiveDocx\Helper; use Zend\Service\LiveDocx\MailMerge; @@ -19,22 +18,20 @@ $cacheId = md5(__FILE__); -$cacheFrontendOptions = array( - 'lifetime' => 2592000, // 30 days - 'automatic_serialization' => true -); - -$cacheBackendOptions = array( - 'cache_dir' => __DIR__ . '/cache' +$cache = array( + 'adapter' => 'FileSystem', + 'options' => array( + 'cache_dir' => __DIR__ . '/cache', + ), ); -if (!is_dir($cacheBackendOptions['cache_dir'])) { - mkdir($cacheBackendOptions['cache_dir']); +if (!is_dir($cache['options']['cache_dir'])) { + mkdir($cache['options']['cache_dir']); } -$cache = Cache::factory('Core', 'File', $cacheFrontendOptions, $cacheBackendOptions); +$cache = StorageFactory::factory($cache); -if (! $formats = $cache->load($cacheId)) { +if (! $formats = $cache->getItem($cacheId)) { // Cache miss. Connect to backend service (expensive). @@ -49,7 +46,7 @@ $formats->document = $mailMerge->getDocumentFormats(); $formats->image = $mailMerge->getImageExportFormats(); - $cache->save($formats, $cacheId); + $cache->setItem($formats, $cacheId); unset($mailMerge); diff --git a/demos/Zend/Service/LiveDocx/MailMerge/telephone-bill/generate-document.php b/demos/Zend/Service/LiveDocx/MailMerge/telephone-bill/generate-document.php index 09bb903cc37..98fb7fd53e7 100755 --- a/demos/Zend/Service/LiveDocx/MailMerge/telephone-bill/generate-document.php +++ b/demos/Zend/Service/LiveDocx/MailMerge/telephone-bill/generate-document.php @@ -2,8 +2,7 @@ require_once dirname(dirname(__DIR__)) . DIRECTORY_SEPARATOR . 'Bootstrap.php'; - -use Zend\Date\Date; +use DateTime; use Zend\Service\LiveDocx\Helper; use Zend\Service\LiveDocx\MailMerge; @@ -31,14 +30,15 @@ ->assign('invoice_number', sprintf("#%'10s", rand(0,1000000000))) ->assign('account_number', sprintf("#%'10s", rand(0,1000000000))); +$date = new DateTime(); + $billData = array ( 'phone' => '+22 (0)333 444 555', - 'date' => Date::now()->toString(Date::DATE_LONG), + 'date' => $date->format('Y-m-d'), 'name' => 'James Henry Brown', 'service_phone' => '+22 (0)333 444 559', 'service_fax' => '+22 (0)333 444 558', - 'month' => sprintf('%s %s', Date::now()->toString(Date::MONTH_NAME), - Date::now()->toString(Date::YEAR)), + 'month' => $date->format('F Y'), 'monthly_fee' => '15.00', 'total_net' => '19.60', 'tax' => '19.00', diff --git a/demos/Zend/Service/LiveDocx/library/Zend/Service/LiveDocx/Helper.php b/demos/Zend/Service/LiveDocx/library/Zend/Service/LiveDocx/Helper.php index 8dc775a88d8..b8802e59159 100755 --- a/demos/Zend/Service/LiveDocx/library/Zend/Service/LiveDocx/Helper.php +++ b/demos/Zend/Service/LiveDocx/library/Zend/Service/LiveDocx/Helper.php @@ -1,33 +1,21 @@ 0) { foreach ($result as $record) { - $date->set($record['createTime']); - $createTimeFormatted = $date->get(Date::RFC_1123); - $date->set($record['modifyTime']); - $modifyTimeFormatted = $date->get(Date::RFC_1123); + $date = new DateTime($record['createTime']); + $createTimeFormatted = $date->format(DateTime::RFC1123); + $date = new DateTime($record['modifyTime']); + $modifyTimeFormatted = $date->format(DateTime::RFC1123); $ret .= sprintf(' Filename : %s%s', $record['filename'], PHP_EOL); $ret .= sprintf(' File Size : %d b%s', $record['fileSize'], PHP_EOL); $ret .= sprintf(' Creation Time : %d (%s)%s', $record['createTime'], $createTimeFormatted, PHP_EOL); @@ -157,9 +143,7 @@ public static function listDecorator($result) $ret .= PHP_EOL; } } - - unset($date); - + return $ret; } diff --git a/demos/Zend/WebServices/Flickr/flickr-search.php b/demos/Zend/WebServices/Flickr/flickr-search.php deleted file mode 100644 index 15f5483e36f..00000000000 --- a/demos/Zend/WebServices/Flickr/flickr-search.php +++ /dev/null @@ -1,41 +0,0 @@ -tagSearch('php'); - -foreach ($photos as $photo) { - echo '
'; - echo $photo->title . "
\n"; -} diff --git a/demos/Zend/WebServices/Protocols/xmlrpc-upc-lookup.php b/demos/Zend/WebServices/Protocols/xmlrpc-upc-lookup.php deleted file mode 100644 index f417b17e9ba..00000000000 --- a/demos/Zend/WebServices/Protocols/xmlrpc-upc-lookup.php +++ /dev/null @@ -1,31 +0,0 @@ -getProxy(); - -print_r( $client->lookupUPC('071641301627') ); diff --git a/demos/Zend/WebServices/Yahoo/yahoo-multi-search.php b/demos/Zend/WebServices/Yahoo/yahoo-multi-search.php deleted file mode 100644 index 1a1773efd78..00000000000 --- a/demos/Zend/WebServices/Yahoo/yahoo-multi-search.php +++ /dev/null @@ -1,153 +0,0 @@ - - - - - - - -

Yahoo! Multi-Search

-
-

- - -

-
-imageSearch($keywords, array("results" => 5)); - - if ($results->totalResults() > 0) { - echo '
'; - echo '

Image Search Results

'; - foreach ($results as $result) { - echo ""; - } - echo '
'; - } - - - $results = $yahoo->webSearch($keywords); - - if ($results->totalResults() > 0) { - echo '
'; - echo '

Web Search Results

'; - foreach ($results as $result) { - echo "

{$result->Title}

"; - echo "

{$result->Summary}
[Cached Version]

"; - } - echo '
'; - } - - - $results = $yahoo->newsSearch($keywords); - - if ($results->totalResults() > 0) { - echo '
'; - echo '

News Search Results

'; - foreach ($results as $result) { - echo "

{$result->Title}

"; - echo "

{$result->Summary}

"; - } - echo '
'; - } - } - catch (Zend_Service_Exception $e) { - echo '

An error occured, please try again later.

'; - } - } -?> -

Powered by the Zend Framework

- - \ No newline at end of file diff --git a/demos/Zend/Wildfire/application/controllers/Boot/Zend-Db-Profiler-Firebug/IndexController.php b/demos/Zend/Wildfire/application/controllers/Boot/Zend-Db-Profiler-Firebug/IndexController.php deleted file mode 100644 index 688fa3979c1..00000000000 --- a/demos/Zend/Wildfire/application/controllers/Boot/Zend-Db-Profiler-Firebug/IndexController.php +++ /dev/null @@ -1,18 +0,0 @@ -getConnection()->exec('CREATE TABLE foo ( - id INTEGNER NOT NULL, - col1 VARCHAR(10) NOT NULL - )'); - - $db->insert('foo', array('id'=>1,'col1'=>'original')); - } -} diff --git a/demos/Zend/Wildfire/application/controllers/Boot/Zend-Log-Writer-Firebug/IndexController.php b/demos/Zend/Wildfire/application/controllers/Boot/Zend-Log-Writer-Firebug/IndexController.php deleted file mode 100644 index f811e3b90fc..00000000000 --- a/demos/Zend/Wildfire/application/controllers/Boot/Zend-Log-Writer-Firebug/IndexController.php +++ /dev/null @@ -1,13 +0,0 @@ -log('This is a log message!', Zend_Log::INFO); - } -} diff --git a/demos/Zend/Wildfire/application/controllers/ErrorController.php b/demos/Zend/Wildfire/application/controllers/ErrorController.php deleted file mode 100644 index 8f093d232ab..00000000000 --- a/demos/Zend/Wildfire/application/controllers/ErrorController.php +++ /dev/null @@ -1,51 +0,0 @@ -err($this->_getParam('error_handler')->exception); - - } catch(Exception $e) { - - /* TODO: You can log this exception somewhere or display it during development. - * DO NOT USE THE logger here as it will create an infinite loop! - */ - - } - } -} - diff --git a/demos/Zend/Wildfire/application/controllers/IndexController.php b/demos/Zend/Wildfire/application/controllers/IndexController.php deleted file mode 100644 index 81fad98cc83..00000000000 --- a/demos/Zend/Wildfire/application/controllers/IndexController.php +++ /dev/null @@ -1,38 +0,0 @@ -getConnection()->exec('CREATE TABLE foo ( - id INTEGNER NOT NULL, - col1 VARCHAR(10) NOT NULL - )'); - - $db->insert('foo', array('id'=>1,'col1'=>'original')); - - $db->fetchAll('SELECT * FROM foo WHERE id = ?', 1); - - $db->update('foo', array('col1'=>'new'), 'id = 1'); - - $db->fetchAll('SELECT * FROM foo WHERE id = ?', 1); - - $db->delete('foo', 'id = 1'); - - $db->getConnection()->exec('DROP TABLE foo'); - } - - public function testmultipledatabasesAction() - { - $profiler1 = new Zend_Db_Profiler_Firebug('All DB Queries for first database'); - - $db1 = Zend_Db::factory('PDO_SQLITE', - array('dbname' => ':memory:', - 'profiler' => $profiler1)); - - $db1->getProfiler()->setEnabled(true); - - $profiler2 = new Zend_Db_Profiler_Firebug('All DB Queries for second database'); - - $db2 = Zend_Db::factory('PDO_SQLITE', - array('dbname' => ':memory:', - 'profiler' => $profiler2)); - - $db2->getProfiler()->setEnabled(true); - - $db1->getConnection()->exec('CREATE TABLE foo ( - id INTEGNER NOT NULL, - col1 VARCHAR(10) NOT NULL - )'); - - $db1->insert('foo', array('id'=>1,'col1'=>'original')); - - $db2->getConnection()->exec('CREATE TABLE foo ( - id INTEGNER NOT NULL, - col1 VARCHAR(10) NOT NULL - )'); - - $db2->insert('foo', array('id'=>1,'col1'=>'original')); - } - -} - diff --git a/demos/Zend/Wildfire/application/controllers/ZendLogWriterFirebugController.php b/demos/Zend/Wildfire/application/controllers/ZendLogWriterFirebugController.php deleted file mode 100644 index bea17aacb49..00000000000 --- a/demos/Zend/Wildfire/application/controllers/ZendLogWriterFirebugController.php +++ /dev/null @@ -1,79 +0,0 @@ -log('Emergency: system is unusable', Zend_Log::EMERG); - $logger->log('Alert: action must be taken immediately', Zend_Log::ALERT); - $logger->log('Critical: critical conditions', Zend_Log::CRIT); - $logger->log('Error: error conditions', Zend_Log::ERR); - $logger->log('Warning: warning conditions', Zend_Log::WARN); - $logger->log('Notice: normal but significant condition', Zend_Log::NOTICE); - $logger->log('Informational: informational messages', Zend_Log::INFO); - $logger->log('Debug: debug messages', Zend_Log::DEBUG); - $logger->log(array('$_SERVER',$_SERVER), Zend_Log::DEBUG); - - $logger->trace('Trace to here'); - - $table = array('Summary line for the table', - array( - array('Column 1', 'Column 2'), - array('Row 1 c 1',' Row 1 c 2'), - array('Row 2 c 1',' Row 2 c 2') - ) - ); - $logger->table($table); - } - - - public function testerrorcontrollerAction() - { - require_once 'Zend/Exception.php'; - throw new Zend_Exception('Test Exception'); - } - - public function testlargemessageAction() - { - $message = array(); - - for ( $i=0 ; $i<300 ; $i++ ) { - $message[] = 'This is message #' . $i; - } - - $logger = Zend_Registry::get('logger'); - $logger->log($message, Zend_Log::INFO); - } -} diff --git a/demos/Zend/Wildfire/application/controllers/ZendWildfirePluginFirePhpController.php b/demos/Zend/Wildfire/application/controllers/ZendWildfirePluginFirePhpController.php deleted file mode 100644 index 24c9c381d02..00000000000 --- a/demos/Zend/Wildfire/application/controllers/ZendWildfirePluginFirePhpController.php +++ /dev/null @@ -1,44 +0,0 @@ - - - Zend_Wildfire Demos and Tests - - - - -We had an error! But it's ok. We are testing the ErrorController. - - - \ No newline at end of file diff --git a/demos/Zend/Wildfire/application/views/scripts/index/index.phtml b/demos/Zend/Wildfire/application/views/scripts/index/index.phtml deleted file mode 100644 index 36c4179e8d7..00000000000 --- a/demos/Zend/Wildfire/application/views/scripts/index/index.phtml +++ /dev/null @@ -1,57 +0,0 @@ - - - Zend_Wildfire Demos and Tests - - - - - - - - - -
-

Zend_Log_Writer_Firebug

- -

Zend_Db_Profiler_Firebug

- -

Zend_Wildfire_Plugin_FirePhp

- - -
-
- -

Requirements

- - -

Instructions

-

Click on the links above and
look for output in the Firebug Console.

- -
- -
- - - \ No newline at end of file diff --git a/demos/Zend/Wildfire/application/views/scripts/zend-db-profiler-firebug/test-logging.phtml b/demos/Zend/Wildfire/application/views/scripts/zend-db-profiler-firebug/test-logging.phtml deleted file mode 100644 index 811241b9038..00000000000 --- a/demos/Zend/Wildfire/application/views/scripts/zend-db-profiler-firebug/test-logging.phtml +++ /dev/null @@ -1,16 +0,0 @@ - - - Zend_Wildfire Demos and Tests - - - - -Test Logging - - - \ No newline at end of file diff --git a/demos/Zend/Wildfire/application/views/scripts/zend-db-profiler-firebug/test-multiple-databases.phtml b/demos/Zend/Wildfire/application/views/scripts/zend-db-profiler-firebug/test-multiple-databases.phtml deleted file mode 100644 index 4868c5b1ac7..00000000000 --- a/demos/Zend/Wildfire/application/views/scripts/zend-db-profiler-firebug/test-multiple-databases.phtml +++ /dev/null @@ -1,16 +0,0 @@ - - - Zend_Wildfire Demos and Tests - - - - -Test Multiple Databases - - - \ No newline at end of file diff --git a/demos/Zend/Wildfire/application/views/scripts/zend-log-writer-firebug/test-error-controller.phtml b/demos/Zend/Wildfire/application/views/scripts/zend-log-writer-firebug/test-error-controller.phtml deleted file mode 100644 index e69de29bb2d..00000000000 diff --git a/demos/Zend/Wildfire/application/views/scripts/zend-log-writer-firebug/test-large-message.phtml b/demos/Zend/Wildfire/application/views/scripts/zend-log-writer-firebug/test-large-message.phtml deleted file mode 100644 index dcc6d63af81..00000000000 --- a/demos/Zend/Wildfire/application/views/scripts/zend-log-writer-firebug/test-large-message.phtml +++ /dev/null @@ -1,16 +0,0 @@ - - - Zend_Wildfire Demos and Tests - - - - -Test Large Message - - - \ No newline at end of file diff --git a/demos/Zend/Wildfire/application/views/scripts/zend-log-writer-firebug/test-logging.phtml b/demos/Zend/Wildfire/application/views/scripts/zend-log-writer-firebug/test-logging.phtml deleted file mode 100644 index 811241b9038..00000000000 --- a/demos/Zend/Wildfire/application/views/scripts/zend-log-writer-firebug/test-logging.phtml +++ /dev/null @@ -1,16 +0,0 @@ - - - Zend_Wildfire Demos and Tests - - - - -Test Logging - - - \ No newline at end of file diff --git a/demos/Zend/Wildfire/application/views/scripts/zend-wildfire-plugin-firephp/test-groups.phtml b/demos/Zend/Wildfire/application/views/scripts/zend-wildfire-plugin-firephp/test-groups.phtml deleted file mode 100644 index 6929734b2a1..00000000000 --- a/demos/Zend/Wildfire/application/views/scripts/zend-wildfire-plugin-firephp/test-groups.phtml +++ /dev/null @@ -1,16 +0,0 @@ - - - Zend_Wildfire Demos and Tests - - - - -Test Groups - - - \ No newline at end of file diff --git a/demos/Zend/Wildfire/public/.htaccess b/demos/Zend/Wildfire/public/.htaccess deleted file mode 100644 index 545b1cbfdf6..00000000000 --- a/demos/Zend/Wildfire/public/.htaccess +++ /dev/null @@ -1,6 +0,0 @@ - -RewriteEngine on - -RewriteRule Boot/(.*) Boot/$1 [QSA,L] - -RewriteRule !\.(js|ico|gif|jpg|png|css)$ index.php \ No newline at end of file diff --git a/demos/Zend/Wildfire/public/Boot/Zend-Db-Profiler-Firebug/TestDocExample.php b/demos/Zend/Wildfire/public/Boot/Zend-Db-Profiler-Firebug/TestDocExample.php deleted file mode 100644 index 6f41c2e61f5..00000000000 --- a/demos/Zend/Wildfire/public/Boot/Zend-Db-Profiler-Firebug/TestDocExample.php +++ /dev/null @@ -1,51 +0,0 @@ -setEnabled(true); - $db = Zend_Db::factory('PDO_SQLITE', array('dbname' => ':memory:')); - $db->setProfiler($profiler); - Zend_Registry::set('db',$db); - - $controller = Zend_Controller_Front::getInstance(); - $controller->setParam('useDefaultControllerAlways',true); - $controller->setParam('noViewRenderer', true); - $controller->setControllerDirectory(dirname(dirname(dirname(__DIR__))).'/application/controllers/Boot/Zend-Db-Profiler-Firebug'); - $controller->dispatch(); - - print 'Test Doc Example with Controller'; - break; - - case 'WithoutController': - - $profiler = new Zend_Db_Profiler_Firebug('All DB Queries'); - $profiler->setEnabled(true); - $db = Zend_Db::factory('PDO_SQLITE', array('dbname' => ':memory:')); - $db->setProfiler($profiler); - - $request = new Zend_Controller_Request_Http(); - $response = new Zend_Controller_Response_Http(); - $channel = Zend_Wildfire_Channel_HttpHeaders::getInstance(); - $channel->setRequest($request); - $channel->setResponse($response); - - $db->getConnection()->exec('CREATE TABLE foo ( - id INTEGNER NOT NULL, - col1 VARCHAR(10) NOT NULL - )'); - - $db->insert('foo', array('id'=>1,'col1'=>'original')); - - $channel->flush(); - $response->sendHeaders(); - - print 'Test Doc Example without Controller'; - break; - -} diff --git a/demos/Zend/Wildfire/public/Boot/Zend-Log-Writer-Firebug/TestDocExample.php b/demos/Zend/Wildfire/public/Boot/Zend-Log-Writer-Firebug/TestDocExample.php deleted file mode 100644 index 21024f22784..00000000000 --- a/demos/Zend/Wildfire/public/Boot/Zend-Log-Writer-Firebug/TestDocExample.php +++ /dev/null @@ -1,41 +0,0 @@ -setParam('useDefaultControllerAlways',true); - $controller->setParam('noViewRenderer', true); - $controller->setControllerDirectory(dirname(dirname(dirname(__DIR__))).'/application/controllers/Boot/Zend-Log-Writer-Firebug'); - $controller->dispatch(); - - print 'Test Doc Example with Controller'; - break; - - case 'WithoutController': - - $writer = new Zend_Log_Writer_Firebug(); - $logger = new Zend_Log($writer); - - $request = new Zend_Controller_Request_Http(); - $response = new Zend_Controller_Response_Http(); - $channel = Zend_Wildfire_Channel_HttpHeaders::getInstance(); - $channel->setRequest($request); - $channel->setResponse($response); - - $logger->log('This is a log message!', Zend_Log::INFO); - - $channel->flush(); - $response->sendHeaders(); - - print 'Test Doc Example without Controller'; - break; -} diff --git a/demos/Zend/Wildfire/public/index.php b/demos/Zend/Wildfire/public/index.php deleted file mode 100644 index c89b27fc317..00000000000 --- a/demos/Zend/Wildfire/public/index.php +++ /dev/null @@ -1,66 +0,0 @@ -setPriorityStyle(8, 'TABLE'); -$writer->setPriorityStyle(9, 'TRACE'); - -$logger = new Zend_Log($writer); -$logger->addPriority('TABLE', 8); -$logger->addPriority('TRACE', 9); - -Zend_Registry::set('logger',$logger); - - -/* - * Add our Firebug DB Profiler to the registry - */ - -require_once 'Zend/Db.php'; -require_once 'Zend/Db/Profiler/Firebug.php'; - -$profiler = new Zend_Db_Profiler_Firebug('All DB Queries'); - -$db = Zend_Db::factory('PDO_SQLITE', - array('dbname' => ':memory:', - 'profiler' => $profiler)); - -$db->getProfiler()->setEnabled(true); - -Zend_Registry::set('db',$db); - - -/* - * Run the front controller - */ - -require_once 'Zend/Controller/Front.php'; - -Zend_Controller_Front::run(dirname(__DIR__).'/application/controllers'); diff --git a/demos/Zend/XmlRpc/xmlrpc-upc-lookup.php b/demos/Zend/XmlRpc/xmlrpc-upc-lookup.php new file mode 100644 index 00000000000..b5bf9fb52c4 --- /dev/null +++ b/demos/Zend/XmlRpc/xmlrpc-upc-lookup.php @@ -0,0 +1,28 @@ + true)); +$loader->register(); + +$server = new Client('http://www.upcdatabase.com/xmlrpc'); + +$client = $server->getProxy(); + +print_r($client->lookup( + array( + 'rpc_key' => '0000...0000', // Set your rpc_key here + 'upc' => '123456789012', + ) + ) +); diff --git a/documentation/manual/de/module_specs/Zend_Service_LiveDocx.xml b/documentation/manual/de/module_specs/Zend_Service_LiveDocx.xml index 81af9ffb1ee..d220884fc5b 100644 --- a/documentation/manual/de/module_specs/Zend_Service_LiveDocx.xml +++ b/documentation/manual/de/module_specs/Zend_Service_LiveDocx.xml @@ -571,7 +571,7 @@ file_put_contents('document.pdf', $document); der Bilder als Prozentwert relativ zur originalen SeitengrĆ¶ĆŸe. Der Bereich dieses Parameters ist von 10 bis 400. $format ist das Format des Bildes, welches von dieser Methode zurĆ¼ckgegeben wird. Die unterstĆ¼tzten Formate - erhƤlt man, wenn man getImageFormats() aufruft. + erhƤlt man, wenn man getImageExportFormats() aufruft. getDocumentFormats()); ]]> - Ein Array an unterstĆ¼tzten Dateiformaten fĆ¼r Bilder erhalten + Ein Array an unterstĆ¼tzten Dateiformaten fĆ¼r Bilder erhalten @@ -862,7 +862,7 @@ $phpLiveDocx = new Zend_Service_LiveDocx_MailMerge(); $phpLiveDocx->setUsername('myUsername') ->setPassword('myPassword'); -Zend_Debug::dump($phpLiveDocx->getImageFormats()); +Zend_Debug::dump($phpLiveDocx->getImageExportFormats()); ]]> diff --git a/documentation/manual/en/figures/zend.tool.framework.clihelp.png b/documentation/manual/en/figures/zend.tool.framework.clihelp.png deleted file mode 100644 index fbeeebd563d..00000000000 Binary files a/documentation/manual/en/figures/zend.tool.framework.clihelp.png and /dev/null differ diff --git a/documentation/manual/en/figures/zend.tool.framework.cliversionunix.png b/documentation/manual/en/figures/zend.tool.framework.cliversionunix.png deleted file mode 100644 index ed9fc3a8d72..00000000000 Binary files a/documentation/manual/en/figures/zend.tool.framework.cliversionunix.png and /dev/null differ diff --git a/documentation/manual/en/figures/zend.tool.framework.cliversionwin32.png b/documentation/manual/en/figures/zend.tool.framework.cliversionwin32.png deleted file mode 100644 index 3837eaec327..00000000000 Binary files a/documentation/manual/en/figures/zend.tool.framework.cliversionwin32.png and /dev/null differ diff --git a/documentation/manual/en/manual-print2.xml.in b/documentation/manual/en/manual-print2.xml.in index 5e22dbd7933..9e9e5f0a81a 100644 --- a/documentation/manual/en/manual-print2.xml.in +++ b/documentation/manual/en/manual-print2.xml.in @@ -852,11 +852,6 @@ - - - - - diff --git a/documentation/manual/en/manual.xml.in b/documentation/manual/en/manual.xml.in index 96c0968de2e..8b1d303b1f8 100644 --- a/documentation/manual/en/manual.xml.in +++ b/documentation/manual/en/manual.xml.in @@ -326,40 +326,6 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - Zend\Authentication @@ -580,70 +546,6 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - Zend_Crypt @@ -668,117 +570,42 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - Zend_Db - + + + + + + + + + + + + + + + + + + + - + - + - + - + - + @@ -1001,6 +828,12 @@ + + + + + + @@ -1118,12 +951,26 @@ - Zend_I18n + + Zend_I18n + + + + + + + + + + + + + @@ -1234,12 +1081,6 @@ - - - - - - @@ -1258,12 +1099,6 @@ - - - - - - @@ -1282,49 +1117,13 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - @@ -1477,35 +1276,6 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - @@ -1788,25 +1558,6 @@ - - - - - - - - - - - - - - - - - - - @@ -2105,11 +1856,6 @@ - - - - - @@ -2242,125 +1988,18 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + Zend_TimeSync + + + + + + + + + + + Zend_Uri @@ -2373,7 +2012,7 @@ Zend\Validator - + diff --git a/documentation/manual/en/module_specs/Zend_Config_Processor.xml b/documentation/manual/en/module_specs/Zend_Config_Processor.xml index 95f0bb3d7fe..f3c6f6f04ae 100644 --- a/documentation/manual/en/module_specs/Zend_Config_Processor.xml +++ b/documentation/manual/en/module_specs/Zend_Config_Processor.xml @@ -40,7 +40,7 @@ Zend\Config\Processor\Translator: translate configuration values - in other languages using Zend\Translator; + in other languages using Zend\I18n\Translator; @@ -188,15 +188,20 @@ echo $config->foo; 'dog'), true); -$italian = array( - 'dog' => 'cane' -); +/* + * The following mapping would exist for the translation + * loader you provide to the translator instance + * $italian = array( + * 'dog' => 'cane' + * ); + */ -$translator = new Translator(Translator::AN_ARRAY, $italian, 'it_IT'); +$translator = new Translator(); +// ... configure the translator ... $processor = new TranslatorProcessor($translator); echo "English: {$config->animal}, "; diff --git a/documentation/manual/en/module_specs/Zend_Currency-Additional.xml b/documentation/manual/en/module_specs/Zend_Currency-Additional.xml deleted file mode 100644 index 2dea4f6fbd2..00000000000 --- a/documentation/manual/en/module_specs/Zend_Currency-Additional.xml +++ /dev/null @@ -1,135 +0,0 @@ - -
Additional informations on Zend_Currency - - -
Currency informations - - - - Sometimes it is necessary to get informations which are related to a currency. - Zend_Currency provides you with several methods to get this - informations. Available methods include the following: - - - - - - getCurrencyList(): Returns a list - of all currencies which are used in the given region as array. Defaults to the - objects locale when no region has been given. - - - - - - getLocale(): Returns the set - locale for the actual currency. - - - - - - getName(): Returns the full name - for the actual currency. When there is no full name available for the actual - currency, it will return the abbreviation for it. - - - - - - getRegionList(): Returns a list - of all regions where this currency is used as array. Defaults to the objects - currency when no currency has been given. - - - - - - getService(): Returns the set - exchange service object for the actual currency. - - - - - - getShortName(): Returns the - abbreviation for the actual currency. - - - - - - getSymbol(): Returns the currency - sign for the currency. When the currency has no symbol, then it will return the - abbreviation for it. - - - - - - getValue(): Returns the set - value for the actual currency. - - - - - - Let's see some code snippets as example: - - - getValue()); -// returns 0 - -var_dump($currency->getRegionList()); -// could return an array with all regions where USD is used - -var_dump($currency->getRegionList('EUR')); -// returns an array with all regions where EUR is used - -var_dump($currency->getName()); -// could return 'US Dollar' - -var_dump($currency->getName('EUR')); -// returns 'Euro' -]]> - - - As you can see, several methods allow to use additional parameters to override the - actual object to get informations for other currencies. Omitting this parameters will - return informations from the actual set currency. - -
- -
Currency Performance Optimization - - - - Zend_Currency's performance can be optimized using - Zend_Cache. The static method - Zend_Currency::setCache($cache) accepts one option: a - Zend_Cache adapter. If the cache adapter is set, the localization - data which is used by Zend_Currency will be cached. Additionally - there are some static methods for manipulating the cache: - getCache(), hasCache(), - clearCache() and removeCache(). - - - Caching currencies - - - 120, - 'automatic_serialization' => true), - array('cache_dir' - => dirname(__FILE__) . '/_files/')); -Zend_Currency::setCache($cache); -]]> - -
-
diff --git a/documentation/manual/en/module_specs/Zend_Currency-Calculation.xml b/documentation/manual/en/module_specs/Zend_Currency-Calculation.xml deleted file mode 100644 index 2d04bd33e86..00000000000 --- a/documentation/manual/en/module_specs/Zend_Currency-Calculation.xml +++ /dev/null @@ -1,119 +0,0 @@ - -
Calculating with currencies - - - - When working with currencies you will sometimes also have to calculate with them. - Zend_Currency allows you to do this with some simple methods. - The following methods are supported for calculation: - - - - - - add(): This method adds the given - currency to the existing currency object. - - - - - - sub(): This method substracts the - given currency from the existing currency object. - - - - - - div(): This method divides the - given currency from the existing currency object. - - - - - - mul(): This method multiplies the - given currency with the existing currency object. - - - - - - mod(): This method calculates the - remaining value (modulo) from dividing the given currency from the existing - currency object. - - - - - - compare(): This method compares - the given currency with the existing currency object. When both values are - equal it returns '0'. When the existing currency value is greater than the - given, this method will return 1. Otherwise you will get '-1' returned. - - - - - - equals(): This method compares - the given currency with the existing currency object. When both values are - equal it returns TRUE, otherwise - FALSE. - - - - - - isMore(): This method compares - the given currency with the existing currency object. When the existing - currency is greater than the given one, you will get TRUE - in return, otherwise FALSE. - - - - - - isLess(): This method compares - the given currency with the existing currency object. When the existing - currency is less than the given one, you will get TRUE - in return, otherwise FALSE. - - - - - - As you can see the multiple methods allow any kind of calculation with - Zend_Currency. See the next snippets as example: - - - 1000, - 'currency' => 'USD', - ) -); - -print $currency; // Could return '$ 1.000,00' - -$currency->add(500); -print $currency; // Could return '$ 1.500,00' -]]> - - 500, - 'currency' => 'USD', - ) -); - -if ($currency->isMore($currency_2)) { - print "First is more"; -} - -$currency->div(5); -print $currency; // Could return '$ 200,00' -]]> -
diff --git a/documentation/manual/en/module_specs/Zend_Currency-Description.xml b/documentation/manual/en/module_specs/Zend_Currency-Description.xml deleted file mode 100644 index 0f9508b99be..00000000000 --- a/documentation/manual/en/module_specs/Zend_Currency-Description.xml +++ /dev/null @@ -1,170 +0,0 @@ - -
What makes a currency? - - - - The currency consists of several informations. A name, a abbreviation and a sign. Each - of these could be relevant to be displayed, but only one at the same time. It would not - be a good practice to display something like "USD 1.000 $". - - - - Therefor Zend_Currency supports the definition of the currency - information which has to be rendered. The following constants can be used: - - - Rendered informations for a currency - - - - - - Constant - Description - - - - - - NO_SYMBOL - No currency representation will be rendered at all - - - - USE_SYMBOL - - - The currency symbol will be rendered. For US Dollar this would be '$' - - - - - USE_SHORTNAME - - - The abbreviation for this currency will be rendered. For US Dollar this - would be 'USD'. Most abbreviations consist of 3 characters - - - - - USE_NAME - - - The full name for this currency will be rendered. For US Dollar the full - name would be "US Dollar" - - - - -
- - Selecting the currency description - - - - Let's assume that your client has again set "en_US" as locale. Using no option the - returned value could look like this: - - - 100, - ) -); - -print $currency; // Could return '$ 100' -]]> - - - By giving the proper option you can define what information which has to be - rendered. - - - 100, - 'display' => Zend_Currency::USE_SHORTNAME, - ) -); - -print $currency; // Could return 'USD 100' -]]> - - - Without providing the display the currency sign will be used - when rendering the object. When the currency has no sign, the abbreviation will be - used as replacement. - - - - Not all currencies have signs - - - - You should note that not all currencies have default currency signs. This means, - that when there is no default sign, and you set the sign to be rendered, you will - not have a rendered currency at all because the sign is an empty string. - - - - - Sometimes it is necessary to change the default informations. You can set each of the - three currency informations independently by giving the proper option. See the following - example. - - - Changing the currency description - - - - Let's assume that your client has again set "en_US" as locale. But now we don't want - to use the default settings but set our own description. This can simply be done - providing the proper option: - - - 100, - 'name' => 'Dollar', - ) -); - -print $currency; // Could return 'Dollar 100' -]]> - - - You could also set a sign or an abbreviations yourself. - - - 100, - 'symbol' => '$$$', - ) -); - -print $currency; // Could return '$$$ 100' -]]> - - - Automatic display settings - - - - When you set a name, abbreviation or sign yourself, than this new information will - automatically be set to be rendered. This simplification prevents you from setting - the proper display option when you set a information. - - - - So using the sign option you can omit - display and don't neet to setting it to - 'USE_SYMBOL'. - - -
diff --git a/documentation/manual/en/module_specs/Zend_Currency-Exchange.xml b/documentation/manual/en/module_specs/Zend_Currency-Exchange.xml deleted file mode 100644 index fbebcf85362..00000000000 --- a/documentation/manual/en/module_specs/Zend_Currency-Exchange.xml +++ /dev/null @@ -1,106 +0,0 @@ - -
Exchanging currencies - - - - Within the previous section we discussed currency calculations. But as you can imaging - calculating currencies does often mean to calculate different currencies from different - countries. - - - - In this case the currencies have to be exchanged so that both use the same currency. - Within real live this information is available by banks or by daily papers. But as we - are in web, we should use available exchange services. - Zend_Currency allows their usage with a simple callback. - - - - First let's write a simple exchange service. - - - - - - We have now created a manual exchange service. It will not fit the real live, but it - shows you how currency exchange works. - - - - Your exchange class must implement the - Zend_Currency_CurrencyInterface interface. This interface - requires the single method getRate() to be implemented. This - method has two parameters it will receive. Both are the short names for the given - currencies. Zend_Currency on the other side needs the exchange - rate to be returned. - - - - In a living exchange class you would probably ask the service provider for the correct - exchange rates. For our example the manual rate will be ok. - - - - Now we will simply attach our exchange class with Zend_Currency. - There are two ways to do this. Eigher by attaching a instance of the Exchange class, or - by simply giving a string with the classname. - - - 1000, - 'currency' => 'EUR', - ) -); - -$service = new SimpleExchange(); - -// attach the exchange service -$currency->setService($service); - -$currency2 = new Zend_Currency( - array( - 'value' => 1000, - 'currency' => 'USD', - ) -); - -print $currency->add($currency2); -]]> - - - The above example will return '$ 3.000' because the 1.000 USD will be - converted by a rate of 2 to 2.000 EUR. - - - Calculation without exchange service - - - - When you try to calculate two currency objects which do not use the same currency - and have no exchange service attached, you will get an exception. The reason is - that Zend_Currency is then not able to switch between the - different currencies. - - -
diff --git a/documentation/manual/en/module_specs/Zend_Currency-Introduction.xml b/documentation/manual/en/module_specs/Zend_Currency-Introduction.xml deleted file mode 100644 index c330095439e..00000000000 --- a/documentation/manual/en/module_specs/Zend_Currency-Introduction.xml +++ /dev/null @@ -1,69 +0,0 @@ - - - -
Introduction to Zend_Currency - - - - Zend_Currency is part of the strong support for I18n in Zend - Framework. It handles all issues related to currency, money representation, formatting, - exchange services and calculation. - - -
Why should you use Zend_Currency? - - - - Zend_Currency offers you the following benefit: - - - - - - Complete Locale support - - - - This component works with all available locales and therefore knows about more - than 100 different localized currencies. This includes informations like - currency names, abbreviations, money signs and much more. - - - - - - Reusable Currency Definitions - - - - Zend_Currency has the advantage that already defined - currency representations can be reused. You could also have 2 different - representations for the same currency. - - - - - - Currency calculation - - - - Zend_Currency allows you also to calculate with currency - values. Therefore, it provides you an interface to exchange services. - - - - - - Additional Methods - - - - Zend_Currency includes several additional methods that - offer detailed informations about currencies like which currency is used - within a defined region and what are the known abbreviations of a currency. - - - -
-
diff --git a/documentation/manual/en/module_specs/Zend_Currency-Number.xml b/documentation/manual/en/module_specs/Zend_Currency-Number.xml deleted file mode 100644 index b725cdfff8c..00000000000 --- a/documentation/manual/en/module_specs/Zend_Currency-Number.xml +++ /dev/null @@ -1,115 +0,0 @@ - -
How does the currency look like? - - - - How the value of a currency will be rendered depends mainly on the used locale. There - are several informations which are set by the locale. Each of them can manually be - overridden by using the proper option. - - - - For example, most locales are using the Latin script for rendering numbers. But there - are languages like "Arabic" which are using other digits. And when you have an Arabic - website you may also want to render other currencies by using the Arabic script. See - the following example: - - - Using a custom script - - - - Let's expect that we are again using our "Dollar" currency. But now we want to - render our currency by using the Arabic script. - - - 1000, - 'script' => 'Arab', - ) -); - -print $currency; // Could return '$ Ł”Ł¬Ł Ł Ł Ł«Ł Ł ' -]]> - - - - For more informations about available scripts look into - Zend_Locale's chapter - about numbering systems. - - - - But also the formatting of a currency number (money value) can be changed. Per default - it depends on the used locale. It includes the separator which will be used between - thousands, which sign will be used as decimal point, and also the used precision. - - - 1000, - 'currency' => 'USD' - 'format' => 'de', - ) -); - -print $currency; // Could return '$ 1.000' -]]> - - - There are two ways to define the format which will be used. You can either give a - locale or define a format manually. - - - - When you are using a locale for defining the format all is done automatically. The - locale 'de', for example, defines '.' as separator for thousands and ',' as decimal - point. Within English this is reversed. - - - 1000, - 'currency' => 'USD' - 'format' => 'de', - ) -); - -$currency_2 = new Zend_Currency( - array( - 'value' => 1000, - 'currency' => 'USD' - 'format' => 'en', - ) -); - -print $currency_1; // Could return '$ 1.000' -print $currency_2; // Could return '$ 1,000' -]]> - - - When you define it manually then you must conform the format as described in - this chapter about - localizing. See the following: - - - 1000, - 'currency' => 'USD' - 'format' => '#0', - ) -); - -print $currency; // Could return '$ 1000' -]]> - - - In the above snippet we deleted the separator and also the precision. - -
diff --git a/documentation/manual/en/module_specs/Zend_Currency-Options.xml b/documentation/manual/en/module_specs/Zend_Currency-Options.xml deleted file mode 100644 index c08a266c5b0..00000000000 --- a/documentation/manual/en/module_specs/Zend_Currency-Options.xml +++ /dev/null @@ -1,167 +0,0 @@ - - - -
Options for currencies - - - - Depending on your needs, several options can be specified at instantiation. All of this - options have default values. But sometimes it is necessary to define how your currencies - will be rendered. This includes for example: - - - - - - Currency symbol, shortname or name: - - - - Zend_Currency knows all currency names, abbreviations and - signs. But sometimes you could be in need to define the string which has to be - displayed as replacement for a currency. - - - - - - Currency position: - - - - The position of the currency symbol is automatically defined. But sometimes you - could be in need to define it manually. - - - - - - Script: - - - - You could define the script which shall be used to display digits. Detailed - information about scripts and their usage can be found in - Zend_Locale's chapter Numeral System Conversion. - - - - - - Number formatting: - - - - The amount of currency (generally known as money value) is formatted by - using the formatting rules defined by the locale. For example is the ',' - sign in English used as separator for thousands, but in German as precision - sign. - - - - - - The following list mentions all options which could be set. They can either be set at - initiation or by using the setFormat() method. In any case - you have to give this options as array. - - - - - - currency: Defines the abbreviation - which can be displayed. - - - - - - display: Defines which part of the - currency should be used for displaying the currency representation. There are 4 - representations which can be used and which are all described in this - table. - - - - - - format: Defines the format which - should be used for displaying numbers. This number-format includes for example - the thousand separator. You can either use a default format by giving a locale - identifier, or define the number-format manually. If no format is set the locale - from the Zend_Currency object will be used. See the chapter about number - formatting for details. - - - - - - locale: Defines a locale for this - currency. It will be used for detecting the default values when other settings - are omitted. Note that when you don't set a locale yourself, it will be detected - automatically which could lead to problems. - - - - - - name: Defines the full currency name - which can be displayed. - - - - - - position: Defines the position at - which the currency description should be displayed. The supported positions are - described this section. - - - - - - precision: Defines the precision which - should be used for the currency representation. The default value depends on the - locale and is for most locales 2. - - - - - - script: Defined which script should - be used for displaying digits. The default script for most locales is - 'Latn', which includes the digits 0 to 9. Other - scripts such as 'Arab' (Arabian) are using other digits. See the chapter about numbering - systems for details and available options. - - - - - - service: Defines the exchange service - which has to be used when calculating with different currencies. - - - - - - symbol: Defines the currency symbol - which can be displayed. - - - - - - value: Defines the currency amount - (money value). Using this option you should also set the - service option. - - - - - - As you can see there is much which could be changed. Still as already mentioned the - default values for this settings conform the official standard for currency - representation in every country. - -
diff --git a/documentation/manual/en/module_specs/Zend_Currency-Position.xml b/documentation/manual/en/module_specs/Zend_Currency-Position.xml deleted file mode 100644 index 613aa0312d0..00000000000 --- a/documentation/manual/en/module_specs/Zend_Currency-Position.xml +++ /dev/null @@ -1,86 +0,0 @@ - -
Where is the currency? - - - - The position where the currency sign or name will be displayed depends on the locale. - Still, when you want to define this setting yourself you have to use the - display option and provide one of the following constants: - - - Available positions for the currency - - - - - - Constant - Description - - - - - - STANDARD - Sets the standard position as defined within the locale - - - - RIGHT - - - Displays the currency representation at the right side of the value - - - - - LEFT - - - Displays the currency representation at the left side of the value - - - - -
- - Setting the currency position - - - - Let's assume that your client has again set "en_US" as locale. Using no option the - returned value could look like this: - - - 100, - ) -); - -print $currency; // Could return '$ 100' -]]> - - - So by using the default setting the currency (in our case $) could either be - rendered left or right from the value. Now let's define a fixed position: - - - 100, - 'position' => Zend_Currency::RIGHT, - ) -); - -print $currency; // Could return '100 $'; -]]> - - - Note that in the second snippet the position of USD is fixed - regardless of the used locale or currency. - - -
diff --git a/documentation/manual/en/module_specs/Zend_Currency-Usage.xml b/documentation/manual/en/module_specs/Zend_Currency-Usage.xml deleted file mode 100644 index 6016546e83e..00000000000 --- a/documentation/manual/en/module_specs/Zend_Currency-Usage.xml +++ /dev/null @@ -1,126 +0,0 @@ - -
Using Zend_Currency - - -
Generic usage - - - - The simplest usecase within an application is to use the clients locale. When you create - a instance of Zend_Currency without giving any options, your - clients locale will be used to set the proper currency. - - - Creating a currency with client settings - - - - Let's assume that your client has set "en_US" as wished language within his browser. - In this case Zend_Currency will automatically detect the - currency which has to be used. - - - - - - The created object would now contain the currency "US Dollar" as this is the actual - assigned currency for US (United States). It has also other options set, like - "$" for the currency sign or "USD" for the abbreviation. - - - - Automatic locale detection does not always work - - - - You should note that this automatic locale detection does not always work properly. - The reason for this behaviour is that Zend_Currency must have - a locale which includes a region. When the client would only set "en" as locale - Zend_Currency would not know which of the more than 30 - countries was meant. In this case an exception would be raised. - - - - A client could also omit the locale settings within his browser. This would lead to - the problem that your environment settings will be used as fallback and could also - lead to an exception. - - -
- -
Currency creation based on a locale - - - - To prevent the problems with your client you could simply set the wished locale - manually. - - - 'en_US')); - -// See the actual settings which are fixed to 'en_US' -// var_dump($currency); -]]> - - - As within our first example the used currency will be "US Dollar". But now we are no - longer dependend on the clients settings. - - - - Zend_Currency also supports the usage of an application-wide - locale. You can set a Zend_Locale instance in the registry as - shown below. With this notation you can avoid setting the locale manually for each - instance when you want to use the same locale throughout the application. - - - -
- -
Currency creation based on a country - - - - Zend_Currency is also able to work on a given country by using - Zend_Locale internally. - - - - - Uppercase territories - - - - When you know that you are using a territory, then you should uppercase it. - Otherwise you could get an in your eyes false locale in return. For example, - when you give "om" then you could expect "ar_OM" to be returned. But in fact it - returns "om", as it's also a language. - - - - Therefor always uppercase the input when you know that a territory is meant. - - -
-
diff --git a/documentation/manual/en/module_specs/Zend_Currency-Value.xml b/documentation/manual/en/module_specs/Zend_Currency-Value.xml deleted file mode 100644 index 0c0d16dd225..00000000000 --- a/documentation/manual/en/module_specs/Zend_Currency-Value.xml +++ /dev/null @@ -1,109 +0,0 @@ - -
How much is my currency? - - - - When you are working with currencies then you normally want to display an amount of - money. And when you work with different currencies then you have to do this with three - different things. The amount you want to display, the precision you want to use, and - probably the exchange rate. - - -
Working with currency values - - - - The currency value, a.k.a. the money, you want to use can easily be set by using the - value option. - - - 1000, - 'currency' => 'USD', - ) -); - -print $currency; // Could return '$ 1.000' -]]> - - - Using the setFormat() method with this array option, and - also by using the setValue() method you can set the value - afterwards. - - - 1000, - 'currency' => 'USD', - ) -); - -print $currency->setValue(2000); // Could return '$ 2.000' -]]> - - - With the getValue() method you will get the actual set - value. - -
- -
Using precision on currencies - - - - When working with currencies they you probably also have to handle precision. - Most currencies use a precision of 2. This means that when you have 100 US dollars - you could also have 50 cents. The related value is simply a floating value. - - - 1000.50, - 'currency' => 'USD', - ) -); - -print $currency; // Could return '$ 1.000,50' -]]> - - - Of course, as the default precision is 2, you will get '00' for the decimal value - when there is no precision to display. - - - 1000, - 'currency' => 'USD', - ) -); - -print $currency; // Could return '$ 1.000,00' -]]> - - - To get rid of this default precision you could simply use the - precision option and set it to '0'. And you can set any other - precision you want to use between 0 and 9. All values will be rounded or streched - when they don't fit the set precision. - - - 1000,30, - 'currency' => 'USD', - 'precision' => 0 - ) -); - -print $currency; // Could return '$ 1.000' -]]> -
-
diff --git a/documentation/manual/en/module_specs/Zend_Date-Additional.xml b/documentation/manual/en/module_specs/Zend_Date-Additional.xml deleted file mode 100644 index bf918208339..00000000000 --- a/documentation/manual/en/module_specs/Zend_Date-Additional.xml +++ /dev/null @@ -1,339 +0,0 @@ - -
Working Examples - - - - Within this chapter, we will describe several additional functions which are also available - through Zend_Date. Of course all described functions have additional - examples to show the expected working and the simple API for the proper - using of them. - - -
Checking Dates - - - - Probably most dates you will get as input are strings. But the problem with strings is - that you can not be sure if the string is a real date. Therefor - Zend_Date has spent an own static function to check date strings. - Zend_Locale has an own function - getDate($date, $locale) which parses a date and returns the - proper and normalized date parts. A monthname for example will be recognised and - returned just a month number. But as Zend_Locale does not know - anything about dates because it is a normalizing and localizing class we have - integrated an own function isDate($date) which checks this. - - - - isDate($date, $format, $locale) can take up to 3 parameters - and needs minimum one parameter. So what we need to verify a date is, of course, the - date itself as string. The second parameter can be the format which the date is - expected to have. If no format is given the standard date format from your locale is - used. For details about how formats should look like see the chapter about self defined formats. - - - - The third parameter is also optional as the second parameter and can be used to give a - locale. We need the locale to normalize monthnames and daynames. So with the third - parameter we are able to recognise dates like '01.JƤnner.2000' or - '01.January.2000' depending on the given locale. - - - - isDate() of course checks if a date does exist. - Zend_Date itself does not check a date. So it is possible to - create a date like '31.February.2000' with - Zend_Date because Zend_Date will - automatically correct the date and return the proper date. In our case - '03.March.2000'. isDate() on the - other side does this check and will return FALSE on - '31.February.2000' because it knows that this date is impossible. - - - Checking Dates - - - - -
- -
Sunrise and Sunset - - - - Zend_Date has also functions integrated for getting informations - from the sun. Often it is necessary to get the time for sunrise or sunset within a - particularly day. This is quite easy with Zend_Date as just the - expected day has to be given and additionally location for which the sunrise or sunset - has to be calculated. - - - - As most people do not know the location of their city we have also spent a helper class - which provides the location data for about 250 capital and other big cities around the - whole world. Most people could use cities near themself as the difference for locations - situated to each other can only be measured within some seconds. - - - - For creating a listbox and choosing a special city the function - Zend_Date_Cities::getCityList() can be used. It returns the - names of all available predefined cities for the helper class. - - - Getting all Available Cities - - - - - - - The location itself can be received with the - Zend_Date_Cities::city() function. It accepts the name of the - city as returned by the Zend_Date_Cities::getCityList() - function and optional as second parameter the horizon to set. - - - - There are 4 defined horizons which can be used with locations to receive the exact time - of sunset and sunrise. The '$horizon' parameter is always optional in - all functions. If it is not set, the 'effective' horizon is used. - - - Types of Supported Horizons for Sunset and Sunrise - - - - - - Horizon - Description - Usage - - - - - - effective - Standard horizon - - - Expects the world to be a ball. This horizon is always used if non is - defined. - - - - - civil - Common horizon - Often used in common medias like TV or radio - - - - nautic - Nautic horizon - Often used in sea navigation - - - - astronomic - Astronomic horizon - Often used for calculation with stars - - - -
- - - Of course also a self-defined location can be given and calculated with. Therefor a - 'latitude' and a 'longitude' has to be given - and optional the 'horizon'. - - - Getting the Location for a City - - - 41.5, 'longitude' => 13.2446); -]]> - - - - As now all needed data can be set the next is to create a - Zend_Date object with the day where sunset or sunrise should be - calculated. For the calculation there are 3 functions available. It is possible to - calculate sunset with 'getSunset()', sunrise with - 'getSunrise()' and all available informations related to the - sun with 'getSunInfo()'. After the calculation the - Zend_Date object will be returned with the calculated time. - - - Calculating Sun Information - - - getSunset($city); -print $sunset->get(Zend_Date::ISO_8601); - -// calculate all sun informations -$info = $date->getSunInfo($city); -foreach ($info as $sun) { - print "\n" . $sun->get(Zend_Date::ISO_8601); -} -]]> - -
- -
Time Zones - - - - Time zones are as important as dates themselves. There are several time zones depending - on where in the world a user lives. So working with dates also means to set the proper - timezone. This may sound complicated but it's easier as expected. As already mentioned - in the first chapter of Zend_Date the default timezone has to be - set. Either by php.ini or by definition within the bootstrap file. - - - - A Zend_Date object of course also stores the actual timezone. - Even if the timezone is changed after the creation of the object it remembers the - original timezone and works with it. It is also not necessary to change the timezone - within the code with PHP functions. Zend_Date - has two built-in functions which makes it possible to handle this. - - - - getTimezone() returns the actual set timezone of within the - Zend_Date object. Remember that Zend_Date - is not coupled with PHP internals. So the returned timezone is not - the timezone of the PHP script but the timezone of the object. - setTimezone($zone) is the second function and makes it possible - to set new timezone for Zend_Date. A given timezone is always - checked. If it does not exist an exception will be thrown. Additionally the actual - scripts or systems timezone can be set to the date object by calling - setTimezone() without the zone parameter. This is also done - automatically when the date object is created. - - - Working with Time Zones - - - getIso(); - -// what timezone do we have ? -print $date->getTimezone(); - -// set another timezone -$date->setTimezone('America/Chicago'); - -// what timezone do we now have ? -print $date->getTimezone(); - -// see the changed date object -print $date->getIso(); -]]> - - - - Zend_Date always takes the actual timezone for object creation as - shown in the first lines of the example. Changing the timezone within the created object - also has an effect to the date itself. Dates are always related to a timezone. Changing - the timezone for a Zend_Date object does not change the time of - Zend_Date. Remember that internally dates are always stored as - timestamps and in GMT. So the timezone means how much hours should be - substracted or added to get the actual global time for the own timezone and region. - - - - Having the timezone coupled within Zend_Date has another positive - effect. It is possible to have several dates with different timezones. - - - Multiple Time Zones - - - getIso(); - -// the date stays unchanged even after changeing the timezone -date_default_timezone_set('America/Chicago'); -print $date->getIso(); - -$otherdate = clone $date; -$otherdate->setTimezone('Brazil/Acre'); - -// view our date object -print $otherdate->getIso(); - -// set the object to the actual systems timezone -$lastdate = clone $date; -$lastdate->setTimezone(); - -// view our date object -print $lastdate->getIso(); -]]> - -
-
diff --git a/documentation/manual/en/module_specs/Zend_Date-Basic.xml b/documentation/manual/en/module_specs/Zend_Date-Basic.xml deleted file mode 100644 index 31a94e0283b..00000000000 --- a/documentation/manual/en/module_specs/Zend_Date-Basic.xml +++ /dev/null @@ -1,173 +0,0 @@ - -
Basic Methods - - - - The following sections show basic usage of Zend_Date primarily by - example. For this manual, "dates" always imply a calendar date with a time, even when not - explicitly mentioned, and vice-versa. The part not specified defaults to an internal - representation of "zero". Thus, adding a date having no calendar date and a time value of 12 - hours to another date consisting only of a calendar date would result in a date having that - calendar date and a time of "noon". - - - - Setting only a specific date, with no time part, implies a time set to 00:00:00. Conversely, - setting only a specific time implies a date internally set to 01.01.1970 plus the number of - seconds equal to the elapsed hours, minutes, and seconds identified by the time. Normally, - people measure things from a starting point, such as the year 0 A.D. However, many software - systems use the first second of the year 1970 as the starting point, and denote times as a - timestamp offset counting the number of seconds elapsed from this starting point. - - -
Current Date - - - - Without any arguments, constructing an instance returns an object in the default locale - with the current, local date using PHP's - time() function to obtain the UNIX timestamp - for the object. Make sure your PHP environment has the correct - default timezone. - - - Creating the Current Date - - - - -
- -
Zend_Date by Example - - - - Reviewing basic methods of Zend_Date is a good place to start for - those unfamiliar with date objects in other languages or frameworks. A small example - will be provided for each method below. - - -
Output a Date - - - - The date in a Zend_Date object may be obtained as a localized - integer or string using the get() method. There are many - available options, which will be explained in later sections. - - - get() - Output a Date - - - get(); -]]> - -
- -
Setting a Date - - - - The set() method alters the date stored in the object, and - returns the final date value as a timestamp (not an object). Again, there are many - options which will be explored in later sections. - - - set() - Set a Date - - - set('13:00:00',Zend_Date::TIMES); -print $date->get(Zend_Date::W3C); -]]> - -
- -
Adding and Subtracting Dates - - - - Adding two dates with add() usually involves adding a real - date in time with an artificial timestramp representing a date part, such as 12 - hours, as shown in the example below. Both add() and - sub() use the same set of options as - set(), which will be explained later. - - - add() - Adding Dates - - - add('12:00:00', Zend_Date::TIMES); - -echo "Date via get() = ", $date->get(Zend_Date::W3C), "\n"; - -// use magic __toString() method to call Zend_Date's toString() -echo "Date via toString() = ", $date, "\n"; -]]> - -
- -
Comparison of Dates - - - - All basic Zend_Date methods can operate on entire dates - contained in the objects, or can operate on date parts, such as comparing the - minutes value in a date to an absolute value. For example, the current minutes in - the current time may be compared with a specific number of minutes using - compare(), as in the example below. - - - compare() - Compare Dates - - - compare(10, Zend_Date::MINUTE) == -1) { - print "This hour is less than 10 minutes old"; -} else { - print "This hour is at least 10 minutes old"; -} -]]> - - - - For simple equality comparisons, use equals(), which - returns a boolean. - - - equals() - Identify a Date or Date Part - - - equals(10, Zend_Date::HOUR)) { - print "It's 10 o'clock. Time to get to work."; -} else { - print "It is not 10 o'clock. You can keep sleeping."; -} -]]> - -
-
-
diff --git a/documentation/manual/en/module_specs/Zend_Date-Constants.xml b/documentation/manual/en/module_specs/Zend_Date-Constants.xml deleted file mode 100644 index 431d4e9d549..00000000000 --- a/documentation/manual/en/module_specs/Zend_Date-Constants.xml +++ /dev/null @@ -1,1651 +0,0 @@ - -
Constants for General Date Functions - - - - Whenever a Zend_Date method has a $parts - parameter, one of the constants below can be used as the argument for that parameter, in - order to select a specific part of a date or indicate the date format used or desired (e.g. - RFC 822). - - -
Using Constants - - - - For example, the constant Zend_Date::HOUR can be used in the ways - shown below. When working with days of the week, calendar dates, hours, minutes, - seconds, and any other date parts that are expressed differently when in different parts - of the world, the object's timezone will automatically be used to compute the correct - value, even though the internal timestamp is the same for the same moment in time, - regardless of the user's physical location in the world. Regardless of the units - involved, output must be expressed either as GMT or - UTC or localized to a locale. The example output below reflects - localization to Europe/GMT+1 hour (e.g. Germany, Austria, France). - - - Operations Involving Zend_Date::HOUR - - - - - - Method - Description - Original date - Result - - - - - - get(Zend_Date::HOUR) - Output of the hour - 2009-02-13T14:53:27+01:00 - 14 - - - - set(12, Zend_Date::HOUR) - Set new hour - 2009-02-13T14:53:27+01:00 - 2009-02-13T12:53:27+01:00 - - - - add(12, Zend_Date::HOUR) - Add hours - 2009-02-13T14:53:27+01:00 - 2009-02-14T02:53:27+01:00 - - - - sub(12, Zend_Date::HOUR) - Subtract hours - 2009-02-13T14:53:27+01:00 - 2009-02-13T02:53:27+01:00 - - - - compare(12, Zend_Date::HOUR) - Compare hour, returns 0, 1 or -1 - 2009-02-13T14:53:27+01:00 - 1 (if object > argument) - - - - copy(Zend_Date::HOUR) - Copies only the hour part - 2009-02-13T14:53:27+01:00 - 1970-01-01T14:00:00+01:00 - - - - equals(14, Zend_Date::HOUR) - Compares the hour, returns TRUE or - FALSE 2009-02-13T14:53:27+01:00 - TRUE - - - - isEarlier(12, Zend_Date::HOUR) - Compares the hour, returns TRUE or - FALSE 2009-02-13T14:53:27+01:00 - TRUE - - - - isLater(12, Zend_Date::HOUR) - Compares the hour, returns TRUE or - FALSE 2009-02-13T14:53:27+01:00 - FALSE - - - -
-
- -
List of All Constants - - - - Each part of a date or time has a unique constant in Zend_Date. - All constants supported by Zend_Date are listed below. - - - Day Constants - - - - - - Constant - Description - Date - Result - - - - - - Zend_Date::DAY - Day (as number, two digits) - 2009-02-13T14:53:27+01:00 - 13 - - - - Zend_Date::DAY_SHORT - Day (as number, one or two digits) - 2009-02-06T14:53:27+01:00 - 6 - - - - Zend_Date::WEEKDAY - Weekday (Name of the day, localized, complete) - 2009-02-13T14:53:27+01:00 - Friday - - - - Zend_Date::WEEKDAY_SHORT - - - Weekday (Name of the day, localized, abbreviated, two to four chars) - - - 2009-02-13T14:53:27+01:00 - Fri for Friday - - - - Zend_Date::WEEKDAY_NAME - - - Weekday (Name of the day, localized, abbreviated, one or two chars) - - - 2009-02-13T14:53:27+01:00 - Fr for Friday - - - - Zend_Date::WEEKDAY_NARROW - - - Weekday (Name of the day, localized, abbreviated, one char) - - - 2009-02-13T14:53:27+01:00 - F for Friday - - - - Zend_Date::WEEKDAY_DIGIT - Weekday (0 = Sunday, 6 = Saturday) - 2009-02-13T14:53:27+01:00 - 5 for Friday - - - - Zend_Date::WEEKDAY_8601 - - - Weekday according to ISO 8601 (1 = Monday, 7 = - Sunday) - - - 2009-02-13T14:53:27+01:00 - 5 for Friday - - - - Zend_Date::DAY_OF_YEAR - Day (as a number, one or two digits) - 2009-02-13T14:53:27+01:00 - 43 - - - - - Zend_Date::DAY_SUFFIX - English addendum for the day (st, nd, rd, th) - 2009-02-13T14:53:27+01:00 - th - - - -
- - Week Constants - - - - - - Constant - Description - Date - Result - - - - - - Zend_Date::WEEK - Week (as number, 1-53) - 2009-02-13T14:53:27+01:00 - 8 - - - -
- - Month Constants - - - - - - Constant - Description - Date - Result - - - - - - Zend_Date::MONTH_NAME - Month (Name of the month, localized, complete) - 2009-02-13T14:53:27+01:00 - February - - - - Zend_Date::MONTH_NAME_SHORT - - - Month (Name of the month, localized, abbreviated, two to four chars) - - - 2009-02-13T14:53:27+01:00 - Feb - - - - Zend_Date::MONTH_NAME_NARROW - - - Month (Name of the month, localized, abbreviated, one or two chars) - - - 2009-02-13T14:53:27+01:00 - F - - - - Zend_Date::MONTH - Month (Number of the month, two digits) - 2009-02-13T14:53:27+01:00 - 02 - - - - Zend_Date::MONTH_SHORT - Month (Number of the month, one or two digits) - 2009-02-13T14:53:27+01:00 - 2 - - - - Zend_Date::MONTH_DAYS - Number of days for this month (number) - 2009-02-13T14:53:27+01:00 - 28 - - - -
- - Year Constants - - - - - - Constant - Description - Date - Result - - - - - - Zend_Date::YEAR - Year (number) - 2009-02-13T14:53:27+01:00 - 2009 - - - - Zend_Date::YEAR_8601 - Year according to ISO 8601 (number) - 2009-02-13T14:53:27+01:00 - 2009 - - - - Zend_Date::YEAR_SHORT - Year (number, two digits) - 2009-02-13T14:53:27+01:00 - 09 - - - - Zend_Date::YEAR_SHORT_8601 - - - Year according to ISO 8601 (number, two digits) - - - 2009-02-13T14:53:27+01:00 - 09 - - - - Zend_Date::LEAPYEAR - - - Is the year a leap year? (TRUE or - FALSE) - - - 2009-02-13T14:53:27+01:00 - FALSE - - - -
- - Time Constants - - - - - - Constant - Description - Date - Result - - - - - - Zend_Date::HOUR - Hour (00-23, two digits) - 2009-02-13T14:53:27+01:00 - 14 - - - - Zend_Date::HOUR_SHORT - Hour (0-23, one or two digits) - 2009-02-13T14:53:27+01:00 - 14 - - - - Zend_Date::HOUR_SHORT_AM - Hour (1-12, one or two digits) - 2009-02-13T14:53:27+01:00 - 2 - - - - Zend_Date::HOUR_AM - Hour (01-12, two digits) - 2009-02-13T14:53:27+01:00 - 02 - - - - Zend_Date::MINUTE - Minute (00-59, two digits) - 2009-02-13T14:53:27+01:00 - 53 - - - - Zend_Date::MINUTE_SHORT - Minute (0-59, one or two digits) - 2009-02-13T14:03:27+01:00 - 3 - - - - Zend_Date::SECOND - Second (00-59, two digits) - 2009-02-13T14:53:27+01:00 - 27 - - - - Zend_Date::SECOND_SHORT - Second (0-59, one or two digits) - 2009-02-13T14:53:07+01:00 - 7 - - - - Zend_Date::MILLISECOND - Millisecond (theoretically infinite) - 2009-02-06T14:53:27.20546 - 20546 - - - - Zend_Date::MERIDIEM - Time of day (forenoon or afternoon) - 2009-02-13T14:53:27+01:00 - afternoon - - - - Zend_Date::SWATCH - Swatch Internet Time - 2009-02-13T14:53:27+01:00 - 620 - - - -
- - Timezone Constants - - - - - - Constant - Description - Date - Result - - - - - - Zend_Date::TIMEZONE - Name der time zone (string, abbreviated) - 2009-02-13T14:53:27+01:00 - CET - - - - Zend_Date::TIMEZONE_NAME - Name of the time zone (string, complete) - 2009-02-13T14:53:27+01:00 - Europe/Paris - - - - Zend_Date::TIMEZONE_SECS - - - Difference of the time zone to GMT in seconds - (integer) - - - 2009-02-13T14:53:27+01:00 - 3600 (seconds to GMT) - - - - Zend_Date::GMT_DIFF - Difference to GMT in seconds (string) - 2009-02-13T14:53:27+01:00 - +0100 - - - - Zend_Date::GMT_DIFF_SEP - - - Difference to GMT in seconds (string, separated) - - - 2009-02-13T14:53:27+01:00 - +01:00 - - - - Zend_Date::DAYLIGHT - - - Summer time or Winter time? (TRUE or - FALSE) - - - 2009-02-13T14:53:27+01:00 - FALSE - - - -
- - Date Format Constants (formats include timezone) - - - - - - Constant - Description - Date - Result - - - - - - Zend_Date::ISO_8601 - - - Date according to ISO 8601 (string, complete) - - - 2009-02-13T14:53:27+01:00 - 2009-02-13T14:53:27+01:00 - - - - Zend_Date::RFC_2822 - Date according to RFC 2822 (string) - 2009-02-13T14:53:27+01:00 - Fri, 13 Feb 2009 14:53:27 +0100 - - - - Zend_Date::TIMESTAMP - - - Unix time - (seconds since 1.1.1970, mixed) - - - 2009-02-13T14:53:27+01:00 - 1234533207 - - - - Zend_Date::ATOM - Date according to ATOM (string) - 2009-02-13T14:53:27+01:00 - 2009-02-13T14:53:27+01:00 - - - - Zend_Date::COOKIE - Date for Cookies (string, for Cookies) - 2009-02-13T14:53:27+01:00 - - - Friday, 13-Feb-09 14:53:27 - Europe/Paris - - - - - Zend_Date::RFC_822 - Date according to RFC 822 (string) - 2009-02-13T14:53:27+01:00 - Fri, 13 Feb 09 14:53:27 +0100 - - - - Zend_Date::RFC_850 - Date according to RFC 850 (string) - 2009-02-13T14:53:27+01:00 - - - Friday, 13-Feb-09 14:53:27 - Europe/Paris - - - - - Zend_Date::RFC_1036 - Date according to RFC 1036 (string) - 2009-02-13T14:53:27+01:00 - Fri, 13 Feb 09 14:53:27 +0100 - - - - Zend_Date::RFC_1123 - Date according to RFC 1123 (string) - 2009-02-13T14:53:27+01:00 - Fri, 13 Feb 2009 14:53:27 +0100 - - - - Zend_Date::RSS - Date for RSS Feeds (string) - 2009-02-13T14:53:27+01:00 - Fri, 13 Feb 2009 14:53:27 +0100 - - - - Zend_Date::W3C - - - Date for HTML or HTTP according - to W3C (string) - - - 2009-02-13T14:53:27+01:00 - 2009-02-13T14:53:27+01:00 - - - -
- - - Especially note Zend_Date::DATES, since this format specifier has - a unique property within Zend_Date as an - input format specifier. When used as an input format for - $part, this constant provides the most flexible acceptance of a - variety of similar date formats. Heuristics are used to automatically extract dates from - an input string and then "fix" simple errors in dates (if any), such as swapping of - years, months, and days, when possible. - - - Date and Time Formats (format varies by locale) - - - - - - Constant - Description - Date - Result - - - - - - Zend_Date::ERA - Epoch (string, localized, abbreviated) - 2009-02-13T14:53:27+01:00 - AD (anno Domini) - - - - Zend_Date::ERA_NAME - Epoch (string, localized, complete) - 2009-02-13T14:53:27+01:00 - anno domini (anno Domini) - - - - Zend_Date::DATES - Standard date (string, localized, default value). - 2009-02-13T14:53:27+01:00 - 13.02.2009 - - - - Zend_Date::DATE_FULL - Complete date (string, localized, complete) - 2009-02-13T14:53:27+01:00 - Friday, 13. February 2009 - - - - Zend_Date::DATE_LONG - Long date (string, localized, long) - 2009-02-13T14:53:27+01:00 - 13. February 2009 - - - - Zend_Date::DATE_MEDIUM - Normal date (string, localized, normal) - 2009-02-13T14:53:27+01:00 - 13.02.2009 - - - - Zend_Date::DATE_SHORT - Abbreviated Date (string, localized, abbreviated) - 2009-02-13T14:53:27+01:00 - 13.02.09 - - - - Zend_Date::TIMES - Standard time (string, localized, default value) - 2009-02-13T14:53:27+01:00 - 14:53:27 - - - - Zend_Date::TIME_FULL - Complete time (string, localized, complete) - 2009-02-13T14:53:27+01:00 - 14:53 Uhr CET - - - - Zend_Date::TIME_LONG - Long time (string, localized, Long) - 2009-02-13T14:53:27+01:00 - 14:53:27 CET - - - - Zend_Date::TIME_MEDIUM - Normal time (string, localized, normal) - 2009-02-13T14:53:27+01:00 - 14:53:27 - - - - Zend_Date::TIME_SHORT - Abbreviated time (string, localized, abbreviated) - 2009-02-13T14:53:27+01:00 - 14:53 - - - - Zend_Date::DATETIME - Standard date with time (string, localized, default value). - 2009-02-13T14:53:27+01:00 - 13.02.2009 14:53:27 - - - - Zend_Date::DATETIME_FULL - Complete date with time (string, localized, complete) - 2009-02-13T14:53:27+01:00 - - - Friday, 13. February 2009 14:53 Uhr - CET - - - - - Zend_Date::DATETIME_LONG - Long date with time (string, localized, long) - 2009-02-13T14:53:27+01:00 - - - 13. February 2009 14:53:27 CET - - - - - Zend_Date::DATETIME_MEDIUM - Normal date with time (string, localized, normal) - 2009-02-13T14:53:27+01:00 - 13.02.2009 14:53:27 - - - - Zend_Date::DATETIME_SHORT - Abbreviated date with time (string, localized, abbreviated) - 2009-02-13T14:53:27+01:00 - 13.02.09 14:53 - - - -
-
- -
Self-Defined OUTPUT Formats with ISO - - - - If you need a date format not shown above, then use a self-defined format composed from - the ISO format token specifiers below. The following examples - illustrate the usage of constants from the table below to create self-defined - ISO formats. The format length is unlimited. Also, multiple usage of - format constants is allowed. - - - - The accepted format specifiers can be changed from ISO Format to - PHP's date format if you are more comfortable with it. However, not - all formats defined in the ISO norm are supported with - PHP's date format specifiers. Use the - Zend_Date::setOptions(array('format_type' => 'php')) method to - switch Zend_Date methods from supporting ISO - format specifiers to PHP date() type - specifiers (see Self-Defined OUTPUT - Formats Using PHP's date() Format Specifiers below). - - - Self-Defined ISO Formats - - - toString("'Era:GGGG='GGGG, ' Date:yy.MMMM.dd'yy.MMMM.dd"); -]]> - - - Constants for ISO 8601 Date Output - - - - - - Constant - Description - Corresponds best to - Result - - - - - - G - Epoch, localized, abbreviated - Zend_Date::ERA - AD - - - - GG - Epoch, localized, abbreviated - Zend_Date::ERA - AD - - - - GGG - Epoch, localized, abbreviated - Zend_Date::ERA - AD - - - - GGGG - Epoch, localized, complete - Zend_Date::ERA_NAME - anno domini - - - - GGGGG - Epoch, localized, abbreviated - Zend_Date::ERA - a - - - - y - Year, at least one digit - Zend_Date::YEAR - 9 - - - - yy - Year, at least two digit - Zend_Date::YEAR_SHORT - 09 - - - - yyy - Year, at least three digit - Zend_Date::YEAR - 2009 - - - - yyyy - Year, at least four digit - Zend_Date::YEAR - 2009 - - - - yyyyy - Year, at least five digit - Zend_Date::YEAR - 02009 - - - - Y - - - Year according to ISO 8601, at least one digit - - - Zend_Date::YEAR_8601 - 9 - - - - YY - - - Year according to ISO 8601, at least two digit - - - Zend_Date::YEAR_SHORT_8601 - 09 - - - - YYY - - - Year according to ISO 8601, at least three digit - - - Zend_Date::YEAR_8601 - 2009 - - - - YYYY - - - Year according to ISO 8601, at least four digit - - - Zend_Date::YEAR_8601 - 2009 - - - - YYYYY - - - Year according to ISO 8601, at least five digit - - - Zend_Date::YEAR_8601 - 02009 - - - - M - Month, one or two digit - Zend_Date::MONTH_SHORT - 2 - - - - MM - Month, two digit - Zend_Date::MONTH - 02 - - - - MMM - Month, localized, abbreviated - Zend_Date::MONTH_NAME_SHORT - Feb - - - - MMMM - Month, localized, complete - Zend_Date::MONTH_NAME - February - - - - MMMMM - Month, localized, abbreviated, one digit - Zend_Date::MONTH_NAME_NARROW - F - - - - w - Week, one or two digit - Zend_Date::WEEK - 5 - - - - ww - Week, two digit - Zend_Date::WEEK - 05 - - - - d - Day of the month, one or two digit - Zend_Date::DAY_SHORT - 9 - - - - dd - Day of the month, two digit - Zend_Date::DAY - 09 - - - - D - Day of the year, one, two or three digit - Zend_Date::DAY_OF_YEAR - 7 - - - - DD - Day of the year, two or three digit - Zend_Date::DAY_OF_YEAR - 07 - - - - DDD - Day of the year, three digit - Zend_Date::DAY_OF_YEAR - 007 - - - - E - Day of the week, localized, abbreviated, one char - Zend_Date::WEEKDAY_NARROW - M - - - - EE - Day of the week, localized, abbreviated, two or more chars - Zend_Date::WEEKDAY_NAME - Mo - - - - EEE - Day of the week, localized, abbreviated, three chars - Zend_Date::WEEKDAY_SHORT - Mon - - - - EEEE - Day of the week, localized, complete - Zend_Date::WEEKDAY - Monday - - - - EEEEE - Day of the week, localized, abbreviated, one digit - Zend_Date::WEEKDAY_NARROW - M - - - - e - Number of the day, one digit - Zend_Date::WEEKDAY_DIGIT - 4 - - - - ee - Number of the day, two digit - Zend_Date::WEEKDAY_NARROW - 04 - - - - a - Time of day, localized - Zend_Date::MERIDIEM - vorm. - - - - h - Hour, (1-12), one or two digit - Zend_Date::HOUR_SHORT_AM - 2 - - - - hh - Hour, (01-12), two digit - Zend_Date::HOUR_AM - 02 - - - - H - Hour, (0-23), one or two digit - Zend_Date::HOUR_SHORT - 2 - - - - HH - Hour, (00-23), two digit - Zend_Date::HOUR - 02 - - - - m - Minute, (0-59), one or two digit - Zend_Date::MINUTE_SHORT - 2 - - - - mm - Minute, (00-59), two digit - Zend_Date::MINUTE - 02 - - - - s - Second, (0-59), one or two digit - Zend_Date::SECOND_SHORT - 2 - - - - ss - Second, (00-59), two digit - Zend_Date::SECOND - 02 - - - - S - Millisecond - Zend_Date::MILLISECOND - 20536 - - - - z - Time zone, localized, abbreviated - Zend_Date::TIMEZONE - CET - - - - zz - Time zone, localized, abbreviated - Zend_Date::TIMEZONE - CET - - - - zzz - Time zone, localized, abbreviated - Zend_Date::TIMEZONE - CET - - - - zzzz - Time zone, localized, complete - Zend_Date::TIMEZONE_NAME - Europe/Paris - - - - Z - Difference of time zone - Zend_Date::GMT_DIFF - +0100 - - - - ZZ - Difference of time zone - Zend_Date::GMT_DIFF - +0100 - - - - ZZZ - Difference of time zone - Zend_Date::GMT_DIFF - +0100 - - - - ZZZZ - Difference of time zone, separated - Zend_Date::GMT_DIFF_SEP - +01:00 - - - - A - Milliseconds from the actual day - Zend_Date::MILLISECOND - 20563 - - - -
- - - - Note that the default ISO format differs from - PHP's format which can be irritating if you have not used in - previous. Especially the format specifiers for Year and Minute - are often not used in the intended way. - - - - For year there are two specifiers available - which are often mistaken. The Y specifier - for the ISO year and the y specifier for the - real year. The difference is small but significant. - Y calculates the ISO year, which is often - used for calendar formats. See for example the 31. December 2007. The real year is - 2007, but it is the first day of the first week in the week 1 of the year 2008. - So, if you are using 'dd.MM.yyyy' you will get - '31.December.2007' but if you use 'dd.MM.YYYY' - you will get '31.December.2008'. As you see this is no bug but a - expected behaviour depending on the used specifiers. - - - - For minute the difference is not so big. ISO - uses the specifier m for the minute, unlike - PHP which uses i. So if you are getting no - minute in your format check if you have used the right specifier. - - -
- -
Self-Defined OUTPUT Formats Using PHP's date() Format Specifiers - - - - If you are more comfortable with PHP's date format specifier than - with ISO format specifiers, then you can use the - Zend_Date::setOptions(array('format_type' => 'php')) method to - switch Zend_Date methods from supporting ISO - format specifiers to PHP date() type - specifiers. Afterwards, all format parameters must be given with PHP's date() format - specifiers. The PHP date format lacks some of the formats - supported by the ISO Format, and vice-versa. If you are not already - comfortable with it, then use the standard ISO format instead. Also, - if you have legacy code using PHP's date format, then either manually - convert it to the ISO format using Zend_Locale_Format::convertPhpToIsoFormat(), - or use setOptions(). The following examples illustrate the - usage of constants from the table below to create self-defined formats. - - - Self-Defined Formats with PHP Specifier - - - 'php')); -$date = new Zend_Date(1234567890, false, $locale); - -// outputs something like 'February 16, 2007, 3:36 am' -print $date->toString('F j, Y, g:i a'); - -print $date->toString("'Format:D M j G:i:s T Y='D M j G:i:s T Y"); -]]> - - - PHP Date format and using constants - - - - It is important to note that Zend_Date's constants are - using the ISO notation. This means, that when you set - Zend_Date to use the PHP notation, - you should not use Zend_Date's constants, but define the - wished format manually. If you don't follow this recommendation, you can get - unexpected results. - - - - - The following table shows the list of PHP date format specifiers with - their equivalent Zend_Date constants and - CLDR and ISO equivalent format specifiers. In most - cases, when the CLDR and ISO format does not have - an equivalent format specifier, the PHP format specifier is not - altered by Zend_Locale_Format::convertPhpToIsoFormat(), and the - Zend_Date methods then recognize these "peculiar" - PHP format specifiers, even when in the default - "ISO" format mode. - - - Constants for PHP Date Output - - - - - - Constant - Description - Corresponds best to - closest CLDR equivalent - Result - - - - - - d - Day of the month, two digit - Zend_Date::DAY - dd - 09 - - - - D - Day of the week, localized, abbreviated, three digit - Zend_Date::WEEKDAY_SHORT - EEE - Mon - - - - j - Day of the month, one or two digit - Zend_Date::DAY_SHORT - d - 9 - - - - l (lowercase L) - Day of the week, localized, complete - Zend_Date::WEEKDAY - EEEE - Monday - - - - N - Number of the weekday, one digit - Zend_Date::WEEKDAY_8601 - e - 4 - - - - S - English suffixes for day of month, two chars - no equivalent - no equivalent - st - - - - w - Number of the weekday, 0=sunday, 6=saturday - Zend_Date::WEEKDAY_DIGIT - no equivalent - 4 - - - - z - Day of the year, one, two or three digit - Zend_Date::DAY_OF_YEAR - D - 7 - - - - W - Week, one or two digit - Zend_Date::WEEK - w - 5 - - - - F - Month, localized, complete - Zend_Date::MONTH_NAME - MMMM - February - - - - m - Month, two digit - Zend_Date::MONTH - MM - 02 - - - - M - Month, localized, abbreviated - Zend_Date::MONTH_NAME_SHORT - MMM - Feb - - - - n - Month, one or two digit - Zend_Date::MONTH_SHORT - M - 2 - - - - t - Number of days per month, one or two digits - Zend_Date::MONTH_DAYS - no equivalent - 30 - - - - L - Leapyear, boolean - Zend_Date::LEAPYEAR - no equivalent - TRUE - - - - o - - - Year according to ISO 8601, at least four digit - - - Zend_Date::YEAR_8601 - YYYY - 2009 - - - - Y - Year, at least four digit - Zend_Date::YEAR - yyyy - 2009 - - - - y - Year, at least two digit - Zend_Date::YEAR_SHORT - yy - 09 - - - - a - Time of day, localized - Zend_Date::MERIDIEM - a (sort of, but likely to be uppercase) - vorm. - - - - A - Time of day, localized - Zend_Date::MERIDIEM - a (sort of, but no guarantee that the format is uppercase) - VORM. - - - - B - Swatch internet time - Zend_Date::SWATCH - no equivalent - 1463 - - - - g - Hour, (1-12), one or two digit - Zend_Date::HOUR_SHORT_AM - h - 2 - - - - G - Hour, (0-23), one or two digit - Zend_Date::HOUR_SHORT - H - 2 - - - - h - Hour, (01-12), two digit - Zend_Date::HOUR_AM - hh - 02 - - - - H - Hour, (00-23), two digit - Zend_Date::HOUR - HH - 02 - - - - i - Minute, (00-59), two digit - Zend_Date::MINUTE - mm - 02 - - - - s - Second, (00-59), two digit - Zend_Date::SECOND - ss - 02 - - - - e - Time zone, localized, complete - Zend_Date::TIMEZONE_NAME - zzzz - Europe/Paris - - - - I - Daylight - Zend_Date::DAYLIGHT - no equivalent - 1 - - - - O - Difference of time zone - Zend_Date::GMT_DIFF - Z or ZZ or ZZZ - +0100 - - - - P - Difference of time zone, separated - Zend_Date::GMT_DIFF_SEP - ZZZZ - +01:00 - - - - T - Time zone, localized, abbreviated - Zend_Date::TIMEZONE - z or zz or zzz - CET - - - - Z - Time zone offset in seconds - Zend_Date::TIMEZONE_SECS - no equivalent - 3600 - - - - c - Standard Iso format output - Zend_Date::ISO_8601 - no equivalent - 2004-02-13T15:19:21+00:00 - - - - r - Standard Rfc 2822 format output - Zend_Date::RFC_2822 - no equivalent - Thu, 21 Dec 2000 16:01:07 +0200 - - - - U - Unix timestamp - Zend_Date::TIMESTAMP - no equivalent - 15275422364 - - - -
-
-
diff --git a/documentation/manual/en/module_specs/Zend_Date-Creation.xml b/documentation/manual/en/module_specs/Zend_Date-Creation.xml deleted file mode 100644 index ce041cbb893..00000000000 --- a/documentation/manual/en/module_specs/Zend_Date-Creation.xml +++ /dev/null @@ -1,162 +0,0 @@ - -
Creation of Dates - - - - Zend_Date provides several different ways to create a new instance of - itself. As there are different needs the most convenient ways will be shown in this chapter. - - -
Create the Actual Date - - - - The simplest way of creating a date object is to create the actual date. You can either - create a new instance with new Zend_Date() or use the convenient - static method Zend_Date::now() which both will return the - actual date as new instance of Zend_Date. The actual date always - include the actual date and time for the actual set timezone. - - - Date Creation by Instance - - - - Date creation by creating a new instance means that you do not need to give an - parameter. Of course there are several parameters which will be described later but - normally this is the simplest and most used way to get the actual date as - Zend_Date instance. - - - - - - Static Date Creation - - - - Sometimes it is easier to use a static method for date creation. Therefor you can - use the now() method. It returns a - new instance of Zend_Date the same way as if you would use - new Zend_Date(). But it will always return the actual date and - can not be changed by giving optional parameters. - - - - -
- -
Create a Date from Database - - - - Databases are often used to store date values. But the problem is, that every database - outputs its date values in a different way. MsSQL databases use a - quite different standard date output than MySQL databases. But for - simplification Zend_Date makes it very easy to create a date - from database date values. - - - - Of course each database can be said to convert the output of a defined column to a - special value. For example you could convert a datetime value to - output a minute value. But this is time expensive and often you are in need of handling - dates in an other way than expected when creating the database query. - - - - So we have one quick and one convenient way of creating dates from database values. - - - Quick Creation of Dates from Database Date Values - - - - All databases are known to handle queries as fast as possible. They are built to act - and respond quick. The quickest way for handling dates is to get unix timestamps - from the database. All databases store date values internal as timestamp (not unix - timestamp). This means that the time for creating a timestamp through a query is - much smaller than converting it to a specified format. - - - - - - Convenient Creation of Dates from Database Date Values - - - - The standard output of all databases is quite different even if it looks the same on - the first eyecatch. But all are part of the ISO Standard and - explained through it. So the easiest way of date creation is the usage of - Zend_Date::ISO_8601. Databases which are known to be - recognised by Zend_Date::ISO_8601 are - MySQL, MsSQL for example. But all - databases are also able to return a ISO-8601 representation of a - date column. ISO-8601 has the big advantage that it is human - readable. The disadvantage is that ISO-8601 needs more time for - computation than a simple unix timestamp. But it should also be mentioned that unix - timestamps are only supported for dates after 1 January 1970. - - - - -
- -
Create Dates from an Array - - - - Dates can also be created by the usage of an array. This is a simple and easy way. The - used array keys are: - - - - day: day of the date as number - - - month: month of the date as number - - - year: full year of the date - hour: hour of the date - minute: minute of the date - second: second of the date - - - Date Creation by Array - - - - Normally you will give a complete date array for creation of a new date instance. - But when you do not give all values, the not given array values are zeroed. This - means that if f.e. no hour is given the hour 0 is used. - - - 2006, - 'month' => 4, - 'day' => 18, - 'hour' => 12, - 'minute' => 3, - 'second' => 10); -$date = new Zend_Date($datearray); -]]> - - 2006, 'month' => 4, 'day' => 18); -$date = new Zend_Date($datearray); -]]> - -
-
diff --git a/documentation/manual/en/module_specs/Zend_Date-Introduction.xml b/documentation/manual/en/module_specs/Zend_Date-Introduction.xml deleted file mode 100644 index 99a5035c226..00000000000 --- a/documentation/manual/en/module_specs/Zend_Date-Introduction.xml +++ /dev/null @@ -1,161 +0,0 @@ - -
Introduction - - - - The Zend_Date component offers a detailed, but simple - API for manipulating dates and times. Its methods accept a wide variety - of types of information, including date parts, in numerous combinations yielding many - features and possibilities above and beyond the existing PHP date related - functions. For the very latest manual updates, please see our online manual (frequently - synced to Subversion). - - - - Although simplicity remains the goal, working with localized dates and times while - modifying, combining, and comparing parts involves some unavoidable complexity. Dates, as - well as times, are often written differently in different locales. For example, some place - the month first, while other write the year first when expressing calendar dates. For more - information about handling localization and normalization, please refer to Zend_Locale. - - - - Zend_Date also supports abbreviated names of months in many - languages. Zend_Locale facilitates the normalization of localized - month and weekday names to timestamps, which may, in turn, be shown localized to other - regions. - - -
Always Set a Default Timezone - - - - Before using any date related functions in PHP or Zend Framework, - first make certain your application has a correct default timezone, by either setting - the TZ environment variable, using the date.timezone - php.ini setting, or using date_default_timezone_set(). - In PHP, we can adjust all date and time related functions to work for - a particular user by setting a default timezone according to the user's expectations. - For a complete list of timezone settings, see the CLDR - Timezone Identifier List. - - - Setting a Default Timezone - - - - - - - When creating Zend_Date instances, their timezone will - automatically become the current default timezone! Thus, the timezone setting - will account for any Daylight Savings Time (DST) in effect, - eliminating the need to explicitly specify DST. - - - - Keep in mind that the timezones UTC and - GMT do not include Daylight Saving Time. This - means that even if you define per hand that Zend_Date should work - with DST, it would automatically be switched back for the instances - of Zend_Date which have been set to UTC or - GMT. - -
- -
Why Use Zend_Date? - - - - Zend_Date offers the following features, which extend the scope - of PHP date functions: - - - - - - Simple API - - - - Zend_Date offers a very simple API, - which combines the best of date and time functionality from four programming - languages. It is possible, for example, to add or compare two times within a - single row. - - - - - - Completely internationalized - - - - All full and abbreviated names of months and weekdays are supported for more - than 130 languages. Methods support both input and the output of dates using the - localized names of months and weekdays, in the conventional format associated - with each locale. - - - - - - Unlimited timestamps - - - - Although PHP 5.2 docs state, "The valid range of a timestamp - is typically from Fri, 13 Dec 1901 20:45:54 GMT to Tue, 19 - Jan 2038 03:14:07 GMT," Zend_Date - supports a nearly unlimited range, with the help of the BCMath extension. If - BCMath is not available, then Zend_Date will have reduced - support only for timestamps within the range of the float type - supported by your server. "The size of a float is platform-dependent, although a - maximum of ~1.8e308 with a precision of roughly 14 decimal - digits is a common value (that's 64 bit IEEE format)." [ - http://www.php.net/float ]. - Additionally, inherent limitations of float data types, and rounding error of - float numbers may introduce errors into calculations. To avoid these problems, - Zend Framework's I18n components use BCMath extension, if available. - - - - - - Support for ISO-8601 date specifications - - - - ISO-8601 date specifications are supported. Even partially - compliant ISO-8601 date specifications will be identified. - These date formats are particularly useful when working with databases. for - example, even though MsSQL and MySQL - differ a little from each other, both are supported by - Zend_Date using the Zend_Date::ISO_8601 format - specification constant. When date strings conform to "Y/m/d" - or "Y-m-d H:i:s", according to PHP - date() format tokens, use - Zend_Date's built-in support for - ISO-8601 formatted dates. - - - - - - Calculate sunrise and sunset - - - - For any place and day, the times for sunrise and sunset can be displayed, so - that you won't miss a single daylight second for working on your favorite - PHP project :) - - - -
-
diff --git a/documentation/manual/en/module_specs/Zend_Date-Overview.xml b/documentation/manual/en/module_specs/Zend_Date-Overview.xml deleted file mode 100644 index 59f3646d495..00000000000 --- a/documentation/manual/en/module_specs/Zend_Date-Overview.xml +++ /dev/null @@ -1,1096 +0,0 @@ - -
Zend_Date API Overview - - - - While the Zend_Date API remains simplistic and - unitary, its design remains flexible and powerful through the rich permutations of - operations and operands. - - -
Zend_Date Options - - -
Selecting the Date Format Type - - - - Several methods use date format strings, in a way similar to - PHP's date(). If you are more - comfortable with PHP's date format specifier than with - ISO format specifiers, then you can use - Zend_Date::setOptions(array('format_type' => 'php')). - Afterward, use PHP's date format specifiers for all functions - which accept a $format parameter. Use - Zend_Date::setOptions(array('format_type' => 'iso')) to - switch back to the default mode of supporting only ISO date - format tokens. For a list of supported format codes, see - Self-Defined OUTPUT Formats - Using PHP's date() Format Specifiers - -
- -
DST and Date Math - - - - When dates are manipulated, sometimes they cross over a DST - change, normally resulting in the date losing or gaining an hour. For exmaple, when - adding months to a date before a DST change, if the resulting - date is after the DST change, then the resulting date will appear - to lose or gain an hour, resulting in the time value of the date changing. For - boundary dates, such as midnight of the first or last day of a month, adding enough - months to cross a date boundary results in the date losing an hour and becoming the - last hour of the preceding month, giving the appearance of an "off by 1" error. To - avoid this situation, the DST change ignored by using the - fix_dst option. When crossing the Summer or Winter - DST boundary, normally an hour is substracted or added depending - on the date. For example, date math crossing the Spring DST leads - to a date having a day value one less than expected, if the time part of the date - was originally 00:00:00. Since Zend_Date is based on - timestamps, and not calendar dates with a time component, the timestamp loses an - hour, resulting in the date having a calendar day value one less than expected. To - prevent such problems use the option fix_dst, which defaults to - TRUE, causing DST to have no effect on date - "math" (addMonth(), subMonth()). - Use Zend_Date::setOptions(array('fix_dst' => false)) to - enable the subtraction or addition of the DST adjustment when - performing date "math". - - - - If your actual timezone within the instance of - Zend_Date is set to UTC or - GMT the option 'fix_dst' will not be - used because these two timezones do not work with DST. - When you change the timezone for this instance again to a timezone which is not - UTC or GMT the previous set 'fix_dst' option - will be used again for date "math". - -
- -
Month Calculations - - - - When adding or substracting months from an existing date, the resulting value for - the day of the month might be unexpected, if the original date fell on a day close - to the end of the month. For example, when adding one month to January 31st, people - familiar with SQL will expect February 28th as the result. On the - other side, people familiar with Excel and OpenOffice will expect March 3rd as the - result. The problem only occurs, if the resulting month does not have the day, which - is set in the original date. For Zend Framework developers, the desired behavior is - selectable using the extend_month option to choose either the - SQL behaviour, if set to FALSE, or the - spreadsheet behaviour when set to TRUE. The default behaviour - for extend_month is FALSE, providing - behavior compatible to SQL. By default, - Zend_Date computes month calculations by truncating dates to - the end of the month (if necessary), without wrapping into the next month when the - original date designates a day of the month exceeding the number of days in the - resulting month. Use Zend_Date::setOptions(array('extend_month' => - true)) to make month calculations work like popular spreadsheet - programs. - -
- -
Speed up Date Localization and Normalization with Zend_Cache - - - - You can speed up Zend_Date by using an - Zend_Cache adapter. This speeds up all methods of - Zend_Date when you are using localized data. For example all - methods which accept Zend_Date::DATE and - Zend_Date::TIME constants would benefit from this. To set an - Zend_Cache adapter to Zend_Date just - use Zend_Date::setOptions(array('cache' => $adapter)). - -
- -
Receiving Syncronised Timestamps with Zend_TimeSync - - - - Normally the clocks from servers and computers differ from each other. - Zend_Date is able to handle such problems with the help of - Zend_TimeSync. You can set a timeserver with - Zend_Date::setOptions(array('timesync' => $timeserver)) - which will set the offset between the own actual timestamp and the real actual - timestamp for all instances of Zend_Date. Using this option - does not change the timestamp of existing instances. So best usage is to set it - within the bootstrap file. - -
-
- -
Working with Date Values - - - - Once input has been normalized via the creation of a Zend_Date - object, it will have an associated timezone, but an internal representation using - standard UNIX timestamps. - In order for a date to be rendered in a localized manner, a timezone must be known - first. The default timezone is always GMT or UTC. - To examine an object's timezone use getTimeZone(). To change an - object's timezone, use setTimeZone(). All manipulations of - these objects are assumed to be relative to this timezone. - - - - Beware of mixing and matching operations with date parts between date objects for - different timezones, which generally produce undesireable results, unless the - manipulations are only related to the timestamp. Operating on - Zend_Date objects having different timezones generally works, - except as just noted, since dates are normalized to UNIX timestamps - on instantiation of Zend_Date. - - - - Most methods expect a constant selecting the desired $part of a date, - such as Zend_Date::HOUR. These constants are valid for all of the - functions below. A list of all available constants is provided in - list of all constants. - If no $part is - specified, then Zend_Date::TIMESTAMP is assumed. Alternatively, a - user-specified format may be used for $part, using the same - underlying mechanism and format codes as Zend_Locale_Format::getDate(). - If a date object is constructed using an obviously invalid date (e.g. a month number - greater than 12), then Zend_Date will throw an exception, unless - no specific date format has been selected -i.e. $part is either - NULL or Zend_Date::DATES (a "loose" format). - - - User-Specified Input Date Format - - - - - - - If the optional $locale parameter is provided, then the - $locale disambiguates the $date operand by - replacing month and weekday names for string $date operands, and even - parsing date strings expressed according to the conventions of that locale (see - Zend_Locale_Format::getDate()). - The automatic normalization of localized $date operands of a - string type occurs when $part is one of the - Zend_Date::DATE* or Zend_Date::TIME* - constants. The locale identifies which language should be used to parse month names and - weekday names, if the $date is a string containing a date. If there - is no $date input parameter, then the $locale - parameter specifies the locale to use for localizing output (e.g. the date format for a - string representation). Note that the $date input parameter might - actually have a type name instead (e.g. $hour for - addHour()), although that does not prevent the use of - Zend_Date objects as arguments for that parameter. If no - $locale was specified, then the locale of the current object is used - to interpret $date, or select the localized format for output. - - - - Since Zend Framework 1.7.0 Zend_Date does also support the usage - of an application wide locale. You can simply set a Zend_Locale - instance to the registry like shown below. With this notation you can forget about - setting the locale manually with each instance when you want to use the same locale - multiple times. - - - -
- -
Basic Zend_Date Operations Common to Many Date Parts - - - - The methods add(), sub(), - compare(), get(), and - set() operate generically on dates. In each case, the - operation is performed on the date held in the instance object. The - $date operand is required for all of these methods, except - get(), and may be a Zend_Date instance - object, a numeric string, or an integer. These methods assume $date - is a timestamp, if it is not an object. However, the $part operand - controls which logical part of the two dates are operated on, allowing operations on - parts of the object's date, such as year or minute, even when $date - contains a long form date string, such as, "December 31, 2007 23:59:59". The result of - the operation changes the date in the object, except for - compare(), and get(). - - - Operating on Parts of Dates - - - add('12', Zend_Date::HOUR); -print $date; -]]> - - - - Convenience methods exist for each combination of the basic operations and several - common date parts as shown in the tables below. These convenience methods help us lazy - programmers avoid having to type out the date - part constants when using the general methods above. Conveniently, they are - named by combining a prefix (name of a basic operation) with a suffix (type of date - part), such as addYear(). In the list below, all combinations - of "Date Parts" and "Basic Operations" exist. For example, the operation "add" exists - for each of these date parts, including addDay(), - addYear(), etc. - - - - These convenience methods have the same equivalent functionality as the basic operation - methods, but expect string and integer $date operands containing only - the values representing the type indicated by the suffix of the convenience method. - Thus, the names of these methods (e.g. "Year" or "Minute") identify the units of the - $date operand, when $date is a string or integer. - - -
List of Date Parts - - - Date Parts - - - - - - Date Part - Explanation - - - - - - - Timestamp - - - - UNIX timestamp, expressed in seconds elapsed since January 1st, 1970 - 00:00:00 GMT. - - - - - - Year - - - Gregorian calendar year (e.g. 2006) - - - - - Month - - - - Gregorian calendar month (1-12, localized names supported) - - - - - - 24 hour - clock - - - - Hours of the day (0-23) denote the hours elapsed, since the start of - the day. - - - - - - minute - - - - Minutes of the hour (0-59) denote minutes elapsed, since the start - of the hour. - - - - - - Second - - - - Seconds of the minute (0-59) denote the elapsed seconds, since the - start of the minute. - - - - - - millisecond - - - - Milliseconds denote thousandths of a second (0-999). - Zend_Date supports two additional methods - for working with time units smaller than seconds. By default, - Zend_Date instances use a precision - defaulting to milliseconds, as seen using - getFractionalPrecision(). To change the - precision use - setFractionalPrecision($precision). - However, precision is limited practically to microseconds, since - Zend_Date uses microtime(). - - - - - - Day - - - - Zend_Date::DAY_SHORT is extracted from - $date if the $date operand is - an instance of Zend_Date or a numeric string. - Otherwise, an attempt is made to extract the day according to the - conventions documented for these constants: - Zend_Date::WEEKDAY_NARROW, - Zend_Date::WEEKDAY_NAME, - Zend_Date::WEEKDAY_SHORT, - Zend_Date::WEEKDAY (Gregorian calendar - assumed) - - - - - - Week - - - - Zend_Date::WEEK is extracted from - $date if the $date operand is - an instance of Zend_Date or a numeric string. - Otherwise an exception is raised. (Gregorian calendar assumed) - - - - - Date - - - Zend_Date::DAY_MEDIUM is extracted from - $date if the $date operand is - an instance of Zend_Date. Otherwise, an - attempt is made to normalize the $date string - into a Zend_Date::DATE_MEDIUM formatted date. - The format of Zend_Date::DAY_MEDIUM depends on - the object's locale. - - - - - Weekday - - - Weekdays are represented numerically as 0 (for Sunday) through 6 - (for Saturday). Zend_Date::WEEKDAY_DIGIT is - extracted from $date, if the - $date operand is an instance of - Zend_Date or a numeric string. Otherwise, an - attempt is made to extract the day according to the conventions - documented for these constants: - Zend_Date::WEEKDAY_NARROW, - Zend_Date::WEEKDAY_NAME, - Zend_Date::WEEKDAY_SHORT, - Zend_Date::WEEKDAY (Gregorian calendar - assumed) - - - - - DayOfYear - - - In Zend_Date, the day of the year represents - the number of calendar days elapsed since the start of the year - (0-365). As with other units above, fractions are rounded down to - the nearest whole number. (Gregorian calendar assumed) - - - - - - Arpa - - - - Arpa dates (i.e. RFC 822 formatted dates) are - supported. Output uses either a "GMT" or "Local differential - hours+min" format (see section 5 of RFC 822). - Before PHP 5.2.2, using the - DATE_RFC822 constant with - PHP date functions sometimes produces incorrect - results. Zend_Date's results are - correct. Example: Mon, 31 Dec 06 23:59:59 GMT - - - - - - Iso - - - - Only complete ISO 8601 dates are supported for - output. Example: 2009-02-14T00:31:30+01:00 - - - - -
-
- -
List of Date Operations - - - - The basic operations below can be used instead of the convenience operations for - specific date parts, if the - appropriate constant - is used for the $part parameter. - - - Basic Operations - - - - - - Basic Operation - Explanation - - - - - - get() - - - - get($part = null, $locale = - null) - - - - Use get($part) to retrieve the date - $part of this object's date localized to - $locale as a formatted string or integer. - When using the BCMath extension, numeric strings might be - returned instead of integers for large values. - - - Behaviour of get() - - - - Unlike get(), the other - get*() convenience methods only return instances of - Zend_Date containing a date - representing the selected or computed date or time. - - - - - - - set() - - - - set($date, $part = null, $locale = - null) - - - - Sets the $part of the current object to the - corresponding value for that part found in the input - $date having a locale - $locale. - - - - - - add() - - - - add($date, $part = null, $locale = - null) - - - - Adds the $part of $date - having a locale $locale to the current - object's date. - - - - - - sub() - - - - sub($date, $part = null, $locale = - null) - - - - Subtracts the $part of - $date having a locale - $locale from the current object's date. - - - - - - copyPart() - - - - copyPart($part, $locale = - null) - - - - Returns a cloned object, with only $part of - the object's date copied to the clone, with the clone have its - locale arbitrarily set to $locale (if - specified). - - - - - - compare() - - - - compare($date, $part = null, $locale = - null) - - - - compares $part of $date to - this object's timestamp, returning 0 if they are equal, 1 if - this object's part was more recent than - $date's part, otherwise -1. - - - - - -
-
-
- -
Comparing Dates - - - - The following basic operations do not have corresponding convenience methods for the - date parts listed in Zend_Date API Overview. - - - Date Comparison Methods - - - - - - Method - Explanation - - - - - - equals() - - - - equals($date, $part = null, $locale = - null) - - - - returns TRUE, if $part of - $date having locale $locale is - the same as this object's date $part, otherwise - FALSE - - - - - - isEarlier() - - - - isEarlier($date, $part = null, $locale = - null) - - - - returns TRUE, if $part of - this object's date is earlier than $part of - $date having a locale $locale - - - - - - isLater() - - - - isLater($date, $part = null, $locale = - null) - - - - returns TRUE, if $part of - this object's date is later than $part of - $date having a locale $locale - - - - - - isToday() - - - - isToday() - - - - Tests if today's year, month, and day match this object's date - value, using this object's timezone. - - - - - - isTomorrow() - - - - isTomorrow() - - - - Tests if tomorrow's year, month, and day match this object's date - value, using this object's timezone. - - - - - - isYesterday() - - - - isYesterday() - - - - Tests if yesterday's year, month, and day match this object's date - value, using this object's timezone. - - - - - - isLeapYear() - - - - isLeapYear() - - - - Use isLeapYear() to determine if the - current object is a leap year, or use - Zend_Date::checkLeapYear($year) to check - $year, which can be a string, integer, or - instance of Zend_Date. Is the year a leap - year? - - - - - - isDate() - - - - isDate($date, $format = null, $locale = - null) - - - - This method checks if a given date is a real date and returns - TRUE if all checks are ok. It works like - PHP's checkdate() - function but can also check for localized month names and for dates - extending the range of checkdate() - - - - - -
-
- -
Getting Dates and Date Parts - - - - Several methods support retrieving values related to a Zend_Date - instance. - - - Date Output Methods - - - - - - Method - Explanation - - - - - - toString() - - - - toString($format = null, $locale = - null) - - - - Invoke directly or via the magic method - __toString(). The - toString() method automatically formats - the date object's value according to the conventions of the - object's locale, or an optionally specified - $locale. For a list of supported format codes, - see Self-Defined - OUTPUT Formats with ISO. - - - - - - toArray() - - - - toArray() - - - - Returns an array representation of the selected date according to - the conventions of the object's locale. The returned array is - equivalent to PHP's getdate() function and - includes: - - - - - - Number of day as 'day' - (Zend_Date::DAY_SHORT) - - - - - - Number of month as 'month' - (Zend_Date::MONTH_SHORT) - - - - - - Year as 'year' - (Zend_Date::YEAR) - - - - - - Hour as 'hour' - (Zend_Date::HOUR_SHORT) - - - - - - Minute as 'minute' - (Zend_Date::MINUTE_SHORT) - - - - - - Second as 'second' - (Zend_Date::SECOND_SHORT) - - - - - - Abbreviated timezone as 'timezone' - (Zend_Date::TIMEZONE) - - - - - - Unix timestamp as 'timestamp' - (Zend_Date::TIMESTAMP) - - - - - - Number of weekday as 'weekday' - (Zend_Date::WEEKDAY_DIGIT) - - - - - - Day of year as 'dayofyear' - (Zend_Date::DAY_OF_YEAR) - - - - - - Week as 'week' - (Zend_Date::WEEK) - - - - - - Delay of timezone to GMT as - 'gmtsecs' - (Zend_Date::GMT_SECS) - - - - - - - - toValue() - - - - toValue($part = null) - - - - Returns an integer representation of the selected date - $part according to the conventions of the - object's locale. Returns FALSE when - $part selects a non-numeric value, such as - Zend_Date::MONTH_NAME_SHORT. - - - Limitation of toValue() - - - - This method calls get() - and casts the result to a PHP integer, which - will give unpredictable results, if - get() returns a numeric string - containing a number too large for a PHP - integer on your system. Use get() - instead. - - - - - - - - get() - - - - - get($part = null, $locale = - null) - - - - This method returns the $part of object's date - localized to $locale as a formatted string or - integer. See get() - for more information. - - - - - - now() - - - - now($locale = null) - - - - This convenience function is equivalent to new - Zend_Date(). It returns the current date as a - Zend_Date object, having - $locale - - - - - -
-
- -
Working with Fractions of Seconds - - - - Several methods support retrieving values related to a Zend_Date - instance. - - - Date Output Methods - - - - - - Method - Explanation - - - - - - - - getFractionalPrecision() - - - - Return the precision of the part seconds - - - - - - setFractionalPrecision() - - - - Set the precision of the part seconds - - - -
-
- -
Sunrise / Sunset - - - - Three methods provide access to geographically localized information about the Sun, - including the time of sunrise and sunset. - - - Miscellaneous Methods - - - - - - Method - Explanation - - - - - - - - getSunrise($location) - - - - Return the date's time of sunrise - - - - - - getSunset($location) - - - - Return the date's time of sunset - - - - - - getSunInfo($location) - - - - Return an array with the date's sun dates - - - -
-
-
diff --git a/documentation/manual/en/module_specs/Zend_Date-Theory.xml b/documentation/manual/en/module_specs/Zend_Date-Theory.xml deleted file mode 100644 index e71998ed5ad..00000000000 --- a/documentation/manual/en/module_specs/Zend_Date-Theory.xml +++ /dev/null @@ -1,74 +0,0 @@ - - - -
Theory of Operation - - - - Why is there only one class Zend_Date for handling dates and times in - Zend Framework? - - - - Many languages split the handling of times and calendar dates into two classes. However, - Zend Framework strives for extreme simplicity, and forcing the developer to manage different - objects with different methods for times and dates becomes a burden in many situations. - Since Zend_Date methods support working with ambiguous dates that - might not include all parts (era, year, month, day, hour, minute, second, timezone), - developers enjoy the flexibility and ease of using the same class and the same methods to - perform the same manipulations (e.g. addition, subtraction, comparison, merging of date - parts, etc.). Splitting the handling of these date fragments into multiple classes would - create complications when smooth interoperation is desired with a small learning curve. A - single class reduces code duplication for similar operations, without the need for a complex - inheritance hierarchy. - - -
Internals - - - - - - UNIX Timestamp - - - - All dates and times, even ambiguous ones (e.g. no year), are represented - internally as absolute moments in time, represented as a UNIX - timestamp expressing the difference between the desired time and - January 1st, 1970 00:00:00 GMT. This was only possible, - because Zend_Date is not limited to - UNIX timestamps nor integer values. The BCMath extension is - required to support extremely large dates outside of the range - Fri, 13 Dec 1901 20:45:54 GMT to - Tue, 19 Jan 2038 03:14:07 GMT. Additional, tiny math - errors may arise due to the inherent limitations of float data types and - rounding, unless using the BCMath extension. - - - - - - Date parts as timestamp offsets - - - - Thus, an instance object representing three hours would be expressed as - three hours after January 1st, 1970 00:00:00 GMT - -i.e. 0 + 3 * 60 * 60 = 10800. - - - - - - PHP functions - - - - Where possible, Zend_Date usually uses - PHP functions to improve performance. - - - -
-
diff --git a/documentation/manual/en/module_specs/Zend_Db-Adapter.xml b/documentation/manual/en/module_specs/Zend_Db-Adapter.xml deleted file mode 100644 index 3660ae401fc..00000000000 --- a/documentation/manual/en/module_specs/Zend_Db-Adapter.xml +++ /dev/null @@ -1,397 +0,0 @@ - -
Zend\Db\Adapter - - - The Adapter object is the most important sub-component of Zend\Db. - It is responsible for adapting any code written in or for Zend\Db - to the targeted php extensions and vendor databases. In doing this, - it creates an abstraction layer for the PHP extensions, which is called - the "Driver" portion of the Zend\Db adapter. It also creates a lightweight - abstraction layer for the various idiosyncrasies that each vendor specific - platform might have in it's SQL/RDBMS implementation which is called the - "Platform" portion of the adapter. - - -
Creating an Adapter (Quickstart) - - - Creating an adapter can simply be done by instantiating the - Zend\Db\Adapter\Adapter class. The most common use case, while not the - most explicit, is to pass an array of information to the Adapter. - - - - - - This driver array is an abstraction for the extension level required - parameters. Here is a table for the - - - Connection Array Keys - - - - Name - Required - Notes - - - - - - driver - - - required - - - Mysqli, Sqlsrv, Pdo_Sqlite, Pdo_Mysql, Pdo-OtherPdoDriver - - - - - database - - - generally required - - - the name of the database (schema) - - - - - username - - - generally required - - - the connection username - - - - - password - - - generally required - - - the connection password - - - - - hostname - - - not generally required - - - the IP address or hostname to connect to - - - - - port - - - not generally required - - - not generally required the port to connect to (if applicable) - - - - - characterset - - - not generally required - - - not generally required the character set to use - - - - -
- - - * other names will work as well. Effectively, if the PHP manual - uses a particular naming, this naming will be supported by our Driver. - For example, dbname in most cases will also work for 'database'. Another - example is that in the case of Sqlsrv, UID will work in place of username. - Which format you chose is up to you, but the above table represents the - official abstraction names. - - - - So, for example, a MySQL connection using ext/mysqli: - - - 'Mysqli', - 'database' => 'zend_db_example', - 'username' => 'developer', - 'password' => 'developer-password' - )); -]]> - - - Another example, of a Sqlite connection via PDO: - - - 'Pdo_Sqlite', - 'database' => 'path/to/sqlite.db' - )); -]]> - - - It is important to know that by using this style of adapter creation, the Adapter - will attempt to create any dependencies that were not explicitly provided. A Driver - object will be created from the contents of the $driver array provided in the - constructor. A Platform object will be created based off the type of Driver object - that was instantiated. And lastly, a default ResultSet object is created and utilized. - Any of these objects can be injected, to do this, see the next section. - - - -
- -
Creating an Adapter (By Injecting Dependencies) - - - The more expressive and explicit way of creating an adapter is by injecting all your - dependencies up front. Zend\Db\Adapter\Adapter uses constructor injection, and all - required dependencies are injected through the constructor, which has the following - signature (in pseudo-code): - - - - - - - What can be injected: - - - - $driver - an array or an instance of Zend\Db\Adapter\Driver\DriverInterface - $platform - (optional) an instance of Zend\Db\Platform\PlatformInterface, the default will be created based off the driver implementation - $queryResultSetPrototype - (optional) an instance of Zend\Db\ResultSet\ResultSet, to understand this object's role, see the section below on querying through the adapter - - -
- -
Query Preparation Through Zend\Db\Adapter\Adapter::query() - - - By default, query() prefers that you use "preparation" as a means for processing SQL - statements. This generally means that you will supply a SQL statement with the values - substituted by placeholders, and then the parameters for those placeholders are - supplied separately. An example of this workflow with Zend\Db\Adapter\Adapter is: - - - query('SELECT * FROM `artist` WHERE `id` = ?', array(5)); -]]> - - - The above example will go through the following steps: - - - - - - create a new Statement object - - - - - prepare an array into a ParameterContainer if necessary - - - - - inject the ParameterContainer into the Statement object - - - - - execute the Statement object, producing a Result object - - - - - check the Result object to check if the supplied sql was a "query", or a result set producing statement - - - - - if it is a result set producing query, clone the ResultSet prototype, inject Result as datasource, return it - - - - - else, return the Result - - - - - -
- - -
Query Execution Through Zend\Db\Adapter\Adapter::query() - - - In some cases, you have to execute statements directly. The primary purpose for - needing to execute sql instead of prepare and execute a sql statement, might be - because you are attempting to execute a DDL statement (which in most extensions - and vendor platforms), are un-preparable. An example of executing: - - - - query('ALTER TABLE ADD INDEX(`foo_index`) ON (`foo_column`))', Adapter::QUERY_MODE_EXECUTE); -]]> - - - The primary difference to notice is that you must provide the Adapter::QUERY_MODE_EXECUTE - (execute) as the second parameter. - - -
- - -
Creating Statements - - - While query() is highly useful for one-off and quick querying of a - database through Adapter, it generally makes more sense to create a - statement and interact with it directly, so that you have greater control - over the prepare-then-execute workflow. To do this, Adapter gives you a - routine called createStatement() that allows you to create a Driver - specific Statement to use so you can manage your own prepare-then-execute workflow. - - - createStatement($sql, $optionalParameters); - $result = $statement->execute(); -]]> - -
- - -
Using The Platform Object - - - The Platform object provides an API to assist in crafting queries in a way that - is specific to the SQL implemetation of a particular vendor. Nuances such - as how identifiers or values are quoted, or what the identifier separator - character is are handled by this object. To get an idea of the capabilities, - the interface for a platform object looks like this: - - - - - - For example, to quote a column name, specific to MySQL's way of quoting: - - - quoteIdentifier('first_name'); // returns `first_name` -]]> - - - Generally speaking, it is easier to get the proper Platform instance from the adapter: - - - getPlatform(); - // or - $platform = $adapter->platform; // magic property access -]]> - -
- - -
Using The Parameter Container - - - The ParameterContainer object is a container for the various parameters that - need to be passed into a Statement object to fulfill all the various - parameterized parts of the SQL statement. This object implements the - ArrayAccess interface. - - -
- -
Examples - - - Creating a Driver and Vendor portable Query, Preparing and Iterating Result - - - platform->quoteIdentifier($name); }; - $fp = function($name) use ($adapter) { return $adapter->driver->formatParameterName($name); }; - - $sql = 'UPDATE ' . $qi('artist') - . ' SET ' . $qi('name') . ' = ' . $fp('name') - . ' WHERE ' . $qi('id') . ' = ' . $fp('id'); - - /* @var $statement Zend\Db\Adapter\DriverStatementInterface */ - $statement = $adapter->query($sql); - - $parameters = array( - 'name' => 'Updated Artist', - 'id' => 1 - ); - - $statement->execute($parameters); - - // DATA INSERTED, NOW CHECK - - /* @var $statement Zend\Db\Adapter\DriverStatementInterface */ - $statement = $adapter->query('SELECT * FROM ' - . $qi('artist') - . ' WHERE id = ' . $fp('id')); - - /* @var $results Zend\Db\ResultSet\ResultSet */ - $results = $statement->execute(array('id' => 1)); - - $row = $results->current(); - $name = $row['name']; -]]> - -
- -
diff --git a/documentation/manual/en/module_specs/Zend_Db-Sql.xml b/documentation/manual/en/module_specs/Zend_Db-Sql.xml deleted file mode 100644 index 6a0b7a0bb89..00000000000 --- a/documentation/manual/en/module_specs/Zend_Db-Sql.xml +++ /dev/null @@ -1,627 +0,0 @@ - -
- Zend\Db\Sql - - - Zend\Db\Sql is a SQL abstraction layer for building platform specific - SQL queries via a object-oriented API. The end result of an Zend\Db\Sql - object will be to either produce a Statement and Parameter container that - represents the target query, or a full string that can be directly executed - against the database platform. To achieve this, there is Zend\Db\Sql - objects require a Zend\Db\Adapter\Adapter object in order to produce - the desired results. - - -
- Zend\Db\Sql\Sql (Quickstart) - - - As there are for primary tasks associated with interacting with a database - (from the DML, or Data Manipulation Language): selecting, inserting, updating - and deleting. As such, there are four primary objects that developers can - interact or buiding queries, Zend\Db\Sql\Select, Insert, Update and Delete. - - - - Since these four tasks are so closely related, and generally used together - within the same application, Zend\Db\Sql\Sql objects help you create them - and produce the result you are attempting to achieve. - - - select(); // @return Zend\Db\Sql\Select -$insert = $sql->insert(); // @return Zend\Db\Sql\Insert -$update = $sql->update(); // @return Zend\Db\Sql\Update -$delete = $sql->delete(); // @return Zend\Db\Sql\Delete -]]> - - - As a developer, you can now interact with these objects, as described in - the sections below, to specialize each query. Once they have been populated - with values, they are ready to either be prepared or executed. - - - - To prepare (using a Select object): - - - from('foo'); -$select->where(array('id' => 2)); - -$statement = $sql->prepareStatementForSqlObject($select); -$results = $statement->execute(); -]]> - - - To execute (using a Select object) - - - from('foo'); -$select->where(array('id' => 2)); - -$selectString = $sql->getSqlStringForSqlObject($select); -$results = $adapter->query($selectString, $adapter::QUERY_MODE_EXECUTE); -]]> - - - Zend\Db\Sql\Sql objects can also be bound to a particular table so that in - getting a select, insert, update, or delete object, they are all primarily - seeded with the same table when produced. - - - where(array('id' => 2)); // $select already has the from('foo') applied -]]> - -
- -
- Zend\Db\Sql's Select, Insert, Update and Delete - - - Each of these objects implement the following (2) interfaces: - - - - - - These are the functions you can call to either produce (a) a prepared statement, - or (b) a string to be executed. - - -
- -
- Zend\Db\Sql\Select - - - Zend\Db\Sql\Select is an object who's primary function is to present a unified - API for building platform specific SQL SELECT queries. The object can be - instantiated and consumed without Zend\Db\Sql\Sql: - - - - - - If a table is provided to the Select object, then from() cannot be called later - to change the name of the table. - - - - Once you have a valid Select object, the following API can be used to further - specify various select statement parts: - - - - - - from(): - - - from('foo'); - -// as an array to specify an alias: -// produces SELECT "t".* FROM "table" AS "t" - -$select->from(array('t' => 'table')); - -// using a Sql\TableIdentifier: -// same output as above - -$select->from(new TableIdentifier(array('t' => 'table'))); -]]> - - - columns(): - - - columns(array('foo', 'bar')); - -// as an associative array with aliases as the keys: -// produces 'bar' AS 'foo', 'bax' AS 'baz' - -$select->columns(array('foo' => 'bar', 'baz' => 'bax')); -]]> - - - join(): - - - join( - 'foo' // table name, - 'id = bar.id', // expression to join on (will be quoted by platform object before insertion), - array('bar', 'baz'), // (optional) list of columns, same requiremetns as columns() above - $select::JOIN_OUTER // (optional), one of inner, outer, left, right also represtned by constants in the API -); - -$select->from(array('f' => 'foo')) // base table - ->join(array('b' => 'bar'), // join table with alias - 'f.foo_id = b.foo_id'); // join expression -]]> - - - where(), having(): - - - - - - order(): - - - order('id DESC'); // produces 'id' DESC - -$select = new Select; -$select->order('id DESC') - ->order('name ASC, age DESC'); // produces 'id' DESC, 'name' ASC, 'age' DESC - -$select = new Select; -$select->order(array('name ASC', 'age DESC')); // produces 'name' ASC, 'age' DESC -]]> - - - limit() and offset(): - - - limit(5); // always takes an integer/numeric -$select->offset(10); // similarly takes an integer/numeric -]]> - -
- -
- Zend\Db\Sql\Insert - - - The Insert API: - - - - - - Similarly to Select objects, the table can be set at construction time - or via into(). - - - - columns(): - - - columns(array('foo', 'bar')); // set the valid columns -]]> - - - values(): - - - values(array( - 'col_1' => 'value1', - 'col_2' => 'value2' -)); -]]> - - values(array('col_2' => 'value2'), $insert::VALUES); -]]> - -
- -
- Zend\Db\Sql\Update - - - - - set(): - - - set(array('foo' => 'bar', 'baz' => bax')); -]]> - - - where(): - - - - -
- -
- Zend\Db\Sql\Delete - - - - - where(): - - - - -
- -
- Zend\Db\Sql\Where & Zend\Db\Sql\Having - - - In the following, we will talk about Where, Having is implies as being the same API. - - - - - Effectively, Where and Having extend from the same base object, a - Predicate (and PredicateSet). All of the parts that make up a where - or having that are and'ed or or'd together are called predicates. The full - set of predicates is called a PredicateSet. This object set generally contains - the values (and identifiers) separate from the fragement they belong to until - the last possible moment when the statement is either used to be prepared - (parameteritized), or exectued. In parameterization, the parameters will be - replaced with their proper placeholder (a named or positional parameter), and - the values stored inside a Adapter\ParameterContainer. When executed, the values - will be interpolated into the fragments they belong to and properly quoted. - - - - It is important to know that in this API, a distinction is made between what - elements are considered identifiers (TYPE_IDENTIFIER) and which of those is - a value (TYPE_VALUE). There is also a special use case type for literal values - (TYPE_LITERAL). These are all exposed via the Zend\Db\Sql\ExpressionInterface - interface. - - - - The Zend\Db\Sql\Where (Predicate/PredicateSet) API: - - - - - - Each method in the Where API will produce a coresponding Predicate object of a similarly - named type, described below, with the full API of the object: - - - - equalTo(), lessThan(), greaterThan(), lessThanOrEqualTo(), greaterThanOrEqualTo(): - - - equalTo('id', 5); - -// same as the following workflow -$where->addPredicate( - new Predicate\Operator($left, Operator::OPERATOR_EQUAL_TO, $right, $leftType, $rightType) -); - -class Operator implements PredicateInterface -{ - const OPERATOR_EQUAL_TO = '='; - const OP_EQ = '='; - const OPERATOR_NOT_EQUAL_TO = '!='; - const OP_NE = '!='; - const OPERATOR_LESS_THAN = '<'; - const OP_LT = '<'; - const OPERATOR_LESS_THAN_OR_EQUAL_TO = '<='; - const OP_LTE = '<='; - const OPERATOR_GREATER_THAN = '>'; - const OP_GT = '>'; - const OPERATOR_GREATER_THAN_OR_EQUAL_TO = '>='; - const OP_GTE = '>='; - - public function __construct($left = null, $operator = self::OPERATOR_EQUAL_TO, $right = null, $leftType = self::TYPE_IDENTIFIER, $rightType = self::TYPE_VALUE); - public function setLeft($left); - public function getLeft(); - public function setLeftType($type); - public function getLeftType(); - public function setOperator($operator); - public function getOperator(); - public function setRight($value); - public function getRight(); - public function setRightType($type); - public function getRightType(); - public function getExpressionData(); -} -]]> - - - like($identifier, $like): - - - like($identifier, $like): - -// same as -$where->addPredicate( - new Predicate\Like($identifier, $like) -); - -// full API - -class Like implements PredicateInterface -{ - public function __construct($identifier = null, $like = null); - public function setIdentifier($identifier); - public function getIdentifier(); - public function setLike($like); - public function getLike(); -} -]]> - - - literal($literal, $parameter); - - - literal($literal, $parameter); - -// same as -$where->addPredicate( - new Predicate\Expression($literal, $parameter) -); - -// full API -class Expression implements ExpressionInterface, PredicateInterface -{ - const PLACEHOLDER = '?'; - public function __construct($expression = null, $valueParameter = null /*[, $valueParameter, ... ]*/); - public function setExpression($expression); - public function getExpression(); - public function setParameters($parameters); - public function getParameters(); - public function setTypes(array $types); - public function getTypes(); -} -]]> - - - isNull($identifier); - - - isNull($identifier); - -// same as -$where->addPredicate( - new Predicate\IsNull($identifier) -); - -// full API -class IsNull implements PredicateInterface -{ - public function __construct($identifier = null); - public function setIdentifier($identifier); - public function getIdentifier(); -} -]]> - - - isNotNull($identifier); - - - isNotNull($identifier); - -// same as -$where->addPredicate( - new Predicate\IsNotNull($identifier) -); - -// full API -class IsNotNull implements PredicateInterface -{ - public function __construct($identifier = null); - public function setIdentifier($identifier); - public function getIdentifier(); -} -]]> - - - in($identifier, array $valueSet = array()); - - - in($identifier, array $valueSet = array()); - -// same as -$where->addPredicate( - new Predicate\In($identifier, $valueSet) -); - -// full API -class In implements PredicateInterface -{ - public function __construct($identifier = null, array $valueSet = array()); - public function setIdentifier($identifier); - public function getIdentifier(); - public function setValueSet(array $valueSet); - public function getValueSet(); -} -]]> - - - between($identifier, $minValue, $maxValue); - - - between($identifier, $minValue, $maxValue); - -// same as -$where->addPredicate( - new Predicate\Between($identifier, $minValue, $maxValue) -); - -// full API -class Between implements PredicateInterface -{ - public function __construct($identifier = null, $minValue = null, $maxValue = null); - public function setIdentifier($identifier); - public function getIdentifier(); - public function setMinValue($minValue); - public function getMinValue(); - public function setMaxValue($maxValue); - public function getMaxValue(); - public function setSpecification($specification); -} -]]> - -
-
- - - - - - - - - diff --git a/documentation/manual/en/module_specs/Zend_Db-TableGateway.xml b/documentation/manual/en/module_specs/Zend_Db-TableGateway.xml deleted file mode 100644 index 15896841af9..00000000000 --- a/documentation/manual/en/module_specs/Zend_Db-TableGateway.xml +++ /dev/null @@ -1,242 +0,0 @@ - -
- Zend\Db\TableGateway - - - The Table Gateway object is intended to provide an object - that represents a table in a database, and the methods of - this object mirror the most common operations on a database - table. In code, the interface for such an object looks like this: - - - - - - There are two primary implementations of the TableGatewayInterface - that are of the most useful: AbstractTableGateway and TableGateway. - The AbstractTableGateway is an abstract basic implementation that provides - functionality for select(), insert(), update(), delete(), as well as an - additional API for doing these same kinds of tasks with explicit SQL - objects. These methods are selectWith(), insertWith(), updateWith() - and deleteWith(). In addition, AbstracTableGateway also implements - a "Feature" API, that allows for expanding the behaviors of the - base TableGateway implementation without having to extend the - class with this new functionality. The TableGateway concrete - implementation simply adds a sensible constructor to the AbstractTableGateway - class so that out-of-the-box, TableGateway does not need to be extended - in order to be consumed and utilized to its fullest. - - - -
- Basic Usage - - - The quickest way to get up and running with Zend\Db\TableGateway is - to configure and utilize the concrete implementation of the TableGateway. - The API of the concrete TableGateway is: - - - - - - The concrete TableGateway object practices constructor injection for - getting dependencies and options into the instance. The table name - and an instance of an Adapter are all that is needed to setup a working - TableGateway object. - - - - Out of the box, this implementation makes no assumptions about table - structure or metadata, and when select() is executed, a simple ResultSet - object with the populated Adapter's Result (the datasource) will be returned - and ready for iteration. - - - select(array('type' => 'PHP')); - -echo 'Projects of type PHP: ' . -foreach ($rowset as $projectRow) { - echo $projectRow['name'] . PHP_EOL; -} - -// or, when expecting a single row: -$artistTable = new TableGateway('artist', $adapter); -$rowset = $artistTable->select(array('id' => 2)); -$artistRow = $rowset->current(); - -var_dump($artistRow->toArray()); -]]> - - - The select() method takes the same arguments as Zend\Db\Sql\Select::where() - with the addition of also being able to accept a closure, which in turn, will - be passed the current Select object that is being used to build the SELECT - query. The following usage is possible: - - - select(function (Select $select) { - $select->where->like('name', 'Brit%'); - $select->order('name ASC')->limit(2); -}); -]]> - -
- -
- TableGateway Features - - - The Features API allows for extending the functionality of the base TableGateway - object without having to polymorphically extend the base class. This allows for - a wider array of possible mixing and matching of features to achieve a particular - behiavior that needs to be attained to make the base implementation of TableGateway - useful for a particular problem. - - - - With the TableGateway object, features should be injected though the constructor. - The constructor can take Features in 3 different forms: as a single feature object, - as a FeatureSet object, or as an array of Feature objects. - - - - There are a number of features built-in and shipped with Zend\Db: - - - - - - GlobalAdapterFeature: the ability to use a global/static adapter without needing - to inject it into a TableGateway instance. This is more useful when you are - extending the AbstractTableGateway implementation: - - - AbstractTableGateway -{ - public function __construct() - { - $this->table = 'my_table'; - $this->featureSet = new Feature\FeatureSet(); - $this->featureSet->addFeature(new Feature\GlobalAdapterFeature()); - $this->initialize(); - } -} - -// elsewhere in code, in a bootstrap -Zend\Db\TableGateway\Feature\GlobalAdapterFeature::setStaticAdapter($adapter); - -// in a controller, or model somewhere -$table = new MyTableGateway(); // adapter is statially loaded -]]> - - - - - MasterSlaveFeature: the ability to use a master adapter for insert(), update(), - and delete() while using a slave adapter for all select() operations. - - - - - - - - - MetadataFeature: the ability populate TableGateway with column information from - a Metadata object. It will also store the primary key information in case - RowGatewayFeature needs to consume this information. - - - - - - - - - EventFeature: the ability utilize a TableGateway object with Zend\EventManager - and to be able to subscribe to various events in a TableGateway lifecycle. - - - - - - - - - RowGatewayFeature: the ability for select() to return a ResultSet object that - upon iteration will - - - select(array('id' => 2)); - -$artistRow = $results->current(); -$artistRow->name = 'New Name'; -$artistRow->save(); -]]> - - - - - -
- -
diff --git a/documentation/manual/en/module_specs/Zend_Feed_Reader.xml b/documentation/manual/en/module_specs/Zend_Feed_Reader.xml index e59b63d4055..d4d4608827e 100644 --- a/documentation/manual/en/module_specs/Zend_Feed_Reader.xml +++ b/documentation/manual/en/module_specs/Zend_Feed_Reader.xml @@ -637,7 +637,7 @@ $labels = $categories->getValues(); Returns the date on which this feed was created. Generally only applicable to Atom where it represents the date the resource described by an Atom 1.0 document was created. The returned date - will be a Zend_Date object. + will be a DateTime object. @@ -646,7 +646,7 @@ $labels = $categories->getValues(); Returns the date on which this feed was last modified. The returned date - will be a Zend_Date object. + will be a DateTime object. @@ -655,7 +655,7 @@ $labels = $categories->getValues(); Returns the date on which this feed was last built. The returned date - will be a Zend_Date object. This is only + will be a DateTime object. This is only supported by RSS - Atom feeds will always return NULL. @@ -1106,7 +1106,7 @@ $labels = $categories->getValues(); and RSS dates should follow RFC 822 or RFC 2822 which is also common. Date methods - will throw an exception if Zend_Date + will throw an exception if DateTime cannot load the date string using one of the above standards, or the PHP recognised possibilities for RSS dates.
diff --git a/documentation/manual/en/module_specs/Zend_Feed_Writer.xml b/documentation/manual/en/module_specs/Zend_Feed_Writer.xml index a899b478029..ea17c4be29f 100644 --- a/documentation/manual/en/module_specs/Zend_Feed_Writer.xml +++ b/documentation/manual/en/module_specs/Zend_Feed_Writer.xml @@ -346,7 +346,7 @@ $out = $feed->export('atom'); only applicable to Atom where it represents the date the resource described by an Atom 1.0 document was created. The expected parameter may be a UNIX timestamp or a - Zend_Date object. + DateTime object. @@ -356,7 +356,7 @@ $out = $feed->export('atom'); Sets the date on which this feed was last modified. The expected parameter may be a UNIX timestamp or a - Zend_Date object. + DateTime object. @@ -366,7 +366,7 @@ $out = $feed->export('atom'); Sets the date on which this feed was last build. The expected parameter may be a UNIX timestamp or a - Zend_Date object. This will only be + DateTime object. This will only be rendered for RSS 2.0 feeds and is automatically rendered as the current date by default when not explicity set. @@ -633,7 +633,7 @@ $out = $feed->export('atom'); only applicable to Atom where it represents the date the resource described by an Atom 1.0 document was created. The expected parameter may be a UNIX timestamp or a - Zend_Date object. If omitted, the date + DateTime object. If omitted, the date used will be the current date and time. @@ -644,7 +644,7 @@ $out = $feed->export('atom'); Sets the date on which this feed was last modified. The expected parameter may be a UNIX timestamp or a - Zend_Date object. If omitted, the date + DateTime object. If omitted, the date used will be the current date and time. diff --git a/documentation/manual/en/module_specs/Zend_Filter-Alnum.xml b/documentation/manual/en/module_specs/Zend_Filter-Alnum.xml index da0d4e1ac33..e8d02fe064e 100644 --- a/documentation/manual/en/module_specs/Zend_Filter-Alnum.xml +++ b/documentation/manual/en/module_specs/Zend_Filter-Alnum.xml @@ -48,7 +48,7 @@ $return = $filter->filter('This is (my) content: 123'); Zend_Filter_Alnum works on almost all languages. But actually there are three exceptions: Chinese, Japanese and Korean. Within these languages the english alphabet is use instead of the characters from these languages. The language - itself is detected by using Zend_Locale. + itself is detected by using Locale.
diff --git a/documentation/manual/en/module_specs/Zend_Filter-Alpha.xml b/documentation/manual/en/module_specs/Zend_Filter-Alpha.xml index 195335abffa..d70193ca1c5 100644 --- a/documentation/manual/en/module_specs/Zend_Filter-Alpha.xml +++ b/documentation/manual/en/module_specs/Zend_Filter-Alpha.xml @@ -49,7 +49,7 @@ print $filter->filter('This is (my) content: 123'); Zend_Filter_Alpha works on most languages; however, there are three exceptions: Chinese, Japanese and Korean. With these languages the english alphabet is used. The language is detected through the use of - Zend_Locale. + Locale. diff --git a/documentation/manual/en/module_specs/Zend_Filter-LocalizedToNormalized.xml b/documentation/manual/en/module_specs/Zend_Filter-LocalizedToNormalized.xml deleted file mode 100644 index fe036d4efb2..00000000000 --- a/documentation/manual/en/module_specs/Zend_Filter-LocalizedToNormalized.xml +++ /dev/null @@ -1,289 +0,0 @@ - -
LocalizedToNormalized and NormalizedToLocalized - - - - These two filters can change given localized input to it's normalized representation and - reverse. They use in Background Zend_Locale to do this transformation - for you. - - -
- Supported options for Zend_Filter_LocalizedToNormalized and - Zend_Filter_NormalizedToLocalized - - - - - The following options are supported for - Zend_Filter_LocalizedToNormalized and - Zend_Filter_NormalizedToLocalized: - - - - - - date_format: This sets the date format - to use for normalization and to detect the localized date format - - - - - - locale: This sets the locale to use - for normalization and to detect the localized format - - - - - - precision: This sets the precision to - use for number conversion - - - -
- -
Workflow - - - - Normalization allows your user to enter informations in his own language notation, and - you can then store the normalized value into your database for example. Localization - on the other hand allows you to display normalized informations in a localized manner - to your user. - - - - - Please note that normalization and localization is not equal to translation. These - filters can not translate strings from one language into another like you could - expect with months or names of days. - - - - - The following input types can be normalized and localized: - - - - - - integer: Integer numbers. Normalization returns the english - notation - - - - - - float: Float numbers. Normalization returns the english - notation - - - - - - numbers: Other numbers, like real. Normalization returns - the english notation - - - - - - time: Time values. The normalized value is a named array - - - - - - date: Date values. The normalized value is a named array - - - - - - Any other input will be returned as is, without changing it. - - - - - You should note that normalized output is always given as string. Otherwise your - environment would transfer the normalized output automatically to the notation used - by the locale your environment is set to. - - -
- -
Normalization for numbers - - - - Any given number like integer, float or real value, can be normalized. Note, that - numbers in scientific notation, can actually not be handled by this filter. - - - - So how does this normalization work in detail for numbers: - - - filter('123.456,78'); -// returns the value '123456.78' -]]> - - - Let's expect you have set the locale 'de' as application wide locale. - Zend_Filter_LocalizedToNormalized will take the set locale and - use it to detect which sort of input you gave. In our example it was a value with - precision. Now the filter will return you the normalized representation for this value - as string. - - - - You can also control how your normalized number has to look like. Therefor you can give - all options which are also used by Zend_Locale_Format. For - details about available options take a look into this - Zend_Locale chapter. - - - - Below is a example with defined precision so you can see how options work: - - - 2)); - -$filter->filter('123.456'); -// returns the value '123456.00' - -$filter->filter('123.456,78901'); -// returns the value '123456.79' -]]> -
- -
Normalization for date and time - - - - Input for date and time values can also be normalized. All given date and time values - will be returned as array, where each date part is given within a own key. - - - filter('12.April.2009'); -// returns array('day' => '12', 'month' => '04', 'year' => '2009') -]]> - - - Let's expect you have set the locale 'de' again. Now the input is automatically detected - as date, and you will get a named array in return. - - - - Of course you can also control how your date input looks like with the - date_format and the locale option. - - - 'ss:mm:HH') -); - -$filter->filter('11:22:33'); -// returns array('hour' => '33', 'minute' => '22', 'second' => '11') -]]> -
- -
Localization for numbers - - - - Any given number like integer, float or real value, can be localized. Note, that - numbers in scientific notation, can actually not be handled by this filter. - - - - So how does localization work in detail for numbers: - - - filter(123456.78); -// returns the value '123.456,78' -]]> - - - Let's expect you have set the locale 'de' as application wide locale. - Zend_Filter_NormalizedToLocalized will take the set locale and - use it to detect which sort of output you want to have. In our example it was a value - with precision. Now the filter will return you the localized representation for this - value as string. - - - - You can also control how your localized number has to look like. Therefor you can give - all options which are also used by Zend_Locale_Format. For - details about how these options are used take a look into this - Zend_Locale chapter. - - - - Below is a example with defined precision so you can see how options - work: - - - 2)); - -$filter->filter(123456); -// returns the value '123.456,00' - -$filter->filter(123456.78901); -// returns the value '123.456,79' -]]> -
- -
Localization for date and time - - - - Normalized for date and time values can also be localized. All given date and time - values will be returned as string, with the format defined by the set locale. - - - filter(array('day' => '12', 'month' => '04', 'year' => '2009'); -// returns '12.04.2009' -]]> - - - Let's expect you have set the locale 'de' again. Now the input is automatically detected - as date, and will be returned in the format defined by the locale 'de'. - - - - Of course you can also control how your date input looks like with the - date_format, and the locale option. - - - 'ss:mm:HH') -); - -$filter->filter(array('hour' => '33', 'minute' => '22', 'second' => '11')); -// returns '11:22:33' -]]> -
-
diff --git a/documentation/manual/en/module_specs/Zend_Filter-Set.xml b/documentation/manual/en/module_specs/Zend_Filter-Set.xml index bcaadd19862..649ecc380cd 100644 --- a/documentation/manual/en/module_specs/Zend_Filter-Set.xml +++ b/documentation/manual/en/module_specs/Zend_Filter-Set.xml @@ -19,7 +19,6 @@ - diff --git a/documentation/manual/en/module_specs/Zend_Http_Request.xml b/documentation/manual/en/module_specs/Zend_Http_Request.xml index 3cd77d65923..beeeecbf7da 100644 --- a/documentation/manual/en/module_specs/Zend_Http_Request.xml +++ b/documentation/manual/en/module_specs/Zend_Http_Request.xml @@ -664,9 +664,9 @@ N/A headers()->get('Content-Type'); // return content type -$request->headers()->addHeader(new Cookie('foo' => 'bar')); -foreach ($request->headers() as $header) { +$request->getHeaders()->get('Content-Type'); // return content type +$request->getHeaders()->addHeader(new Cookie('foo' => 'bar')); +foreach ($request->getHeaders() as $header) { echo $header->getFieldName() . ' with value ' . $header->getFieldValue(); } ]]> diff --git a/documentation/manual/en/module_specs/Zend_Http_Response.xml b/documentation/manual/en/module_specs/Zend_Http_Response.xml index b1cfde7694c..c4b67318ac9 100644 --- a/documentation/manual/en/module_specs/Zend_Http_Response.xml +++ b/documentation/manual/en/module_specs/Zend_Http_Response.xml @@ -75,7 +75,7 @@ EOS); $response = new Response(); $response->setStatusCode(Response::STATUS_CODE_200); -$response->headers()->addHeaders(array( +$response->getHeaders()->addHeaders(array( 'HeaderField1' => 'header-field-value', 'HeaderField2' => 'header-field-value2', ); @@ -479,7 +479,7 @@ EOS); use Zend\Http\Response; $response = new Response(); $response->setStatusCode(Response::STATUS_CODE_200); -$response->headers()->addHeaders(array( +$response->getHeaders()->addHeaders(array( 'HeaderField1' => 'header-field-value', 'HeaderField2' => 'header-field-value2', ); diff --git a/documentation/manual/en/module_specs/Zend_Ldap-API-Ldap-Converter-Converter.xml b/documentation/manual/en/module_specs/Zend_Ldap-API-Ldap-Converter-Converter.xml index 9928aa592f2..754176afcdf 100644 --- a/documentation/manual/en/module_specs/Zend_Ldap-API-Ldap-Converter-Converter.xml +++ b/documentation/manual/en/module_specs/Zend_Ldap-API-Ldap-Converter-Converter.xml @@ -227,7 +227,7 @@ string|null - toLdapDateTime(integer|string|DateTime|Zend\Date\Date $date, boolean $asUtc) + toLdapDateTime(integer|string|DateTime $date, boolean $asUtc) @@ -235,7 +235,7 @@ Converts a timestamp, a DateTime Object, a string that is parseable by strtotime() - or a Zend\Date\Date into its + or a DateTime into its LDAP date/time representation. If diff --git a/documentation/manual/en/module_specs/Zend_Loader-Broker.xml b/documentation/manual/en/module_specs/Zend_Loader-Broker.xml deleted file mode 100644 index f26d0425bd2..00000000000 --- a/documentation/manual/en/module_specs/Zend_Loader-Broker.xml +++ /dev/null @@ -1,211 +0,0 @@ - -
The Broker Interface - - -
Overview - - - - Withing Zend Framework, a number of components have a need to: - - - - Dynamically load adapters, helpers, or other plugins - - - - Allow specifying such adapters, helpers, and plugins by a "short name" variant, - in order to allow overriding defaults; in other words, to allow slipstreaming - custom variants into the component. - - - - - - The Broker interface provides a simple contract for - managing these extensions. At its simplest, it allows you to register and unregister - concrete extension instances, mapping them to a short name. For added flexibility, it - allows specifying a plugin class - loader that may be used to resolve the short names to class names, and thus - dynamically resolve the name to a new class instance. - - - - A concrete implementation of this interface is provided with the PluginBroker class. - -
- -
Quick Start - - - - A concrete interface must simply follow the contract as specified in the interface: - - - -
- -
Configuration Options - - - - This component defines no configuration options, as it is an interface. - -
- -
Available Methods - - - - - load - Locate and return a plugin instance - - - - - load - - $plugin, array $options = null - - - - - load() - - - - load() is intended to do the heavy lifting of the - broker. The $plugin argument should be a short name, - preferably case-insensitive, describing the plugin to load. The broker's - responsibility is then to return an instance of the appropriate plugin. For new - instances, the $options argument can be used to seed and - configure the plugin. - - - - - - - register - Register a plugin - - - - - register - - $name, $plugin - - - - - register() - - - - register() allows explicitly registering a plugin with - the broker. The provided $name will be used to refer to the - plugin later via load() or - unregister(). $plugin may be either - a string class name or an object instance; the implementation will determine - usage. - - - - - - - unregister - Unregister a plugin from the broker - - - - - unregister - - $name - - - - - unregister() - - - - Used to remove a plugin from the broker. Based on the implementation, this may - simply remove a previous instance registered in the broker, or it may prevent - ever loading it again. - - - - - - - setClassLoader - Specify a class loader to be used for plugin class lookups - - - - - setClassLoader - - Zend\Loader\ShortNameLocator $loader - - - - - setClassLoader() - - - - Plugins are supposed to be dynamic, overridable functionality. A class loader is - used to dynamically determine what plugin class to use when a given plugin is - retrieved from the broker. This method allows you to specify what implementation - to utilize. - - - - - - - getClassLoader - Retrieve the plugin class loader - - - - - getClassLoader - - - - - getClassLoader() - - - - Retrieves the currently registered plugin class loader. - - - -
- -
Examples - - - - Please see the Quick Start for the - interface specification. - -
-
diff --git a/documentation/manual/en/module_specs/Zend_Loader-PluginBroker.xml b/documentation/manual/en/module_specs/Zend_Loader-PluginBroker.xml deleted file mode 100644 index accc1535a3c..00000000000 --- a/documentation/manual/en/module_specs/Zend_Loader-PluginBroker.xml +++ /dev/null @@ -1,505 +0,0 @@ - -
The PluginBroker - - -
Overview - - - - Many components within Zend Framework offer extensibility via adapters, helpers, - filters, and other plugins. Using full class names is often unwieldy, or prevents the - ability to slipstream in alternate implementations. The - PluginBroker provides a standard mechanism for the following: - - - - - - Resolving plugin names to class instances. - - - - - - Lazy loading plugin instances only when called upon, with the options requested. - - - - - - Storing plugin instances between invocations. - - - - - - In sum, it acts as a factory/builder, service locator, and object registry. - - - - The PluginBroker is designed to work in conjunction with a ShortNameLocator -- usually a PluginClassLoader, but sometimes a - PrefixPathLoader. The - ShortNameLocator provides the ability to resolve a plugin - name to a class; the PluginBroker then instantiates, stores, and - returns an object of that class. - - - - Classes utilizing any sort of plugin architecture should embed a - PluginBroker instance. Often in such situations, only plugins of - a specific type or meeting specific criteria are desired. For thse situations, you may - extend the PluginBroker and either specify a validator callback - or override the validatePlugin() method in order to validate an - instantiated plugin against your criteria. - -
- -
Quick Start - - - - Typically, a component will define an extension to the - PluginBroker. In these cases, you simply instantiate the broker, - and then retrieve a given plugin, optionally passing in constructor arguments. - - - load('url', array('router' => $router)); -echo $urlHelper->simple('sign', 'guestbook'); -]]> - - - You can seed the broker as well, using the register() method. - This is useful for cases where you have an instance of the plugin object already, or - when you want to manually configure it before injecting it into the broker. - - - register('url', $urlHelper); -]]> -
- -
Configuration Options - - - PluginBroker Options - - - - class_loader - - - - The value of this option may be one of the following: - - - - - A string indicating a fully qualified class name to use for the - class loader. The class must implement - ShortNameLocator. - - - - An object implementing - ShortNameLocator. - - - - An array or Traversable object - containing the keys class and optionally - options. An object of the type described in - class will be instantiated, with the - options provided, if any. The class must - implement ShortNameLocator. - - - - - - - plugins - - - - The value of this option should be an array or - Traversable object, containing plugin - name/plugin object pairs. - - - - - - validator - - - - The value must be a valid callback, and will be used as a validator for - loaded and registered plugins. - - - - -
- -
Available Methods - - - - - load - Resolve a plugin name to an object instance - - - - - load - - $plugin, array $options = null - - - - - load() - - - - This method attempts to resolve a plugin name to an object instance. In order to - do this, it first delegates to the attached class loader instance to resolve the - plugin name to a class name, and then instantiates the class with the given - $options, if any. Options are assumed to be in the order in - which they appear in the constructor -- in other words, it acts as an array of - arguments to the constructor. - - - - If a plugin has been loaded previously, or registered manually, it will be - returned immediately. - - - - If the class loader cannot locate a corresponding class, or if the plugin - instance does not validate, an exception will be thrown. - - - - - - - register - Register a plugin instance by name - - - - - register - - $name, $plugin - - - - - register() - - - - Registers a $plugin instance by a given - $name. If the $plugin does not pass - validation, an exception will be raised. - - - - - - - unregister - Unregister a plugin instance - - - - - unregister - - $name - - - - - unregister() - - - - If the plugin instance referenced by $name has been - previously loaded, that instance is removed from the registry. Note that this - does not prevent you from loading the plugin again; however, a new instance will - be returned in such a case. - - - - - - - getPlugins - Retrieve all loaded plugins - - - - - getPlugins - - - - - - - getPlugins() - - - - Retrieves a set of name/plugin pairs, indicating all currently loaded plugins. - - - - - - - isLoaded - Determine if a given plugin has been loaded - - - - - isLoaded - - $name - - - - - isLoaded() - - - - Returns true if the plugin referenced by - $name has been loaded by the broker previously, - false otherwise. - - - - - - - setClassLoader - Specify the plugin class loader to use when resolving plugins to class - names - - - - - setClassLoader - - ShortNameLocator $loader - - - - - setClassLoader() - - - - Use this method to set a plugin class loader to use when resolving plugin names - to class names. As noted in the signature, the object must adhere to the - ShortNameLocator interface. - - - - - - - getClassLoader - Retrieve the plugin class resolver - - - - - getClassLoader - - - - - getClassLoader() - - - - Retrieves the plugin class resolver; the object will always be an implemenation - of ShortNameLocator. - - - - - - - setValidator - Specify a validation callback to verify plugin instances - - - - - setValidator - - $callback - - - - - setValidator() - - - - In order to "lock down" the plugin broker to plugins that satisfy specific - criteria -- such as implementing specific interfaces -- you may specify a - validation callback. The callback will receive a plugin instance, and should - return a boolean value (true indicating validations pass, - false indicating failure). - - - - As an example, the following would specify a validator that restricts plugins to - implementing Traversable: - - - setValidator(function($plugin) { - return ($plugin instanceof \Traversable); -}); -]]> - - - Passing a null value will clear the validator; otherwise, the method expects any - valid PHP callback, including closures. - - - - - - - getValidator - Return the validator callback - - - - - getValidator - - - - - getValidator() - - - - The mirror of setValidator(), this method will return - the plugin validation callback, if any. - - - -
- -
Examples - - - Plugin validation callback - - - - It's often overkill to extend the PluginBroker, particularly - if all you want to do is ensure the plugins are of an appropriate type. Fortunately, - the setValidator() method makes this trivial. - - - - In the following example, we'll ensure that the plugins returned all are - Traversable and implement - ArrayAccess. - - - setClassLoader(new HelperLoader) - ->setValidator(function($plugin) { - return ( - ($plugin instanceof \Traversable) - && ($plugin instanceof \ArrayAccess) - ); - }); -]]> - - - Any plugins loaded that do not satisfy that criteria will no raise an exception in - the broker. - - - - Creating a custom broker - - - - In the previous example, we illustrated configuring a plugin broker instance that - utilizes a custom PluginClassLoader and a validator closure. - The problem with this sort of configuration is that you likely don't want to do this - within your classes or code that often -- it's easier and more useful to simply use - objects. As such, you'll want to investigate extending the - PluginBroker. - - - - The obvious flex point is to override the getClassLoader() - to lazy load the appropriate class loader. Even easier is simply overwriting the - $defaultClassLoader property, which is a string indicating the - default plugin loader class to utilize. - - - - Less obvious is how to override validation. You have two options: create a - constructor that registers a validator, or override the protected method - validatePlugin(). We prefer the latter, as it prevents - later users from altering validation by injecting a validation callback. - - - - The following code is equivalent to the previous example, but creates a custom - plugin broker class. - - - - - - You may now use this class as a plugin broker anywhere in your code, typehint on it, - etc. - - -
-
diff --git a/documentation/manual/en/module_specs/Zend_Loader-PluginSpecBroker.xml b/documentation/manual/en/module_specs/Zend_Loader-PluginSpecBroker.xml deleted file mode 100644 index 55fe1d4198b..00000000000 --- a/documentation/manual/en/module_specs/Zend_Loader-PluginSpecBroker.xml +++ /dev/null @@ -1,240 +0,0 @@ - -
- The PluginSpecBroker - -
- Overview - - - This class is an extension of the - PluginBroker. It provides the additional ability of allowing the registration - of plugin names with related options, for the purposes of allowing - lazy-loading of plugins and/or specifying default options. - -
- -
- Quick Start - - - Typically, a component will define an extension to the - PluginSpecBroker. In these cases, you instantiate the broker, - optionally providing specifications. - - - array('routes' => array( - 'foo' => array( - 'route' => '/foo/:id', - 'defaults' => array( - 'module' => 'foo', - 'controller' => 'products', - 'action' => 'item', - ), - 'reqs' => array( - 'id' => '\d+', - ), - ), - )), -)); - -$router = $broker->load('router'); -// routes will be configured per specification -]]> -
- -
- Configuration Options - - - All PluginBroker options are - supported, in addition to those listed below. - - - - PluginSpecBroker Options - - - specs - - - - The value of this option should be an array or - Traversable object, containing plugin - name/configuration pairs. - - - - -
- -
- Available Methods - - - All PluginBroker methods are - available. The methods below either differ in capabilities, or are specific to this - implementation. - - - - - load - Resolve a plugin name to an object instance - - - - - load - - $plugin, array $options = null - - - - - - load() - - - This method acts like parent in all ways. - However, if a specification has been loaded previously via the constructor, - setOptions(), or - registerSpec(), those options will be used if - $options is null. - - - - - - - registerSpec - Register a plugin specification by name - - - - - registerSpec - - $name, array $spec = null - - - - - - registerSpec() - - - Registers a plugin specification using the given $name. The - specification is simply a set of arguments to pass to the object constructor - when first loaded by the broker. - - - - - - - registerSpecs - Register many plugin specifications at once - - - - - registerSpecs - - $specs - - - - - - registerSpecs() - - - Registers many plugin specifications at once. $specs must be - an array or Traversable object. It is iterated, - and the key/value pairs are passed as arguments to - registerSpec(). - - - - - - - unregisterSpec - Unregister a plugin specification - - - - - unregisterSpec - - $name - - - - - - unregisterSpec() - - - If a plugin specficiation referenced by $name has been - previously registered, that specification is removed. - - - - - - - getRegisteredPlugins - Retrieve all registered plugins and specifications - - - - - getRegisteredPlugins - - - - - - - - getRegisteredPlugins() - - - Retrieves the names of all loaded plugins, as well as all plugin specifications - registered. - - - - - - - hasPlugin - Determine if a plugin has been loaded or registered - - - - - hasPlugin - - $name - - - - - - hasPlugin() - - - Use this method to determine whether or not the plugin by the name of - $name has been loaded or registered, or whether or not a - plugin specification has been provided. - - - -
-
diff --git a/documentation/manual/en/module_specs/Zend_Locale-AppendixLanguages.xml b/documentation/manual/en/module_specs/Zend_Locale-AppendixLanguages.xml deleted file mode 100644 index c89d6c316ac..00000000000 --- a/documentation/manual/en/module_specs/Zend_Locale-AppendixLanguages.xml +++ /dev/null @@ -1,3218 +0,0 @@ - - - -
Supported locales - - - - Zend_Locale provides information on several locales. The following - table shows all languages and their related locales, sorted by language: - - - List of all supported languages - - - - - - Language - Locale - Region - - - - - - Afar - aa - --- - - - - aa_DJ - Djibouti - - - - aa_ER - Eritrea - - - - aa_ET - Ethiopia - - - - Afrikaans - af - --- - - - - af_NA - Namibia - - - - af_ZA - South Africa - - - - Akan - ak - --- - - - - ak_GH - Ghana - - - - Amharic - am - --- - - - - am_ET - Ethiopia - - - - Arabic - ar - --- - - - - ar_AE - United Arab Emirates - - - - ar_BH - Bahrain - - - - ar_DZ - Algeria - - - - ar_EG - Egypt - - - - ar_IQ - Iraq - - - - ar_JO - Jordan - - - - ar_KW - Kuwait - - - - ar_LB - Lebanon - - - - ar_LY - Libya - - - - ar_MA - Morocco - - - - ar_OM - Oman - - - - ar_QA - Qatar - - - - ar_SA - Saudi Arabia - - - - ar_SD - Sudan - - - - ar_SY - Syria - - - - ar_TN - Tunisia - - - - ar_YE - Yemen - - - - Assamese - as - --- - - - - as_IN - India - - - - Asu - asa - --- - - - - asa_TZ - Tanzania - - - - Azerbaijani - az - --- - - - - az_Arab - --- - - - - az_Arab_IR - Iran - - - - az_AZ - Azerbaijan - - - - az_Cyrl - --- - - - - az_Cyrl_AZ - Azerbaijan - - - - az_IR - Iran - - - - az_Latn - --- - - - - az_Latn_AZ - Azerbaijan - - - - Belarusian - be - --- - - - - be_BY - Belarus - - - - Bemba - bem - --- - - - - bem_ZM - Zambia - - - - Bena - bez - --- - - - - bez_TZ - Tanzania - - - - Bulgarian - bg - --- - - - - bg_BG - Bulgaria - - - - Bambara - bm - --- - - - - bm_ML - Mali - - - - Bengali - bn - --- - - - - bn_BD - Bangladesh - - - - bn_IN - India - - - - Tibetan - bo - --- - - - - bo_CN - China - - - - bn_IN - India - - - - Breton - br - --- - - - - br_FR - France - - - - Bodo - brx - --- - - - - brx_IN - India - - - - Bosnian - bs - --- - - - - bs_BA - Bosnia and Herzegovina - - - - Blin - byn - --- - - - - byn_ER - Eritrea - - - - Catalan - ca - --- - - - - ca_ES - Spain - - - - Atsam - cch - --- - - - - cch_NG - Nigeria - - - - Chiga - cgg - --- - - - - cgg_UG - Uganda - - - - Cherokee - chr - --- - - - - chr_US - United States - - - - Czech - cs - --- - - - - cs_CZ - Czech Republic - - - - Welsh - cy - --- - - - - cy_GB - United Kingdom - - - - Danish - da - --- - - - - da_DK - Denmark - - - - Taita - dav - --- - - - - dav_KE - Kenya - - - - German - de - --- - - - - de_AT - Austria - - - - de_BE - Belgium - - - - de_CH - Switzerland - - - - de_DE - Germany - - - - de_LI - Liechtenstein - - - - de_LU - Luxembourg - - - - Divehi - dv - --- - - - - dv_MV - Maldives - - - - Dzongkha - dz - --- - - - - dz_BT - Bhutan - - - - Embu - ebu - --- - - - - ebu_KE - Kenya - - - - Ewe - ee - --- - - - - ee_GH - Ghana - - - - ee_TG - Togo - - - - Greek - el - --- - - - - el_CY - Cyprus - - - - el_GR - Greece - - - - English - en - --- - - - - en_AS - American Samoa - - - - en_AU - Australia - - - - en_BE - Belgium - - - - en_BW - Botswana - - - - en_BZ - Belize - - - - en_CA - Canada - - - - en_Dsrt - --- - - - - en_Dsrt_US - United States - - - - en_GB - United Kingdom - - - - en_GU - Guam - - - - en_HK - Hong Kong - - - - en_IE - Ireland - - - - en_IN - India - - - - en_JM - Jamaica - - - - en_MH - Marshall Islands - - - - en_MP - Northern Mariana Islands - - - - en_MT - Malta - - - - en_MU - Mauritius - - - - en_NA - Namibia - - - - en_NZ - New Zealand - - - - en_PH - Philippines - - - - en_PK - Pakistan - - - - en_SG - Singapore - - - - en_Shaw - --- - - - - en_TT - Trinidad and Tobago - - - - en_UM - United States Minor Outlying Islands - - - - en_US - United States - - - - en_VI - U.S. Virgin Islands - - - - en_ZA - South Africa - - - - en_ZW - Zimbabwe - - - - en_ZZ - Unknown Region - - - - Esperanto - eo - --- - - - - Spanish - es - --- - - - - es_419 - --- - - - - es_AR - Argentina - - - - es_BO - Bolivia - - - - es_CL - Chile - - - - es_CO - Colombia - - - - es_CR - Costa Rica - - - - es_DO - Dominican Republic - - - - es_EC - Ecuador - - - - es_ES - Spain - - - - es_GQ - Equatorial Guinea - - - - es_GT - Guatemala - - - - es_HN - Honduras - - - - es_MX - Mexico - - - - es_NI - Nicaragua - - - - es_PA - Panama - - - - es_PE - Peru - - - - es_PR - Puerto Rico - - - - es_PY - Paraguay - - - - es_SV - El Salvador - - - - es_US - United States - - - - es_UY - Uruguay - - - - es_VE - Venezuela - - - - Estonian - et - --- - - - - et_EE - Estonia - - - - Basque - eu - --- - - - - eu_ES - Spain - - - - Persian - fa - --- - - - - fa_AF - Afghanistan - - - - fa_IR - Iran - - - - Fulah - ff - --- - - - - ff_SN - Senegal - - - - Finnish - fi - --- - - - - fi_FI - Finland - - - - Filipino - fil - --- - - - - fil_PH - Philippines - - - - Faroese - fo - --- - - - - fo_FO - Faroe Islands - - - - French - fr - --- - - - - fr_BE - Belgium - - - - fr_BF - Burkina Faso - - - - fr_BI - Burundi - - - - fr_BJ - Benin - - - - fr_BL - Saint BarthĆ©lemy - - - - fr_CA - Canada - - - - fr_CD - Congo - Kinshasa - - - - fr_CF - Central African Republic - - - - fr_CG - Congo - Brazzaville - - - - fr_CH - Switzerland - - - - fr_CI - CĆ“te dā€™Ivoire - - - - fr_CM - Cameroon - - - - fr_DJ - Djibouti - - - - fr_FR - France - - - - fr_GA - Gabon - - - - fr_GN - Guinea - - - - fr_GP - Guadeloupe - - - - fr_GQ - Equatorial Guinea - - - - fr_KM - Comoros - - - - fr_LU - Luxembourg - - - - fr_MC - Monaco - - - - fr_MF - Saint Martin - - - - fr_MG - Madagascar - - - - fr_ML - Mali - - - - fr_MQ - Martinique - - - - fr_NE - Niger - - - - fr_RE - RĆ©union - - - - fr_RW - Rwanda - - - - fr_SN - Senegal - - - - fr_TD - Chad - - - - fr_TG - Togo - - - - Friulian - fur - --- - - - - fur_IT - Italy - - - - Irish - ga - --- - - - - ga_IE - Ireland - - - - Ga - gaa - --- - - - - gaa_GH - Ghana - - - - Geez - gez - --- - - - - gez_ER - Eritrea - - - - gez_ET - Ethiopia - - - - Gallegan - gl - --- - - - - gl_ES - Spain - - - - Swiss German - gsw - --- - - - - gsw_CH - Swiss - - - - Gujarati - gu - --- - - - - gu_IN - India - - - - Gusii - guz - --- - - - - guz_KE - Kenya - - - - Manx - gv - --- - - - - gv_GB - United Kingdom - - - - Hausa - ha - --- - - - - ha_Arab - --- - - - - ha_Arab_NG - Nigeria - - - - ha_Arab_SD - Sudan - - - - ha_GH - Ghana - - - - ha_Latn - --- - - - - ha_Latn_GH - Ghana - - - - ha_Latn_NE - Niger - - - - ha_Latn_NG - Nigeria - - - - ha_NE - Niger - - - - ha_NG - Nigeria - - - - ha_SD - Sudan - - - - Hawaiian - haw - --- - - - - haw_US - United States - - - - Hebrew - he - --- - - - - he_IL - Israel - - - - Hindi - hi - --- - - - - hi_IN - India - - - - Croatian - hr - --- - - - - hr_HR - Croatia - - - - Hungarian - hu - --- - - - - hu_HU - Hungary - - - - Armenian - hy - --- - - - - Interlingua - ia - --- - - - - Indonesian - id - --- - - - - id_ID - Indonesia - - - - Igbo - ig - --- - - - - ig_NG - Nigeria - - - - Sichuan Yi - ii - --- - - - - ii_CN - China - - - - Indonesian - in - --- - - - - Icelandic - is - --- - - - - is_IS - Iceland - - - - Italian - it - --- - - - - it_CH - Switzerland - - - - it_IT - Italy - - - - Inuktitut - iu - --- - - - - Hebrew - iw - --- - - - - Japanese - ja - --- - - - - ja_JP - Japan - - - - Machame - jmc - --- - - - - jmc_TZ - Tanzania - - - - Georgian - ka - --- - - - - ka_GE - Georgia - - - - Kabyle - kab - --- - - - - kab_DZ - Algeria - - - - Jju - kaj - --- - - - - kaj_NG - Nigeria - - - - Kamba - kam - --- - - - - kam_KE - Kenya - - - - Tyap - kcg - --- - - - - kcg_NG - Nigeria - - - - Makonde - kde - --- - - - - kde_TZ - Tanzania - - - - Kabuverdianu - kea - --- - - - - kea_CV - Cape Verde - - - - Koro - kfo - --- - - - - kfo_CI - Ivory Coast - - - - Koyra Chiini - khq - --- - - - - khq_ML - Mali - - - - Kikuyu - ki - --- - - - - ki_KE - Kenya - - - - Kazakh - kk - --- - - - - kk_Cyrl - --- - - - - kk_Cyrl_KZ - Kazakhstan - - - - kk_KZ - Kazakhstan - - - - Kalaallisut - kl - --- - - - - kl_GL - Greenland - - - - Kalenjin - kln - --- - - - - kln_KE - Kenya - - - - Khmer - km - --- - - - - km_KH - Cambodia - - - - Kannada - kn - --- - - - - kn_IN - India - - - - Korean - ko - --- - - - - ko_KR - South Korea - - - - Konkani - kok - --- - - - - kok_IN - India - - - - Kpelle - kpe - --- - - - - kpe_GN - Guinea - - - - kpe_LR - Liberia - - - - Shambala - ksb - --- - - - - ksb_TZ - Tanzania - - - - Colognian - ksh - --- - - - - ksh_DE - Germany - - - - Kurdish - ku - --- - - - - ku_Arab - --- - - - - ku_Arab_IQ - Iraq - - - - ku_Arab_IR - Iran - - - - ku_IQ - Iraq - - - - ku_IR - Iran - - - - ku_Latn - --- - - - - ku_Latn_SY - Syria - - - - ku_Latn_TR - Turkey - - - - ku_SY - Syria - - - - ku_TR - Turkey - - - - Cornish - kw - --- - - - - kw_GB - United Kingdom - - - - Kirghiz - ky - --- - - - - ky_KG - Kyrgyzstan - - - - Langi - lag - --- - - - - lag_TZ - Tanzania - - - - Ganda - lg - --- - - - - lg_UG - Uganda - - - - Lingala - ln - --- - - - - ln_CD - Congo - Kinshasa - - - - ln_CG - Congo - Brazzaville - - - - Lao - lo - --- - - - - lo_LA - Laos - - - - Lithuanian - lt - --- - - - - lt_LT - Lithuania - - - - Luo - luo - --- - - - - luo_KE - Kenya - - - - Luyia - luy - --- - - - - luy_KE - Kenya - - - - Latvian - lv - --- - - - - lv_LV - Latvia - - - - Masai - mas - --- - - - - mas_KE - Kenya - - - - mas_TZ - Tanzania - - - - Meru - mer - --- - - - - mer_KE - Kenya - - - - Morisyen - mfe - --- - - - - mfe_MU - Mauritius - - - - Malagasy - mg - --- - - - - mg_MG - Madagascar - - - - Maori - mi - --- - - - - mi_NZ - New Zealand - - - - Macedonian - mk - --- - - - - mk_MK - Macedonia - - - - Malayalam - ml - --- - - - - ml_IN - India - - - - Mongolian - mn - --- - - - - mn_CN - China - - - - mn_Cyrl - --- - - - - mn_Cyrl_MN - Mongolia - - - - mn_Mong - --- - - - - mn_Mong_CN - China - - - - mn_MN - Mongolia - - - - Romanian - mo - --- - - - - Marathi - mr - --- - - - - mr_IN - India - - - - Malay - ms - --- - - - - ms_BN - Brunei - - - - ms_MY - Malaysia - - - - Maltese - mt - --- - - - - mt_MT - Malta - - - - Burmese - my - --- - - - - my_MM - Myanmar - - - - Nama - naq - --- - - - - naq_NA - Namibia - - - - Norwegian Bokmal - nb - --- - - - - nb_NO - Norway - - - - North Ndebele - nd - --- - - - - nd_ZW - Zimbabwe - - - - Low German - nds - --- - - - - nds_DE - Germany - - - - Nepali - ne - --- - - - - ne_IN - India - - - - ne_NP - Nepal - - - - Dutch - nl - --- - - - - nl_BE - Belgium - - - - nl_NL - Netherlands - - - - Norwegian Nynorsk - nn - --- - - - - nn_NO - Norway - - - - Norwegian - no - --- - - - - South Ndebele - nr - --- - - - - nr_ZA - South Africa - - - - Northern Sotho - nso - --- - - - - nso_ZA - South Africa - - - - Nyanja - ny - --- - - - - ny_MW - Malawi - - - - Nyankole - nyn - --- - - - - nyn_UG - Uganda - - - - Occitan - oc - --- - - - - oc_FR - France - - - - Oromo - om - --- - - - - om_ET - Ethiopia - - - - om_KE - Kenya - - - - Oriya - or - --- - - - - or_IN - India - - - - Punjabi - pa - --- - - - - pa_Arab - --- - - - - pa_Arab_PK - Pakistan - - - - pa_Guru - --- - - - - pa_Guru_IN - India - - - - pa_IN - India - - - - pa_PK - Pakistan - - - - Polish - pl - --- - - - - pl_PL - Poland - - - - Pashto - ps - --- - - - - ps_AF - Afghanistan - - - - Portuguese - pt - --- - - - - pt_AO - Angola - - - - pt_BR - Brazil - - - - pt_GW - Guinea-Bissau - - - - pt_MZ - Mozambique - - - - pt_PT - Portugal - - - - Romansh - rm - --- - - - - rm_CH - Switzerland - - - - Romanian - ro - --- - - - - ro_MD - Moldova - - - - ro_RO - Romania - - - - Rombo - rof - --- - - - - rof_TZ - Tanzania - - - - Russian - ru - --- - - - - ru_MD - Moldova - - - - ru_RU - Russia - - - - ru_UA - Ukraine - - - - Kinyarwanda - rw - --- - - - - rw_RW - Rwanda - - - - Rwa - rwk - --- - - - - rwk_TZ - Tanzania - - - - Sanskrit - sa - --- - - - - sa_IN - India - - - - Samburu - saq - --- - - - - saq_KE - Kenya - - - - Northern Sami - se - --- - - - - se_FI - Finland - - - - se_NO - Norway - - - - Sena - seh - --- - - - - seh_MZ - Mozambique - - - - Koyraboro Senni - ses - --- - - - - ses_ML - Mali - - - - Sango - sg - --- - - - - sg_CF - Central African Republic - - - - Serbo-Croatian - sh - --- - - - - sh_BA - Bosnia and Herzegovina - - - - sh_CS - Serbia and Montenegro - - - - sh_YU - Serbia - - - - Tachelhit - shi - --- - - - - shi_Latn - --- - - - - shi_Latn_MA - Morocco - - - - shi_MA - Morocco - - - - shi_Tfng - --- - - - - shi_Tfng_MA - Morocco - - - - Sinhala - si - --- - - - - si_LK - Sri Lanka - - - - Sidamo - sid - --- - - - - sid_ET - Ethiopia - - - - Slovak - sk - --- - - - - sk_SK - Slovakia - - - - Slovenian - sl - --- - - - - sl_SI - Slovenia - - - - Shona - sn - --- - - - - sn_ZW - Zimbabwe - - - - Somali - so - --- - - - - so_DJ - Djibouti - - - - so_ET - Ethiopia - - - - so_KE - Kenya - - - - so_SO - Somalia - - - - Albanian - sq - --- - - - - sq_AL - Albania - - - - Serbian - sr - --- - - - - sr_BA - Bosnia and Herzegovina - - - - sr_CS - Serbia and Montenegro - - - - sr_Cyrl - --- - - - - sr_Cyrl_BA - Bosnia and Herzegovina - - - - sr_Cyrl_CS - Serbia and Montenegro - - - - sr_Cyrl_ME - Montenegro - - - - sr_Cyrl_RS - Serbia - - - - sr_Cyrl_YU - Serbia - - - - sr_Latn - --- - - - - sr_Latn_BA - Bosnia and Herzegovina - - - - sr_Latn_CS - Serbia and Montenegro - - - - sr_Latn_ME - Montenegro - - - - sr_Latn_RS - Serbia - - - - sr_Latn_YU - Serbia - - - - sr_ME - Montenegro - - - - sr_RS - Serbia - - - - sr_YU - Serbia - - - - Swati - ss - --- - - - - ss_SZ - Swaziland - - - - ss_ZA - South Africa - - - - Saho - ssy - --- - - - - ssy_ER - Eritrea - - - - Southern Sotho - st - --- - - - - st_LS - Lesotho - - - - st_ZA - South Africa - - - - Swedish - sv - --- - - - - sv_FI - Finland - - - - sv_SE - Sweden - - - - Swahili - sw - --- - - - - sw_KE - Kenya - - - - sw_TZ - Tanzania - - - - Syriac - syr - --- - - - - syr_SY - Syria - - - - Tamil - ta - --- - - - - ta_IN - India - - - - ta_LK - Sri Lanka - - - - Telugu - te - --- - - - - te_IN - India - - - - Teso - teo - --- - - - - teo_KE - Kenya - - - - teo_UG - Uganda - - - - Tajik - tg - --- - - - - tg_Cyrl - --- - - - - tg_Cyrl_TJ - Tajikistan - - - - tg_TJ - Tajikistan - - - - Thai - th - --- - - - - th_TH - Thailand - - - - Tigrinya - ti - --- - - - - ti_ER - Eritrea - - - - ti_ET - Ethiopia - - - - Tigre - tig - --- - - - - tig_ER - Eritrea - - - - Tagalog - tl - --- - - - - tl_PH - Philippines - - - - Tswana - tn - --- - - - - tn_ZA - South Africa - - - - Tonga - to - --- - - - - to_TO - Tonga - - - - Turkish - tr - --- - - - - tr_TR - Turkey - - - - Taroko - trv - --- - - - - trv_TW - Taiwan - - - - Tsonga - ts - --- - - - - ts_ZA - South Africa - - - - Tatar - tt - --- - - - - tt_RU - Russia - - - - - tzm - --- - - - - tzm_Latn - --- - - - - tzm_Latn_MA - Morocco - - - - tzm_MA - Morocco - - - - Uighur - ug - --- - - - - ug_Arab - --- - - - - ug_Arab_CN - China - - - - ug_CN - China - - - - Ukrainian - uk - --- - - - - uk_UA - Ukraine - - - - Urdu - ur - --- - - - - ur_IN - India - - - - ur_PK - Pakistan - - - - Uzbek - uz - --- - - - - uz_Arab - --- - - - - uz_Arab_AF - Afghanistan - - - - uz_AF - Afghanistan - - - - uz_Cyrl - --- - - - - uz_Cyrl_UZ - Uzbekistan - - - - uz_Latn - --- - - - - uz_Latn_UZ - Uzbekistan - - - - uz_UZ - Uzbekistan - - - - Venda - ve - --- - - - - ve_ZA - South Africa - - - - Vietnamese - vi - --- - - - - vi_VN - Vietnam - - - - Vunjo - vun - --- - - - - vun_TZ - Tanzania - - - - Walamo - wal - --- - - - - wal_ET - Ethiopia - - - - Wolof - wo - --- - - - - wo_Latn - --- - - - - wo_Latn_SN - Senegal - - - - wo_SN - Senegal - - - - Xhosa - xh - --- - - - - xh_ZA - South Africa - - - - Soga - xog - --- - - - - xog_UG - Uganda - - - - Yoruba - yo - --- - - - - yo_NG - Nigeria - - - - Chinese - zh - --- - - - - zh_CN - China - - - - zh_Hans - --- - - - - zh_Hans_CN - China - - - - zh_Hans_HK - Hong Kong - - - - zh_Hans_MO - Macau - - - - zh_Hans_SG - Singapore - - - - zh_Hant - --- - - - - zh_Hant_HK - Hong Kong - - - - zh_Hant_MO - Macau - - - - zh_Hant_TW - Taiwan - - - - zh_HK - Hong Kong - - - - zh_MO - Macau - - - - zh_SG - Singapore - - - - zh_TW - Taiwan - - - - Zulu - zu - --- - - - - zu_ZA - South Africa - - - -
-
diff --git a/documentation/manual/en/module_specs/Zend_Locale-DatesTimes.xml b/documentation/manual/en/module_specs/Zend_Locale-DatesTimes.xml deleted file mode 100644 index 3616566ab32..00000000000 --- a/documentation/manual/en/module_specs/Zend_Locale-DatesTimes.xml +++ /dev/null @@ -1,481 +0,0 @@ - -
Working with Dates and Times - - - - Zend_Locale_Format provides several methods for working with dates - and times to help convert and normalize between different formats for different locales. Use - Zend_Date for manipulating dates, and working with date strings that - already conform to one of the many internationally - recognized standard formats, or one of the localized date formats supported by - Zend_Date. Using an existing, pre-defined format offers - advantages, including the use of well-tested code, and the assurance of some degree of - portability and interoperability (depending on the standard used). The examples below do not - follow these recommendations, since using non-standard date formats would needlessly - increase the difficulty of understanding these examples. - - -
Normalizing Dates and Times - - - - The getDate() method parses strings containing dates in - localized formats. The results are returned in a structured array, with well-defined - keys for each part of the date. In addition, the array will contain a key 'date_format' - showing the format string used to parse the input date string. Since a localized date - string may not contain all parts of a date/time, the key-value pairs are optional. for - example, if only the year, month, and day is given, then all time values are suppressed - from the returned array, and vice-versa if only hour, minute, and second were given as - input. If no date or time can be found within the given input, an exception will be - thrown. - - - - If setOption(array('fix_date' => true)) is set the - getDate() method adds a key 'fixed' with a whole number value - indicating if the input date string required "fixing" by rearranging the day, month, or - year in the input to fit the format used. - - - Key values for getDate() with option 'fix_date' - - - - - - value - meaning - - - - - - 0 - nothing to fix - - - - 1 - fixed false month - - - - 2 - swapped day and year - - - - 3 - swapped month and year - - - - 4 - swapped month and day - - - -
- - - For those needing to specify explicitly the format of the date string, the following - format token specifiers are supported. If an invalid format specifier is used, such as - the PHP 'i' specifier when in ISO format mode, - then an error will be thrown by the methods in Zend_Locale_Format - that support user-defined formats. - - - - These specifiers (below) are a small subset of the full "ISO" set supported by - Zend_Date's toString(). If you need to - use PHP date() compatible format specifiers, - then first call setOptions(array('format_type' => 'php')). And - if you want to convert only one special format string from PHP - date() compatible format to "ISO" format use - convertPhpToIsoFormat(). Currently, the only practical - difference relates to the specifier for minutes ('m' using the ISO - default, and 'i' using the PHP date format). - - - Return values - - - - - - getDate() format character - Array key - Returned value - Minimum - Maximum - - - - - - d - day - integer - 1 - 31 - - - - M - month - integer - 1 - 12 - - - - y - year - integer - no limit - PHP integer's maximum - - - - h - hour - integer - 0 - PHP integer's maximum - - - - m - minute - integer - 0 - PHP integer's maximum - - - - s - second - integer - 0 - PHP integer's maximum - - - -
- - Normalizing a date - - - - 'dd.MM.yyyy') - ); - -// creates a Zend_Date object for this date -$dateObject = Zend_Date('13.04.2006', - array('date_format' => 'dd.MM.yyyy')); - -print_r($dateString); // outputs: - -Array -( - [format] => dd.MM.yyyy - [day] => 13 - [month] => 4 - [year] => 2006 -) - -// alternatively, some types of problems with input data can be -// automatically corrected -$date = Zend_Locale_Format::getDate('04.13.2006', - array('date_format' => 'dd.MM.yyyy', - 'fix_date' => true) - ); - -print_r($date); // outputs: - -Array -( - [format] => dd.MM.yyyy - [day] => 13 - [month] => 4 - [year] => 2006 - [fixed] => 4 -) -]]> - - - - Since getDate() is "locale-aware", specifying the - $locale is sufficient for date strings adhering to that locale's - format. The option 'fix_date' uses simple tests to determine if the - day or month is not valid, and then applies heuristics to try and correct any detected - problems. Note the use of 'Zend_Locale_Format::STANDARD' as the - value for 'date_format' to prevent the use of a class-wide default - date format set using setOptions(). This forces getDate to use - the default date format for $locale. - - - Normalizing a date by locale - - - - Zend_Locale_Format::STANDARD, - 'locale' => $locale) - ); - -print_r ($date); -]]> - - - - A complete date and time is returned when the input contains both a date and time in the - expected format. - - - Normalizing a date with time - - - - Zend_Locale_Format::STANDARD, - 'locale' => $locale) - ); - -print_r ($date); -]]> - - - - If a specific format is desired, specify the $format argument, - without giving a $locale. Only single-letter codes - (H, m, s, y, M, d), and MMMM and EEEE are supported in the $format. - - - Normalizing a userdefined date - - - - 'ddyyyyMM ssmmHH') - ); - -print_r ($date); -]]> - - - - The format can include the following signs : - - - Format definition - - - - - - Format Letter - Description - - - - - - d or dd - 1 or 2 digit day - - - - M or MM - 1 or 2 digit month - - - - y or yy - 1 or 2 digit year - - - - yyyy - 4 digit year - - - - h - 1 or 2 digit hour - - - - m - 1 or 2 digit minute - - - - s - 1 or 2 digit second - - - -
- - - Examples for proper formats are - - - Example formats - - - - - - Formats - Input - Output - - - - - - dd.MM.yy - 1.4.6 - ['day'] => 1, ['month'] => 4, ['year'] => 6 - - - - dd.MM.yy - 01.04.2006 - ['day'] => 1, ['month'] => 4, ['year'] => 2006 - - - - yyyyMMdd - 1.4.6 - ['day'] => 6, ['month'] => 4, ['year'] => 1 - - - -
- - Database date format - - - - To parse a database date value (f.e. MySql or MsSql), use - Zend_Date's ISO_8601 format instead of getDate(). - - - - - The option 'fix_date' uses simple tests to determine if the day or - month is not valid, and then applies heuristics to try and correct any detected - problems. getDate() automatically detects and corrects some - kinds of problems with input, such as misplacing the year: - - - Automatic correction of input dates - - - 'ddMMyy', - 'fix_date' => true) - ); - -// instead of 41 for the day, the 41 will be returned as year value -print_r ($date); -]]> - -
- -
Testing Dates - - - - Use checkDateFormat($inputString, array('date_format' => $format, - $locale)) to check if a given string contains all expected date parts. - The checkDateFormat() method uses - getDate(), but without the option - 'fixdate' to avoid returning TRUE when the - input fails to conform to the date format. If errors are detected in the input, such as - swapped values for months and days, the option 'fixdate' method - will apply heuristics to "correct" dates before determining their validity. - - - Date testing - - - - Zend_Locale_Format::STANDARD, - $locale) - ) { - print "date"; -} else { - print "not a date"; -} -]]> - -
- -
Normalizing a Time - - - - Normally, a time will be returned with a date, if the input contains both. If the proper - format is not known, but the locale relevant to the user input is known, then - getTime() should be used, because it uses the default time - format for the selected locale. - - - Normalize an unknown time - - - - Zend_Locale_Format::STANDARD, - 'locale' => $locale)) { - print "time"; -} else { - print "not a time"; -} -]]> - -
- -
Testing Times - - - - Use checkDateFormat() to check if a given string contains a - proper time. The usage is exact the same as with checking Dates, only - date_format should contain the parts which you expect to have. - - - Testing a time - - - 'HH:mm:ss', - 'locale' => $locale)) { - print "time"; -} else { - print "not a time"; -} -]]> - -
-
diff --git a/documentation/manual/en/module_specs/Zend_Locale-Functions.xml b/documentation/manual/en/module_specs/Zend_Locale-Functions.xml deleted file mode 100644 index 2af0a9f583a..00000000000 --- a/documentation/manual/en/module_specs/Zend_Locale-Functions.xml +++ /dev/null @@ -1,1986 +0,0 @@ - -
Using Zend_Locale - - - - Zend_Locale also provides localized information about locales for - each locale, including localized names for other locales, days of the week, month names, - etc. - - -
Copying, Cloning, and Serializing Locale Objects - - - - Use object cloning to - duplicate a locale object exactly and efficiently. Most locale-aware methods also accept - string representations of locales, such as the result of - $locale->toString(). - - - clone - - - serialize(); -// re-create the original object -$localeObject = unserialize($serializedLocale); - -// Obtain a string identification of the locale -$stringLocale = $locale->toString(); - -// Make a cloned copy of the $local object -$copiedLocale = clone $locale; - -print "copied: ", $copiedLocale->toString(); - -// PHP automatically calls toString() via __toString() -print "copied: ", $copiedLocale; -]]> - -
- -
Equality - - - - Zend_Locale also provides a convenience function to compare two - locales. All locale-aware classes should provide a similar equality check. - - - Check for equal locales - - - equals($mylocale)) { - print "Locales are equal"; -} -]]> - -
- -
Default locales - - - - The method getFallback() returns an array of relevant locales - using information from the user's web browser (if available), information from the - environment of the host server, and Zend Framework settings. As with the constructor - for Zend_Locale, the first parameter selects a preference of - which information to consider (BROWSER, - ENVIRONMENT, or FRAMEWORK) first. - The second parameter toggles between returning all matching locales or only the - first or best match. Locale-aware components normally use only the first locale. A - quality rating is included, when available. - - - Get default locales - - - getFallback(); -print_r($found); - -// Return only browser locales -$found2 = $locale->getFallback(Zend_Locale::BROWSER,TRUE); -print_r($found2); -]]> - - - - To obtain only the default locales relevant to the BROWSER, - ENVIRONMENT, or FRAMEWORK, use - the corresponding method: - - - - - getEnvironment() - - - - - - getBrowser() - - - - - - getLocale() - - - - -
- -
Set a new locale - - - - A new locale can be set with the function setLocale(). This - function takes a locale string as parameter. If no locale is given, a locale is - automatically selected. - - - setLocale - - - toString(); - -// new locale -$locale->setLocale('aa_DJ'); -print $locale->toString(); -]]> - -
- -
Getting the language and region - - - - Use getLanguage() to obtain a string containing the two - character language code from the string locale identifier. Use - getRegion() to obtain a string containing the two character - region code from the string locale identifier. - - - getLanguage and getRegion - - - getLanguage(); - -// if locale is 'de_AT' then 'AT' will be returned as region -print $locale->getRegion(); -]]> - -
- -
Get the locale by giving a territory - - - - When you only have the territory or country then it's also possible to get a locale - from that information. You can manually search if there is a locale for this territory - by using getLocaleToTerritory(). This method returns a - locale for the given territory or NULL when there was has no locale - been found. - - - getLocaleToTerritory - - - - - - Uppercase territories - - - - When you know that you are using a territory, then you should uppercase it. - Otherwise you could get an in your eyes false locale in return when you use other - methods. For example: When you give "om" then - getLocaleToTerritory() returns you "ar_OM" as it knows that - you mean a territory. But all other methods will return "om", as it's also a - language. - - - - So when you know that the given string is a territory, eighter use - getLocaleToTerritory() yourself before creating a locale, - or uppercase the input. - - -
- -
Obtaining localized strings - - - - getTranslationList() gives you access to localized information - of several types. These information are useful if you want to display localized data to - a customer without the need of translating it. They are already available for your - usage. - - - - The requested list of information is always returned as named array. If you want to give - more than one value to a explicit type where you wish to receive values from, you have - to give an array instead of multiple values. - - - getTranslationList - - - value pairs... -// [de] -> Deutsch -// [en] -> Englisch - -// use one of the returned key as value for the getTranslation() method -// of another language -print Zend_Locale::getTranslation('de', 'language', 'zh'); -// returns the translation for the language 'de' in chinese -]]> - - - - You can receive this information for all languages. But not all information is - completely available for all languages. Some of these types are also available through - an own function for simplicity. See this list for detailed information. - - - - Details for getTranslationList($type = null, $locale = null, $value = null) - - - - - - - Type - Description - - - - - - Language - - - Returns a localized list of all languages. The language part of the - locale is returned as key and the translation as value - - - - - Script - - - Returns a localized list of all scripts. The script is returned as key - and the translation as value - - - - - Territory - - - Returns a localized list of all territories. This contains countries, - continents and territories. To get only territories and continents use - '1' as value. To get only countries use '2' as value. The country part - of the locale is used as key where applicable. In the other case the - official ISO code for this territory is used. The - translated territory is returned as value. When you omit the value you - will get a list with both. - - - - - Variant - - - Returns a localized list of known variants of scripts. The variant is - returned as key and the translation as value - - - - - Key - - - Returns a localized list of known keys. This keys are generic values - used in translation. These are normally calendar, collation and - currency. The key is returned as array key and the translation as value - - - - - Type - - - Returns a localized list of known types of keys. These are variants of - types of calendar representations and types of collations. When you use - 'collation' as value you will get all types of collations returned. When - you use 'calendar' as value you will get all types of calendars - returned. When you omit the value you will get a list all both returned. - The type is used as key and the translation as value - - - - - Layout - - - Returns a list of rules which describes how to format special text parts - - - - - Characters - Returns a list of allowed characters within this locale - - - - Delimiters - Returns a list of allowed quoting characters for this locale - - - - Measurement - - - Returns a list of known measurement values. This list is depreciated - - - - - Months - - - Returns a list of all month representations within this locale. There - are several different representations which are all returned as sub - array. If you omit the value you will get a list of all months from the - 'gregorian' calendar returned. You can give any known calendar as value - to get a list of months from this calendar returned. Use Zend_Date for simplicity - - - - - Month - - - Returns a localized list of all month names for this locale. If you omit - the value you will get the normally used gregorian full name of the - months where each month number is used as key and the translated month - is returned as value. You can get the months for different calendars and - formats if you give an array as value. The first array entry has to be - the calendar, the second the used context and the third the width to - return. Use Zend_Date for - simplicity - - - - - Days - - - Returns a list of all day representations within this locale. There are - several different representations which are all returned as sub array. - If you omit the value you will get a list of all days from the - 'gregorian' calendar returned. You can give any known calendar as value - to get a list of days from this calendar returned. Use Zend_Date for simplicity - - - - - Day - - - Returns a localized list of all day names for this locale. If you omit - the value you will get the normally used gregorian full name of the days - where the english day abbreviation is used as key and the translated day - is returned as value. You can get the days for different calendars and - formats if you give an array as value. The first array entry has to be - the calendar, the second the used context and the third the width to - return. Use Zend_Date for - simplicity - - - - - Week - - - Returns a list of values used for proper week calculations within a - locale. Use Zend_Date for - simplicity - - - - - Quarters - - - Returns a list of all quarter representations within this locale. There - are several different representations which are all returned as sub - array. If you omit the value you will get a list of all quarters from - the 'gregorian' calendar returned. You can give any known calendar as - value to get a list of quarters from this calendar returned - - - - - Quarter - - - Returns a localized list of all quarter names for this locale. If you - omit the value you will get the normally used gregorian full name of the - quarters where each quarter number is used as key and the translated - quarter is returned as value. You can get the quarters for different - calendars and formats if you give an array as value. The first array - entry has to be the calendar, the second the used context and the third - the width to return - - - - - Eras - - - Returns a list of all era representations within this locale. If you - omit the value you will get a list of all eras from the 'gregorian' - calendar returned. You can give any known calendar as value to get a - list of eras from this calendar returned - - - - - Era - - - Returns a localized list of all era names for this locale. If you omit - the value you will get the normally used gregorian full name of the eras - where each era number is used as key and the translated era is returned - as value. You can get the eras for different calendars and formats if - you give an array as value. The first array entry has to be the calendar - and the second the width to return - - - - - Date - - - Returns a localized list of all date formats for this locale. The name - of the dateformat is used as key and the format itself as value.If you - omit the value you will get the date formats for the gregorian calendar - returned. You can get the date formats for different calendars if you - give the wished calendar as string. Use Zend_Date for simplicity - - - - - Time - - - Returns a localized list of all time formats for this locale. The name - of the timeformat is used as key and the format itself as value. If you - omit the value you will get the time formats for the gregorian calendar - returned. You can get the time formats for different calendars if you - give the wished calendar as string. Use Zend_Date for simplicity - - - - - DateTime - - - Returns a localized list of all known date-time formats for this locale. - The name of the date-time format is used as key and the format itself as - value. If you omit the value you will get the date-time formats for the - gregorian calendar returned. You can get the date-time formats for - different calendars if you give the wished calendar as string. Use Zend_Date for simplicity - - - - - DateItem - - - Returns a list of default formats for given date or time items - - - - - DateInterval - - - Returns a list of date or time formats which are used when you want to - display intervals. The list is a multidimentional array where the first - dimension is the interval format, and the second dimension is the token - with the greatest difference. - - - - - Field - - - Returns a localized list of date fields which can be used to display - calendars or date strings like 'month' or 'year' in a wished language. - If you omit the value you will get this list for the gregorian calendar - returned. You can get the list for different calendars if you give the - wished calendar as string - - - - - Relative - - - Returns a localized list of relative dates which can be used to display - textual relative dates like 'yesterday' or 'tomorrow' in a wished - language. If you omit the value you will get this list for the gregorian - calendar returned. You can get the list for different calendars if you - give the wished calendar as string - - - - - Symbols - - - Returns a localized list of characters used for number representations - - - - - NameToCurrency - - - Returns a localized list of names for currencies. The currency is used - as key and the translated name as value. Use Zend_Currency for - simplicity - - - - - CurrencyToName - - - Returns a list of currencies for localized names. The translated name is - used as key and the currency as value. Use Zend_Currency for - simplicity - - - - - CurrencySymbol - - - Returns a list of known localized currency symbols for currencies. The - currency is used as key and the symbol as value. Use Zend_Currency for - simplicity - - - - - Question - - - Returns a list of localized strings for acceptance ('yes') and - negation ('no'). Use Zend_Locale's getQuestion - method for simplicity - - - - - CurrencyFraction - - - Returns a list of fractions for currency values. The currency is used as - key and the fraction as integer value. Use Zend_Currency for - simplicity - - - - - CurrencyRounding - - - Returns a list of how to round which currency. The currency is used as - key and the rounding as integer value. Use Zend_Currency for - simplicity - - - - - CurrencyToRegion - - - Returns a list of currencies which are known to be used within a region. - The ISO3166 value ('region') is used as array key - and the ISO4217 value ('currency') as array value. - Use Zend_Currency for - simplicity - - - - - RegionToCurrency - - - Returns a list of regions where a currency is used . The - ISO4217 value ('currency') is used as array key and - the ISO3166 value ('region') as array value. When a - currency is used in several regions these regions are separated with a - whitespace. Use Zend_Currency for - simplicity - - - - - RegionToTerritory - - - Returns a list of territories with the countries or sub territories - which are included within that territory. The ISO - territory code ('territory') is used as array key and the - ISO3166 value ('region') as array value. When a - territory contains several regions these regions are separated with a - whitespace - - - - - TerritoryToRegion - - - Returns a list of regions and the territories where these regions are - located. The ISO3166 code ('region') is used as - array key and the ISO territory code ('territory') as - array value. When a region is located in several territories these - territories are separated with a whitespace - - - - - ScriptToLanguage - - - Returns a list of scripts which are used within a language. The language - code is used as array key and the script code as array value. When a - language contains several scripts these scripts are separated with a - whitespace - - - - - LanguageToScript - - - Returns a list of languages which are using a script. The script code - is used as array key and the language code as array value. When a script - is used in several languages these languages are separated with a - whitespace - - - - - TerritoryToLanguage - - - Returns a list of languages and the countries where they are spoken. The - language is used as array key and the country code as array value. When - a language is used in several countries these countries are separated - with a whitespace - - - - - LanguageToTerritory - - - Returns a list of countries and the languages which are spoken within - them. The country code is used as array key and the language code - as array value. When several languages are spoken within a territory - then these languages are separated with a whitespace - - - - - TimezoneToWindows - - - Returns a list of windows timezones and the related - ISO timezone. The windows timezone is used as array - key and the ISO timezone as array value - - - - - WindowsToTimezone - - - Returns a list of ISO timezones and the related - windows timezone. The ISO timezone is used as array - key and the windows timezone as array value - - - - - TerritoryToTimezone - - - Returns a list of regions or territories and the related - ISO timezone. The ISO timezone is - used as array key and the territory code as array value - - - - - TimezoneToTerritory - - - Returns a list of timezones and the related region or territory code. - The region or territory code is used as array key and the - ISO timezone as array value - - - - - CityToTimezone - - - Returns a localized list of cities which can be used as translation for - a related timezone. Not for all timezones is a translation available, - but for a user is the real city written in his languages more accurate - than the ISO name of this timezone. The - ISO timezone is used as array key and the translated - city as array value - - - - - TimezoneToCity - - - Returns a list of timezones for localized city names. The localized city - is used as array key and the ISO timezone name as - array value - - - - - PhoneToTerritory - - - Returns a list of phone codes which are known to be used within a - territory. The territory (region) is used as array key and the telephone - code as array value - - - - - TerritoryToPhone - - - Returns a list of territories where a phone is used . The phone code - is used as array key and the territory (region) as array value. When a - phone code is used in several territories these territories are - separated with a whitespace - - - - - NumericToTerritory - - - Returns a list of 3 digit number codes for territories. - The territory (region) is used as array key and the 3 digit number code - as array value - - - - - TerritoryToNumeric - - - Returns a list of territories with their 3 digit number code. The 3 - digit number code is used as array key and the territory (region) as - array value - - - - - Alpha3ToTerritory - - - Returns a list of 3 sign character codes for territories. - The territory (region) is used as array key and the 3 sign character - code as array value - - - - - TerritoryToAlpha3 - - - Returns a list of territories with their 3 sign character code. The 3 - sign character code is used as array key and the territory (region) as - array value - - - - - PostalToTerritory - - - Returns a list of territories with a regex for postal codes which are - included within that territory. The ISO territory - code ('territory') is used as array key and the regex as array value. - - - - - NumberingSystem - - - Returns a list of scripts with the notation for digits used within the - script - - - - - FallbackToChar - - - Returns a list of replacement characters for often used unicode - characters. This can be used to replace "Ā©" with "(C)" for example - - - - - CharToFallback - - - Returns a list of unicode characters for often used replacement - characters. This can be used to replace "(C)" with "Ā©" for example - - - - - LocaleUpgrade - - - Returns a list of locale dependencies which can be used to upgrade a - language to a full qualified locale - - - - - Unit - - - Returns a list of localized calendar units. This can be used to - translate the strings "day", "month" and so on automatically - - - - -
- - - If you are in need of a single translated value, you can use the - getTranslation() method. It always returns a string but it - accepts some different types than the getTranslationList() - method. Also value is the same as before with one difference. You have to give the - detail you want to get returned as additional value. - - - - - Because you have almost always give a value as detail this parameter has to be given - as first parameter. This differs from the - getTranslationList() method. - - - - - See the following table for detailed information: - - - Details for getTranslation($value = null, $type = null, $locale = null) - - - - - - Type - Description - - - - - - Language - - - Returns a translation for a language. To select the wished translation - you must give the language code as value - - - - - Script - - - Returns a translation for a script. To select the wished translation you - must give the script code as value - - - - - - Territory or Country - - - - Returns a translation for a territory. This can be countries, continents - and territories. To select the wished variant you must give the - territory code as value - - - - - Variant - - - Returns a translation for a script variant. To select the wished variant - you must give the variant code as value - - - - - Key - - - Returns translation for a known keys. This keys are generic values used - in translation. These are normally calendar, collation and currency. To - select the wished key you must give the key code as value - - - - - DefaultCalendar - - - Returns the default calendar for the given locale. For most locales this - will be 'gregorian'. Use Zend_Date for simplicity - - - - - MonthContext - - - Returns the default context for months which is used within the given - calendar. If you omit the value the 'gregorian' calendar will be used. - Use Zend_Date for - simplicity - - - - - DefaultMonth - - - Returns the default format for months which is used within the given - calendar. If you omit the value the 'gregorian' calendar will be used. - Use Zend_Date for - simplicity - - - - - Month - - - Returns a translation for a month. You have to give the number of the - month as integer value. It has to be between 1 and 12. If you want to - receive data for other calendars, contexts or formats, then you must - give an array instead of an integer with the expected values. The array - has to look like this: array( 'calendar', 'context', 'format', - 'month number'). If you give only an integer then the - default values are the 'gregorian' calendar, the context 'format' and - the format 'wide'. Use Zend_Date for simplicity - - - - - DayContext - - - Returns the default context for Ā“days which is used within the given - calendar. If you omit the value the 'gregorian' calendar will be used. - Use Zend_Date for - simplicity - - - - - DefaultDay - - - Returns the default format for days which is used within the given - calendar. If you omit the value the 'gregorian' calendar will be used. - Use Zend_Date for - simplicity - - - - - Day - - - Returns a translation for a day. You have to give the english - abbreviation of the day as string value ('sun', 'mon', etc.). If you - want to receive data for other calendars, contexts or format, then you - must give an array instead of an integer with the expected values. The - array has to look like this: array('calendar', 'context', - 'format', 'day abbreviation'). If you give only an - string then the default values are the 'gregorian' calendar, the context - 'format' and the format 'wide'. Use Zend_Date for simplicity - - - - - Quarter - - - Returns a translation for a quarter. You have to give the number of the - quarter as integer and it has to be between 1 and 4. If you want to - receive data for other calendars, contexts or formats, then you must - give an array instead of an integer with the expected values. The array - has to look like this: array('calendar', 'context', - 'format', 'quarter number'). If you give only an - string then the default values are the 'gregorian' calendar, - the context 'format' and the format 'wide' - - - - - Am - - - Returns translation for 'AM' in the expected locale. If you want to - receive data for other calendars provide a string with the expected - calendar. If you omit the value then the 'gregorian' calendar will be - used. Use Zend_Date for simplicity - - - - - Pm - - - Returns translation for 'PM' in the expected locale. If you want to - receive data for other calendars provide a string with the expected - calendar. If you omit the value then the 'gregorian' calendar will be - used. Use Zend_Date for - simplicity - - - - - Era - - - Returns a translation for an era within a locale. You have to give the - era number as string or integer. If you want to receive data for other - calendars or formats, then you must give an array instead of the era - number with the expected values. The array has to look like this: - array('calendar', 'format', 'era number'). If - you give only a string then the default values are the 'gregorian' - calendar and the 'abbr' format - - - - - DefaultDate - - - Returns the default date format which is used within the given - calendar. If you omit the value the 'gregorian' calendar will be used. - Use Zend_Date for - simplicity - - - - - Date - - - Returns the date format for a given calendar or format within a locale. - If you omit the value then the 'gregorian' calendar will be used with - the 'medium' format. If you give a string then the 'gregorian' calendar - will be used with the given format. Or you can also give an array which - will have to look like this: array('calendar', - 'format'). Use Zend_Date for simplicity - - - - - DefaultTime - - - Returns the default time format which is used within the given calendar. - If you omit the value the 'gregorian' calendar will be used. Use - Zend_Date for simplicity - - - - - Time - - - Returns the time format for a given calendar or format within a locale. - If you omit the value then the 'gregorian' calendar will be used with - the 'medium' format. If you give a string then the 'gregorian' calendar - will be used with the given format. Or you can also give an array which - will have to look like this: - array('calendar', 'format'). Use Zend_Date for simplicity - - - - - DateTime - - - Returns the datetime format for the given locale which indicates how to - display date with times in the same string within the given calendar. If - you omit the value the 'gregorian' calendar will be used. Use - Zend_Date for simplicity - - - - - DateItem - Returns the default format for a given date or time item - - - - DateInterval - - - Returns the interval format for a given date or time format. The first - value is the calendar format, normally 'gregorian'. The second value is - the interval format and the third value the token with the greatest - difference. For example: array('gregorian', 'yMMMM', 'y') returns the - interval format for the date format 'yMMMM' where 'y' has the greatest - difference. - - - - - Field - - - Returns a translated date field which can be used to display calendars - or date strings like 'month' or 'year' in a wished language. You must - give the field which has to be returned as string. In this case the - 'gregorian' calendar will be used. You can get the field for other - calendar formats if you give an array which has to look like this: - array('calendar', 'date field') - - - - - Relative - - - Returns a translated date which is relative to today which can include - date strings like 'yesterday' or 'tomorrow' in a wished language. You - have to give the number of days relative to tomorrow to receive the - expected string. Yesterday would be '-1', tomorrow '1' and so on. This - will use the 'gregorian' calendar. if you want to get relative dates for - other calendars you will have to give an array which has to look like - this: array('calendar', 'relative days'). Use - Zend_Date for simplicity - - - - - DecimalNumber - - - Returns the format for decimal numbers within a given locale. Use Zend_Locale_Format for - simplicity - - - - - ScientificNumber - - - Returns the format for scientific numbers within a given locale - - - - - PercentNumber - - - Returns the format for percentage numbers within a given locale - - - - - CurrencyNumber - - - Returns the format for displaying currency numbers within a given - locale. Use Zend_Currency for - simplicity - - - - - NameToCurrency - - - Returns the translated name for a given currency. The currency has to be - given in ISO format which is for example 'EUR' for - the currency 'euro'. Use Zend_Currency for - simplicity - - - - - CurrencyToName - - - Returns a currency for a given localized name. Use Zend_Currency for - simplicity - - - - - CurrencySymbol - - - Returns the used symbol for a currency within a given locale. Not for - all currencies exists a symbol. Use - Zend_Currency for - simplicity - - - - - Question - - - Returns a localized string for acceptance ('yes') and negation ('no'). - You have to give either 'yes' or 'no' as value to receive the expected - string. Use Zend_Locale's - getQuestion method for simplicity - - - - - CurrencyFraction - - - Returns the fraction to use for a given currency. You must give the - currency as ISO value. Use Zend_Currency - for simplicity - - - - - CurrencyRounding - - - Returns how to round a given currency. You must give the currency as - ISO value. If you omit the currency then the - 'DEFAULT' rounding will be returned. Use Zend_Currency - for simplicity - - - - - CurrencyToRegion - - - Returns the currency for a given region. The region code has to be given - as ISO3166 string for example 'AT' for austria. Use - Zend_Currency for - simplicity - - - - - RegionToCurrency - - - Returns the regions where a currency is used. The currency has to be - given as ISO4217 code for example 'EUR' for euro. - When a currency is used in multiple regions, these regions are separated - with a whitespace character. Use Zend_Currency for - simplicity - - - - - RegionToTerritory - - - Returns the regions for a given territory. The territory has to be given - as ISO4217 string for example '001' for world. The - regions within this territory are separated with a whitespace character - - - - - TerritoryToRegion - - - Returns the territories where a given region is located. The region has - to be given in ISO3166 string for example 'AT' for - austria. When a region is located in multiple territories then these - territories are separated with a whitespace character - - - - - ScriptToLanguage - - - Returns the scripts which are used within a given language. The language - has to be given as ISO language code for example 'en' - for english. When multiple scripts are used within a language then these - scripts are separated with a whitespace character - - - - - LanguageToScript - - - Returns the languages which are used within a given script. The script - has to be given as ISO script code for example 'Latn' - for latin. When a script is used in multiple languages then these - languages are separated with a whitespace character - - - - - TerritoryToLanguage - - - Returns the territory where a given language is used. The language has - to be given as ISO language code for example 'en' for - english. When the given language is spoken within multiple territories - then these territories are separated with a whitespace character - - - - - LanguageToTerritory - - - Returns the language which is spoken within a given territory. The - territory has to be given as ISO3166 code for - example 'IT' for italia. When multiple languages are spoken within the - given territory then these languages are separated with a whitespace - character - - - - - TimezoneToWindows - - - Returns a ISO timezone for a given windows timezone - - - - - WindowsToTimezone - - - Returns a windows timezone for a given ISO timezone - - - - - TerritoryToTimezone - - - Returns the territory for a given ISO timezone - - - - - TimezoneToTerritory - - - Returns the ISO timezone for a given territory - - - - - CityToTimezone - - - Returns the localized city for a given ISO timezone. - Not for all timezones does a city translation exist - - - - - TimezoneToCity - - - Returns the ISO timezone for a given localized city - name. Not for all cities does a timezone exist - - - - - PhoneToTerritory - - - Returns the telephone code for a given territory (region). The territory - code has to be given as ISO3166 string for example - 'AT' for austria - - - - - TerritoryToPhone - - - Returns the territory (region) where a telephone code is used. The - telephone code has to be given as plain integer code for example '43' - for +43. When a telephone code is used in multiple territories - (regions), these territories are separated with a whitespace character - - - - - NumericToTerritory - - - Returns the 3 digit number code for a given territory (region). The - territory code has to be given as ISO3166 string - for example 'AT' for austria - - - - - TerritoryToNumeric - - - Returns the territory (region) for a 3 digit number code. The 3 digit - number code has to be given as plain integer code for example '43' - - - - - Alpha3ToTerritory - - - Returns the 3 sign character code for a given territory (region). The - territory code has to be given as ISO3166 string - for example 'AT' for austria - - - - - TerritoryToAlpha3 - Returns the territory (region) for a 3 sign character code - - - - PostalToTerritory - - - Returns the a regex for postal codes for a given territory. The - territory has to be given as ISO4217 string for - example '001' for world - - - - - NumberingSystem - - - Returns a scripts with the notation for digits used within this script - - - - - FallbackToChar - - - Returns a replacement character for a often used unicode character. - This can be used to replace "Ā©" with "(C)" for example - - - - - CharToFallback - - - Returns a unicode character for a often used replacement character. - This can be used to replace "(C)" with "Ā©" for example - - - - - LocaleUpgrade - - - Returns a locale dependencies for a given language which can be used to - upgrade this language to a full qualified locale - - - - - Unit - - - Returns a localized calendar unit. This can be used to translate - the strings "day", "month" and so on automatically. The first parameter - has to be the type, and the second parameter has to be the count - - - - -
- - - - With Zend Framework 1.5 several old types have been renamed. This has to be done - because of several new types, some misspelling and to increase the usability. See - this table for a list of old to new types: - - - - Differences between Zend Framework 1.0 and 1.5 - - - - - - Old type - New type - - - - - - Country - Territory (with value '2') - - - - Calendar - Type (with value 'calendar') - - - - Month_Short - Month (with array('gregorian', 'format', 'abbreviated') - - - - Month_Narrow - Month (with array('gregorian', 'stand-alone', 'narrow') - - - - Month_Complete - Months - - - - Day_Short - Day (with array('gregorian', 'format', 'abbreviated') - - - - Day_Narrow - Day (with array('gregorian', 'stand-alone', 'narrow') - - - - DateFormat - Date - - - - TimeFormat - Time - - - - Timezones - CityToTimezone - - - - Currency - NameToCurrency - - - - Currency_Sign - CurrencySymbol - - - - Currency_Detail - CurrencyToRegion - - - - Territory_Detail - TerritoryToRegion - - - - Language_Detail - LanguageToTerritory - - - -
- - - The example below demonstrates how to obtain the names of things in different languages. - - - getTranslationList - - - - - - - The next example shows how to find the name of a language in another language, when the - two letter iso country code is not known. - - - Converting country name in one language to another - - - - - - - To generate a list of all languages known by Zend_Locale, with - each language name shown in its own language, try the example below in a web page. - Similarly, getTranslationList() and - getTranslation() could be used to create a table mapping - your native language names for regions to the names of the regions shown in another - language. Use a try .. catch block to handle exceptions that occur - when using a locale that does not exist. Not all languages are also locales. In the - example, below exceptions are ignored to prevent early termination. - - - All Languages written in their native language - - - $content) { - try { - $output = Zend_Locale::getTranslation($language, 'language', $language); - if (is_string($output)) { - print "\n
[".$language."] ".$output; - } - } catch (Exception $e) { - continue; - } -} -]]>
-
-
- -
Obtaining translations for "yes" and "no" - - - - Frequently, programs need to solicit a "yes" or "no" response from the user. Use - getQuestion() to obtain an array containing the correct word(s) - or regex strings to use for prompting the user in a particular $locale (defaults to the - current object's locale). The returned array will contain the following information : - - - - - - yes and no: A generic string representation for yes and no - responses. This will contain the first and most generic response from yesarray - and noarray. - - - - yesarray and noarray: An array with all known yes and - no responses. Several languages have more than just two responses. In general - this is the full string and its abbreviation. - - - - yesexpr and noexpr: A generated regex which allows you - to handle user response, and search for yes or no. - - - - - - All of this information are of course localized and depend on the set locale. See the - following example for the information you can receive: - - - getQuestion() - - - getQuestion('de')); - -- - - Output - - - - -Array -( - [yes] => ja - [no] => nein - [yesarray] => Array - ( - [0] => ja - [1] => j - ) - - [noarray] => Array - ( - [0] => nein - [1] => n - ) - - [yesexpr] => ^([jJ][aA]?)|([jJ]?) - [noexpr] => ^([nN]([eE][iI][nN])?)|([nN]?) -) -]]> - - - - - Until 1.0.3 yesabbr from the underlaying locale data was also - available. Since 1.5 this information is no longer standalone available, but you - will find the information from it within yesarray. - - -
- -
Get a list of all known locales - - - - Sometimes you will want to get a list of all known locales. This can be used for several - tasks like the creation of a selectbox. For this purpose you can use the static - getLocaleList() method which will return a list of all known - locales. - - - getLocaleList() - - - - - - - - Note that the locales are returned as key of the array you will receive. The value - is always a boolean TRUE. - - -
- -
Detecting locales - - - - When you want to detect if a given input, regardless of its source, is a locale you - should use the static isLocale() method. The first parameter of - this method is the string which you want to check. - - - Simple locale detection - - - - - - - As you can see, the output of this method is always a boolean. There is only one reason - you could get an exception when calling this method. When your system does not provide - any locale and Zend Framework is not able to detect it automatically. Normally this - shows that there is a problem with your OS in combination with PHP's - setlocale(). - - - - You should also note that any given locale string will automatically be degraded if the - region part does not exist for this locale. In our previous example the language - 'to' does not exist in the region 'RU, but - you will still get TRUE returned as - Zend_Locale can work with the given input. - - - - Still it's sometimes useful to prevent this automatic degrading, and this is where the - second parameter of isLocale() comes in place. The - strict parameter defaults to FALSE and can be - used to prevent degrading when set to TRUE. - - - Strict locale detection - - - - - - - Now that you are able to detect if a given string is a locale you could add locale aware - behaviour to your own classes. But you will soon detect that this always leads to - the same 15 lines of code. Something like the following example: - - - Implement locale aware behaviour - - - toString(); -} -]]> - - - - With Zend Framework 1.8 we added a static findLocale() method - which returns a locale string which you can work with. It processes the following - tasks: - - - - - - Detects if a given string is a locale - - - - - - Degrades the locale if it does not exist in the given region - - - - - - Upgrades the locale when it is detected as region without language - - - - - - Returns a previous set application wide locale if no input is given - - - - - - Detects the locale from browser when the previous detections failed - - - - - - Detects the locale from environment when the previous detections failed - - - - - - Detects the locale from framework when the previous detections failed - - - - - - Returns always a string which represents the found locale. - - - - - - The following example shows how these checks and the above code can be simplified with - one single call: - - - Locale aware behaviour as with Zend Framework 1.8 - - - - -
-
diff --git a/documentation/manual/en/module_specs/Zend_Locale-Introduction.xml b/documentation/manual/en/module_specs/Zend_Locale-Introduction.xml deleted file mode 100644 index 36c84465645..00000000000 --- a/documentation/manual/en/module_specs/Zend_Locale-Introduction.xml +++ /dev/null @@ -1,574 +0,0 @@ - -
Introduction - - - - Zend_Locale is the Frameworks answer to the question, "How can the - same application be used around the whole world?" Most people will say, "That's easy. Let's - translate all our output to several languages." However, using simple translation tables to - map phrases from one language to another is not sufficient. Different regions will have - different conventions for first names, surnames, salutory titles, formatting of numbers, - dates, times, currencies, etc. - - - - We need Localization - and complementary Internationalization. Both are often abbreviated to - L10n and I18n. Internationalization - refers more to support for use of systems, regardless of special needs unique to groups of - users related by language, region, number format conventions, financial conventions, time - and date conventions, etc. Localization involves adding explicit support to systems for - special needs of these unique groups, such as language translation, and support for local - customs or conventions for communicating plurals, dates, times, currencies, names, symbols, - sorting and ordering, etc. L10n and I18n - compliment each other. Zend Framework provides support for these through a combination of - components, including Zend_Locale, Zend_Date, - Zend_Measure, Zend_Translator, - Zend_Currency, and Zend_TimeSync. - - - Zend_Locale and setLocale() - - - - PHP's documentation states that - setlocale() is not threadsave because it is maintained per - process and not per thread. This means that, in multithreaded environments, you can have - the problem that the locale changes while the script never has changed the locale - itself. This can lead to unexpected behaviour when you use - setlocale() in your scripts. - - - - When you are using Zend_Locale you will not have this - limitations, because Zend_Locale is not related to or coupled - with PHP's setlocale(). - - - -
What is Localization - - - - Localization means that an application (or homepage) can be used from different users - which speak different languages. But as you already have expected Localization means - more than only translating strings. It includes - - - - - - Zend_Locale - Backend support of locales available for - localization support within other Zend Framework components. - - - - - - Zend_Translator - Translating of strings. - - - - - - Zend_Date - Localization of dates, times. - - - - - - Zend_Calendar - Localization of calendars (support for - non-Gregorian calendar systems) - - - - - - Zend_Currency - Localization of currencies. - - - - - - Zend_Locale_Format - Parsing and generating localized - numbers. - - - - - - Zend_Locale_Data - Retrieve localized standard strings - as country names, language names and more from the - CLDR. - - - -
- -
What is a Locale? - - - - Each computer user makes use of Locales, even when they don't know it. Applications - lacking localization support, normally have implicit support for one particular locale - (the locale of the author). When a class or function makes use of localization, we say - it is locale-aware. How does the code know which localization the - user is expecting? - - - - A locale string or object identifying a supported locale gives - Zend_Locale and its subclasses access to information about the - language and region expected by the user. Correct formatting, normalization, and - conversions are made based on this information. - -
- -
How are Locales Represented? - - - - Locale identifiers consist of information about the user's language and - preferred/primary geographic region (e.g. state or province of home or workplace). The - locale identifier strings used in Zend Framework are internationally defined standard - abbreviations of language and region, written as language_REGION. - Both the language and region parts are abbreviated to alphabetic, - ASCII characters. - - - - - Be aware that there exist not only locales with 2 characters as most people think. - Also there are languages and regions which are not only abbreviated with 2 - characters. Therefor you should NOT strip the region and language yourself, but use - Zend_Locale when you want to strip language or region from a - locale string. Otherwise you could have unexpected behaviour within your code when - you do this yourself. - - - - - A user from USA would expect the language English and the region - USA, yielding the locale identifier "en_US". A user in Germany - would expect the language German and the region Germany, - yielding the locale identifier "de_DE". See the list - of pre-defined locale and region combinations, if you need to select a - specific locale within Zend Framework. - - - Choosing a specific locale - - - - - - - A German user in America might expect the language German and the region - USA, but these non-standard mixes are not supported directly as - recognized "locales". Instead, if an invalid combination is used, then it will - automatically be truncated by dropping the region code. For example, "de_IS" would be - truncated to "de", and "xh_RU" would be truncated to "xh", because neither of these - combinations are valid. Additionally, if the base language code is not supported (e.g. - "zz_US") or does not exist, then a default "root" locale will be used. The "root" locale - has default definitions for internationally recognized representations of dates, times, - numbers, currencies, etc. The truncation process depends on the requested information, - since some combinations of language and region might be valid for one type of data (e.g. - dates), but not for another (e.g. currency format). - - - - Beware of historical changes, as Zend Framework components do not know about or attempt - to track the numerous timezone changes made over many years by many regions. For - example, we can see a historical - list showing dozens of changes made by governments to when and if a - particular region observes Daylight Savings Time, and even which timezone a particular - geographic area belongs. Thus, when performing date math, the math performed by Zend - Framework components will not adjust for these changes, but instead will give the - correct time for the timezone using current, modern rules for DST and - timezone assignment for geographic regions. - -
- -
Selecting the Right Locale - - - - For most situations, new Zend_Locale() will automatically select the - correct locale, with preference given to information provided by the user's web browser. - However, if new Zend_Locale(Zend_Locale::ENVIRONMENT) is used, then - preference will be given to using the host server's environment configuration, as - described below. - - - Automatically selecting a locale - - - - - - - The search algorithm used by Zend_Locale for automatic selection - of a locale uses three sources of information: - - - - - const Zend_Locale::BROWSER - The user's Web browser - provides information with each request, which is published by - PHP in the global variable - $_SERVER['HTTP_ACCEPT_LANGUAGE']. if no matching locale - can be found, then preference is given to ENVIRONMENT - and lastly FRAMEWORK. - - - - - - const Zend_Locale::ENVIRONMENT - PHP - publishes the host server's locale via the PHP internal - function setlocale(). If no matching locale can be - found, then preference is given to FRAMEWORK and lastly - BROWSER. - - - - - - const Zend_Locale::FRAMEWORK - When Zend Framework has - a standardized way of specifying component defaults (planned, but not yet - available), then using this constant during instantiation will give - preference to choosing a locale based on these defaults. If no matching - locale can be found, then preference is given to - ENVIRONMENT and lastly BROWSER. - - - - -
- -
Usage of automatic Locales - - - - Zend_Locale provides three additional locales. These locales do - not belong to any language or region. They are "automatic" locales which means that they - have the same effect as the method getFallback() but without the - negative effects like creating an instance. These "automatic" locales can be used - anywhere, where also a standard locale and also the definition of a locale, its string - representation, can be used. This offers simplicity for situations like working with - locales which are provided by a browser. - - - - There are three locales which have a slightly different behaviour: - - - - - 'browser' - Zend_Locale should - work with the information which is provided by the user's Web browser. It - is published by PHP in the global variable - $_SERVER['HTTP_ACCEPT_LANGUAGE']. - - - - If a user provides more than one locale within his browser, - Zend_Locale will use the first found locale. If the - user does not provide a locale or the script is being called from the - command line the automatic locale 'environment' will - automatically be used and returned. - - - - - - 'environment' - Zend_Locale - should work with the information which is provided by the host server. It - is published by PHP via the internal function - setlocale(). - - - - If a environment provides more than one locale, - Zend_Locale will use the first found locale. If the - host does not provide a locale the automatic locale - 'browser' will automatically be used and returned. - - - - - - 'auto' - Zend_Locale should - automatically detect any locale which can be worked with. It will first - search for a users locale and then, if not successful, search for the host - locale. - - - - If no locale can be detected, it will throw an exception and tell you that - the automatic detection has been failed. - - - - - - Using automatic locales - - - - -
- -
Using a default Locale - - - - In some environments it is not possible to detect a locale automatically. You can expect - this behaviour when you get an request from command line or the requesting browser has - no language tag set and additionally your server has the default locale 'C' set or - another proprietary locale. - - - - In such cases Zend_Locale will normally throw an exception with a - message that the automatic detection of any locale was not successful. You have two - options to handle such a situation. Either through setting a new locale per hand, or - defining a default locale. - - - Handling locale exceptions - - - - - - - But this has one big negative effect. You will have to set your locale object within - every class using Zend_Locale. This could become very unhandy if - you are using multiple classes. - - - - Since Zend Framework Release 1.5 there is a much better way to handle this. You can set - a default locale which the static setFallback() method. Of - course, every unknown or not fully qualified locale will also throw an exception. - setFallback() should be the first call before you initiate any - class using Zend_Locale. See the following example for details: - - - Setting a default locale - - - - - - - In the case that no locale can be detected, automatically the locale - de will be used. Otherwise, the detected locale will be used. - -
- -
ZF Locale-Aware Classes - - - - In the Zend Framework, locale-aware classes rely on Zend_Locale - to automatically select a locale, as explained above. For example, in a Zend Framework - web application, constructing a date using Zend_Date without - specifying a locale results in an object with a locale based on information provided by - the current user's web browser. - - - Dates default to correct locale of web users - - - - - - - To override this default behavior, and force locale-aware Zend Framework components to - use specific locales, regardless of the origin of your website visitors, explicitly - specify a locale as the third argument to the constructor. - - - Overriding default locale selection - - - - - - - If you know many objects should all use the same default locale, explicitly specify the - default locale to avoid the overhead of each object determining the default locale. - - - Performance optimization when using a default locale - - - - -
- -
Application wide locale - - - - Zend Framework allows the usage of an application wide locale. You simply set an - instance of Zend_Locale to the registry with the key - 'Zend_Locale'. Then this instance will be used within all locale aware classes of - Zend Framework. This way you set one locale within your registry and then you can forget - about setting it again. It will automatically be used in all other classes. See the - below example for the right usage: - - - Usage of an application wide locale - - - getLocale(); -echo $date->getDate(); -]]> - -
- -
Zend_Locale_Format::setOptions(array $options) - - - - The 'precision' option of a value is used to truncate or stretch extra digits. A value - of '-1' disables modification of the number of digits in the fractional part of the - value. The 'locale' option helps when parsing numbers and dates using separators and - month names. The date format 'format_type' option selects between - CLDR/ISO date format specifier tokens and PHP's - date() tokens. The 'fix_date' option enables or disables heuristics that attempt to - correct invalid dates. The 'number_format' option specifies a default number format for - use with toNumber() (see this section). - - - - The 'date_format' option can be used to specify a default date format string, but beware - of using getDate(), checkdateFormat() and getTime() after using setOptions() with a - 'date_format'. To use these four methods with the default date format for a locale, use - array('date_format' => null, 'locale' => $locale) for their options. - - - Dates default to correct locale of web users - - - 'en_US', - 'fix_date' => true, - 'format_type' => 'php')); -]]> - - - - For working with the standard definitions of a locale the option - Zend_Locale_Format::STANDARD can be used. Setting the option - Zend_Locale_Format::STANDARD for date_format - uses the standard definitions from the actual set locale. Setting it for - number_format uses the standard number format for this locale. - And setting it for locale uses the standard locale for this environment or browser. - - - Using STANDARD definitions for setOptions() - - - 'en_US', - 'date_format' => 'dd.MMMM.YYYY')); -// overriding the global set date format -$date = Zend_Locale_Format::getDate('2007-04-20', - array('date_format' => - Zend_Locale_Format::STANDARD); - -// global setting of the standard locale -Zend_Locale_Format::setOptions(array('locale' => Zend_Locale_Format::STANDARD, - 'date_format' => 'dd.MMMM.YYYY')); -]]> - -
- -
Speed up Zend_Locale and its subclasses - - - - Zend_Locale and its subclasses can be speeded up by the usage of - Zend_Cache. Use the static method - Zend_Locale::setCache($cache) if you are using - Zend_Locale. Zend_Locale_Format can be - speeded up the using the option cache within - Zend_Locale_Format::setOptions(array('cache' => $adapter));. - If you are using both classes you should only set the cache for - Zend_Locale, otherwise the last set cache will overwrite the - previous set cache. For convenience there are also the static methods - getCache(), hasCache(), - clearCache() and removeCache(). - - - - When no cache is set, then Zend_Locale will automatically set a - cache itself. Sometimes it is wished to prevent that a cache is set, even if this - degrades performance. In this case the static - disableCache(true) method should be used. It does not only - disable the actual set cache, without erasing it, but also prevents that a cache is - automatically generated when no cache is set. - -
-
diff --git a/documentation/manual/en/module_specs/Zend_Locale-Parsing.xml b/documentation/manual/en/module_specs/Zend_Locale-Parsing.xml deleted file mode 100644 index f68158f8004..00000000000 --- a/documentation/manual/en/module_specs/Zend_Locale-Parsing.xml +++ /dev/null @@ -1,521 +0,0 @@ - -
- Normalization and Localization - - - Zend_Locale_Format is an internal component used by - Zend_Locale. All locale aware classes use - Zend_Locale_Format for normalization and localization of numbers and - dates. Normalization involves parsing input from a variety of data representations, like - dates, into a standardized, structured representation, such as a PHP - array with year, month, and day elements. - - - - The exact same string containing a number or a date might mean different things to people - with different customs and conventions. Disambiguation of numbers and dates requires rules - about how to interpret these strings and normalize the values into a standardized data - structure. Thus, all methods in Zend_Locale_Format require a locale - in order to parse the input data. - - - Default "root" Locale - - - If no locale is specified, then normalization and localization will use the standard - "root" locale, which might yield unexpected behavior, if the input originated in a - different locale, or output for a specific locale was expected. - - - - -
- Number normalization: getNumber($input, Array $options) - - - There are many number systems - different from the common decimal - system (e.g. "3.14"). - Numbers can be normalized with the getNumber() function to - obtain the standard decimal representation. for all number-related discussions in this - manual, Arabic/European - numerals - (0,1,2,3,4,5,6,7,8,9) are implied, unless explicitly stated otherwise. The - options array may contain a 'locale' to define grouping and decimal characters. The - array may also have a 'precision' to truncate excess digits from the result. - - - - Number normalization - - $locale, - 'precision' => 3) - ); - -print $number; // will return 13524.678 -]]> - - -
- Precision and Calculations - - - Since getNumber($value, array $options = array()) can - normalize extremely large numbers, check the result carefully before using finite - precision calculations, such as ordinary PHP math operations. For - example, if ((string)int_val($number) != $number) { use BCMath or GMP. Most PHP - installations support the BCMath extension. - - - - Also, the precision of the resulting decimal representation can be rounded to a - desired length with getNumber() with the option - 'precision'. If no precision is given, no rounding occurs. Use - only PHP integers to specify the precision. - - - - If the resulting decimal representation should be truncated to a desired length - instead of rounded the option 'number_format' can be used - instead. Define the length of the decimal representation with the desired length - of zeros. The result will then not be rounded. So if the defined precision within - number_format is zero the value "1.6" will return "1", not "2. - See the example nearby: - - - - Number normalization with precision - - 1, - 'locale' => $locale) - ); -print $number; // will return 13524.7 - -$number = Zend_Locale_Format::getNumber('13.524,678', - array('number_format' => '#.00', - 'locale' => $locale) - ); -print $number; // will return 13524.67 -]]> - -
-
- -
- Number localization - - - toNumber($value, array $options = array()) can localize numbers - to the following supported locales. This - function will return a localized string of the given number in a conventional format for - a specific locale. The 'number_format' option explicitly specifies a non-default number - format for use with toNumber(). - - - - Number localization - - $locale)); - -// will return 13.547,36 -print $number; -]]> - - - - - Unlimited length - - - toNumber() can localize numbers with unlimited length. - It is not related to integer or float limitations. - - - - - - The same way as within getNumber(), - toNumber() handles precision. If no precision is given, the - complete localized number will be returned. - - - - Number localization with precision - - 2, - 'locale' => $locale)); - -// will return 13.547,37 -print $number; -]]> - - - - Using the option 'number_format' a self defined format for generating a number can be - defined. The format itself has to be given in CLDR format as - described below. The locale is used to get separation, precision and other number - formatting signs from it. German for example defines ',' as precision separation and in - English the '.' sign is used. - - - - Format tokens for self generated number formats - - - - - Token - Description - Example format - Generated output - - - - - - #0 - Generates a number without precision and separation - #0 - 1234567 - - - - , - - - Generates a separation with the length from separation to next - separation or to 0 - - - #,##0 - 1,234,567 - - - - #,##,##0 - - - Generates a standard separation of 3 and all following separations with - 2 - - - #,##,##0 - 12,34,567 - - - - . - Generates a precision - #0.# - 1234567.1234 - - - - 0 - Generates a precision with a defined length - #0.00 - 1234567.12 - - - -
- - - Using a self defined number format - - '#,#0.00', - 'locale' => 'de') - ); - -// will return 1.35.47,36 -print $number; - -$number = Zend_Locale_Format::toNumber(13547.3, - array('number_format' => '#,##0.00', - 'locale' => 'de') - ); - -// will return 13.547,30 -print $number; -]]> - -
- -
- Number testing - - - isNumber($value, array $options = array()) checks if a given - string is a number and returns TRUE or FALSE. - - - - Number testing - - 'de_AT'))) { - print "Number"; -} else { - print "not a Number"; -} -]]> - -
- -
- Float value normalization - - - Floating point values can be parsed with the - getFloat($value, array $options = array()) function. A floating - point value will be returned. - - - - Floating point value normalization - - 2, - 'locale' => $locale) - ); - -// will return 13524.68 -print $number; -]]> - -
- -
- Floating point value localization - - - toFloat() can localize floating point values. This function - will return a localized string of the given number. - - - - Floating point value localization - - 1, - 'locale' => $locale) - ); - -// will return 13.547,4 -print $number; -]]> - -
- -
- Floating point value testing - - - isFloat($value, array $options = array()) checks if a given - string is a floating point value and returns TRUE or - FALSE. - - - - Floating point value testing - - $locale))) { - print "float"; -} else { - print "not a float"; -} -]]> - -
- -
- Integer value normalization - - - Integer values can be parsed with the getInteger() function. A - integer value will be returned. - - - - Integer value normalization - - $locale)); - -// will return 13524 -print $number; -]]> - -
- -
- Integer point value localization - - - toInteger($value, array $options = array()) can localize - integer values. This function will return a localized string of the given number. - - - - Integer value localization - - $locale)); - -// will return 13.547 -print $number; -]]> - -
- -
- Integer value testing - - - isInteger($value, array $options = array()) checks if a given - string is an integer value and returns TRUE or - FALSE. - - - - Integer value testing - - $locale))) { - print "integer"; -} else { - print "not an integer"; -} -]]> - -
- -
- Numeral System Conversion - - - Zend_Locale_Format::convertNumerals() converts digits between - different numeral - systems, including the standard Arabic/European/Latin numeral system - (0,1,2,3,4,5,6,7,8,9), not to be confused with Eastern Arabic - numerals sometimes used with the Arabic language to express numerals. - Attempts to use an unsupported numeral system will result in an exception, to avoid - accidentally performing an incorrect conversion due to a spelling error. All characters - in the input, which are not numerals for the selected numeral system, are copied to the - output with no conversion provided for unit separator characters. - Zend_Locale* components rely on the data provided by - CLDR (see their list - of scripts grouped by language). - - - - In CLDR and hereafter, the Europena/Latin numerals will - be referred to as "Latin" or by the assigned 4-letter code "Latn". - Also, the CLDR refers to this numeral systems as "scripts". - - - - Suppose a web form collected a numeric input expressed using Eastern Arabic digits - "Ł”ā€ŽŁ Ł ". Most software and PHP functions expect input using Arabic - numerals. Fortunately, converting this input to its equivalent Latin numerals "100" - requires little effort using convertNumerals($inputNumeralString, - $sourceNumeralSystem, $destNumeralSystem), which returns the - $input with numerals in the script - $sourceNumeralSystem converted to the script - $destNumeralSystem. - - - - Converting numerals from Eastern Arabic scripts to European/Latin scripts - - - - - - Similarly, any of the supported numeral systems may be converted to any other supported - numeral system. - - - - Converting numerals from Latin script to Eastern Arabic script - - - - - - - Getting 4 letter CLDR script code using a native-language name of the script - - - - - - - For a list of supported numeral systems call - Zend_Locale::getTranslationList('numberingsystem', 'en'). - -
-
diff --git a/documentation/manual/en/module_specs/Zend_Mail-AdditionalHeaders.xml b/documentation/manual/en/module_specs/Zend_Mail-AdditionalHeaders.xml index 5f86cda1ff9..d9747d1cf91 100644 --- a/documentation/manual/en/module_specs/Zend_Mail-AdditionalHeaders.xml +++ b/documentation/manual/en/module_specs/Zend_Mail-AdditionalHeaders.xml @@ -17,7 +17,7 @@ setDate($date = null): sets the Date: header. This method uses current time stamp by default. Or You can pass time stamp, - date string or Zend_Date instance to this method. + date string or DateTime instance to this method. diff --git a/documentation/manual/en/module_specs/Zend_Measure-Creation.xml b/documentation/manual/en/module_specs/Zend_Measure-Creation.xml deleted file mode 100644 index e389e8440c9..00000000000 --- a/documentation/manual/en/module_specs/Zend_Measure-Creation.xml +++ /dev/null @@ -1,121 +0,0 @@ - -
Creation of Measurements - - - - When creating a measurement object, Zend_Measure_* methods expect the - input/original measurement data value as the first parameter. This can be a - numeric argument, a - String without units, or a - localized string with unit(s) - specified. The second parameter defines the type of the measurement. Both - parameters are mandatory. The language may optionally be specified as the third parameter. - - -
Creating measurements from integers and floats - - - - In addition to integer data values, floating point types may be used, but - "simple decimal fractions like 0.1 or 0.7 cannot - be converted into their internal binary counterparts without a little loss of - precision," sometimes giving surprising results. Also, do not compare two - "float" type numbers for equality. - - - Creation using integer and floating values - - - - -
- -
Creating measurements from strings - - - - Many measurements received as input to Zend Framework applications can only be passed - to Zend_Measure_* classes as strings, such as numbers written - using roman numerals - or extremely large binary values that exceed the precision of PHP's - native integer and float types. Since integers can be denoted using strings, if there is - any risk of losing precision due to limitations of PHP's native - integer and float types, using strings instead. - Zend_Measure_Number uses the BCMath extension to support - arbitrary precision, as shown in the example below, to avoid limitations in many - PHP functions, such as bin2dec(). - - - Creation using strings - - - - -
- -
Measurements from localized strings - - - - When a string is entered in a localized notation, the correct interpretation can not be - determined without knowing the intended locale. The division of decimal digits with "." - and grouping of thousands with "," is common in the English language, but not so in - other languages. For example, the English number "1,234.50" would be interpreted as - meaning "1.2345" in German. To deal with such problems, the locale-aware - Zend_Measure_* family of classes offer the possibility to specify - a language or region to disambiguate the input data and properly interpret the intended - semantic value. - - - Localized string - - - - - - - Since Zend Framework 1.7.0 Zend_Measure does also support the - usage of an application wide locale. You can simply set a - Zend_Locale instance to the registry like shown below. With this - notation you can forget about setting the locale manually with each instance when you - want to use the same locale multiple times. - - - -
-
diff --git a/documentation/manual/en/module_specs/Zend_Measure-Edit.xml b/documentation/manual/en/module_specs/Zend_Measure-Edit.xml deleted file mode 100644 index 1101fd39252..00000000000 --- a/documentation/manual/en/module_specs/Zend_Measure-Edit.xml +++ /dev/null @@ -1,270 +0,0 @@ - -
Manipulating Measurements - - - - Parsing and normalization of input, combined with output to localized notations makes data - accessible to users in different locales. Many additional methods exist in - Zend_Measure_* components to manipulate and work with this data, - after it has been normalized. - - - - - - Convert - - - - - - Add and subtract - - - - - - Compare to boolean - - - - - - Compare to greater/smaller - - - - - - Manually change values - - - - - - Manually change types - - - - -
Convert - - - - Probably the most important feature is the conversion into different units of - measurement. The conversion of a unit can be done any number of times using the method - convertTo(). Units of measurement can only be converted to - other units of the same type (class). Therefore, it is not possible to convert (e.g.) a - length into a weight, which would might encourage poor programming practices and allow - errors to propagate without exceptions. - - - - The convertTo() method accepts an optional parameter. With - this parameter you can define an precision for the returned output. The standard - precision is '2'. - - - Convert - - - convertTo('KILOGRAM'); - -// constants are considered "better practice" than strings -print "Ton:".$unit->convertTo(Zend_Measure_Weight::TON); - -// define a precision for the output -print "Ton:".$unit->convertTo(Zend_Measure_Weight::TON, 3); -]]> - -
- -
Add and subtract - - - - Measurements can be added together using add() and subtracted - using sub(). The result will use the same type as the - originating object. Dynamic objects support a fluid style of programming, where complex - sequences of operations can be nested without risk of side-effects altering the input - objects. - - - - Adding units - - - add($unit2); - -echo $sum; // outputs "300 cm" -]]> - - - - Automatic conversion - - - - Adding one object to another will automatically convert it to the correct unit. It - is not necessary to call convertTo() - before adding different units. - - - - - Subtract - - - - Subtraction of measurements works just like addition. - - - sub($unit2); - -echo $sum; -]]> - - -
- -
Compare - - - - Measurements can also be compared, but without automatic unit conversion. Thus, - equals() returns TRUE, only if both the - value and the unit of measure are identical. - - - - Different measurements - - - equals($unit2)) { - print "Both measurements are identical"; -} else { - print "These are different measurements"; -} -]]> - - - Identical measurements - - - setType(Zend_Measure_Length::CENTIMETER); - -if ($unit->equals($unit2)) { - print "Both measurements are identical"; -} else { - print "These are different measurements"; -} -]]> - - -
- -
Compare - - - - To determine if a measurement is less than or greater than another, use - compare(), which returns 0, -1 or 1 depending on the difference - between the two objects. Identical measurements will return 0. Lesser ones will return a - negative, greater ones a positive value. - - - - Difference - - - compare($unit); -print "Lesser:".$unit2->compare($unit3); -print "Greater:".$unit3->compare($unit2); -]]> - - -
- -
Manually change values - - - - To change the value of a measurement explicitly, use - setValue(). to overwrite the current value. The parameters are - the same as the constructor. - - - - Changing a value - - - setValue(1.2); -echo $unit; - -$unit->setValue(1.2, Zend_Measure_Length::KILOMETER); -echo $unit; - -$unit->setValue("1.234,56", Zend_Measure_Length::MILLIMETER,$locale); -echo $unit; -]]> - - -
- -
Manually change types - - - - To change the type of a measurement without altering its value use - setType(). - - - Changing the type - - - setType(Zend_Measure_Length::KILOMETER); -echo $unit; // outputs "1000 km" -]]> - -
-
diff --git a/documentation/manual/en/module_specs/Zend_Measure-Introduction.xml b/documentation/manual/en/module_specs/Zend_Measure-Introduction.xml deleted file mode 100644 index b125e2da884..00000000000 --- a/documentation/manual/en/module_specs/Zend_Measure-Introduction.xml +++ /dev/null @@ -1,61 +0,0 @@ - -
Introduction - - - - - Zend_Measure_* classes provide a generic and easy way for working - with measurements. Using Zend_Measure_* classes, you can convert - measurements into different units of the same type. They can be added, subtracted and - compared against each other. From a given input made in the user's native language, the unit - of measurement can be automatically extracted. Numerous units of measurement are supported. - - - Converting measurements - - - - The following introductory example shows automatic conversion of units of measurement. - To convert a measurement, its value and its type have to be known. The value can be an - integer, a float, or even a string containing a number. Conversions are only possible - for units of the same type (mass, area, temperature, velocity, etc.), not between types. - - - convertTo(Zend_Measure_Length::YARD); -]]> - - - - Zend_Measure_* includes support for many different units of - measurement. The units of measurement all have a unified notation: - Zend_Measure_<TYPE>::NAME_OF_UNIT, where <TYPE> - corresponds to a well-known physical or numerical property. . Every unit of measurement - consists of a conversion factor and a display unit. A detailed list can be found in the - chapter Types of measurements. - - - The meter measurement - - - - The meter is used for measuring lengths, so its type constant can - be found in the Length class. To refer to this unit of - measurement, the notation Length::METER must be used. The display - unit is m. - - - - -
diff --git a/documentation/manual/en/module_specs/Zend_Measure-Output.xml b/documentation/manual/en/module_specs/Zend_Measure-Output.xml deleted file mode 100644 index 0f34627fb93..00000000000 --- a/documentation/manual/en/module_specs/Zend_Measure-Output.xml +++ /dev/null @@ -1,117 +0,0 @@ - -
Outputting measurements - - - - - Measurements can be output in a number of different ways. - - - - Automatic output - - - - Outputting values - - - - Output with unit of measurement - - - - Output as localized string - - -
Automatic output - - - - Zend_Measure supports outputting of strings automatically. - - Automatic output - - - - - - - Measurement output - - - - Output can be achieved simply by using - echo or - print. - - -
- -
Outputting values - - - - The value of a measurement can be output using getValue(). - - Output a value - - - getValue(); -]]> - - - - - The getValue() method accepts an optional parameter - round which allows to define a precision for the generated - output. The standard precision is '2'. - -
- -
Output with unit of measurement - - - - The function getType() returns the current unit of measurement. - - Outputting units - - - getType(); -]]> - - -
- -
Output as localized string - - - - Outputting a string in a format common in the users' country is usually desirable. For - example, the measurement "1234567.8" would become "1.234.567,8" for Germany. This - functionality will be supported in a future release. - -
-
diff --git a/documentation/manual/en/module_specs/Zend_Measure-Types.xml b/documentation/manual/en/module_specs/Zend_Measure-Types.xml deleted file mode 100644 index 8459dea3862..00000000000 --- a/documentation/manual/en/module_specs/Zend_Measure-Types.xml +++ /dev/null @@ -1,393 +0,0 @@ - -
Types of measurements - - - - All supported measurement types are listed below, each with an example of the standard usage - for such measurements. - - - List of measurement types - - - - - - Typ - Class - Standardunit - Description - - - - - - Acceleration - Zend_Measure_Acceleration - Meter per square second | m/sĀ² - - - Zend_Measure_Acceleration covers the - physical factor of acceleration. - - - - - Angle - Zend_Measure_Angle - Radiant | rad - - - Zend_Measure_Angle covers angular dimensions. - - - - - Area - Zend_Measure_Area - Square meter | mĀ² - Zend_Measure_Area covers square measures. - - - - Binary - Zend_Measure_Binary - Byte | b - - - Zend_Measure_Binary covers binary conversions. - - - - - Capacitance - Zend_Measure_Capacitance - Farad | F - - - Zend_Measure_Capacitance covers physical factor of - capacitance. - - - - - Cooking volumes - Zend_Measure_Cooking_Volume - Cubic meter | mĀ³ - - - Zend_Measure_Cooking_Volume covers volumes - which are used for cooking or written in cookbooks. - - - - - Cooking weights - Zend_Measure_Cooking_Weight - Gram | g - - - Zend_Measure_Cooking_Weight covers the weights - which are used for cooking or written in cookbooks. - - - - - Current - Zend_Measure_Current - Ampere | A - - - Zend_Measure_Current covers the physical factor of - current. - - - - - Density - Zend_Measure_Density - Kilogram per cubic meter | kg/mĀ³ - - - Zend_Measure_Density covers the physical factor of - density. - - - - - Energy - Zend_Measure_Energy - Joule | J - - - Zend_Measure_Energy covers the physical factor of - energy. - - - - - Force - Zend_Measure_Force - Newton | N - - - Zend_Measure_Force covers the physical factor of - force. - - - - - Flow (mass) - Zend_Measure_Flow_Mass - Kilogram per second | kg/s - - - Zend_Measure_Flow_Mass covers the physical factor of - flow rate. The weight of the flowing mass is used as reference point within - this class. - - - - - Flow (mole) - Zend_Measure_Flow_Mole - Mole per second | mol/s - - - Zend_Measure_Flow_Mole covers the physical factor of - flow rate. The density of the flowing mass is used as reference point within - this class. - - - - - Flow (volume) - Zend_Measure_Flow_Volume - Cubic meter per second | mĀ³/s - - - Zend_Measure_Flow_Volume covers the physical factor - of flow rate. The volume of the flowing mass is used as reference point - within this class. - - - - - Frequency - Zend_Measure_Frequency - Hertz | Hz - - - Zend_Measure_Frequency covers the physical factor of - frequency. - - - - - Illumination - Zend_Measure_Illumination - Lux | lx - - - Zend_Measure_Illumination covers the physical factor - of light density. - - - - - Length - Zend_Measure_Length - Meter | m - - - Zend_Measure_Length covers the physical factor of - length. - - - - - Lightness - Zend_Measure_Lightness - Candela per square meter | cd/mĀ² - - - Zend_Measure_Ligntness covers the physical factor of - light energy. - - - - - Number - Zend_Measure_Number - Decimal | (10) - - - Zend_Measure_Number converts between number formats. - - - - - Power - Zend_Measure_Power - Watt | W - - - Zend_Measure_Power covers the physical factor of - power. - - - - - Pressure - Zend_Measure_Pressure - Newton per square meter | N/mĀ² - - - Zend_Measure_Pressure covers the physical factor of - pressure. - - - - - Speed - Zend_Measure_Speed - Meter per second | m/s - - - Zend_Measure_Speed covers the physical factor of - speed. - - - - - Temperature - Zend_Measure_Temperature - Kelvin | K - - - Zend_Measure_Temperature covers the physical factor - of temperature. - - - - - Time - Zend_Measure_Time - Second | s - - - Zend_Measure_Time covers the physical factor of time. - - - - - Torque - Zend_Measure_Torque - Newton meter | Nm - - - Zend_Measure_Torque covers the physical factor of - torque. - - - - - Viscosity (dynamic) - Zend_Measure_Viscosity_Dynamic - Kilogram per meter second | kg/ms - - - Zend_Measure_Viscosity_Dynamic covers the physical - factor of viscosity. The weight of the fluid is used as reference point - within this class. - - - - - Viscosity (kinematic) - Zend_Measure_Viscosity_Kinematic - Square meter per second | mĀ²/s - - - Zend_Measure_Viscosity_Kinematic covers the physical - factor of viscosity. The distance of the flown fluid is used as reference - point within this class. - - - - - Volume - Zend_Measure_Volume - Cubic meter | mĀ³ - - - Zend_Measure_Volume covers the physical factor of - volume (content). - - - - - Weight - Zend_Measure_Weight - Kilogram | kg - - - Zend_Measure_Weight covers the physical factor of - weight. - - - - -
- -
Hints for Zend_Measure_Binary - - - - Some popular binary conventions, include terms like kilo-, mega-, giga, etc. in normal - language use imply base 10, such as 1000 or 10Ā³. However, in the binary format for - computers these terms have to be seen for a conversion factor of 1024 instead of 1000. - To preclude confusions a few years ago the notation BI was introduced. Instead of - kilobyte, kibibyte for kilo-binary-byte should be used. - - - - In the class BINARY both notations can be found, such as KILOBYTE = 1024 - binary - conputer conversion KIBIBYTE = 1024 - new notation KILO_BINARY_BYTE = 1024 - new, - or the notation, long format - KILOBYTE_SI = 1000 - SI notation for kilo (1000). DVDs for example are - marked with the SI-notation, but almost all harddisks are marked in computer binary - notation. - -
- -
Hints for Zend_Measure_Number - - - - The best known number format is the decimal system. Additionally this class supports the - octal system, the hexadecimal system, the binary system, the roman number system and - some other less popular systems. Note that only the decimal part of numbers is handled. - Any fractional part will be stripped. - -
- -
Roman numbers - - - - For the roman number system digits greater 4000 are supported. In reality these digits - are shown with a crossbeam on top of the digit. As the crossbeam can not be shown within - the computer, an underline has to be used instead of it. - - - convertTo(Zend_Measure_Number::DECIMAL); -]]> -
-
diff --git a/documentation/manual/en/module_specs/Zend_Mvc-QuickStart.xml b/documentation/manual/en/module_specs/Zend_Mvc-QuickStart.xml index 4ee2142699e..6a5fe19f6db 100644 --- a/documentation/manual/en/module_specs/Zend_Mvc-QuickStart.xml +++ b/documentation/manual/en/module_specs/Zend_Mvc-QuickStart.xml @@ -19,6 +19,29 @@ and module repositories. This can be done in the following ways. +
+ Using Composer + + + Simply clone the ZendSkeletonApplication + repository: + + + git clone git://github.com/zendframework/ZendSkeletonApplication.git my-application +]]> + + + Then run Composer's install command to install the ZF library and any other configured dependencies: + + + php ./composer.phar install +]]> + +
+ +
Using Git @@ -183,7 +206,10 @@ return array( ; -class Module implements AutoloaderProvider +use Zend\ModuleManager\Feature\AutoloaderProviderInterface; +use Zend\ModuleManager\Feature\ConfigProviderInterface; + +class Module implements AutoloaderProviderInterface, ConfigProviderInterface { public function getAutoloaderConfig() { @@ -304,8 +330,7 @@ class HelloController extends AbstractActionController { public function worldAction() { - $request = $this->getRequest(); - $message = $request->query()->get('message', 'foo'); + $message = $this->params()->fromQuery('message', 'foo'); return new ViewModel(array('message' => $message)); } } @@ -331,13 +356,13 @@ class HelloController extends AbstractActionController We're pulling a message from the query parameters (yes, this is a - superbly bad idea in production!). + superbly bad idea in production! Always sanitize your inputs!). - We're returning an array of values that will get processed later. + We're returning a ViewModel with an array of values that will get processed later. @@ -371,7 +396,7 @@ class HelloController extends AbstractActionController Greetings! -

You said "escape($message) ?>".

+

You said "escapeHtml($message) ?>".

]]>
@@ -380,11 +405,12 @@ class HelloController extends AbstractActionController - What is the method escape()? It's actually a + What is the method escapeHtml()? It's actually a view helper, and it's designed - to help mitigate from XSS attacks. Never trust user + to help mitigate XSS attacks. Never trust user input; if you are at all uncertain about the source of a given variable - in your view script, escape it. + in your view script, escape it using one of the provided escape view helper depending + on the type of data you have.
@@ -401,8 +427,8 @@ class HelloController extends AbstractActionController ZendSkeletonApplication ships with a "default route" that will likely get you to this action. That route - basically expects "/{controller}/{action}", which allows - you to specify this: "/zend-user-hello/world". We're + basically expects "/{module}/{controller}/{action}", which allows + you to specify this: "/zend-user/hello/world". We're going to create a route here mainly for illustration purposes, as creating explicit routes is a recommended practice. The application will look for a @@ -410,6 +436,50 @@ class HelloController extends AbstractActionController routing. The default generated router is a Zend\Mvc\Router\Http\TreeRouteStack. + + + To use the "default route" functionality, you will need to add a + the following route definition to your module. Replace + + + ' => array( + 'type' => 'Literal', + 'options' => array( + 'route' => '/', + 'defaults' => array( + '__NAMESPACE__' => '\Controller', + 'controller' => '-Index', + 'action' => 'index', + ), + ), + 'may_terminate' => true, + 'child_routes' => array( + 'default' => array( + 'type' => 'Segment', + 'options' => array( + 'route' => '/[:controller[/:action]]', + 'constraints' => array( + 'controller' => '[a-zA-Z][a-zA-Z0-9_-]*', + 'action' => '[a-zA-Z][a-zA-Z0-9_-]*', + ), + 'defaults' => array( + ), + ), + ), + ), + ), + 'controller' => array( + 'classes' => array( + '-Index' => '\Controller\IndexController', + // Do similar for each other controller in your module + ), + ), + // ... other configuration ... +); +]]> + @@ -504,16 +574,10 @@ return array( Now we can test things out! Create a new vhost pointing its document root to the public directory of your - application, and fire it up in a browser. You should see a simple - page with these details: + application, and fire it up in a browser. You should see the + default homepage template of ZendSkeletonApplication. - - Now alter the location in your URL to append the path "hello/world", and load the page. You should now get the diff --git a/documentation/manual/en/module_specs/Zend_Mvc-Routing.xml b/documentation/manual/en/module_specs/Zend_Mvc-Routing.xml index 48ad8132c0b..a16fa11427d 100644 --- a/documentation/manual/en/module_specs/Zend_Mvc-Routing.xml +++ b/documentation/manual/en/module_specs/Zend_Mvc-Routing.xml @@ -332,6 +332,32 @@ $route = Literal::factory(array( +
+ Zend\Mvc\Router\Http\Method + + + The Method route is used to match the http method or 'verb' + specified in the request (See RFC 2616 Sec. 5.1.1). It can optionally + be configured to match against multiple methods by providing a comma-separated + list of method tokens. + + + 'post,put', + 'defaults' => array( + 'action' => 'form-submit' + ), +)); + ]]> + + + The above route would match an http "POST" or "PUT" request and + return a RouteMatch object containing + a key "action" with a value of "form-submit". + +
+
Zend\Mvc\Router\Http\Part diff --git a/documentation/manual/en/module_specs/Zend_Reflection-Examples.xml b/documentation/manual/en/module_specs/Zend_Reflection-Examples.xml deleted file mode 100644 index f436247adb8..00000000000 --- a/documentation/manual/en/module_specs/Zend_Reflection-Examples.xml +++ /dev/null @@ -1,94 +0,0 @@ - -
Zend_Reflection Examples - - - Performing reflection on a file - - - The %s file\n". - " has %d lines\n", - $r->getFileName(), - $r->getEndLine() -); - -$classes = $r->getClasses(); -echo " It has " . count($classes) . ":\n"; -foreach ($classes as $class) { - echo " " . $class->getName() . "\n"; -} - -$functions = $r->getFunctions(); -echo " It has " . count($functions) . ":\n"; -foreach ($functions as $function) { - echo " " . $function->getName() . "\n"; -} -]]> - - - Performing reflection on a class - - - getDocblock()->getShortDescription(), - $r->getDocblock()->getLongDescription(), -); - -// Get the declaring file reflection -$file = $r->getDeclaringFile(); -]]> - - - Performing reflection on a method - - - getName(), - $r->getReturn() -); - -foreach ($r->getParameters() as $key => $param) { - printf( - "Param at position '%d' is of type '%s'\n", - $key, - $param->getType() - ); -} -]]> - - - Performing reflection on a docblock - - - getDocblock(); - -printf( - "The short description: %s\n". - "The long description:\n%s\n", - $r->getDocblock()->getShortDescription(), - $r->getDocblock()->getLongDescription(), -); - -foreach ($docblock->getTags() as $tag) { - printf( - "Annotation tag '%s' has the description '%s'\n", - $tag->getName(), - $tag->getDescription() - ); -} -]]> - -
diff --git a/documentation/manual/en/module_specs/Zend_Reflection-Introduction.xml b/documentation/manual/en/module_specs/Zend_Reflection-Introduction.xml deleted file mode 100644 index b06e2eefa5f..00000000000 --- a/documentation/manual/en/module_specs/Zend_Reflection-Introduction.xml +++ /dev/null @@ -1,62 +0,0 @@ - - - -
Introduction - - - - Zend_Reflection is a drop-in extension to PHP's - own Reflection API, - providing several additional features: - - - - - - Ability to retrieve return values types. - - - - - - Ability to retrieve method and function parameter types. - - - - - - Ability to retrieve class property types. - - - - - - DocBlocks gain a Reflection class, allowing introspection of - docblocks. This provides the ability to determine what annotation - tags have been defined as well as to retrieve their values, and the - ability to retrieve the short and long descriptions. - - - - - - Files gain a Reflection class, allowing introspection of PHP - files. This provides the ability to determine what functions and classes - are defined in a given file, as well as to introspect them. - - - - - - Ability to override any Reflection class with your own variant, for - the entire reflection tree you create. - - - - - - In general, Zend_Reflection works just like the standard - Reflection API, but provides a few additional methods for retrieving - artifacts not defined in the Reflection API. - -
diff --git a/documentation/manual/en/module_specs/Zend_Reflection-Reference.xml b/documentation/manual/en/module_specs/Zend_Reflection-Reference.xml deleted file mode 100644 index 04f16aadf2d..00000000000 --- a/documentation/manual/en/module_specs/Zend_Reflection-Reference.xml +++ /dev/null @@ -1,487 +0,0 @@ - - - -
Zend_Reflection Reference - - - - The various classes in Zend_Reflection mimic the - API of PHP's Reflection API - with one - important difference. PHP's Reflection API does not - provide introspection into docblock annotation tags, nor into parameter variable - types or return types. - - - - Zend_Reflection analyzes method docblock annotations to - determine parameter variable types and the return type. Specifically, - the @param and @return annotations are used. - However, you can also check for any other annotation tags, as well as - the standard "short" and "long" descriptions. - - - - Each reflection object in Zend_Reflection overrides the - getDocblock() method to return an instance of - Zend_Reflection_Docblock. This class provides introspection - into the docblocks and annotation tags. - - - - Zend_Reflection_File is a new reflection class that allows - introspection of PHP files. With it, you can retrieve the classes, - functions, and global PHP code contained in the file. - - - - Finally, the various methods that return other reflection objects - allow a second parameter, the name of the reflection class to use for - the returned reflection object. - - -
Zend_Reflection_Docblock - - - - Zend_Reflection_Docblock is the heart of - Zend_Reflection's value-add over PHP's - Reflection API. It provides the following methods: - - - - - - getContents(): returns the full contents of the - docblock. - - - - - - getStartLine(): returns the starting position of - the docblock within the defining file. - - - - - - getEndLine(): get last line of docblock within the - defining file. - - - - - - getShortDescription(): get the short, one-line - description (usually the first line of the docblock). - - - - - - getLongDescription(): get the long description from - the docblock. - - - - - - hasTag($name): determine if the docblock has the - given annotation tag. - - - - - - getTag($name): Retrieve the given annotation tag - reflection object, or a boolean FALSE if it's not - present. - - - - - - getTags($filter): Retrieve all tags, or all tags - matching the given $filter string. The tags - returned will be an array of - Zend_Reflection_Docblock_Tag objects. - - - -
- -
Zend_Reflection_Docblock_Tag - - - - Zend_Reflection_Docblock_Tag provides reflection for - individual annotation tags. Most tags consist of only a name and a - description. In the case of some special tags, the class provides a - factory method for retrieving an instance of the appropriate class. - - - - The following methods are defined for - Zend_Reflection_Docblock_Tag: - - - - - - factory($tagDocblockLine): instantiate the - appropriate tag reflection class and return it. - - - - - - getName(): return the annotation tag name. - - - - - - getDescription(): return the annotation - description. - - - -
- -
Zend_Reflection_Docblock_Tag_Param - - - - Zend_Reflection_Docblock_Tag_Param is a specialized - version of Zend_Reflection_Docblock_Tag. The - @param annotation tag description consists of the - parameter type, variable name, and variable description. It adds the - following methods to Zend_Reflection_Docblock_Tag: - - - - - - getType(): return the parameter variable type. - - - - - - getVariableName(): return the parameter variable - name. - - - -
- -
Zend_Reflection_Docblock_Tag_Return - - - - Like Zend_Reflection_Docblock_Tag_Param, - Zend_Reflection_Docblock_Tag_Return is a specialized - version of Zend_Reflection_Docblock_Tag. The - @return annotation tag description consists of the - return type and variable description. It adds the following method - to Zend_Reflection_Docblock_Tag: - - - - - - getType(): return the return type. - - - -
- -
Zend_Reflection_File - - - - Zend_Reflection_File provides introspection into - PHP files. With it, you can introspect the classes, functions, and - bare PHP code defined in a file. It defines the following methods: - - - - - - getFileName(): retrieve the filename of the file - being reflected. - - - - - - getStartLine(): retrieve the starting line of the - file (always "1"). - - - - - - getEndLine() retrieve the last line / number of - lines in the file. - - - - - - getDocComment($reflectionClass = - 'Zend_Reflection_Docblock'): retrive the file-level - docblock reflection object. - - - - - - getClasses($reflectionClass = - 'Zend_Reflection_Class'): retrieve an array of - reflection objects, one for each class defined in the file. - - - - - - getFunctions($reflectionClass = - 'Zend_Reflection_Function'): retrieve an array of - reflection objects, one for each function defined in the file. - - - - - - getClass($name = null, $reflectionClass = - 'Zend_Reflection_Class'): retrieve the reflection - object for a single class. - - - - - - getContents(): retrieve the full contents of the - file. - - - -
- -
Zend_Reflection_Class - - - - Zend_Reflection_Class extends - ReflectionClass, and follows its API. It adds one - additional method, getDeclaringFile(), which may be - used to retrieve the Zend_Reflection_File reflection - object for the defining file. - - - - Additionally, the following methods add an additional argument for - specifying the reflection class to use when fetching a reflection - object: - - - - - - getDeclaringFile($reflectionClass = - 'Zend_Reflection_File') - - - - - - getDocblock($reflectionClass = - 'Zend_Reflection_Docblock') - - - - - - getInterfaces($reflectionClass = - 'Zend_Reflection_Class') - - - - - - getMethod($reflectionClass = 'Zend_Reflection_Method') - - - - - - getMethods($filter = -1, $reflectionClass = - 'Zend_Reflection_Method') - - - - - getParentClass($reflectionClass = 'Zend_Reflection_Class') - - - - - getProperty($name, $reflectionClass = 'Zend_Reflection_Property') - - - - - - getProperties($filter = -1, $reflectionClass = - 'Zend_Reflection_Property') - - - -
- -
Zend_Reflection_Extension - - - - Zend_Reflection_Extension extends - ReflectionExtension, and follows its API. It overrides - the following methods to add an additional argument for specifying - the reflection class to use when fetching a reflection object: - - - - - - getFunctions($reflectionClass = - 'Zend_Reflection_Function'): retrieve an array of - reflection objects representing the functions defined by the extension. - - - - - - getClasses($reflectionClass = - 'Zend_Reflection_Class'): retrieve an array of - reflection objects representing the classes defined by the extension. - - - -
- -
Zend_Reflection_Function - - - - Zend_Reflection_Function adds a method for retrieving - the function return type, as well as overrides several methods to - allow specifying the reflection class to use for returned reflection - objects. - - - - - - getDocblock($reflectionClass = - 'Zend_Reflection_Docblock'): retrieve the function - docblock reflection object. - - - - - - getParameters($reflectionClass = - 'Zend_Reflection_Parameter'): retrieve an array of - all function parameter reflection objects. - - - - - - getReturn(): retrieve the return type reflection - object. - - - -
- -
Zend_Reflection_Method - - - - Zend_Reflection_Method mirrors - Zend_Reflection_Function, and only overrides one - additional method: - - - - - - getParentClass($reflectionClass = - 'Zend_Reflection_Class'): retrieve the parent class - reflection object. - - - -
- -
Zend_Reflection_Parameter - - - - Zend_Reflection_Parameter adds a method for retrieving - the parameter type, as well as overrides methods to allow specifying - the reflection class to use on returned reflection objects. - - - - - - getDeclaringClass($reflectionClass = - 'Zend_Reflection_Class'): get the declaring class of - the parameter as a reflection object (if available). - - - - - - getClass($reflectionClass = - 'Zend_Reflection_Class'): get the class of - the parameter as a reflection object (if available). - - - - - - getDeclaringFunction($reflectionClass = - 'Zend_Reflection_Function'): get the function of - the parameter as a reflection object (if available). - - - - - - getType(): get the parameter type. - - - -
- -
Zend_Reflection_Property - - - - Zend_Reflection_Property overrides a single method in - order to allow specifying the returned reflection object class: - - - - - - getDeclaringClass($reflectionClass = - 'Zend_Reflection_Class'): retrieve the declaring - class of the property as a reflection object. - - - -
-
diff --git a/documentation/manual/en/module_specs/Zend_Service.xml b/documentation/manual/en/module_specs/Zend_Service.xml index abaf99f43d2..726670cb68c 100644 --- a/documentation/manual/en/module_specs/Zend_Service.xml +++ b/documentation/manual/en/module_specs/Zend_Service.xml @@ -103,12 +103,6 @@ Windows Azure - - - - Yahoo! - - diff --git a/documentation/manual/en/module_specs/Zend_Service_Delicious.xml b/documentation/manual/en/module_specs/Zend_Service_Delicious.xml index 53e9b64519f..8fee494c221 100644 --- a/documentation/manual/en/module_specs/Zend_Service_Delicious.xml +++ b/documentation/manual/en/module_specs/Zend_Service_Delicious.xml @@ -45,7 +45,7 @@ foreach ($posts as $post) { * most recent date will be used. * * @param string $tag Optional filtering by tag - * @param Zend_Date $dt Optional filtering by date + * @param DateTime $dt Optional filtering by date * @param string $url Optional filtering by url * @return Zend_Service_Delicious_PostList */ diff --git a/documentation/manual/en/module_specs/Zend_Service_LiveDocx.xml b/documentation/manual/en/module_specs/Zend_Service_LiveDocx.xml index 7f5133465d0..3928de493c2 100644 --- a/documentation/manual/en/module_specs/Zend_Service_LiveDocx.xml +++ b/documentation/manual/en/module_specs/Zend_Service_LiveDocx.xml @@ -556,11 +556,11 @@ file_put_contents('document.pdf', $document); relative to the original page size. The range of this parameter is 10 to 400. $format is the format of the images returned by this method. The supported formats can be obtained by calling - getImageFormats(). + getImageExportFormats(). setLocale('en_US'); $phpLiveDocx = new Zend_Service_LiveDocx_MailMerge(); @@ -573,8 +573,8 @@ $phpLiveDocx->setLocalTemplate('template.docx'); $phpLiveDocx->assign('software', 'Magic Graphical Compression Suite v1.9') ->assign('licensee', 'DaĆÆ Lemaitre') ->assign('company', 'Megasoft Co-operation') - ->assign('date', $date->get(Zend_Date::DATE_LONG)) - ->assign('time', $date->get(Zend_Date::TIME_LONG)) + ->assign('date', $date->format('Y-m-d')) + ->assign('time', $date->format('H:i:s')) ->assign('city', 'Lyon') ->assign('country', 'France'); @@ -826,7 +826,7 @@ Zend_Debug::dump($phpLiveDocx->getDocumentFormats()); ]]> - Get Array of Supported Image File Formats + Get Array of Supported Image File Formats @@ -842,7 +842,7 @@ $phpLiveDocx = new Zend_Service_LiveDocx_MailMerge(); $phpLiveDocx->setUsername('myUsername') ->setPassword('myPassword'); -Zend_Debug::dump($phpLiveDocx->getImageFormats()); +Zend_Debug::dump($phpLiveDocx->getImageExportFormats()); ]]> diff --git a/documentation/manual/en/module_specs/Zend_Service_Yahoo.xml b/documentation/manual/en/module_specs/Zend_Service_Yahoo.xml deleted file mode 100644 index c20faa02094..00000000000 --- a/documentation/manual/en/module_specs/Zend_Service_Yahoo.xml +++ /dev/null @@ -1,1102 +0,0 @@ - -
Zend_Service_Yahoo - - -
Introduction - - - - Zend_Service_Yahoo is a simple API for using - many of the Yahoo! REST APIs. - Zend_Service_Yahoo allows you to search Yahoo! Web search, Yahoo! - News, Yahoo! Local, Yahoo! Images. In order to use the Yahoo! REST - API, you must have a Yahoo! Application ID. To obtain an Application - ID, please complete and submit the Application ID Request Form. - -
- -
Searching the Web with Yahoo! - - - - Zend_Service_Yahoo enables you to search the Web with Yahoo! - using the webSearch() method, which accepts a string query - parameter and an optional second parameter as an array of search options. For full - details and an option list, please visit the Yahoo! Web Search - Documentation. The webSearch() method returns a - Zend_Service_Yahoo_WebResultSet object. - - - Searching the Web with Yahoo! - - - webSearch('PHP'); -foreach ($results as $result) { - echo $result->Title .'
'; -} -]]>
-
-
- -
Finding Images with Yahoo! - - - - You can search for Images with Yahoo using Zend_Service_Yahoo's - imageSearch() method. This method accepts a string query - parameter and an optional array of search options, as for the webSearch() - method. For full details and an option list, please visit the Yahoo! Image - Search Documentation. - - - Finding Images with Yahoo! - - - imageSearch('PHP'); -foreach ($results as $result) { - echo $result->Title .'
'; -} -]]>
-
-
- -
Finding videos with Yahoo! - - - - You can search for videos with Yahoo using Zend_Service_Yahoo's - videoSearch() method. For full details and an option list, - please visit the Yahoo! Video - Search Documentation. - - - Finding videos with Yahoo! - - - videoSearch('PHP'); -foreach ($results as $result) { - echo $result->Title .'
'; -} -]]>
-
-
- -
Finding Local Businesses and Services with Yahoo! - - - - You can search for local businesses and services with Yahoo! by using the - localSearch() method. For full details, please see the Yahoo! Local - Search Documentation. - - - Finding Local Businesses and Services with Yahoo! - - - localSearch('Apple Computers', array('zip' => '95014')); -foreach ($results as $result) { - echo $result->Title .'
'; -} -]]>
-
-
- -
Searching Yahoo! News - - - - Searching Yahoo! News is simple; just use the newsSearch() - method, as in the following example. For full details, please see the Yahoo! News Search - Documentation. - - - Searching Yahoo! News - - - newsSearch('PHP'); -foreach ($results as $result) { - echo $result->Title .'
'; -} -]]>
-
-
- -
Searching Yahoo! Site Explorer Inbound Links - - - - Searching Yahoo! Site Explorer Inbound Links is simple; just use the - inlinkDataSearch() method, as in the following example. For - full details, please see the Yahoo! - Site Explorer Inbound Links Documentation. - - - Searching Yahoo! Site Explorer Inbound Links - - - inlinkDataSearch('http://framework.zend.com/'); -foreach ($results as $result) { - echo $result->Title .'
'; -} -]]>
-
-
- -
Searching Yahoo! Site Explorer's PageData - - - - Searching Yahoo! Site Explorer's PageData is simple; just use the - pageDataSearch() method, as in the following example. For full - details, please see the Yahoo! - Site Explorer PageData Documentation. - - - Searching Yahoo! Site Explorer's PageData - - - pageDataSearch('http://framework.zend.com/'); -foreach ($results as $result) { - echo $result->Title .'
'; -} -]]>
-
-
- -
Zend_Service_Yahoo Classes - - - - The following classes are all returned by the various Yahoo! searches. Each search type - returns a type-specific result set which can be easily iterated, with each result being - contained in a type result object. All result set classes implement the - SeekableIterator interface, allowing for easy iteration and - seeking to a specific result. - - - - - Zend_Service_Yahoo_ResultSet - - - - - - Zend_Service_Yahoo_WebResultSet - - - - - - Zend_Service_Yahoo_ImageResultSet - - - - - - Zend_Service_Yahoo_VideoResultSet - - - - - - Zend_Service_Yahoo_LocalResultSet - - - - - - Zend_Service_Yahoo_NewsResultSet - - - - - - Zend_Service_Yahoo_InlinkDataResultSet - - - - - - Zend_Service_Yahoo_PageDataResultSet - - - - - - Zend_Service_Yahoo_Result - - - - - - Zend_Service_Yahoo_WebResult - - - - - - Zend_Service_Yahoo_ImageResult - - - - - - Zend_Service_Yahoo_VideoResult - - - - - - Zend_Service_Yahoo_LocalResult - - - - - - Zend_Service_Yahoo_NewsResult - - - - - - Zend_Service_Yahoo_InlinkDataResult - - - - - - Zend_Service_Yahoo_PageDataResult - - - - - - Zend_Service_Yahoo_Image - - - - - -
Zend_Service_Yahoo_ResultSet - - - - Each of the search specific result sets is extended from this base class. - - - - Each of the specific result sets returns a search specific Zend_Service_Yahoo_Result - objects. - - -
Zend_Service_Yahoo_ResultSet::totalResults() - - - - - int totalResults - - - - - Returns the number of results returned for the search. - -
- -
Properties - - - Zend_Service_Yahoo_ResultSet - - - - - - Name - Type - Description - - - - - - totalResultsAvailable - int - Total number of results found. - - - - totalResultsReturned - int - Number of results in the current result set - - - - firstResultPosition - int - - - Position of the first result in this set relative to the total - number of results. - - - - -
- - - Back to Class List - -
-
- -
Zend_Service_Yahoo_WebResultSet - - - - Zend_Service_Yahoo_WebResultSet represents a Yahoo! Web - Search result set. - - - - - Zend_Service_Yahoo_WebResultSet extends Zend_Service_Yahoo_ResultSet - - - - - Back to Class List - -
- -
Zend_Service_Yahoo_ImageResultSet - - - - Zend_Service_Yahoo_ImageResultSet represents a Yahoo! Image - Search result set. - - - - - Zend_Service_Yahoo_ImageResultSet extends Zend_Service_Yahoo_ResultSet - - - - - Back to Class List - -
- -
Zend_Service_Yahoo_VideoResultSet - - - - Zend_Service_Yahoo_VideoResultSet represents a Yahoo! Video - Search result set. - - - - - Zend_Service_Yahoo_VideoResultSet extends Zend_Service_Yahoo_ResultSet - - - - - Back to Class List - -
- -
Zend_Service_Yahoo_LocalResultSet - - - - Zend_Service_Yahoo_LocalResultSet represents a Yahoo! Local - Search result set. - - - Zend_Service_Yahoo_LocalResultSet Properties - - - - - - Name - Type - Description - - - - - - resultSetMapURL - string - - - The URL of a webpage containing a map graphic - with all returned results plotted on it. - - - - -
- - - - Zend_Service_Yahoo_LocalResultSet extends Zend_Service_Yahoo_ResultSet - - - - - Back to Class List - -
- -
Zend_Service_Yahoo_NewsResultSet - - - - Zend_Service_Yahoo_NewsResultSet represents a Yahoo! News - Search result set. - - - - - Zend_Service_Yahoo_NewsResultSet extends Zend_Service_Yahoo_ResultSet - - - - - Back to Class List - -
- -
Zend_Service_Yahoo_InlinkDataResultSet - - - - Zend_Service_Yahoo_InlinkDataResultSet represents a Yahoo! - Inbound Link Search result set. - - - - - Zend_Service_Yahoo_InlinkDataResultSet extends Zend_Service_Yahoo_ResultSet - - - - - Back to Class List - -
- -
Zend_Service_Yahoo_PageDataResultSet - - - - Zend_Service_Yahoo_PageDataResultSet represents a Yahoo! - PageData Search result set. - - - - - Zend_Service_Yahoo_PageDataResultSet extends Zend_Service_Yahoo_ResultSet - - - - - Back to Class List - -
- -
Zend_Service_Yahoo_Result - - - - Each of the search specific results is extended from this base class. - - -
Properties - - - Zend_Service_Yahoo_Result Properties - - - - - - Name - Type - Description - - - - - - Title - string - Title of the Result item - - - - Url - string - The URL of the result item - - - - ClickUrl - string - - - The URL for linking to the result item - - - - -
- - - Back to Class List - -
-
- -
Zend_Service_Yahoo_WebResult - - - - Each Web Search result is returned as a - Zend_Service_Yahoo_WebResult object. - - -
Properties - - - Zend_Service_Yahoo_WebResult Properties - - - - - - Name - Type - Description - - - - - - Summary - string - Result summary - - - - MimeType - string - Result MIME type - - - - ModificationDate - string - - - The last modification date of the result as a - UNIX timestamp. - - - - - CacheUrl - string - - - Yahoo! web cache URL for the result, if it - exists. - - - - - CacheSize - int - The size of the Cache entry - - - -
- - - Back to Class List - -
-
- -
Zend_Service_Yahoo_ImageResult - - - - Each Image Search result is returned as a - Zend_Service_Yahoo_ImageResult object. - - -
Properties - - - Zend_Service_Yahoo_ImageResult Properties - - - - - - Name - Type - Description - - - - - - Summary - string - Result summary - - - - RefererUrl - string - - - The URL of the page which contains the image - - - - - FileSize - int - The size of the image file in bytes - - - - FileFormat - string - The format of the image (bmp, gif, jpeg, png, etc.) - - - - Height - int - The height of the image - - - - Width - int - The width of the image - - - - Thumbnail - - - Zend_Service_Yahoo_Image - - - Image thumbnail - - - -
- - - Back to Class List - -
-
- -
Zend_Service_Yahoo_VideoResult - - - - Each Video Search result is returned as a - Zend_Service_Yahoo_VideoResult object. - - -
Properties - - - Zend_Service_Yahoo_VideoResult Properties - - - - - - Name - Type - Description - - - - - - Summary - string - Result summary - - - - RefererUrl - string - - - The URL of the page which contains the video - - - - - FileSize - int - The size of the video file in bytes - - - - FileFormat - string - - - The format of the video (avi, flash, mpeg, msmedia, quicktime, - realmedia, etc.) - - - - - Height - int - The height of the video in pixels - - - - Width - int - The width of the video in pixels - - - - Duration - int - The length of the video in seconds - - - - Channels - int - Number of audio channels in the video - - - - Streaming - boolean - Whether the video is streaming or not - - - - Thumbnail - - - Zend_Service_Yahoo_Image - - - Image thumbnail - - - -
- - - Back to Class List - -
-
- -
Zend_Service_Yahoo_LocalResult - - - - Each Local Search result is returned as a - Zend_Service_Yahoo_LocalResult object. - - -
Properties - - - Zend_Service_Yahoo_LocalResult Properties - - - - - - Name - Type - Description - - - - - - Address - string - Street Address of the result - - - - City - string - City in which the result resides in - - - - State - string - State in which the result resides in - - - - Phone - string - Phone number for the result - - - - Rating - int - User submitted rating for the result - - - - Distance - float - - - The distance to the result from your specified location - - - - - MapUrl - string - A URL of a map for the result - - - - BusinessUrl - string - - - The URL for the business website, if known - - - - - BusinessClickUrl - string - - - The URL for linking to the business website, - if known - - - - -
- - - Back to Class List - -
-
- -
Zend_Service_Yahoo_NewsResult - - - - Each News Search result is returned as a - Zend_Service_Yahoo_NewsResult object. - - -
Properties - - - Zend_Service_Yahoo_NewsResult Properties - - - - - - Name - Type - Description - - - - - - Summary - string - Result summary - - - - NewsSource - string - The company who distributed the article - - - - NewsSourceUrl - string - - - The URL for the company who distributed the - article - - - - - Language - string - The language the article is in - - - - PublishDate - string - - - The date the article was published as a UNIX - timestamp - - - - - ModificationDate - string - - - The date the article was last modified as a - UNIX timestamp - - - - - Thumbnail - - - Zend_Service_Yahoo_Image - - - Image Thumbnail for the article, if it exists - - - -
- - - Back to Class List - -
-
- -
Zend_Service_Yahoo_InlinkDataResult - - - - Each Inbound Link Search result is returned as a - Zend_Service_Yahoo_InlinkDatabResult object. - - - - Back to Class List - -
- -
Zend_Service_Yahoo_PageDataResult - - - - Each Page Data Search result is returned as a - Zend_Service_Yahoo_PageDatabResult object. - - - - Back to Class List - -
- -
Zend_Service_Yahoo_Image - - - - All images returned either by the Yahoo! Image Search or the Yahoo! News Search - are represented by Zend_Service_Yahoo_Image objects - - -
Properties - - - Zend_Service_Yahoo_Image Properties - - - - - - Name - Type - Description - - - - - - Url - string - Image URL - - - - Width - int - Image Width - - - - Height - int - Image Height - - - -
- - - Back to Class List - -
-
-
-
diff --git a/documentation/manual/en/module_specs/Zend_TimeSync-Working.xml b/documentation/manual/en/module_specs/Zend_TimeSync-Working.xml deleted file mode 100644 index 9fabd2e4883..00000000000 --- a/documentation/manual/en/module_specs/Zend_TimeSync-Working.xml +++ /dev/null @@ -1,281 +0,0 @@ - -
Working with Zend_TimeSync - - - - Zend_TimeSync can return the actual time from any given - NTP or SNTP time server. - It can automatically handle multiple servers and provides a simple interface. - - - - - All examples in this chapter use a public, generic time server: - 0.europe.pool.ntp.org. You should use a public, generic time server - which is close to your application server. See http://www.pool.ntp.org for information. - - - -
Generic Time Server Request - - - - Requesting the time from a time server is simple. First, you provide the time server - from which you want to request the time. - - - getDate()->format(DateTime::ISO8601); -]]> - - - So what is happening in the background of Zend_TimeSync? First - the syntax of the time server is checked. In our example, - '0.pool.ntp.org' is checked and recognised as a possible address - for a time server. Then when calling getDate() the actual set - time server is requested and it will return its own time. - Zend_TimeSync then calculates the difference to the actual time - of the server running the script and returns a DateTime object - with the correct time. - - - - For details about DateTime and its methods see the - - DateTimedocumentation. - -
- -
Multiple Time Servers - - - - Not all time servers are always available to return their time. Servers may be - unavailable during maintenance, for example. When the time cannot be requested from the - time server, you will get an exception. - - - - Zend_TimeSync is a simple solution that can handle multiple time - servers and supports an automatic fallback mechanism. There are two supported ways; you - can either specify an array of time servers when creating the instance, or you can add - additional time servers to the instance using the addServer() - method. - - - addServer('3.pool.ntp.org'); - -print $server->getDate()->format(DateTime::ISO8601); -]]> - - - There is no limit to the number of time servers you can add. When a time server can not - be reached, Zend_TimeSync will fallback and try to connect to the - next time server. - - - - When you supply more than one time server- which is considered a best practice for - Zend_TimeSync- you should name each server. You can name your - servers with array keys, with the second parameter at instantiation, or with the second - parameter when adding another time server. - - - '0.pool.ntp.org', - 'fallback' => '1.pool.ntp.org', - 'reserve' => '2.pool.ntp.org')); -$server->addServer('3.pool.ntp.org', 'additional'); - -print $server->getDate()->format(DateTime::ISO8601); -]]> - - - Naming the time servers allows you to request a specific time server as we will see - later in this chapter. - -
- -
Protocols of Time Servers - - - - There are different types of time servers. Most public time servers use the - NTP protocol. But there are other time synchronization - protocols available. - - - - You set the proper protocol in the address of the time server. There are two - protocols which are supported by Zend_TimeSync: - NTP and SNTP. The default protocol is - NTP. If you are using NTP, you can omit the - protocol in the address as demonstrated in the previous examples. - - - 'ntp:\\0.pool.ntp.org', - 'fallback' => 'ntp:\\1.pool.ntp.org', - 'reserve' => 'ntp:\\2.pool.ntp.org')); -$server->addServer('sntp:\\internal.myserver.com', 'additional'); - -print $server->getDate()->format(DateTime::ISO8601); -]]> - - - Zend_TimeSync can handle mixed time servers. So you are not - restricted to only one protocol; you can add any server independently from its protocol. - -
- -
Using Ports for Time Servers - - - - As with every protocol within the world wide web, the NTP and - SNTP protocols use standard ports. NTP uses port - 123 and SNTP uses port 37. - - - - But sometimes the port that the protocols use differs from the standard one. You can - define the port which has to be used for each server within the address. Just add the - number of the port after the address. If no port is defined, then - Zend_TimeSync will use the standard port. - - - 'ntp:\\0.pool.ntp.org:200', - 'fallback' => 'ntp:\\1.pool.ntp.org')); -$server->addServer('sntp:\\internal.myserver.com:399', 'additional'); - -print $server->getDate()->format(DateTime::ISO8601); -]]> -
- -
Time Servers Options - - - - There is only one option within Zend_TimeSync which will be used - internally: timeout. You can set any self-defined option you are in - need of and request it, however. - - - - The option timeout defines the number of seconds after which - a connection is detected as broken when there was no response. The default value is - 1, which means that Zend_TimeSync will - fallback to the next time server if the requested time server does not respond in one - second. - - - - With the setOptions() method, you can set any option. This - function accepts an array where the key is the option to set and the value is the value - of that option. Any previously set option will be overwritten by the new value. If you - want to know which options are set, use the getOptions() - method. It accepts either a key which returns the given option if specified, or, if no - key is set, it will return all set options. - - - 3, 'myoption' => 'timesync')); -$server = new Zend_TimeSync(array('generic' => 'ntp:\\0.pool.ntp.org', - 'fallback' => 'ntp:\\1.pool.ntp.org')); -$server->addServer('sntp:\\internal.myserver.com', 'additional'); - -print $server->getDate()->format(DateTime::ISO8601); -print_r(Zend_TimeSync::getOptions(); -print "Timeout = " . Zend_TimeSync::getOptions('timeout'); -]]> - - - As you can see, the options for Zend_TimeSync are static. Each - instance of Zend_TimeSync will use the same options. - -
- -
Using Different Time Servers - - - - Zend_TimeSync's default behavior for requesting a time is to - request it from the first given server. But sometimes it is useful to set a different - time server from which to request the time. This can be done with the - setServer() method. To define the used time server set the - alias as a parameter within the method. To get the actual used time server call the - getServer() method. It accepts an alias as a parameter which - defines the time server to be returned. If no parameter is given, the current time - server will be returned. - - - 'ntp:\\0.pool.ntp.org', - 'fallback' => 'ntp:\\1.pool.ntp.org')); -$server->addServer('sntp:\\internal.myserver.com', 'additional'); - -$actual = $server->getServer(); -$server = $server->setServer('additional'); -]]> -
- -
Information from Time Servers - - - - Time servers not only offer the time itself, but also additional information. You can - get this information with the getInfo() method. - - - 'ntp:\\0.pool.ntp.org', - 'fallback' => 'ntp:\\1.pool.ntp.org')); - -print_r ($server->getInfo()); -]]> - - - The returned information differs with the protocol used and can also differ with the - server used. - -
- -
Handling Exceptions - - - - Exceptions are collected for all time servers and returned as an array. So you can - iterate through all thrown exceptions as shown in the following example: - - - 'ntp://a.foo.bar.org', - 'invalid_b' => 'sntp://b.foo.bar.org', -); - -$server = new Zend_TimeSync($serverlist); - -try { - $result = $server->getDate(); - echo $result->format(DateTime::ISO8601); -} catch (Zend_TimeSync_Exception $e) { - - $exceptions = $e->get(); - - foreach ($exceptions as $key => $myException) { - echo $myException->getMessage(); - echo '
'; - } -} -]]>
-
-
diff --git a/documentation/manual/en/module_specs/Zend_TimeSync.xml b/documentation/manual/en/module_specs/Zend_TimeSync.xml deleted file mode 100644 index 62ad90391c5..00000000000 --- a/documentation/manual/en/module_specs/Zend_TimeSync.xml +++ /dev/null @@ -1,202 +0,0 @@ - - - -
Introduction - - - - Zend_TimeSync is able to receive internet or network time from a time - server using the NTP or SNTP protocol. - With Zend_TimeSync, Zend Framework is able to act independently from - the time settings of the server where it is running. - - - - To be independent from the actual time of the server, Zend_TimeSync - works with the difference of the real time which is sent through NTP or SNTP and the - internal server's time. - - - Background - - - - Zend_TimeSync is not able to change the server's time, but it - will return a DateTime instance from - which the difference from the server's time can be worked with. - - - -
Why Zend_TimeSync ? - - - - So why would someone use Zend_TimeSync ? - - - - Normally every server within a multi-server farm will have a service running which - synchronizes its own time with a time server. So within a standard environment it should - not be necessary to use Zend_TimeSync. But it can become handy if - there is no service available and if you don't have the right to install such a service. - - - - Here are some example use cases, for which Zend_TimeSync is - perfect suited: - - - - - - Server without time service - - - - If your application is running on a server and this server does not have any - time service running, it may make sense to use - Zend_TimeSync in your application. - - - - - - Separate database server - - - - If your database is running on a different server and this server is not - connected with NTP or SNTP - to the application server, you might have problems using storing and using time - stamp data. - - - - - - Multiple servers - - - - If your application is running on more than one server and these servers' time - bases are not syncronized, you can expect problems within your application when - part of the application is coming from one server and another part from another - server. - - - - - - Batch processing - - - - If you want to work with a time service within a batch file or within a - command line application, Zend_TimeSync may be of use. - - - - - - Zend_TimeSync may provide a good solution in all of these cases - and can be used if you are unable to run any services on your server. - -
- -
What is NTP ? - - - - The Network Time Protocol (NTP) is a protocol - for synchronizing multiple systems' clocks over packet-switched, variable-latency data - networks. NTP uses UDP port 123 as its transport layer. See the wikipedia article - for details about this protocol. - -
- -
What is SNTP? - - - - The Simple Network Time Protocol (SNTP) is a - protocol synchronizing multiple systems' clocks over packet-switched, variable-latency - data networks. SNTP uses UDP port 37 as its transport layer. It is closely related to - the Network Time Protocol, but simpler. - -
- -
Problematic usage - - - - Be warned that when you are using Zend_TimeSync you will have to - think about some details related to the structure of time sync and the internet itself. - Correct usage and best practices will be described here. Read carefully before you begin - using Zend_TimeSync. - -
- -
Decide which server to use - - - - You should select the time server that you want to use very carefully according to the - following criteria: - - - - - - Distance - - - - The distance from your application server to the time server. If your server is - in Europe, it would make little sense to select a time server in Tahiti. Always - select a server which is not far away. This reduces the request time and overall - network load. - - - - - - Speed - - - - How long it takes to receive the request is also relevant. Try different servers - to get the best result. If you are requesting a server which is never - accessible, you will always have an unnecessary delay. - - - - - - Splitting - - - - Do not always use the same server. All time servers will lock out requests from - servers that are flooding the server. If your application requires heavy use of - time servers, you should consider one of the pools described later. - - - - - - So where can you find a time server? Generally you can use any timeserver you can - connect to. This can be a time server within your LAN or any public time server you have - access to. If you decide to use a public time server, you should consider using a server - pool. Server pools are public addresses from which you will get a random, pooled time - server by requesting the time. This way you will not have to split your requests. There - are public server pools available for many regions which you may use to avoid problems - mentioned above. - - - - See pool.ntp.org to find your nearest - server pool. For example, if your server is located within Germany you can connect to - 0.europe.pool.ntp.org. - -
-
diff --git a/documentation/manual/en/module_specs/Zend_Tool-Extending.xml b/documentation/manual/en/module_specs/Zend_Tool-Extending.xml deleted file mode 100644 index ea60a0d6fe1..00000000000 --- a/documentation/manual/en/module_specs/Zend_Tool-Extending.xml +++ /dev/null @@ -1,885 +0,0 @@ - -
Extending Zend_Tool - - -
Overview of Zend_Tool - - - - Zend_Tool_Framework is a framework for exposing common - functionalities such as the creation of project scaffolds, code - generation, search index generation, and much more. Functionality may be - written and exposed via PHP classes dropped into the - PHP include_path, providing incredible - flexibility of implementation. The functionality may then be consumed by writing - implementation and/or protocol-specific clients -- such as console - clients, XML-RPC, SOAP, and much more. - - - - Zend_Tool_Project builds on and extends the capabilities of - Zend_Tool_Framework to that of managing a "project". In general, - a "project" is a planned endeavor or an initiative. In the computer world, projects - generally are a collection of resources. These resources can be files, directories, - databases, schemas, images, styles, and more. - -
- -
Zend_Tool_Framework Extensions - - -
Overall Architecture - - - - Zend_Tool_Framework provides the following: - - - - - - Common interfaces and abstracts that allow - developers to create functionality and capabilities that are - dispatchable by tooling clients. - - - - - - Base client functionality and a concrete - console implementation that connect external tools and - interfaces to the Zend_Tool_Framework. The Console - client may be used in CLI environments such as unix - shells and the Windows console. - - - - - - "Provider" and "Manifest" interfaces that - can be utilized by the tooling system. "Providers" represent the - functional aspect of the framework, and define the actions that - tooling clients may call. "Manifests" act as metadata registries - that provide additional context for the various defined - providers. - - - - - - An introspective loading system that will - scan the environment for providers and determine what is - required to dispatch them. - - - - - - A standard set of system providers that - allow the system to report what the full capabilities of the - system are as well as provide useful feedback. This also - includes a comprehensive "Help System". - - - - - - Definitions that you should be aware of through this manual with respect - to Zend_Tool_Framework include: - - - - - - Zend_Tool_Framework - The framework which exposes - tooling capabilities. - - - - - - Tooling Client - A developer tool that connects - to and consumes Zend_Tool_Framework. - - - - - - Client - The subsystem of - Zend_Tool_Framework that exposes an interface such - that tooling clients can connect, query and execute commands. - - - - - - Console Client / Command Line Interface / - zf.php - The tooling client for the command - line. - - - - - Provider - A subsystem and a collection of - built-in functionality that the framework exports. - - - - - - Manifest - A subsystem for defining, - organizing, and disseminating provider requirement data. - - - - - - Zend_Tool_Project Provider - A set of providers - specifically for creating and maintaining Zend Framework-based - projects. - - - -
- -
Understanding the CLI Client - - - - The CLI, or command line tool (internally known as the console - tool), is currently the primary interface for dispatching - Zend_Tool requests. With the CLI tool, - developers can issue tooling requests inside the "command line windows", also - commonly known as a "terminal" window. This environment is predominant in the *nix - environment, but also has a common implementation in windows with the - cmd.exe, console2 and also with the Cygwin project. - - -
Setting up the CLI tool - - - - To issue tooling requests via the command line client, you first - need to set up the client so that your system can handle the "zf" - command. The command line client, for all intents and purposes, is - the .sh or .bat file that is provided - with your Zend Framework distribution. In trunk, it can be found here: - http://framework.zend.com/svn/framework/standard/trunk/bin/. - - - - As you can see, there are 3 files in the /bin/ - directory: a zf.php, zf.sh, and - zf.bat. The zf.sh and the - zf.bat are the operating system specific client - wrappers: zf.sh for the *nix environment, and - zf.bat for the Win32 environment. These client wrappers are - responsible for finding the proper php.exe, finding the - zf.php, and passing on the client request. The - zf.php is the responsible for handling understanding - your environment, constructing the proper include_path, and passing - what is provided on the command line to the proper library component - for dispatching. - - - - Ultimately, you want to ensure two things to make everything work - regardless of the operating system you are on: - - - - - - zf.sh/zf.bat is reachable from your system - path. This is the ability to call zf from - anywhere on your command line, regardless of what your - current working directory is. - - - - - - ZendFramework/library is in your - include_path. - - - - - - - Note: while the above are the most ideal - requirements, you can simply download Zend Framework and expect it - to work as ./path/to/zf.php some command. - - -
- -
Setting up the CLI tool on Unix-like Systems - - - - The most common setup in the *nix environment, is to copy the - zf.sh and zf.php into the same - directory as your PHP binary. This can generally be found in - one of the following places: - - - - - - To find out the location of your PHP binary, you can execute - 'which php' on the command line. This will return the location of the - PHP binary you will be using to run PHP - scripts in this environment. - - - - The next order of business is to ensure that Zend Framework - library is set up correctly inside of the system PHP - include_path. To find out where your - include_path is located, you can execute - php -i and look for the include_path - variable, or more succinctly, execute - php -i | grep include_path. Once you have found where - your include_path is located (this will generally be - something like /usr/lib/php, - /usr/share/php, /usr/local/lib/php, or - similar), ensure that the contents of the /library/ - directory are put inside your include_path specified - directory. - - - - Once you have done those two things, you should be able to issue a - command and get back the proper response like this: - - - - - - - - If you do not see this type of output, go back and check your setup - to ensure you have all of the necessary pieces in the proper place. - - - - There are a couple of alternative setups you might want to employ - depending on your servers configuration, your level of access, or - for other reasons. - - - - Alternative Setup involves keeping the Zend - Framework download together as is, and creating a link from a - PATH location to the zf.sh. What this - means is you can place the contents of the ZendFramework download into a - location such as /usr/local/share/ZendFramework, or more - locally like /home/username/lib/ZendFramework, and creating - a symbolic link to the zf.sh. - - - - Assuming you want to put the link inside /usr/local/bin - (this could also work for placing the link inside - /home/username/bin/ for example) you would issue a - command similar to this: - - - - - - This will create a link which you should be able to access globally - on the command line. - -
- -
Setting up the CLI tool on Windows - - - - The most common setup in the Windows Win32 environment, is to copy - the zf.bat and zf.php into the same - directory as your PHP binary. This can generally be found in - one of the following places: - - - - - - You should be able to run php.exe on the command line. - If you are not able to, first check the documentation that came with - your PHP distribution, or ensure that the path to - php.exe is in your - Windows PATH environment variable. - - - - The next order of business is to ensure that Zend Framework - library is set up correctly inside of the system PHP - include_path. To find out where your - include_path is located, you can type - php -i and look for the include_path - variable, or more succinctly execute - php -i | grep include_path if you have Cygwin setup with - grep available. Once you have found where your - include_path is located (this will generally be - something like C:\PHP\pear, - C:\PHP\share, - C:\Program%20Files\ZendServer\share or similar), ensure - that the contents of the library/ directory are put inside your - include_path specified directory. - - - - Once you have done those two things, you should be able to issue a - command and get back the proper response like this: - - - - - - - - If you do not see this type of output, go back and check your setup - to ensure you have all of the necessary pieces in the proper place. - - - - There are a couple of alternative setups you might want to employ - depending on your server's configuration, your level of access, or - for other reasons. - - - - Alternative Setup involves keeping the Zend - Framework download together as is, and altering both your system - PATH as well as the php.ini file. - In your user's environment, make sure to add - C:\Path\To\ZendFramework\bin, so that your - zf.bat file is executable. Also, alter the - php.ini file to ensure that - C:\Path\To\ZendFramework\library is in your - include_path. - -
- -
Other Setup Considerations - - - - If for some reason you do not want Zend Framework library inside - your include_path, there is another option. There are - two special environment variables that zf.php will - utilize to determine the location of your Zend Framework - installation. - - - - The first is ZEND_TOOL_INCLUDE_PATH_PREPEND, which will - prepend the value of this environment variable to the system - (php.ini) include_path before loading - the client. - - - - Alternatively, you might want to use - ZEND_TOOL_INCLUDE_PATH to completely - replace the system include_path - for one that makes sense specifically for the zf - command line tool. - -
-
- -
Creating Providers - - - - In general, a provider, on its own, is nothing more than the shell for a - developer to bundle up some capabilities they wish to dispatch with the - command line (or other) clients. It is an analogue to what a - "controller" is inside of your MVC application. - - -
How Zend_Tool finds your Providers - - - - By default Zend_Tool uses the BasicLoader to find all - the providers that you can run. It recursivly iterates all - include path directories and opens all files that end - with "Manifest.php" or "Provider.php". All classes in these - files are inspected if they implement either - Zend_Tool_Framework_Provider_Interface - or Zend_Tool_Framework_Manifest_ProviderManifestable. - Instances of the provider interface make up for the real functionality - and all their public methods are accessible as provider actions. - The ProviderManifestable interface however requires the implementation of a - method getProviders() which returns an array of - instantiated provider interface instances. - - - - The following naming rules apply on how you can access the providers - that were found by the IncludePathLoader: - - - - - - The last part of your classname split by underscore is used - for the provider name, e.g. "My_Provider_Hello" leads to your - provider being accessible by the name "hello". - - - - - - If your provider has a method getName() - it will be used instead of the previous method to determine - the name. - - - - - - If your provider has "Provider" as prefix, e.g. it is called - My_HelloProvider it will be stripped - from the name so that the provider will be called "hello". - - - - - - The IncludePathLoader does not follow symlinks, that means - you cannot link provider functionality into your include paths, - they have to be physically present in the include paths. - - - Exposing Your Providers with a Manifest - - - - You can expose your providers to Zend_Tool by - offering a manifest with a special filename ending with "Manifest.php". - A Provider Manifest is an implementation of the - Zend_Tool_Framework_Manifest_ProviderManifestable - and requires the getProviders() method to return - an array of instantiated providers. In anticipation of our first - own provider My_Component_HelloProvider - we will create the following manifest: - - - - -
- -
Basic Instructions for Creating Providers - - - - As an example, if a developer wants to add the capability of showing - the version of a datafile that his 3rd party component is working - from, there is only one class the developer would need to implement. - Assuming the component is called My_Component, he would - create a class named My_Component_HelloProvider in a - file named HelloProvider.php somewhere on the - include_path. This class would implement - Zend_Tool_Framework_Provider_Interface, and the body of - this file would only have to look like the following: - - - - - - Given that code above, and assuming the developer wishes to access - this functionality through the console client, the call would look - like this: - - - -
- -
The response object - - - - As discussed in the architecture section Zend_Tool allows - to hook different clients for using your Zend_Tool - providers. To keep compliant with different clients you should use the response - object to return messages from your providers instead of using - echo() or a similiar output mechanism. Rewritting our - hello provider with this knowledge it looks like: - - - _registry->getResponse - ->appendContent("Hello from my provider!"); - } -} -]]> - - - As you can see one has to extend the - Zend_Tool_Framework_Provider_Abstract to gain access to - the Registry which holds the - Zend_Tool_Framework_Client_Response instance. - -
- -
Advanced Development Information - - -
Passing Variables to a Provider - - - - The above "Hello World" example is great for simple commands, but - what about something more advanced? As your scripting and tooling - needs grow, you might find that you need the ability to accept - variables. Much like function signatures have parameters, your - tooling requests can also accept parameters. - - - - Just as each tooling request can be isolated to a method within a - class, the parameters of a tooling request can also be isolated in a - very well known place. Parameters of the action methods of a - provider can include the same parameters you want your client to - utilize when calling that provider and action combination. For - example, if you wanted to accept a name in the above example, you - would probably do this in OO code: - - - - - - The above example can then be called via the command line - zf say hello Joe. "Joe" will be supplied to the provider - as a parameter of the method call. Also note, as you see that the - parameter is optional, that means it is also optional on the command - line, so that zf say hello will still work, and default - to the name "Ralph". - -
- -
Prompt the User for Input - - - - There are cases when the workflow of your provider requires - to prompt the user for input. This can be done by requesting - the client to ask for more the required input by calling: - - - _registry - ->getClient() - ->promptInteractiveInput("Whats your name?"); - $name = $name->getContent(); - - echo 'Hello' . $name . ', from my provider!'; - } -} -]]> - - - This command throws an exception if the current client is not - able to handle interactive requests. In case of the default Console Client - however you will be asked to enter the name. - -
- -
Pretending to execute a Provider Action - - - - Another interesting feature you might wish to implement is - pretendability. Pretendabilty is the ability - for your provider to "pretend" as if it is doing the requested - action and provider combination and give the user as much - information about what it would do without - actually doing it. This might be an important notion when doing - heavy database or filesystem modifications that the user might not - otherwise want to do. - - - - Pretendability is easy to implement. There are two parts to this - feature: 1) marking the provider as having the ability to "pretend", - and 2) checking the request to ensure the current request was indeed - asked to be "pretended". This feature is demonstrated in the code - sample below. - - - _registry->getRequest()->isPretend()) { - echo 'I would say hello to ' . $name . '.'; - } else { - echo 'Hello' . $name . ', from my provider!'; - } - } -} -]]> - - - To run the provider in pretend mode just call: - - - -
- -
Verbose and Debug modes - - - - You can also run your provider actions in "verbose" or "debug" modes. - The semantics in regard to this actions have to be implemented by you - in the context of your provider. You can access debug or verbose modes - with: - - - _registry->getRequest()->isVerbose()) { - echo "Hello::say has been called\n"; - } - if($this->_registry->getRequest()->isDebug()) { - syslog(LOG_INFO, "Hello::say has been called\n"); - } - } -} -]]> -
- -
Accessing User Config and Storage - - - - Using the Enviroment variable ZF_CONFIG_FILE or the - .zf.ini in your home directory you can inject configuration parameters into - any Zend_Tool provider. Access to this configuration - is available via the registry that is passed to your provider if you extend - Zend_Tool_Framework_Provider_Abstract. - - - _registry->getConfig()->username; - if(!empty($username)) { - echo "Hello $username!"; - } else { - echo "Hello!"; - } - } -} -]]> - - - The returned configuration is of the type - Zend_Tool_Framework_Client_Config but internally the - __get() and __set() magic - methods proxy to a Zend_Config of the given - configuration type. - - - - The storage allows to save arbitrary data for later reference. This can be - useful for batch processing tasks or for re-runs of your tasks. You can - access the storage in a similar way like the configuration: - - - _registry->getStorage()->get("myUsername"); - echo "Hello $aValue!"; - } -} -]]> - - - The API of the storage is very simple: - - - - - - - When designing your providers that are config or storage aware remember - to check if the required user-config or storage keys really exist for a - user. You won't run into fatal errors when none of these are provided - though, since empty ones are created upon request. - - -
-
-
-
- -
Zend_Tool_Project Extensions - - - - Zend_Tool_Project exposes a rich set of functionality and - capabilities that make the task of creating new providers, specficially those targetting - project easier and more manageable. - - -
Overall Architecture - - - - This same concept applies to Zend Framework projects. In Zend Framework projects, - you have controllers, actions, views, models, databases and so on and so forth. In - terms of Zend_Tool, we need a way to track these types of - resources - thus Zend_Tool_Project. - - - - Zend_Tool_Project is capable of tracking project resources - throughout the development of a project. So, for example, if in one command you - created a controller, and in the next command you wish to create an action within - that controller, Zend_Tool_Project is gonna have to - know about the controller file you created so that you can (in - the next action), be able to append that action to it. This is what keeps our - projects up to date and stateful. - - - - Another important point to understand about projects is that typically, resources - are organized in a hierarchical fashion. With that in mind, - Zend_Tool_Project is capable of serializing the current - project into a internal representation that allows it to keep track of not only - what resources are part of a project at any given time, but - also where they are in relation to one another. - -
- - -
Creating Providers - - - - Project specific providers are created in the same fashion as plain framework - providers, with one exception: project providers must extend the - Zend_Tool_Project_Provider_Abstract. This class comes with - some significant functionality that helps developers load existing project, obtian - the profile object, and be able to search the profile, then later store any changes - to the current project profile. - - - _loadExistingProfile(); - - /* ... do project stuff here */ - - $this->_storeProfile(); - } -} -]]> -
- - -
-
diff --git a/documentation/manual/en/module_specs/Zend_Tool-Usage-CLI.xml b/documentation/manual/en/module_specs/Zend_Tool-Usage-CLI.xml deleted file mode 100644 index 5482974a767..00000000000 --- a/documentation/manual/en/module_specs/Zend_Tool-Usage-CLI.xml +++ /dev/null @@ -1,596 +0,0 @@ - -
Using Zend_Tool On The Command Line - - - - The CLI, or command line tool (internally known as the console tool), - is currently the primary interface for dispatching Zend_Tool - requests. With the CLI tool, developers can issue tooling requests - inside the "command line window", also commonly known as a "terminal" window. This - environment is predominant in the *nix environment, but also has a common implementation - in windows with the cmd.exe, console2 and also with the Cygwin project. - - - - -
Installation - - -
Download And Go - - - - First download Zend Framework. This can be done by going to framework.zend.com - and downloading the latest release. After you've downloaded the package and placed - it on your system. The next step is to make the zf command available to your - system. The easiest way to do this, is to copy the proper files from the bin/ - directory of the download, and place these files within the - same directory as the location of the PHP - cli binary. - -
- -
Installing Via Pear - - - - To install via PEAR, you must use the 3rd party zfcampus.org site to retrieve the - latest Zend Framework PEAR package. These packages are typically built within a day - of an official Zend Framework release. The benefit of installing via the PEAR - package manager is that during the install process, the ZF library will end up on - the include_path, and the zf.php and zf scripts will end up in a place on your - system that will allow you to run them without any additional setup. - - - - - - That is it. After the initial install, you should be able to continue on by - running the zf command. Go good way to check to see if it't there is to run - zf --help - -
- -
Installing by Hand - - - - Installing by hand refers to the process of forcing the zf.php and Zend Framework - library to work together when they are placed in non-convential places, or at least, - in a place that your system cannot dispatch from easily (typical of programs in your - system PATH). - - - - If you are on a *nix or mac system, you can also create a link from somewhere in - your path to the zf.sh file. If you do this, you do not need to worry about having - Zend Framework's library on your include_path, as the zf.php and zf.sh files will - be able to access the library relative to where they are (meaning the ./bin/ files - are ../library/ relative to the Zend Framework library). - - - - There are a number of other options available for setting up the zf.php and library - on your system. These options revolve around setting specific environment - variables. These are described in the later section on "customizing the CLI - environement". The environment variables for setting the zf.php include_path, - ZF_INCLUDE_PATH and ZF_INCLUDE_PATH_PREPEND, are the ones of most interest. - -
-
- -
General Purpose Commands - - -
Version - - - - This will show the current version number of the copy of Zend Framework the zf.php - tool is using. - - - -
- -
Built-in Help - - - - The built-in help system is the primary place where you can get up-to-date - information on what your system is capable of doing. The help system is dynamic in - that as providers are added to your system, they are automatically dispatchable, and - as such, the parameters required to run them will be in the help screen. The - easiest way to retrieve the help screen is the following: - - - - - - This will give you an overview of the various capabilities of the system. - Sometimes, there are more finite commands than can be run, and to gain more - information about these, you might have to run a more specialized help command. - For specialized help, simply replace any of the elements of the command with a "?". - This will tell the help system that you want more information about what commands - can go in place of the question mark. For example: - - - - - - The above means "show me all 'actions' for the provider 'controller'"; while the - following: - - - - - - means "show me all providers that support the 'show' action". This works for - drilling down into options as well as you can see in the following examples: - - - -
- -
Manifest - - - - This will show what information is in the tooling systems manifest. This is more - important for provider developers than casual users of the tooling system. - - - -
- - -
- -
Project Specific Commands - - -
Project - - - - The project provider is the first command you might want to run. This will setup the - basic structure of your application. This is required before any of the other - providers can be executed. - - - - - - This will create a project in a directory called ./MyProjectName. From this point - on, it is important to note that any subsequent commands on the command line must be - issued from within the project directory you had just created. So, after creation, - changing into that directory is required. - -
- -
Project - - - - The module provider allows for the easy creation of a Zend Framework module. A - module follows the hMVC pattern loosely. When creating modules, it will take the - same structure used at the application/ level, and duplicate it inside of the chosen - name for your module, inside of the "modules" directory of the application/ - directory without duplicating the modules directory itself. For example: - - - - - - This will create a module named Blog at application/modules/Blog, and all of the - artifacts that a module will need. - -
- -
Controller - - - - The controller provider is responsible for creating (mostly) empty controllers as - well as their corresponding view script directories and files. To utilize it to - create an 'Auth' controlller, for example, execute: - - - - - - This will create a controller named Auth, specifically it will create a file at - application/controllers/AuthController.php with the AuthController inside. - If you wish to create a controller for a module, use any of the following: - - - - - - Note: In the first command, 1 is the value for the "includeIndexAction" flag. - -
- -
Action - - - - To create an action within an existing controller: - - - -
- -
View - - - - To create a view outside of the normal controller/action creation, you would use - one of the following: - - - - - - This will create a view script in the controller folder of Auth. - -
- -
Model - - - - The model provider is only responsible for creating the proper model files, - with the proper name inside the application folder. For example - - - - - - If you wish to create a model within a specific module: - - - - - - The above will create a 'Post' model inside of the 'Blog' module. - -
- -
Form - - - - The form provider is only responsible for creating the proper form file and - init() method, with the proper name inside the application folder. For example: - - - - - - If you wish to create a model within a specific module: - - - - - - The above will create a 'Comment' form inside of the 'Blog' module. - -
- -
DbAdapter - - - - To configure a DbAdapter, you will need to provide the information as a url - encoded string. This string needs to be in quotes on the command line. - - - - For example, to enter the following information: - - - - adapter: Pdo_Mysql - - - - username: test - - - - password: test - - - - dbname: test - - - - The following will have to be run on the command line: - - - - - - This assumes you wish to store this information inside of the - 'production' space of the application configuration file. The following will - demonstrate an sqlite configuration, in the 'development' section of the - application config file. - - - -
- -
DbTable - - - - The DbTable provider is responsible for creating - Zend_Db_Table model/data access files for your application to - consume, with the proper class name, and in the proper location in the application. - The two important pieces of information are the DbTable name, - and the actual database table name. For example: - - - - - - The DbTable provider is also capable of creating the proper files by - scanning the database configured with the above DbAdapter provider. - - - - - - When executing the above, it might make sense to use the pretend / "-p" - flag first so that you can see what would be done, and what tables can - be found in the database. - - - -
- -
Layout - - - - Currently, the only supported action for layouts is simply to enable them - will setup the proper keys in the application.ini file for the application - resource to work, and create the proper directories and layout.phtml file. - - - -
-
- -
Environment Customization - - -
The Storage Directory - - - - The storage directory is important so that providers may have a place to find - custom user generated logic that might change the way they behave. One example - can be found below is the placement of a custom project profile file. - - - -
- -
The Configuration File - - - - This will create the proper zf.ini file. This should - be run after zf --setup storage-directory. If it is not, it will - be located inside the users home directory. If it is, it will be located inside - the users storage directory. - - - -
- -
Environment Locations - - - - These should be set if you wish to override the default places where zf will - attempt to read their values. - - - - - ZF_HOME - - - - the directory this tool will look for a home directory - - - directory must exist - - - search order: - - - ZF_HOME environment variable - HOME environment variable - then HOMEPATH environment variable - - - - - - - ZF_STORAGE_DIRECTORY - - - - where this tool will look for a storage directory - - - directory must exist - - - search order: - - - - ZF_STORAGE_DIRECTORY environment variable - - - $homeDirectory/.zf/ directory - - - - - - - ZF_CONFIG_FILE - - - - where this tool will look for a configuration file - - - - search order: - - - - ZF_CONFIG_FILE environment variable - - - - $homeDirectory/.zf.ini file if it exists - - - - $storageDirectory/zf.ini file if it exists - - - - - - - - ZF_INCLUDE_PATH - - - - set the include_path for this tool to use this value - - - - original behavior: - - - - - use PHP's include_path to find ZF - - - - - use the ZF_INCLUDE_PATH environment variable - - - - - use the path ../library (relative to zf.php) to find ZF - - - - - - - - - ZF_INCLUDE_PATH_PREPEND - - - - prepend the current php.ini include_path with this value - - - - -
-
-
diff --git a/documentation/manual/en/module_specs/Zend_Tool_Framework-Architecture.xml b/documentation/manual/en/module_specs/Zend_Tool_Framework-Architecture.xml deleted file mode 100644 index 156aaab4a02..00000000000 --- a/documentation/manual/en/module_specs/Zend_Tool_Framework-Architecture.xml +++ /dev/null @@ -1,406 +0,0 @@ - -
Architecture - - -
Registry - - - - Because providers and manifests may come from anywhere in the - include_path, a registry is provided to simplify access - to the various pieces of the toolchain. This registry is injected - into registry-aware components, which may then pull dependencies - from them as necessary. Most dependencies registered with the - registry will be sub-component-specific repositories. - - - - The interface for the registry consists of the following definition: - - - - - - The various objects the registry manages will be discussed in their - appropriate sections. - - - - Classes that should be registry-aware should implement - Zend_Tool_Framework_Registry_EnabledInterface. This - interface merely allows initialization of the registry in the target - class. - - - -
- -
Providers - - - - Zend_Tool_Framework_Provider represents the functional - or "capability" aspect of the framework. Fundamentally, - Zend_Tool_Framework_Provider will provide the - interfaces necessary to produce "providers", or bits of tooling - functionality that can be called and used inside the - Zend_Tool_Framework toolchain. The simplistic nature of - implementing this provider interface allows the developer a - "one-stop-shop" of adding functionality or capabilities to - Zend_Tool_Framework. - - - - The provider interface is an empty interface and enforces no methods - (this is the Marker Interface pattern): - - - - - - Or, if you wish, you can implement the base (or abstract) Provider - which will give you access to the - Zend_Tool_Framework_Registry: - - - -
- -
Loaders - - - - The purpose of a Loader is to find Providers and Manifest files that - contain classes which implement either - Zend_Tool_Framework_Provider_Interface or - Zend_Tool_Framework_Manifest_Interface. Once these files are - found by a loader, providers are loaded into the Provider Repository and - manifest metadata is loaded into the Manifest Repository. - - - - To implement a loader, one must extend the following abstract class: - - - - - - The _getFiles() method should return an array of files - (absolute paths). The built-in loader supplied with Zend Framework is called the - IncludePath loader. By default, the Tooling framework will use an - include_path based loader to find files that might include Providers - or Manifest Metadata objects. - Zend_Tool_Framework_Loader_IncludePathLoader, without - any other options, will search for files inside the include path - that end in Mainfest.php, Tool.php or - Provider.php. Once found, they will be tested (by the - load() method of the - Zend_Tool_Framework_Loader_Abstract) to determine if - they implement any of the supported interfaces. If they do, an - instance of the found class is instantiated, and it is appended to - the proper repository. - - - - - - As you can see, the IncludePath loader will search all include_paths - for the files that match the $_filterAcceptFilePattern - and not match the $_filterDenyDirectoryPattern. - -
- -
Manifests - - - - In short, the Manifest shall contain specific or arbitrary metadata - that is useful to any provider or client, as well as be responsible - for loading any additional providers into the provider repository. - - - - To introduce metadata into the manifest repository, all one must do - is implement the empty Zend_Tool_Framework_Manifest_Interface, - and provide a getMetadata() method which shall return an array - of objects that implement Zend_Tool_Framework_Manifest_Metadata. - - - - - - Metadata objects are loaded (by a loader defined below) into the - Manifest Repository (Zend_Tool_Framework_Manifest_Repository). - Manifests will be processed after all Providers have been found to be - loaded into the provider repository. This shall allow Manifests to - create Metadata objects based on what is currently inside the - provider repository. - - - - There are a few different metadata classes that can be used to - describe metadata. The - Zend_Tool_Framework_Manifest_Metadata is the base - metadata object. As you can see by the following code - snippet, the base metadata class is fairly lightweight and - abstract in nature: - - - - - - There are other built in metadata classes as well for describing - more specialized metadata: ActionMetadata and - ProviderMetadata. These classes will help you describe - in more detail metadata that is specific to either actions or - providers, and the reference is expected to be a reference to an - action or a provider respectively. These classes are described in - the following code snippet. - - - - - - 'Type' in these classes is used to describe the type of metadata the - object is responsible for. In the cases of the - ActionMetadata, the type would be 'Action', and - conversely in the case of the ProviderMetadata the type - is 'Provider'. These metadata types will also include additional - structured information about both the "thing" they are describing as - well as the object (the getReference()) they are - referencing with this new metadata. - - - - In order to create your own metadata type, all one must do is extend - the base Zend_Tool_Framework_Manifest_Metadata class - and return these new metadata objects via a local Manifest - class or object. These user based classes will live in the Manifest - Repository - - - - Once these metadata objects are in the repository, there are then two - different methods that can be used in order to search for them in - the repository. - - - findMetadatas(array( - * 'action' => 'Foo', - * 'name' => 'cliActionName' - * )); - * - * Will find any metadata objects that have a key with name 'action' value - * of 'Foo', AND a key named 'name' value of 'cliActionName' - * - * Note: to either exclude or include name/value pairs that exist in the - * search criteria but do not appear in the object, pass a bool value to - * $includeNonExistentProperties - */ - public function findMetadatas(Array $searchProperties = array(), - $includeNonExistentProperties = true); - - /** - * The following will return exactly one of the matching search criteria, - * regardless of how many have been returned. First one in the manifest is - * what will be returned. - */ - public function findMetadata(Array $searchProperties = array(), - $includeNonExistentProperties = true) - { - $metadatas = $this->getMetadatas($searchProperties, - $includeNonExistentProperties); - return array_shift($metadatas); - } -} -]]> - - - Looking at the search methods above, the signatures allow for - extremely flexible searching. In order to find a metadata object, - simply pass in an array of matching constraints via an array. If - the data is accessible through the Property accessor (the - getSomething() methods implemented on the metadata - object), then it will be passed back to the user as a "found" - metadata object. - -
- -
Clients - - - - Clients are the interface which bridges a user or external tool into - the Zend_Tool_Framework system. Clients can come in all - shapes and sizes: RPC endpoints, Command Line Interface, or - even a web interface. Zend_Tool has implemented the command - line interface as the default interface for interacting with - the Zend_Tool_Framework system. - - - - To implement a client, one would need to extend the following - abstract class: - - - - - - As you can see, there 1 method is required to fulfill the needs of a - client (two others suggested), the initialization, prehandling and post handling. For a - more in depth study of how the command line client works, please see - the source - code. - -
-
diff --git a/documentation/manual/en/module_specs/Zend_Tool_Framework-CliTool.xml b/documentation/manual/en/module_specs/Zend_Tool_Framework-CliTool.xml deleted file mode 100644 index ab238b125a3..00000000000 --- a/documentation/manual/en/module_specs/Zend_Tool_Framework-CliTool.xml +++ /dev/null @@ -1,279 +0,0 @@ - -
Using the CLI Tool - - - - The CLI, or command line tool (internally known as the console tool), - is currently the primary interface for dispatching Zend_Tool - requests. With the CLI tool, developers can issue tooling requests - inside the "command line windows", also commonly known as a "terminal" - window. This environment is predominant in the *nix environment, but - also has a common implementation in windows with the - cmd.exe, console2 and also with the Cygwin project. - - -
Setting up the CLI tool - - - - To issue tooling requests via the command line client, you first - need to set up the client so that your system can handle the "zf" - command. The command line client, for all intents and purposes, is - the .sh or .bat file that is provided with - your Zend Framework distribution. In trunk, it can be found here: - http://framework.zend.com/svn/framework/standard/trunk/bin/. - - - - As you can see, there are 3 files in the /bin/ - directory: a zf.php, zf.sh, and - zf.bat. The zf.sh and the - zf.bat are the operating system specific client - wrappers: zf.sh for the *nix environment, and - zf.bat for the Win32 environment. These client wrappers are - responsible for finding the proper php.exe, finding the - zf.php, and passing on the client request. The - zf.php is the responsible for handling understanding - your environment, constructing the proper include_path, and passing - what is provided on the command line to the proper library component - for dispatching. - - - - Ultimately, you want to ensure two things to make everything work - regardless of the operating system you are on: - - - - - - zf.sh/zf.bat is reachable from your system - path. This is the ability to call zf from - anywhere on your command line, regardless of what your - current working directory is. - - - - - - ZendFramework/library is in your - include_path. - - - - - - - Note: while the above are the most ideal - requirements, you can simply download Zend Framework and expect it - to work as ./path/to/zf.php some command. - - -
- -
Setting up the CLI tool on Unix-like Systems - - - - The most common setup in the *nix environment, is to copy the - zf.sh and zf.php into the same directory - as your PHP binary. This can generally be found in one of the - following places: - - - - - - To find out the location of your PHP binary, you can execute 'which - php' on the command line. This will return the location of the PHP - binary you will be using to run PHP scripts in this environment. - - - - The next order of business is to ensure that Zend Framework - library is set up correctly inside of the system PHP - include_path. To find out where your - include_path is located, you can execute php -i - and look for the include_path variable, or more succinctly, - execute php -i | grep include_path. Once you have found where - your include_path is located (this will generally be - something like /usr/lib/php, /usr/share/php, - /usr/local/lib/php, or similar), ensure that the contents of the - /library/ directory are put - inside your include_path specified directory. - - - - Once you have done those two things, you should be able to issue a - command and get back the proper response like this: - - - - - - - - If you do not see this type of output, go back and check your setup - to ensure you have all of the necessary pieces in the proper place. - - - - There are a couple of alternative setups you might want to employ - depending on your servers configuration, your level of access, or - for other reasons. - - - - Alternative Setup involves keeping the Zend - Framework download together as is, and creating a link from a PATH - location to the zf.sh. What this means is you can - place the contents of the ZendFramework download into a location - such as /usr/local/share/ZendFramework, or more locally - like /home/username/lib/ZendFramework, and creating a - symbolic link to the zf.sh. - - - - Assuming you want to put the link inside /usr/local/bin - (this could also work for placing the link inside - /home/username/bin/ for example) you would issue a - command similar to this: - - - - - - This will create a link which you should be able to access globally - on the command line. - -
- -
Setting up the CLI tool on Windows - - - - The most common setup in the Windows Win32 environment, is to copy - the zf.bat and zf.php into the same - directory as your PHP binary. This can generally be found in one of - the following places: - - - - - - You should be able to run php.exe on the command line. - If you are not able to, first check the documentation that came with - your PHP distribution, or ensure that the path to - php.exe is in your - Windows PATH environment variable. - - - - The next order of business is to ensure that Zend Framework - library is set up correctly inside of the system PHP - include_path. To find out where your - include_path is located, you can type php -i and - look for the include_path variable, or more succinctly - execute php -i | grep include_path if you have Cygwin setup with - grep available. Once you have found where your - include_path is located (this will generally be - something like C:\PHP\pear, C:\PHP\share, - C:\Program%20Files\ZendServer\share or similar), ensure - that the contents of the library/ directory are put inside your - include_path specified directory. - - - - Once you have done those two things, you should be able to issue a - command and get back the proper response like this: - - - - - - - - If you do not see this type of output, go back and check your setup - to ensure you have all of the necessary pieces in the proper place. - - - - There are a couple of alternative setups you might want to employ - depending on your server's configuration, your level of access, or - for other reasons. - - - - Alternative Setup involves keeping the Zend - Framework download together as is, and altering both your system - PATH as well as the php.ini file. - In your user's environment, make sure to add - C:\Path\To\ZendFramework\bin, so that your - zf.bat file is executable. Also, alter the - php.ini file to ensure that - C:\Path\To\ZendFramework\library is in your - include_path. - -
- -
Other Setup Considerations - - - - If for some reason you do not want Zend Framework library inside - your include_path, there is another option. There are - two special environment variables that zf.php will - utilize to determine the location of your Zend Framework - installation. - - - - The first is ZEND_TOOL_INCLUDE_PATH_PREPEND, which will - prepend the value of this environment variable to the system - (php.ini) include_path before loading the - client. - - - - Alternatively, you might want to use - ZEND_TOOL_INCLUDE_PATH to completely - replace the system include_path - for one that makes sense specifically for the zf - command line tool. - -
- -
Where To Go Next? - - - - At this point, you should be set up to start initiating some more - "interesting" commands. To get going, you can issue the - zf --help command to see what is available to you. - - - - - - - - Continue on to the Zend_Tool_Project "Create Project" - section to understand how to use the zf script for - project creation. - -
-
diff --git a/documentation/manual/en/module_specs/Zend_Tool_Framework-Extending.xml b/documentation/manual/en/module_specs/Zend_Tool_Framework-Extending.xml deleted file mode 100644 index 559dc3394a0..00000000000 --- a/documentation/manual/en/module_specs/Zend_Tool_Framework-Extending.xml +++ /dev/null @@ -1,178 +0,0 @@ - -
Extending and Configuring Zend_Tool_Framework - - -
Customizing Zend_Tool Console Client - - - - As of Zend Framework 1.9, Zend_Tool_Framework allows developers - to store information, provider specific configuration values, and custom files in a - special location on the developers machine. These configuration values and files can be - used by providers to extend functionality, customize functionality, or any other reasons - a provider sees fit. - - - - The primary purpose, and the purpose most immediately used by existing providers is to - allow developers to customize the way the "out of the box" providers do work. - - - - One of the more commonly requested features is to be able to provide custom project - profiles to Zend_Tool_Project's Project Provider. This would - allow developers to store a custom profile in a special place that can be used - repeatedly by the Zend_Tool system in order to build custom - profiles. Another commonly requested feature is to be able to configure the behavior of - providers with a configuration setting. In order to achieve this, not only do we have to - have a Zend_Tool configuration file, but we also have to have a - place to find this configuration file. - - -
The Home Directory - - - - Before the Console Client can start searching for a Zend_Tool - configuration file or a local storage directory, it must first be able to identify - where the "home directory" is located. - - - - On *nix-based machines, PHP will be populated with an environment - variable named HOME with a path to the current users home - directory. Typically, this path will be very similar to - /home/myusername. - - - - On Windows-based machines, PHP will typically be populated with - an environment variable named HOMEPATH with the current users - home directory. This directory is usually found in either - C:\Documents and Settings\Username\, or in Vista at - C:\Users\Username. - - - - If either a home directory cannot be found, or you wish to change the location of - where Zend_Tool_Framework Console Client finds the home - directory, you can provide an environment variable named - ZF_HOME to specify where to find the home directory. - -
- -
Local Storage - - - - Once a home directory can be located, Zend_Tool_Framework's - Console Client can either autodiscover the local storage directory, or it can be - told where to expect the local storage directory. - - - - Assuming the home directory has been found (here noted as $HOME), - the Console Client will then look for the local storage directory in - $HOME/.zf/. If found, it will set the local storage directory - to this location. - - - - If the directory cannot be found, or the developer wishes to override this location, - that can be done by setting an environment variable. Regardless if - $HOME has been previously set or not, the developer may supply - the environment variable ZF_STORAGE_DIR. - - - - Once the path to a local storage directory is found, the directory - must exist for it to be passed into the - Zend_Tool_Framework runtime, as it will not be created for - you. - -
- -
User Configuration - - - - Like local storage, once a home directory can be located, - Zend_Tool_Framework's Console Client can then either attempt - to autodiscover the path to a configuration file, or it can be told specifically - where to find the configuration file. - - - - Assuming the home directory has been found (here noted as $HOME), - the Console Client will then attempt to look for the existence of a configuration - file located at $HOME/.zf.ini. This file, if found, will be - used as the configuration file for Zend_Tool_Framework. - - - - If that location does not exist, but a local storage directory does, then the - Console Client will then attempt to locate the configuration file within the local - storage directory. Assuming the local storage directory exists in - $LOCAL_STORAGE, then if a file exists as - $LOCAL_STORAGE/zf.ini, it will be found by the Console Client - and utilized as the Zend_Tool_Framework configuration file. - - - - If the file cannot be autodiscovered or the developer wishes to specify the location - of location of the configuration file, the developer can do so by setting an - environment variable. If the environment variable - ZF_CONFIG_FILE is set, then its value will be used as the - location of the configuration file to use with the Console Client. The - ZF_CONFIG_FILE can point to any - Zend_Config readable INI, - XML or PHP File. - - - - If the file does not exist in either the autodiscovered or the provided location, it - will not be used as Zend_Tool_Framework does not attempt to - create the file automatically. - -
- -
User Configuration File Content - - - - The configuration file should be structured as a Zend_Config - configuration file, in INI format, and without any sections being - defined. First level keys should be used by the provider searching for a specific - value. For example, if the "Project" provider is expecting a "profiles" directory, - then it should typically be understood that it will search for the following - INI key value pair: - - - - - - The only reserved INI prefix is the value "php". The "php" prefix - to values will be reserved to store names and values of runtime settable - PHP values, such as include_path or - error_reporting. To override the - include_path and error_reporting with an - INI value, a developer would set: - - - - - - - The reserved prefix "php" only works with INI files. You - can't set PHP INI values with - PHP or XML config. - - -
-
-
diff --git a/documentation/manual/en/module_specs/Zend_Tool_Framework-Introduction.xml b/documentation/manual/en/module_specs/Zend_Tool_Framework-Introduction.xml deleted file mode 100644 index 9ca4063dcc6..00000000000 --- a/documentation/manual/en/module_specs/Zend_Tool_Framework-Introduction.xml +++ /dev/null @@ -1,126 +0,0 @@ - - - -
Introduction - - - - Zend_Tool_Framework is a framework for exposing common - functionalities such as the creation of project scaffolds, code - generation, search index generation, and much more. Functionality may be - written and exposed via PHP classes dropped into the - PHP include_path, providing incredible - flexibility of implementation. The functionality may then be consumed by writing - implementation and/or protocol-specific clients -- such as console - clients, XML-RPC, SOAP, and much more. - - - - Zend_Tool_Framework provides the following: - - - - - - Common interfaces and abstracts that allow - developers to create functionality and capabilities that are - dispatchable by tooling clients. - - - - - - Base client functionality and a concrete - console implementation that connect external tools and - interfaces to the Zend_Tool_Framework. The Console - client may be used in CLI environments such as unix shells and - the Windows console. - - - - - - "Provider" and "Manifest" interfaces that - can be utilized by the tooling system. "Providers" represent the - functional aspect of the framework, and define the actions that - tooling clients may call. "Manifests" act as metadata registries - that provide additional context for the various defined - providers. - - - - - - An introspective loading system that will - scan the environment for providers and determine what is - required to dispatch them. - - - - - - A standard set of system providers that - allow the system to report what the full capabilities of the - system are as well as provide useful feedback. This also - includes a comprehensive "Help System". - - - - - - Definitions that you should be aware of through this manual with respect - to Zend_Tool_Framework include: - - - - - - Zend_Tool_Framework - The framework which exposes - tooling capabilities. - - - - - - Tooling Client - A developer tool that connects - to and consumes Zend_Tool_Framework. - - - - - - Client - The subsystem of - Zend_Tool_Framework that exposes an interface such that - tooling clients can connect, query and execute commands. - - - - - - Console Client / Command Line Interface / - zf.php - The tooling client for the command line. - - - - - - Provider - A subsystem and a collection of - built-in functionality that the framework exports. - - - - - - Manifest - A subsystem for defining, - organizing, and disseminating provider requirement data. - - - - - - Zend_Tool_Project Provider - A set of providers - specifically for creating and maintaining Zend Framework-based projects. - - - -
diff --git a/documentation/manual/en/module_specs/Zend_Tool_Framework-SystemProviders.xml b/documentation/manual/en/module_specs/Zend_Tool_Framework-SystemProviders.xml deleted file mode 100644 index 47e39285330..00000000000 --- a/documentation/manual/en/module_specs/Zend_Tool_Framework-SystemProviders.xml +++ /dev/null @@ -1,49 +0,0 @@ - - - -
Shipped System Providers - - - - In addition to the more useful project based providers that come shipped - with Zend_Tool_Project, there are also some more basic, but - interesting providers that come built into - Zend_Tool_Framework. Some of these exist for the purpose - of providing a means via the command line to extract information, such - as the version, while others are intended to aid the developer when - creating additional providers. - - -
The Version Provider - - - - The Version provider is included so that you may determine which - version of the framework that the zf or - Zend_Tool is currently set to work with. - - - - Through the command line, simply run zf show version. - -
- -
The Manifest Provider - - - - The Manifest provider is included so that you may determine what - kind of "manifest" information is available during the - Zend_Tool runtime. Manifest data is information that - is attached to specific objects during Zend_Tool's - runtime. Inside the manifest you will find the console specific - namings that you are expected to use when calling certain commands. - Data found in the manifest can be used by any provider or client on - an as-needed basis. - - - - Through the command line, simply run zf show manifest. - -
-
diff --git a/documentation/manual/en/module_specs/Zend_Tool_Framework-WritingProviders.xml b/documentation/manual/en/module_specs/Zend_Tool_Framework-WritingProviders.xml deleted file mode 100644 index 6439731e072..00000000000 --- a/documentation/manual/en/module_specs/Zend_Tool_Framework-WritingProviders.xml +++ /dev/null @@ -1,398 +0,0 @@ - -
Creating Providers to use with Zend_Tool_Framework - - - - In general, a provider, on its own, is nothing more than the shell for a - developer to bundle up some capabilities they wish to dispatch with the - command line (or other) clients. It is an analogue to what a - "controller" is inside of your MVC application. - - -
How Zend_Tool finds your Providers - - - - By default Zend_Tool uses the IncludePathLoader to find all - the providers that you can run. It recursivly iterates all - include path directories and opens all files that end - with "Manifest.php" or "Provider.php". All classes in these - files are inspected if they implement either - Zend_Tool_Framework_Provider_Interface - or Zend_Tool_Framework_Manifest_ProviderManifestable. - Instances of the provider interface make up for the real functionality - and all their public methods are accessible as provider actions. - The ProviderManifestable interface however requires the implementation of a method - getProviders() which returns an array of - instantiated provider interface instances. - - - - The following naming rules apply on how you can access the providers - that were found by the IncludePathLoader: - - - - - - The last part of your classname split by underscore is used - for the provider name, e.g. "My_Provider_Hello" leads to your - provider being accessible by the name "hello". - - - - - - If your provider has a method getName() - it will be used instead of the previous method to determine - the name. - - - - - - If your provider has "Provider" as prefix, e.g. it is called - My_HelloProvider it will be stripped - from the name so that the provider will be called "hello". - - - - - - - The IncludePathLoader does not follow symlinks, that means - you cannot link provider functionality into your include paths, - they have to be physically present in the include paths. - - - - Exposing Your Providers with a Manifest - - - - You can expose your providers to Zend_Tool by offering a - manifest with a special filename ending with "Manifest.php". - A Provider Manifest is an implementation of the - Zend_Tool_Framework_Manifest_ProviderManifestable - and requires the getProviders() method to return - an array of instantiated providers. In anticipation of our first - own provider My_Component_HelloProvider - we will create the following manifest: - - - - -
- -
Basic Instructions for Creating Providers - - - - As an example, if a developer wants to add the capability of showing - the version of a datafile that his 3rd party component is working - from, there is only one class the developer would need to implement. - Assuming the component is called My_Component, he would - create a class named My_Component_HelloProvider in a - file named HelloProvider.php somewhere on the - include_path. This class would implement - Zend_Tool_Framework_Provider_Interface, and the body of - this file would only have to look like the following: - - - - - - Given that code above, and assuming the developer wishes to access - this functionality through the console client, the call would look - like this: - - - -
- -
The response object - - - - As discussed in the architecture section Zend_Tool allows to hook - different clients for using your Zend_Tool providers. To keep - compliant with different clients you should use the response object to return messages - from your providers instead of using echo() or a similiar - output mechanism. Rewritting our hello provider with this knowledge it looks like: - - - _registry->getResponse - ->appendContent("Hello from my provider!"); - } -} -]]> - - - As you can see one has to extend the - Zend_Tool_Framework_Provider_Abstract to gain access to the - Registry which holds the Zend_Tool_Framework_Client_Response - instance. - -
- -
Advanced Development Information - - -
Passing Variables to a Provider - - - - The above "Hello World" example is great for simple commands, but - what about something more advanced? As your scripting and tooling - needs grow, you might find that you need the ability to accept - variables. Much like function signatures have parameters, your - tooling requests can also accept parameters. - - - - Just as each tooling request can be isolated to a method within a - class, the parameters of a tooling request can also be isolated in a - very well known place. Parameters of the action methods of a - provider can include the same parameters you want your client to - utilize when calling that provider and action combination. For - example, if you wanted to accept a name in the above example, you - would probably do this in OO code: - - - - - - The above example can then be called via the command line - zf say hello Joe. "Joe" will be supplied to the provider as - a parameter of the method call. Also note, as you see that the - parameter is optional, that means it is also optional on the command - line, so that zf say hello will still work, and default - to the name "Ralph". - -
- -
Prompt the User for Input - - - - There are cases when the workflow of your provider requires - to prompt the user for input. This can be done by requesting - the client to ask for more the required input by calling: - - - _registry - ->getClient() - ->promptInteractiveInput("Whats your name?"); - $name = $nameResponse->getContent(); - - echo 'Hello' . $name . ', from my provider!'; - } -} -]]> - - - This command throws an exception if the current client is not - able to handle interactive requests. In case of the default Console Client - however you will be asked to enter the name. - -
- -
Pretending to execute a Provider Action - - - - Another interesting feature you might wish to implement is - pretendability. Pretendabilty is the ability - for your provider to "pretend" as if it is doing the requested - action and provider combination and give the user as much - information about what it would do without - actually doing it. This might be an important notion when doing - heavy database or filesystem modifications that the user might not - otherwise want to do. - - - - Pretendability is easy to implement. There are two parts to this - feature: 1) marking the provider as having the ability to "pretend", - and 2) checking the request to ensure the current request was indeed - asked to be "pretended". This feature is demonstrated in the code - sample below. - - - _registry->getRequest()->isPretend()) { - echo 'I would say hello to ' . $name . '.'; - } else { - echo 'Hello' . $name . ', from my provider!'; - } - } -} -]]> - - - To run the provider in pretend mode just call: - - - -
- -
Verbose and Debug modes - - - - You can also run your provider actions in "verbose" or "debug" modes. - The semantics in regard to this actions have to be implemented by you - in the context of your provider. You can access debug or verbose modes - with: - - - _registry->getRequest()->isVerbose()) { - echo "Hello::say has been called\n"; - } - if($this->_registry->getRequest()->isDebug()) { - syslog(LOG_INFO, "Hello::say has been called\n"); - } - } -} -]]> -
- -
Accessing User Config and Storage - - - - Using the Enviroment variable ZF_CONFIG_FILE or the - .zf.ini in your home directory you can inject configuration parameters into - any Zend_Tool provider. Access to this configuration is - available via the registry that is passed to your provider if you extend - Zend_Tool_Framework_Provider_Abstract. - - - _registry->getConfig()->username; - if(!empty($username)) { - echo "Hello $username!"; - } else { - echo "Hello!"; - } - } -} -]]> - - - The returned configuration is of the type - Zend_Tool_Framework_Client_Config but internally the - __get() and __set() magic methods - proxy to a Zend_Config of the given configuration type. - - - - The storage allows to save arbitrary data for later reference. This can be useful - for batch processing tasks or for re-runs of your tasks. You can access the storage - in a similar way like the configuration: - - - _registry->getStorage()->get("myUsername"); - echo "Hello $aValue!"; - } -} -]]> - - - The API of the storage is very simple: - - - - - - - When designing your providers that are config or storage aware remember to - check if the required user-config or storage keys really exist for a user. - You won't run into fatal errors when none of these are provided though, - since empty ones are created upon request. - - -
-
-
diff --git a/documentation/manual/en/module_specs/Zend_Tool_Project-CreateProject.xml b/documentation/manual/en/module_specs/Zend_Tool_Project-CreateProject.xml deleted file mode 100644 index 55b6e4e8217..00000000000 --- a/documentation/manual/en/module_specs/Zend_Tool_Project-CreateProject.xml +++ /dev/null @@ -1,70 +0,0 @@ - - - -
Create A Project - - - - - The following examples will assume you have the command line interface of - Zend_Tool_Framework available to you. - - - - - - To issue any of the commands for Zend_Tool_Project with - CLI, you must be in the directory where the project was - initially created. - - - - - To get started with Zend_Tool_Project, you simply need to create a - project. Creating a project is simple: go to a place on your filesystem, create a directory, - change to that directory, then issue the following command: - - - - /tmp/project$ zf create project - - - - Optionally, you can create a directory anywhere by the following: - - - - $ zf create project /path/to/non-existent-dir - - - - The following table will describe the capabilities of providers that are available to - you. As you can see in this table, there is a "Project" provider. The Project provider - has a couple of actions associated to it, and with those actions a number of options that - can be used to modify the behavior of the action and provider. - - - Project Provider Options - - - - - - Provider Name - Available Actions - Parameters - CLI Usage - - - - - - Project - Create / Show - create - [path=null, profile='default'] - zf create project some/path - - - -
-
diff --git a/documentation/manual/en/module_specs/Zend_Tool_Project-Internals.xml b/documentation/manual/en/module_specs/Zend_Tool_Project-Internals.xml deleted file mode 100644 index 26bffcde9e0..00000000000 --- a/documentation/manual/en/module_specs/Zend_Tool_Project-Internals.xml +++ /dev/null @@ -1,20 +0,0 @@ - - - -
Zend_Tool_Project Internals - - -
Zend_Tool_Project Internal Xml Structure - - - - -
- -
Zend_Tool_Project Internal Extending - - - - -
-
diff --git a/documentation/manual/en/module_specs/Zend_Tool_Project-Providers.xml b/documentation/manual/en/module_specs/Zend_Tool_Project-Providers.xml deleted file mode 100644 index 49904f2a8a9..00000000000 --- a/documentation/manual/en/module_specs/Zend_Tool_Project-Providers.xml +++ /dev/null @@ -1,83 +0,0 @@ - - - -
Zend_Tool Project Providers - - - - Below is a table of all of the providers shipped with - Zend_Tool_Project. - - - Project Provider Options - - - - - - Provider Name - Available Actions - Parameters - CLI Usage - - - - - - Controller - Create - create - [name, indexActionIncluded=true] - zf create controller foo - - - - Action - Create - create - [name, controllerName=index, viewIncluded=true] - - - zf create action bar foo - (or zf create action --name bar --controlller-name=foo) - - - - - Controller - Create - create - [name, indexActionIncluded=true] - zf create controller foo - - - - Profile - Show - show - [] - zf show profile - - - - View - Create - create - [controllerName,actionNameOrSimpleName] - - - zf create view foo bar - (or zf create view -c foo -a bar) - - - - - Test - Create / Enable / Disable - create - [libraryClassName] - - - zf create test My_Foo_Baz / - zf disable test / - zf enable test - - - - -
-
diff --git a/documentation/manual/en/module_specs/Zend_Tool_Project.xml b/documentation/manual/en/module_specs/Zend_Tool_Project.xml deleted file mode 100644 index 38642f13057..00000000000 --- a/documentation/manual/en/module_specs/Zend_Tool_Project.xml +++ /dev/null @@ -1,39 +0,0 @@ - - - -
Introduction - - - - Zend_Tool_Project builds on and extends the capabilities of - Zend_Tool_Framework to that of managing a "project". In general, a - "project" is a planned endeavor or an initiative. In the computer world, projects generally - are a collection of resources. These resources can be files, directories, databases, - schemas, images, styles, and more. - - - - This same concept applies to Zend Framework projects. In Zend Framework projects, you have - controllers, actions, views, models, databases and so on and so forth. In terms of - Zend_Tool, we need a way to track these types of resources - thus - Zend_Tool_Project. - - - - Zend_Tool_Project is capable of tracking project resources throughout - the development of a project. So, for example, if in one command you created a controller, - and in the next command you wish to create an action within that controller, - Zend_Tool_Project is gonna have to know about - the controller file you created so that you can (in the next action), be able to append that - action to it. This is what keeps our projects up to date and stateful. - - - - Another important point to understand about projects is that typically, resources are - organized in a hierarchical fashion. With that in mind, - Zend_Tool_Project is capable of serializing the current project into - a internal representation that allows it to keep track of not only what - resources are part of a project at any given time, but also where they - are in relation to one another. - -
diff --git a/documentation/manual/en/module_specs/Zend_Translator-Adapters.xml b/documentation/manual/en/module_specs/Zend_Translator-Adapters.xml deleted file mode 100644 index dff4252e27f..00000000000 --- a/documentation/manual/en/module_specs/Zend_Translator-Adapters.xml +++ /dev/null @@ -1,462 +0,0 @@ - -
Adapters for Zend_Translator - - - Zend_Translator can handle different adapters for translation. - Each adapter has its own advantages and disadvantages. - Below is a comprehensive list of all supported adapters for - translation source files. - - - Adapters for Zend_Translator - - - - - - Adapter - Description - Usage - - - - - - Array - Use PHP arrays - Small pages; simplest usage; only for programmers - - - - Csv - Use comma separated (*.csv/*.txt) files - - - Simple text file format; fast; possible problems with unicode characters - - - - - Gettext - Use binary gettext (*.mo) files - GNU standard for linux; thread-safe; needs tools for translation - - - - Ini - Use simple INI (*.ini) files - - - Simple text file format; fast; possible problems with unicode characters - - - - - Tbx - Use termbase exchange (*.tbx/*.xml) files - - - Industry standard for inter application terminology strings; - XML format - - - - - Tmx - Use tmx (*.tmx/*.xml) files - - - Industry standard for inter application translation; XML - format; human readable - - - - - Qt - Use qt linguist (*.ts) files - - - Cross platform application framework; XML format; human - readable - - - - - Xliff - Use xliff (*.xliff/*.xml) files - - - A simpler format as TMX but related to it; - XML format; human readable - - - - - XmlTm - Use xmltm (*.xml) files - - - Industry standard for XML document translation memory; - XML format; human readable - - - - - Others - *.sql - Different other adapters may be implemented in the future - - - -
- -
How to decide which translation adapter to use - - - - You should decide which Adapter you want to use for - Zend_Translator. Frequently, external criteria such as a project - requirement or a customer requirement determines this for you, but if you are in - the position to do this yourself, the following hints may simplify - your decision. - - - - - When deciding your adapter you should also be aware of the used - encoding. Even if Zend Framework declares UTF-8 as default - encoding you will sometimes be in the need of other encoding. - Zend_Translator will not change any encoding which is defined - within the source file which means that if your Gettext source - is build upon ISO-8859-1 it will also return strings in this encoding - without converting them. There is only one restriction: - - - - When you use a XML based source format like TMX or XLIFF you must - define the encoding within the XML files header because - XML files without defined encoding will be treated as UTF-8 by - any XML parser by default. You should also be aware that actually - the encoding of XML files is limited to the encodings supported - by PHP which are UTF-8, ISO-8859-1 and US-ASCII. - - - -
Zend_Translator_Adapter_Array - - - - The Array Adapter is the Adapter which is simplest to use for - programmers. - But when you have numerous translation strings or many - languages you should think about another Adapter. - For example, if you have 5000 translation strings, - the Array Adapter is possibly not the best choice for you. - - - - You should only use this Adapter for small sites with a handful - of languages, and if you or your programmer team creates the - translations yourselves. - -
- -
Zend_Translator_Adapter_Csv - - - - The Csv Adapter is the Adapter which is simplest to use for - customers. - CSV files are readable by standard text editors, but - text editors often do not support utf8 character sets. - - - - You should only use this Adapter if your customer wants to do - translations himself. - - - - - Beware that the Csv Adapter has problems when your Csv files are encoded - differently than the locale setting of your environment. This is due to a Bug of - PHP itself which will not be fixed before - PHP 6.0 (http://bugs.php.net/bug.php?id=38471). So you should - be aware that the Csv Adapter due to PHP restrictions is not - locale aware. - - -
- -
Zend_Translator_Adapter_Gettext - - - - The Gettext Adapter is the Adapter which is used most - frequently. Gettext is a translation source format which was - introduced by GNU, and is now used worldwide. - It is not human readable, but there are several freeware tools - (for instance, POEdit), - which are very helpful. The Zend_Translator Gettext Adapter is - not implemented using PHP's gettext extension. - You can use the Gettext Adapter even if you do not have - the PHP gettext extension installed. - Also the Adapter is thread-safe and the PHP gettext extension - is currently not thread-safe. - - - - Most people will use this adapter. - With the available tools, professional translation is - very simple. But gettext data are is stored in a - machine-readable format, which is not readable without tools. - -
- -
Zend_Translator_Adapter_Ini - - - - The Ini Adapter is a very simple Adapter which can even be used - directly by customers. - INI files are readable by standard text editors, but - text editors often do not support utf8 character sets. - - - - You should only use this Adapter when your customer wants to do translations - himself. Do not use this adapter as generic translation source. - - - Regression in PHP 5.3 - - - - Prior to PHP 5.3, parse_ini_file() - and parse_ini_string() handled non-ASCII characters - within INI option keys worked without an issue. However, - starting with PHP 5.3, any such keys will now be silently - dropped in the returned array from either function. If you had keys utilizing - UTF-8 or Latin-1 characters, you may find your translations no longer work when - using the INI adapter. If this is the case, we recommend - utilizing a different adapter. - - -
- -
Zend_Translator_Adapter_Tbx - - - - The Tbx Adapter is an Adapter which will be used by customers - which already use the TBX format for their internal translation - system. Tbx is no standard translation format but more a collection - of already translated and pre translated source strings. When you - use this adapter you have to be sure that all your needed source - string are translated. - TBX is a XML file based format and a completely new format. - XML files are human-readable, but the parsing is not as fast - as with gettext files. - - - - This adapter is perfect for companies when pre translated - source files already exist. - The files are human readable and system-independent. - -
- -
Zend_Translator_Adapter_Tmx - - - - The Tmx Adapter is the Adapter which will be used by most - customers which have multiple systems which use the same - translation source, or when the translation source must be - system-independent. - TMX is a XML file based format, which is announced to be the - next industry standard. - XML files are human-readable, but the parsing is not as fast - as with gettext files. - - - - Most medium to large companies use this adapter. - The files are human readable and system-independent. - -
- -
Zend_Translator_Adapter_Qt - - - - The Qt Adapter is for all customers which have TS files as their - translation source which are made by QtLinguist. - QT is a XML file based format. - XML files are human-readable, but the parsing is not as fast - as with gettext files. - - - - Several big players have build software upon the QT framework. - The files are human readable and system-independent. - -
- -
Zend_Translator_Adapter_Xliff - - - - The Xliff Adapter is the Adapter which will be used by most customers which - want to have XML files but do not have tools for TMX. - XLIFF is a XML file based format, which is related to TMX but - simpler as it does not support all possibilities of it. - XML files are human-readable, but the parsing is not as fast - as with gettext files. - - - - Most medium companies use this adapter. - The files are human readable and system-independent. - -
- -
Zend_Translator_Adapter_XmlTm - - - - The XmlTm Adapter is the Adapter which will be used by customers - which do their layout themself. XmlTm is a format which allows the - complete HTML source to be included in the translation source, so - the translation is coupled with the layout. - XLIFF is a XML file based format, which is related to XLIFF but - its not as simple to read. - - - - This adapter should only be used when source files already exist. - The files are human readable and system-independent. - -
-
- -
Integrate self written Adapters - - - - Zend_Translator allows you to integrate and use self written - Adapter classes. They can be used like the standard Adapter classes which - are already included within Zend_Translator. - - - - Any adapter class you want to use with Zend_Translator must be a - subclass of Zend_Translator_Adapter. - Zend_Translator_Adapter is an abstract class which already defines - all what is needed for translation. What has to be done by you, is the definition of the - reader for translation datas. - - - - The usage of the prefix "Zend" should be limited to Zend Framework. - If you extend Zend_Translator with your own adapter, you should - name it like "Company_Translator_Adapter_MyFormat". The following code shows an - example of how a self written adapter class could be implemented: - - - 'Company_Translator_Adapter_MyFormat', - 'content' => '/path/to/translate.xx', - 'locale' => 'en', - 'myoption' => 'myvalue' - ) - ); -} catch (Exception $e) { - // File not found, no adapter class... - // General failure -} -]]> -
- -
Speedup all Adapters - - - - Zend_Translator allows you use internally - Zend_Cache to fasten the loading of translation sources. This - comes very handy if you use many translation sources or extensive source formats like - XML based files. - - - - To use caching you will just have to give a cache object to the - Zend_Translator::setCache() method. It takes a instance of - Zend_Cache as only parameter. Also if you use any adapter direct - you can use the setCache() method. For convenience there are - also the static methods getCache(), - hasCache(), clearCache() and - removeCache(). - - - 'gettext', - 'content' => '/path/to/translate.mo', - 'locale' => 'en' - ) -); - -// to clear the cache somewhere later in your code -Zend_Translator::clearCache(); -]]> - - - - You must set the cache before you use or initiate - any adapter or instance of Zend_Translator. Otherwise your - translation source will not be cached until you add a new source with the - addTranslation() method. - - - - - When the attached cache supports tagging you can set a own tag string by using the - option tag. This allows you do delete only the cache from this - single instance of Zend_Translator. When you are not using this - option the default tag Zend_Translator is used. - - - - Using the option tag you must give the used tag to - clearCache() to declare which tag you want to delete. - - - 'gettext', - 'content' => '/path/to/translate.mo', - 'locale' => 'en', - 'tag' => 'MyTag' - ) -); - -// somewhere later in your code -Zend_Translator::clearCache('MyTag'); -]]> -
-
diff --git a/documentation/manual/en/module_specs/Zend_Translator-Additional.xml b/documentation/manual/en/module_specs/Zend_Translator-Additional.xml deleted file mode 100644 index 3d09376bbe9..00000000000 --- a/documentation/manual/en/module_specs/Zend_Translator-Additional.xml +++ /dev/null @@ -1,1289 +0,0 @@ - -
Additional features for translation - - - - There are several additional features which are supported by - Zend_Translator. Read here for these additional informations. - - -
Options for adapters - - - - Options can be used with all adapters. Of course the options are different for all - adapters. You can set options when you create the adapter. Actually there is one option - which is available to all adapters: 'clear' sets if translation - data should be added to existing one or not. Standard behaviour is to add new - translation data to existing one. But the translation data is only cleared for the - selected language. So other languages remain untouched. - - - - You can set options temporarily by giving them to - addTranslation(). And you can use the method - setOptions() to set options permanent. - - - Using translation options - - - 'csv', - 'content' => '/path/to/mytranslation.csv', - 'locale' => 'de', - 'delimiter' => ':' - ) -); - -... - -// clear the defined language and use new translation data -$translate->addTranslation( - array( - 'content' => '/path/to/new.csv', - 'locale' => 'fr', - 'clear' => true - ) -); -]]> - - - - Here you can find all available options for the different adapters with a description - of their usage: - - - Options for translation adapters - - - - - - Option - Adapter - Description - Default value - - - - - - adapter - Zend_Translator only - - - Defines the adapter which will be used for the translation. This option - can only be given when a new instance of - Zend_Translator is created. When it is set - afterwards, then it will be ignored - - - Must be set as it has no default value - - - - clear - all - - - If set to TRUE, the already read translations will - be cleared. This can be used instead of creating a new instance when - reading new translation data - - - FALSE - - - - cache - all - - - Sets a cache for the translation adapter. This must be a instance of - Zend_Cache_Core - - - - Per default no cache is set - - - - - content - all - - - Sets the content for the translation adapter. This could be an array, - a filename or a directory. Which type of content is supported depends - on the used adapter - - - - The default value depends on the used adapter - - - - - disableNotices - all - - - If set to TRUE, all notices regarding not available - translations will be disabled. You should set this option to - TRUE in production environment - - - FALSE - - - - ignore - all - - - All directories and files beginning with this prefix will be ignored - when searching for files. This value defaults to - '.' which leads to the behavior that all hidden - files will be ignored. Setting this value to 'tmp' - would mean that directories and files like 'tmpImages' and - 'tmpFiles' would be ignored as well as all subsequent - directories. This option also accepts an array which can be used when - you want to ignore more than one prefix. - - - . - - - - log - all - - - An instance of Zend_Log where untranslated - messages and notices will be written to - - - NULL - - - - logMessage - all - The message which will be written into the log - - - Untranslated message within '%locale%': %message% - - - - - logPriority - all - The priority which is used to write the message into the log - - - 5 - - - - - logUntranslated - all - - - When this option is set to TRUE, all message IDs - which can not be translated will be written into the attached log - - - FALSE - - - - reload - all - - - When this option is set to TRUE, then files are - reloaded into the cache. This option can be used to recreate the cache, - or to add translations to already cached data after the cache has - already been created. - - - FALSE - - - - route - all - - - This option allows to use reroute from non existing translations to - other languages. See the Rerouting - Section for details about this option. - - - NULL - - - - routeHttp - all - - - This option uses the browsers HTTP language header to set the routing - between languages. See the Rerouting - Section for details about this option. - - - true - - - - scan - all - - - If set to NULL, no scanning of the directory - structure will be done. If set to - Zend_Translator::LOCALE_DIRECTORY the - locale will be detected within the directory. If set to - Zend_Translator::LOCALE_FILENAME the locale will - be detected within the filename. See this chapter - for details - - - NULL - - - - tag - all - - - Sets an individual tag which is used for the attached cache. Using this - option allows to use and clear the cache for single instances. When this - option is not set, the attached cache is used for all instances combined - - - Zend_Translator - - - - delimiter - Csv - - - Defines which sign is used as delimiter for separating source and - translation - - - ; - - - - enclosure - Csv - - - Defines the enclosure character to be used. Defaults to a doublequote - - - " - - - - length - Csv - - - Defines the maximum length of a csv line. When set to 0 it will be - detected automatically - - - 0 - - - - useId - Xliff and Tmx - - - If you set this option to FALSE, then the source - string will be used as message Id. The default for this option is - TRUE, which means that the Id from the trans-unit - element will be used as message Id - - - TRUE - - - -
- - - When you want to have self defined options, you are also able to use them within all - adapters. The setOptions() method can be used to define your - option. setOptions() needs an array with the options you want - to set. If an given option exists it will be signed over. You can define as much options - as needed as they will not be checked by the adapter. Just make sure not to overwrite - any existing option which is used by an adapter. - - - - To return the option you can use the getOptions() method. When - getOptions() is called without a parameter it will return all - options set. When the optional parameter is given you will only get the specified - option. - -
- -
Handling languages - - - - When working with different languages there are a few methods which will be useful. - - - - The getLocale() method can be used to get the currently set - language. It can either hold an instance of Zend_Locale or the - identifier of a locale. - - - - The setLocale() method sets a new standard language for - translation. This prevents the need of setting the optional language parameter more than - once to the translate() method. If the given language does not - exist, or no translation data is available for the language, - setLocale() tries to downgrade to the language without the - region if any was given. A language of en_US would be downgraded to - en. When even the downgraded language can not be found an exception - will be thrown. - - - - The isAvailable() method checks if a given language is already - available. It returns TRUE if data for the given language exist. - - - - And finally the getList() method can be used to get all - currently set languages for an adapter returned as array. - - - Handling languages with adapters - - - getLocale(); - -// you can use the optional parameter while translating -echo $translate->_("my_text", "fr"); -// or set a new language -$translate->setLocale("fr"); -echo $translate->_("my_text"); -// refer to the base language -// fr_CH will be downgraded to fr -$translate->setLocale("fr_CH"); -echo $translate->_("my_text"); - -// check if this language exist -if ($translate->isAvailable("fr")) { - // language exists -} -]]> - - -
Automatical handling of languages - - - - Note that as long as you only add new translation sources with the - addTranslation() method - Zend_Translator will automatically set the best fitting - language for your environment when you use one of the automatic locales which are - 'auto' or 'browser'. So normally you will - not need to call setLocale(). This should only be used in - conjunction with automatic source detection. - - - - The algorithm will search for the best fitting locale depending on the user's - browser and your environment. See the following example for details: - - - Automatically language detection - - - 'gettext', - 'content' => 'my_it.mo', - 'locale' => 'auto', - 'scan' => Zend_Translator::LOCALE_FILENAME - ) -); - -// Example 2: -// Best found fitting language is 'fr' -$translate = new Zend_Translator( - array( - 'adapter' => 'gettext', - 'content' => 'my_fr.mo', - 'locale' => 'auto', - 'scan' => Zend_Translator::LOCALE_FILENAME - ) -); - -// Example 3: -// Best found fitting language is 'de' ('de_AT' will be degraded) -$translate = new Zend_Translator( - array( - 'adapter' => 'gettext', - 'content' => 'my_de.mo', - 'locale' => 'auto', - 'scan' => Zend_Translator::LOCALE_FILENAME - ) -); - -// Example 4: -// Returns 'it' as translation source and overrides the automatic settings -$translate = new Zend_Translator( - array( - 'adapter' => 'gettext', - 'content' => 'my_it.mo', - 'locale' => 'auto', - 'scan' => Zend_Translator::LOCALE_FILENAME - ) -); - -$translate->addTranslation(array('content' => 'my_ru.mo', 'locale' => 'ru')); -$translate->setLocale('it_IT'); -]]> - - - - After setting a language manually with the setLocale() - method the automatic detection will be switched off and overridden. - - - - If you want to use it again, you can set the language - auto with setLocale() which will - reactivate the automatic detection for Zend_Translator. - - - - Since Zend Framework 1.7.0 Zend_Translator also recognises an - application wide locale. You can simply set a Zend_Locale - instance to the registry like shown below. With this notation you can forget about - setting the locale manually with each instance when you want to use the same locale - multiple times. - - - 'gettext', 'content' => 'my_de.mo') -); - -if (!$translate->isAvailable($locale->getLanguage())) { - // not available languages are rerouted to another language - $translate->setLocale($defaultlanguage); -} - -$translate->getLocale(); -]]> -
- -
Using a country as language - - - - You can also use a country as locale parameter. This could be useful when you - provide your user with flags, which represent the country in which he lives, and - when he selects his flag, he would automatically get the default language for this - country. - - - - For example, when the user selected US then you would get - en_US in return as locale which is being used. This leads - automatically to the language en which is the default language - for the country US. - - - 'gettext', - 'content' => 'my_de.mo', - 'locale' => 'US' - ) -); -]]> - - Always uppercase countries - - - - Using this syntax you should always uppercase the input when you know that it's - a country. The reason is that there are also languages which have the same - letters as a country. Take for example om. You could expect - to get ar_OM when you mean the country "Oman", or you could - expect the language "Oromo" which is spoken in Kenia for example. - - - - As Zend_Translator is related to languages it will always - use the language in this case. Therefor always uppercase the locale when you - want it to be recognised as country. - - -
-
- -
Automatic source detection - - - - Zend_Translator can detect translation sources automatically. So - you don't have to declare each source file manually. You can let - Zend_Translator do this job and scan the complete directory - structure for source files. - - - - - Automatic source detection is available since Zend Framework version 1.5 . - - - - - The usage is quite the same as initiating a single translation source with one - difference. You must give a directory which has to be scanned instead a file. - - - Scanning a directory structure for sources - - - 'tmx', 'content' => '/language') -); -]]> - - - - So Zend_Translator does not only search the given directory, but - also all subdirectories for translation source files. This makes the usage quite - simple. But Zend_Translator will ignore all files which are not - sources or which produce failures while reading the translation data. So you have to - make sure that all of your translation sources are correct and readable because you - will not get any failure if a file is bogus or can not be read. - - - - - Depending on how deep your directory structure is and how much files are within - this structure it can take a long time for Zend_Translator - to complete. - - - - - In our example we have used the TMX format which includes the - language to be used within the source. But many of the other source formats are not - able to include the language within the file. Even this sources can be used with - automatic scanning if you do some pre-requisits as described below: - - -
Language through naming directories - - - - One way to include automatic language detection is to name the directories related - to the language which is used for the sources within this directory. This is the - easiest way and is used for example within standard gettext implementations. - - - - Zend_Translator needs the 'scan' option - to know that it should search the names of all directories for languages. See the - following example for details: - - - Directory scanning for languages - - - 'gettext', - 'content' => '/language', - 'scan' => Zend_Translator::LOCALE_DIRECTORY - ) -); -]]> - - - - - This works only for adapters which do not include the language within the - source file. Using this option for example with TMX will be - ignored. Also language definitions within the filename will be ignored when - using this option. - - - - - - You should be aware if you have several subdirectories under the same - structure. Assuming we have a structure like - /language/module/de/en/file.mo. In this case the path - contains multiple strings which would be detected as locale. It could be either - de or en. In such a case the behaviour - is undefined and it is recommended to use file detection in such situations. - - -
- -
Language through filenames - - - - Another way to detect the language automatically is to use special filenames. You - can either name the complete file or parts of a file after the used language. To - use this way of detection you will have to set the 'scan' - option at initiation. There are several ways of naming the sourcefiles which are - described below: - - - Filename scanning for languages - - - 'gettext', - 'content' => '/language', - 'scan' => Zend_Translator::LOCALE_FILENAME - ) -); -]]> - - -
Complete filename - - - - Having the whole file named after the language is the simplest way but only - viable if you have only one file per language. - - - -
- -
Extension of the file - - - - Another simple way to use the extension of the file for language detection. - But this may be confusing since you will no longer have an idea which extension - the file originally had. - - - -
- -
Filename tokens - - - - Zend_Translator is also capable of detecting the language - if it is included within the filename. But if you go this way you will have to - separate the language with a token. There are three supported tokens which can - be used: a dot '.', an underscore '_', or a hyphen '-'. - - - detects english -/languages/view_de.mo -> detects german -/languages/view_it.mo -> detects italian -]]> - - - The first found string delimited by a token which can be interpreted as a - locale will be used. See the following example for details. - - - detects english -/languages/view_en_es.mo -> detects english and overwrites the first file -/languages/view_it_it.mo -> detects italian -]]> - - - All three tokens are used to detect the locale. When the filename contains - multiple tokens, the first found token depends on the order of the tokens - which are used. See the following example for details. - - - detects english because '_' will be used before '-' -/languages/view-en_it.mo -> detects italian because '_' will be used before '-' -/languages/view_en.it.mo -> detects italian because '.' will be used before '_' -]]> -
-
- -
Ignoring special files and directories - - - - Sometimes it is useful to exclude files or even directories from being added - automatically. Therefor you can use the ignore option which - accepts 3 possible usages. - - -
Ignore a special directory or file - - - - Per default Zend_Translator is set to ignore all - files and directories beginning with - '/.'. This means that - all SVN files will be ignored. - - - - You can set your own syntax by giving a string for the - ignore option. The directory separator will be attached - automatically and has to be omitted. - - - 'test'); -$translate = new Zend_Translator( - array( - 'adapter' => $adapter, - 'content' => $content, - 'locale' => $locale, - 'ignore' => 'test' - ) -); -]]> - - - The above example will ignore all files and directories beginning with - test. This means for example - /test/en.mo, /testing/en.mo and - /dir/test_en.mo. But it would still add - /mytest/en.mo or /dir/atest.mo. - - - Prevent SVN files from being searched - - - - When you set this option, then the default - '/.' will - be erased. This means that Zend_Translator will then - add all files from the hidden SVN directories. When you - are working with SVN, then you should use the array - syntax described in the next section. - - -
- -
Ignore several directories or files - - - - You can also ignore several files and directories. Instead of a string, - you can simply give an array with all wished names which will be ignored. - - - array('.', 'test', 'old')); -$translate = new Zend_Translator( - array( - 'adapter' => $adapter, - 'content' => $content, - 'locale' => $locale, - 'ignore' => array('.', 'test', 'old') - ) -); -]]> - - - In the above case all 3 syntax will be ignored. But still they have to - begin with the syntax to be detected and ignored. - -
- -
Ignore specific names - - - - To ignore files and directories which are not beginning with a defined syntax - but have a special syntax anywhere within their name you can use a regular - expression. - - - - To use a regular expression the array key of the ignore - option has to begin with regex. - - - array( - 'regex' => '/test/u', - 'regex_2' => '/deleted$/u' - ) -); -$translate = new Zend_Translator( - array( - 'adapter' => $adapter, - 'content' => $content, - 'locale' => $locale, - 'ignore' => array('regex' => '/test/u', 'regex_2' => '/deleted$/u') - ) -); -]]> - - - In the above case we defined 2 regular expressions. The files and directories - will always being searched with all given regular expressions. In our example - this means that any files which contains test anywhere in - their name will be ignored. Additionally all files and directories which end - with deleted will not be added as translation. - -
-
-
- -
Routing for translations - - - - Not every message ID can be translated. But sometimes is can be useful to output the - translation from another language instead of returning the message ID itself. You can - archive this by using the route option. - - - - You can add one route for every language. See the following example: - - - $adapter, - 'content' => $content, - 'locale' => $locale, - 'route' => array('fr' => 'en', 'de' => 'fr') - ) -); -]]> - - - The above returns a english translation for all messages which can not be translated to - french. And it returns a french translation for all messages which can not be translated - to german. It will even return an english translation for all messages which can wether - be translated to german nor to french. So you can even define a complete translation - chain. - - - - Per default the option routeHttp is set. This option defines that - the users HTTP language header will be used to set the routing. Manually set routings - will be added to the browsers routing when the option route is given - additionally. - - - - When you don't want to use the browsers HTTP language header simply set the option - routeHttp to false. - - - - These features seems not be interesting for anyone. But be aware that returning - translations for wrong or other languages can be problematic when the user does not - understand this language. So you should always use this feature sparingly. - -
- -
Combining multiple translation sources - - - - When you are working with multiple translations you may come into a situation where you - want to use different source types. For example the resource files which are provided - by the framework and your own translations which are available by using the gettext - adapter. - - - - By combining multiple translation adapters you can use them within one instance. See - the following example: - - - 'gettext', - 'content' => '\path\to\translation.mo', - 'locale' => 'en' - ) -); - -$translate_second = new Zend_Translator( - array( - 'adapter' => 'array', - 'content' => '\resources\languages\en\Zend_Validate.php', - 'locale' => 'en' - ) -); - -$translate->addTranslation(array('content' => $translate_second)); -]]> - - - Now the first instance holds all translations from the second instance and you can use - it within the application even if you used different source types. - - - Memory savings - - - - As you may have noted the second instance is no longer used as soon as it has been - added to the first instance. To save some memory you may want to unset it. - - - - - When you are scanning for directories you may additionally want to use only one defined - language. The predefined resources for example are available in more than 10 languages. - But your application is not available in all of those language. Therefor you can also - add only one language from the second adapter. - - - addTranslation( - array( - 'content' => $translate_second, - 'locale' => 'en' - ) -); -]]> - - - This allows you still to scan through the directories and still add only those languages - which are relevant for your application. - -
- -
Checking for translations - - - - Normally text will be translated without any computation. But sometimes it is necessary - to know if a text is translated or not, therefor the - isTranslated() method can be used. - - - - isTranslated($messageId, $original = false, $locale = null) - takes the text you want to check as its first parameter, and as optional third parameter - the locale for which you want to do the check. The optional second parameter declares - whether translation is fixed to the declared language or a lower set of translations - can be used. If you have a text which can be returned for 'en' but not for 'en_US' you - will normally get the translation returned, but by setting $original - to TRUE, isTranslated() will return - FALSE. - - - Checking if a text is translatable - - - 'Nachricht 1', - 'message2' => 'Nachricht 2', - 'message3' => 'Nachricht 3'); - -$translate = new Zend_Translator( - array( - 'adapter' => 'array', - 'content' => $english, - 'locale' => 'de_AT' - ) -); - -if ($translate->isTranslated('message1')) { - print "'message1' can be translated"; -} - -if (!($translate->isTranslated('message1', true, 'de'))) { - print "'message1' can not be translated to 'de'" - . " as it's available only in 'de_AT'"; -} - -if ($translate->isTranslated('message1', false, 'de')) { - print "'message1' can be translated in 'de_AT' as it falls back to 'de'"; -} -]]> - -
- -
How to log not found translations - - - - When you have a bigger site or you are creating the translation files manually, you - often have the problem that some messages are not translated. But there is an easy - solution for you when you are using Zend_Translator. - - - - You have to follow two or three simple steps. First, you have to create an instance of - Zend_Log. Then you have to attach this instance to - Zend_Translator. See the following example: - - - Log translations - - - 'gettext', - 'content' => $path, - 'locale' => 'de' - ) -); - -// Create a log instance -$writer = new Zend_Log_Writer_Stream('/path/to/file.log'); -$log = new Zend_Log($writer); - -// Attach it to the translation instance -$translate->setOptions( - array( - 'log' => $log, - 'logUntranslated' => true - ) -); - -$translate->translate('unknown string'); -]]> - - - - Now you will have a new notice in the log: - Untranslated message within 'de': unknown string. - - - - - You should note that any translation which can not be found will be logged. This - means all translations when a user requests a language which is not supported. Also - every request for a message which can not be translated will be logged. Be aware, - that 100 people requesting the same translation, will result 100 logged notices. - - - - - This feature can not only be used to log messages but also to attach this untranslated - messages into an empty translation file. To do so you will have to write your own log - writer which writes the format you want to have and strips the prepending "Untranslated - message". - - - - You can also set the 'logMessage' option when you want to have your - own log message. Use the '%message%' token for placing the - messageId within your log message, and the '%locale%' token for the - requested locale. See the following example for a self defined log message: - - - Self defined log messages - - - 'gettext', - 'content' => $path, - 'locale' => 'de' - ) -); - -// Create a log instance -$writer = new Zend_Log_Writer_Stream('/path/to/file.log'); -$log = new Zend_Log($writer); - -// Attach it to the translation instance -$translate->setOptions( - array( - 'log' => $log, - 'logMessage' => "Missing '%message%' within locale '%locale%'", - 'logUntranslated' => true - ) -); - -$translate->translate('unknown string'); -]]> - - - - Additionally you are also able to change the priority which is used to write the message - into the log. Per default the priority Zend_Log::NOTICE is used. - It equals with 5. When you want to change the priority you can use - any of Zend_Log's priorities. See the following example: - - - Self defined log priority - - - 'gettext', - 'content' => $path, - 'locale' => 'de', - 'log' => $log, - 'logMessage' => "Missing '%message%' within locale '%locale%'", - 'logPriority' => Zend_Log::ALERT, - 'logUntranslated' => true - ) -); - -$translate->translate('unknown string'); -]]> - -
- -
Accessing source data - - - - Sometimes it is useful to have access to the translation source data. Therefor - the following two functions are provided. - - - - The getMessageIds($locale = null) method returns all known - message IDs as array. - - - - When you want to know the message ID for a given translation then you can use the - getMessageId() method. - - - - The getMessages($locale = null) method returns the complete - translation source as an array. The message ID is used as key and the translation data - as value. - - - - Both methods accept an optional parameter $locale which, if set, - returns the translation data for the specified language. If this parameter is not given, - the actual set language will be used. Keep in mind that normally all translations should - be available in all languages. Which means that in a normal situation you will not have - to set this parameter. - - - - Additionally the getMessages() method can be used to return the - complete translation dictionary using the pseudo-locale 'all'. This will return all - available translation data for each added locale. - - - - - Attention: the returned array can be very big, - depending on the number of added locales and the amount of translation data. - - - - Handling languages with adapters - - - getMessageIds(); -print_r($messageIds); - -// or just for the specified language -$messageIds = $translate->getMessageIds('en_US'); -print_r($messageIds); - -// returns all the complete translation data -$source = $translate->getMessages(); -print_r($source); -]]> - -
-
diff --git a/documentation/manual/en/module_specs/Zend_Translator-Introduction.xml b/documentation/manual/en/module_specs/Zend_Translator-Introduction.xml deleted file mode 100644 index 696d6abcebf..00000000000 --- a/documentation/manual/en/module_specs/Zend_Translator-Introduction.xml +++ /dev/null @@ -1,158 +0,0 @@ - - - -
Introduction - - - - Zend_Translator is Zend Framework's solution for multilingual - applications. - - - - In multilingual applications, the content must be translated into - several languages and display content depending on the user's language. - PHP offers already several ways to handle such problems, however - the PHP solution has some problems: - - - - - - Inconsistent API: - There is no single API for the different source formats. - The usage of gettext for example is very complicated. - - - - - - PHP supports only gettext and native array: - PHP itself offers only support for array or gettext. - All other source formats have to be coded manually, - because there is no native support. - - - - - - No detection of the default language: - The default language of the user cannot be detected without - deeper knowledge of the backgrounds for - the different web browsers. - - - - - - Gettext is not thread-safe: - PHP's gettext library is not thread safe, and it - should not be used in a multithreaded environment. - This is due to problems with gettext itself, not PHP, - but it is an existing problem. - - - - - - Zend_Translator does not have the above problems. This is why we - recommend using Zend_Translator instead of PHP's - native functions. The benefits of Zend_Translator are: - - - - - - Supports multiple source formats: - Zend_Translator supports several source formats, including - those supported by PHP, and other formats including TMX - and CSV files. - - - - - - Thread-safe gettext: - The gettext reader of Zend_Translator is thread-safe. - There are no problems using it in multi-threaded environments. - - - - - - Easy and generic API: - The API of Zend_Translator is very simple - and requires only a handful of functions. - So it's easy to learn and easy to maintain. - All source formats are handled the same way, so if the format - of your source files change from Gettext to TMX, - you only need to change one line of code to specify the - storage adapter. - - - - - - Detection of the user's standard language: - The preferred language of the user accessing the site can be - detected and used by Zend_Translator. - - - - - - Automatic source detection: - Zend_Translator is capable of detecting and integrating - multiple source files and additionally detect the locale to be used depending on - directory or filenames. - - - - -
Starting multi-lingual - - - - So let's get started with multi-lingual business. - What we want to do is translate our string - output so the view produces the translated output. - Otherwise we would have to write one view - for each language, and no one would like to do this. - Generally, multi-lingual sites are very simple in their design. - There are only four steps you would have to do: - - - - - - Decide which adapter you want to use; - - - - - - Create your view and integrate Zend_Translator in your - code; - - - - - - Create the source file from your code; - - - - - - Translate your source file to the desired language. - - - - - - The following sections guide you through all four steps. - Read through the next few pages to create your own - multi-lingual web application. - -
-
diff --git a/documentation/manual/en/module_specs/Zend_Translator-Plurals.xml b/documentation/manual/en/module_specs/Zend_Translator-Plurals.xml deleted file mode 100644 index bb2ebd37e2f..00000000000 --- a/documentation/manual/en/module_specs/Zend_Translator-Plurals.xml +++ /dev/null @@ -1,373 +0,0 @@ - -
Plural notations for Translation - - - - As of Zend Framework 1.9, Zend_Translator is able to provide plural - support. Professional translation will always have the need to use plurals as they are - native in almost all languages. - - - - So what are plurals? Generally spoken plurals are words which take into account numeric - meanings. But as you may imagine each language has it's own definition of plurals. - English, for example, supports one plural. We have a singular definition, for example - "car", which means implicit one car, and we have the plural definition, "cars" which could - mean more than one car but also zero cars. Other languages like Russian or Polish have - more plurals and also the rules for plurals are different. - - - - When you want to use plurals with Zend_Translator you must not need - to know how the plurals are defined, only the translator must know as he does the - translation. The only information you need to have is the language. - - - - There are two ways for using plurals... the traditional one, which means that you use a own - method, and a modern one, which allows you to do plural translations with the same method - as normal translations. - - -
Traditional plural translations - - - - People who worked with gettext in past will be more common with traditional plural - translations. There is a own plural() method which can be - used for plural translations. - - - Example of traditional plural translations - - - - The plural() method accepts 4 parameters. The first - parameter is the singular messageId, the second is the plural messageId and the - third is the number or amount. - - - - The number will be used to detect the plural which has to be returned. A optional - fourth parameter can be used to give a locale which will be used to return the - translation. - - - 'gettext', - 'content' => '/path/to/german.mo', - 'locale' => 'de' - ) -); -$translate->plural('Car', 'Cars', $number); -]]> - -
- -
Modern plural translations - - - - As traditional plural translations are restricted to source code using English plurals - we added a new way for plural translations. It allows to use the same - translate() for standard and for plural translations. - - - - To use plural translations with translate() you need to give - an array as messageId instead of an string. This array must have the original plural - messageId's, then the amount and at last an optional locale when your given messageId's - are not in English notation. - - - Example of modern plural translations - - - - When we want to translate the same plural definitions like in the previous our - example would have to be defined like below. - - - 'gettext', - 'content' => '/path/to/german.mo', - 'locale' => 'de' - ) -); -$translate->translate(array('Car', 'Cars', $number)); -]]> - - - - Using modern plural translations it is also possible to use any language as source - for messageId's. - - - Example of modern plural translations using a different source language - - - - Let's expect we want to use Russian and let's also expect that the given - messageId's are Russian and not English. - - - 'gettext', - 'content' => '/path/to/german.mo', - 'locale' => 'de' - ) -); -$translate->translate( - array( - 'Car', - 'Cars first plural', - 'Cars second plural', - $number, - 'ru' - ) -); -]]> - - - - As you can see you can give more than just the one English plural. But you must give - the source language in this case so Zend_Translator knows which - plural rules it has to apply. - - - - When you omit the plural language then English will be used per default and any - additional plural definition will be ignored. - -
- -
Plural source files - - - - Not all source formats support plural forms. Look into this list for details: - - - Plural support - - - - - - Adapter - Plurals supported - - - - - - Array - yes - - - - Csv - yes - - - - Gettext - yes - - - - Ini - no - - - - Qt - no - - - - Tbx - no - - - - Tmx - no - - - - Xliff - no - - - - XmlTm - no - - - -
- - - Below you can find examples of plural defined source files. - - -
Array source with plural definitions - - - - An array with plural definitions has to look like the following example. - - - array( - 'plural_0 (ru)', - 'plural_1 (ru)', - 'plural_2 (ru)', - 'plural_3 (ru)' - ), - 'plural_1' => '' -); -]]> - - - In the above example 'plural_0' and 'plural_1' are the - plural definitions from the source code. And the array at 'plural_0' - has all translated plural forms available. Take a look at the following example - with real content and translation from English source to German. - - - array( - 'Auto', - 'Autos' - ), - 'Cars' => '' -); -]]> - - - When your translated language supports more plural forms then simply add them to - the array below the first plural form. When your source language supports more - plural forms, than simply add a new empty translation. - -
- -
Csv source with plural definitions - - - - A csv file with plural definitions has to look like the following example. - - - - - - All translated plural forms have to be added after the first plural of the source - language. And all further plural forms of the source language have to be added - below but without translation. Note that you must add a delimiter to empty - source plurals. - -
- -
Gettext source with plural definitions - - - - Gettext sources support plural forms out of the box. There is no need for adoption - as the *.mo file will contain all necessary data. - - - - - Note that gettext does not support the usage of source languages which are not - using english plural forms. When you plan to use a source language which - supports other plural forms like russian for example, then you can not use - gettext sources. - - -
-
- -
Custom plural rules - - - - In rare cases it could be useful to be able to define own plural rules. See Chinese for - example. This language defines two plural rules. Per default it does not use plurals. - But in rare cases it uses a rule like (number == 1) ? 0 : 1. - - - - Also when you want to use a language which has no known plural rules, and would want to - define your own rules. - - - - This can be done by using Zend_Translator_Plural::setRule(). - The method expects two parameters which must be given. A rule, which is simply a - callback to a self defined method. And a locale for which the rule will be used. - - - - Your rule could look like this: - - - - - - As you see, your rule must accept one parameter. It is the number which you will use to - return which plural the translation has to use. In our example we defined that when we - get a '10' the plural definition 0 has to be used, in all other cases we're using 1. - - - - Your rules can be as simple or as complicated as you want. You must only return an - integer value. The plural definition 0 stands for singular translation, and 1 stands for - the first plural rule. - - - - To activate your rule, and to link it to the wished locale, you have to call it like - this: - - - - - - Now we linked our plural definition to the Chinese language. - - - - You can define one plural rule for every language. But you should be aware that you set - the plural rules before you are doing translations. - - - Define custom plurals only when needed - - - - Zend_Translator defines plurals for most known languages. - You should not define own plurals when you are not in need. The default rules work - most of time. - - -
-
diff --git a/documentation/manual/en/module_specs/Zend_Translator-SourceCreation.xml b/documentation/manual/en/module_specs/Zend_Translator-SourceCreation.xml deleted file mode 100644 index d160bb81ba3..00000000000 --- a/documentation/manual/en/module_specs/Zend_Translator-SourceCreation.xml +++ /dev/null @@ -1,386 +0,0 @@ - -
Creating source files - - - - Below you will find a description of the different source formats - which can be used with Zend_Translator. - - - - - Note that most of the described formats should be created by using - a tool or a generation process. These Tools and processes are not part - of Zend Framework and for most of the described formats free tools - are available. - - - -
Creating Array source files - - - Array source files are plain arrays. But you have to define them - manually since there is no tool to aid this. - But because they are so simple, it's the fastest way to look up - messages if your code works as expected. It's generally the best - adapter to get started with translation business. - - - 'message1', - 'message2' => 'message2', - 'message3' => 'message3'); - -$german = array( - 'message1' => 'Nachricht1', - 'message2' => 'Nachricht2', - 'message3' => 'Nachricht3'); - -$translate = new Zend_Translator( - array( - 'adapter' => 'array', - 'content' => $english, - 'locale' => 'en' - ) -); -$translate->addTranslation(array('content' => $german, 'locale' => 'de')); -]]> - - - Since release 1.5 it is also supported to have arrays included within an external file. - You just have to provide the filename and Zend_Translator will - automatically include it and look for the array. See the following example for details: - - - 'Nachricht1', - 'message2' => 'Nachricht2', - 'message3' => 'Nachricht3'); - -// controller -$translate = new Zend_Translator( - array( - 'adapter' => 'array', - 'content' => '/path/to/myarray.php', - 'locale' => 'de' - ) -); -]]> - - - - Files which do not return an array will fail to be included. - Also any output within this file will be ignored and suppressed. - - -
- -
Creating Gettext source files - - - Gettext source files are created by GNU's gettext library. - There are several free tools available that can parse your - code files and create the needed gettext source files. - These have the extension *.mo - and they are binary files. - An open source tool for creating the files is - poEdit. - This tool also supports you during the translation process itself. - - - 'gettext', - 'content' => '/path/to/english.mo', - 'locale' => 'en' - ) -); -$translate->addTranslation( - array( - 'content' => '/path/to/german.mo', - 'locale' => 'de' - ) -); -]]> - - - As you can see the adapters are used exactly the same way, - with one small difference: - change array to gettext. All other usages are - exactly the same as with all other adapters. - With the gettext adapter you no longer have to be aware of - gettext's standard directory structure, - bindtextdomain and textdomain. - Just give the path and filename to the adapter. - - - - - You should always use UTF-8 as source encoding. - Otherwise you will have problems when using two - different source encodings. - E.g. one of your source files is encoded - with ISO-8815-11 and another one with CP815. - You can set only one encoding for your source file, - so one of your languages probably will not display correctly. - - - - UTF-8 is a portable format which supports all languages. - When using UTF-8 for all languages, you will eliminate - the problem of incompatible encodings. - - - - - Many gettext editors add adapter informations as empty translation string. - This is the reason why empty strings are not translated when using the - gettext adapter. Instead they are erased from the translation table and - provided by the getAdapterInfo() method. It will return - the adapter informations for all added gettext files as array using the - filename as key. - - - 'gettext', - 'content' => '/path/to/english.mo', - 'locale' => 'en' - ) -); -print_r($translate->getAdapterInfo()); -]]> -
- -
Creating TMX source files - - - TMX source files are a new industry standard. - They have the advantage of being XML files and so they are - readable by every editor and of course by humans. - You can either create TMX files manually with a text editor, - or you can use a special tool. But most tools currently available for - creating TMX source files are not freely available. - - - Example TMX file - - - - -
-
- - - Nachricht1 - message1 - - - Nachricht2 - message2 - - -
-]]>
- - 'tmx', - 'content' => 'path/to/mytranslation.tmx', - 'locale' => 'en' - ) -); -]]> -
- - - TMX files can have several languages within the same file. - All other included languages are added automatically, - so you do not have to call addTranslation(). - - - - If you want to have only specified languages from the source translated you can - set the option defined_language' to TRUE. - With this option you can add the wished languages explicitly with - addTranslation(). The default value for this option is to add all - languages. - - - Option useId - - - - When you set the useId option to FALSE - then the srclang header will be used to define the language - which sets the message. - - - - In our example the message key would message1 per default. - When this option is set to FALSE the message key - Nachricht1 would be used. - - - - Note that the tuv entry which is related to the - srclang entry must be the first - tuv entry which is set like shown in the above example. - - -
- -
Creating CSV source files - - - CSV source files are small and human readable. - If your customers want to translate their own, - you will probably use the CSV adapter. - - - Example CSV file - - - - 'csv', - 'content' => '/path/to/mytranslation.csv', - 'locale' => 'de' - ) -); -$translate->addTranslation( - array( - 'content' => 'path/to/other.csv', - 'locale' => 'fr' - ) -); -]]> - - - - There are three different options for the CSV adapter. - You can set delimiter, limit and - enclosure. - - - - The default delimiter for CSV string is ';', but - with the option delimiter - you can decide to use another one. - - - - The default limit for a line within a CSV file is '0'. This means - that the end of a CSV line is searched automatically. If you set - limit to any value, then the CSV file will be - read faster, but any line exceeding this limit will be truncated. - - - - The default enclosure to use for CSV files is '". You can - set a different one using the option enclosure. - - - Second CSV file example - - - - 'csv', - 'content' => '/path/to/mytranslation.csv', - 'locale' => 'de', - 'delimiter' => ',' - ) -); - -$translate->addTranslation( - array( - 'content' => '/path/to/other.csv', - 'locale' => 'fr' - ) -); -]]> - - - - - When you are using non-ASCII characters within your CSV file, like umlauts or UTF-8 - chars, then you should always use enclosure. Omitting the enclosure can lead to - missing characters in your translation. - - -
- -
Creating INI source files - - - INI source files are human readable but normally not very small as - they also include other data beside translations. If you have data which shall be - editable by your customers you can use the INI adapter. - - - Example INI file - - - - 'ini', - 'content' => '/path/to/mytranslation.ini', - 'locale' => 'de' - ) -); -$translate->addTranslation( - array( - 'content' => '/path/to/other.ini', - 'locale' => 'it' - ) -); -]]> - - - - INI files have several restrictions. If a value in the - INI file contains any non-alphanumeric characters it needs to be - enclosed in double-quotes ("). There are also reserved words which - must not be used as keys for INI files. These include: - NULL, yes, no, TRUE, and - FALSE. Values NULL, no - and FALSE results in "", - yes and TRUE results in '1'. Characters - {}|&~![()" must not be used anywhere in the key and have a - special meaning in the value. Do not use them as it will produce unexpected behaviour. - -
-
diff --git a/documentation/manual/en/module_specs/Zend_Translator-Using.xml b/documentation/manual/en/module_specs/Zend_Translator-Using.xml deleted file mode 100644 index 0bdcb91e6d1..00000000000 --- a/documentation/manual/en/module_specs/Zend_Translator-Using.xml +++ /dev/null @@ -1,322 +0,0 @@ - -
Using Translation Adapters - - - - The next step is to use the adapter within your code. - - - Example of single-language PHP code - - - - - - - The example above shows some output with no support for translation. - You probably write your code in your native language. - Generally you need to translate not only the output, - but also error and log messages. - - - - The next step is to integrate Zend_Translator into your existing code. - Of course it is much easier if you had already written your code with - translation in mind, than changing your code afterwards. - - - Example of multi-lingual PHP code - - - 'gettext', - 'content' => '/my/path/source-de.mo', - 'locale' => 'de' - ) -); -$translate->addTranslation( - array( - 'content' => '/path/to/translation/fr-source.mo', - 'locale' => 'fr' - ) -); - -print $translate->_("Example") . "\n"; -print "=======\n"; -print $translate->_("Here is line one") . "\n"; -printf($translate->_("Today is the %1\$s") . "\n", date('d.m.Y')); -print "\n"; - -$translate->setLocale('fr'); -print $translate->_("Here is line two") . "\n"; -]]> - - - - Now let's take a deeper look into what has been done and how to - integrate Zend_Translator into your own code. - - - - Create a new Zend_Translator object and define the base adapter: - - - 'gettext', - 'content' => '/path/to/translation/source-de.mo', - 'locale' => 'de' - ) -); -]]> - - - In this example we chose the - Gettext Adapter. - We place our file source-de.mo - into the directory /path/to/translation. - The gettext file will have German translation included, - and we also added another language source for French. - - - - The next step is to wrap all strings which are to be translated. - The simplest approach is to have only simple strings or sentences - like this: - - - _("Example") . "\n"; -print "=======\n"; -print $translate->_("Here is line one") . "\n"; -]]> - - - Some strings do not needed to be translated. - The separating line is always a separating line, - even in other languages. - - - - Having data values integrated into a translation string is also - supported through the use of embedded parameters. - - - _("Today is the %1\$s") . "\n", date("d.m.Y")); -]]> - - - Instead of print(), use the printf() - function and replace all parameters with %1\$s parts. - The first is %1\$s, the second is %2\$s, - and so on. This way a translation can be done without knowing - the exact value. In our example, the date is always the actual day, - but the string can be translated without the knowledge of the actual - day. - - - - Each string is identified in the translation storage by a message ID. - You can use message IDs instead of strings in your code, like this: - - - _(1) . "\n"; -print "=======\n"; -print $translate->_(2) . "\n"; -]]> - - - But doing this has several disadvantages: - - - - You can not see what your code should output just by viewing your code. - - - - Also you will have problems if some strings are not translated. - You must always keep in mind how translation works. - First Zend_Translator checks whether the specified language has a - translation for the given message ID or string. - If no translation string has been found it refers to the next lower - level language as defined within Zend_Locale. - So "de_AT" becomes - "de" only. - If there is no translation found for - "de" either, - then the original message is returned. - This way you always have an output, even in case the message translation - does not exist in your message storage. - Zend_Translator never throws an error or exception when translating - strings. - - -
Translation Source Structures - - - - Your next step is to create the translation sources for the - languages you want to translate. - Every adapter is created its own way as described here, - but there are common features applicable for all adapters. - - - - You have to decide where to store your translation source files. - Using Zend_Translator you are not restricted in any way. - The following structures are preferable: - - - - - - Single structured source - - - - - - Positive: all source files for every languages are stored - in one directory. No splitting of related files. - - - - - - Language structured source - - - - - - Positive: Every language is stored in their own directories. - Easy translation, as every language team has to translate - only one directory. Also the usage of multiple files is transparent. - - - - - - Application structured source - - - - - - Positive: all source files for every language are stored - in one directory. No splitting of related files. - - - - Negative: having multiple files for the same language can be - problematic. - - - - - - Gettext structured source - - - - - - Positive: existing gettext sources can be used without changing - structure. - - - - Negative: having sub-sub directories may be confusing - for people who have not used gettext before. - - - - - - File structured source - - - - - - Positive: translation files are localted near their source. - - - - Negative: too many and also small translation files result in - being tedious to translate. - Also every file has to be added as translation source. - - - - - - Single structured and language structured source files are most - usable for Zend_Translator. - - - - So now, that we know which structure we want to have, - we should create our translation source files. - -
-
diff --git a/documentation/manual/en/module_specs/Zend_View-Helpers-Currency.xml b/documentation/manual/en/module_specs/Zend_View-Helpers-Currency.xml deleted file mode 100644 index 58323c55bea..00000000000 --- a/documentation/manual/en/module_specs/Zend_View-Helpers-Currency.xml +++ /dev/null @@ -1,148 +0,0 @@ - -
Currency Helper - - - - Displaying localized currency values is a common task; the - Zend_Currency view helper is intended to simply this task. See the - Zend_Currency documentation for specifics - on this localization feature. In this section, we will focus simply on usage of the view - helper. - - - - There are several ways to initiate the Currency view helper: - - - - - - Registered, through a previously registered instance in - Zend_Registry. - - - - - - Afterwards, through the fluent interface. - - - - - - Directly, through instantiating the class. - - - - - - A registered instance of Zend_Currency is the preferred usage for - this helper. Doing so, you can select the currency to be used prior to adding the adapter to - the registry. - - - - There are several ways to select the desired currency. First, you may simply provide a - currency string; alternately, you may specify a locale. The preferred way is to use a - locale as this information is automatically detected and selected via the - HTTP client headers provided when a user accesses your application, and - ensures the currency provided will match their locale. - - - - - We are speaking of "locales" instead of "languages" because a language may vary based on - the geographical region in which it is used. For example, English is spoken in different - dialects: British English, American English, etc. As a currency always correlates to a - country you must give a fully-qualified locale, which means providing both the language - and region. Therefore, we say "locale" instead of "language." - - - - Registered instance - - - - To use a registered instance, simply create an instance of - Zend_Currency and register it within - Zend_Registry using Zend_Currency as its - key. - - - currency(1234.56); -// this returns 'ā‚¬ 1.234,56' -]]> - - - - If you are more familiar with the fluent interface, then you can also create an instance - within your view and configure the helper afterwards. - - - Within the view - - - - To use the fluent interface, create an instance of Zend_Currency, - call the helper without a parameter, and call the setCurrency() - method. - - - currency()->setCurrency($currency)->currency(1234.56); -// this returns 'ā‚¬ 1.234,56' -]]> - - - - If you are using the helper without Zend_View then you can - also use it directly. - - - Direct usage - - - currency(1234.56); // this returns 'ā‚¬ 1.234,56' -]]> - - - - As already seen, the currency() method is used to return the - currency string. Just call it with the value you want to display as a currency. It also - accepts some options which may be used to change the behaviour and output of the helper. - - - Direct usage - - - currency(1234.56); // this returns 'ā‚¬ 1.234,56' -echo $helper->currency(1234.56, array('precision' => 1)); -// this returns 'ā‚¬ 1.234,6' -]]> - - - - For details about the available options, search for Zend_Currency's - toCurrency() method. - -
diff --git a/documentation/manual/en/module_specs/Zend_View-Helpers-Navigation.xml b/documentation/manual/en/module_specs/Zend_View-Helpers-Navigation.xml index 7d8bcf65b5a..3fde732feb4 100644 --- a/documentation/manual/en/module_specs/Zend_View-Helpers-Navigation.xml +++ b/documentation/manual/en/module_specs/Zend_View-Helpers-Navigation.xml @@ -55,7 +55,7 @@ All built-in helpers extend Zend_View_Helper_Navigation_HelperAbstract, which adds integration with ACL and - translation. The abstract class + translation. The abstract class implements the interface Zend_View_Helper_Navigation_Helper, which defines the following methods: @@ -247,12 +247,9 @@ $this->navigation()->addPage(array( The navigation helpers support translation of page labels and titles. - You can set a translator of type Zend_Translator - or Zend_Translator_Adapter in the helper using - $helper->setTranslator($translator), or like with other - I18n-enabled components; by adding the translator to - the registry by using the key - Zend_Translator. + You can set a translator of type Zend\I18n\Translator + in the helper using + $helper->setTranslator($translator). diff --git a/documentation/manual/en/module_specs/Zend_View-Helpers-Translator.xml b/documentation/manual/en/module_specs/Zend_View-Helpers-Translator.xml deleted file mode 100644 index 93bc9dd096d..00000000000 --- a/documentation/manual/en/module_specs/Zend_View-Helpers-Translator.xml +++ /dev/null @@ -1,271 +0,0 @@ - -
Translator Helper - - - - Often web sites are available in several languages. To translate the - content of a site you should simply use Zend_Translator and to - integrate Zend_Translator within your view you should use - the Translator View Helper. - - - - In all following examples we are using the simple Array Translation - Adapter. Of course you can also use any instance of - Zend_Translator and also any subclasses of - Zend_Translator_Adapter. There are several ways to initiate - the Translator View Helper: - - - - - - Registered, through a previously registered instance in - Zend_Registry - - - - - - Afterwards, through the fluent interface - - - - - - Directly, through initiating the class - - - - - - A registered instance of Zend_Translator is the preferred - usage for this helper. You can also select the locale to be used simply - before you add the adapter to the registry. - - - - - We are speaking of locales instead of languages because a language - also may contain a region. For example English is spoken in - different dialects. There may be a translation for British and one - for American English. Therefore, we say "locale" instead of - "language." - - - - Registered instance - - - - To use a registered instance just create an instance of - Zend_Translator or Zend_Translator_Adapter - and register it within Zend_Registry using - Zend_Translator as its key. - - - 'array', - 'content' => array('simple' => 'einfach'), - 'locale' => 'de' - ) -); -Zend_Registry::set('Zend_Translator', $adapter); - -// within your view -echo $this->translate('simple'); -// this returns 'einfach' -]]> - - - - If you are more familiar with the fluent interface, then you can also - create an instance within your view and initiate the helper afterwards. - - - Within the view - - - - To use the fluent interface, create an instance of - Zend_Translator or Zend_Translator_Adapter, - call the helper without a parameter, and call the - setTranslator() method. - - - 'array', - 'content' => array('simple' => 'einfach'), - 'locale' => 'de' - ) -); -$this->translate()->setTranslator($adapter)->translate('simple'); -// this returns 'einfach' -]]> - - - - If you are using the helper without Zend_View then you can - also use it directly. - - - Direct usage - - - 'array', - 'content' => array('simple' => 'einfach'), - 'locale' => 'de' - ) -); - -// initiate the adapter -$translate = new Zend_View_Helper_Translator($adapter); -print $translate->translate('simple'); // this returns 'einfach' -]]> - - - You would use this way if you are not working with - Zend_View and need to create translated output. - - - - - As already seen, the translate() method is used to return - the translation. Just call it with the needed messageid of your - translation adapter. But it can also replace parameters within the - translation string. Therefore, it accepts variable parameters in two ways: - either as a list of parameters, or as an array of parameters. As examples: - - - Single parameter - - - - To use a single parameter just add it to the method. - - - translate("Today is %1\$s", $date); -// could return 'Heute ist Monday' -]]> - - - - - Keep in mind that if you are using parameters which are also text, - you may also need to translate these parameters. - - - - List of parameters - - - - Or use a list of parameters and add it to the method. - - - translate("Today is %1\$s in %2\$s. Actual time: %3\$s", - $date, - $month, - $time); -// Could return 'Heute ist Monday in April. Aktuelle Zeit: 11:20:55' -]]> - - - Array of parameters - - - - Or use an array of parameters and add it to the method. - - - translate("Today is %1\$s in %2\$s. Actual time: %3\$s", $date); -// Could return 'Heute ist Monday in April. Aktuelle Zeit: 11:20:55' -]]> - - - - Sometimes it is necessary to change the locale of the translation. This - can be done either dynamically per translation or statically for all - following translations. And you can use it with both a parameter list - and an array of parameters. In both cases the locale must be given as - the last single parameter. - - - Change locale dynamically - - - translate("Today is %1\$s in %2\$s. Actual time: %3\$s", $date, 'it'); -]]> - - - - This example returns the Italian translation for the messageid. But it - will only be used once. The next translation will use the locale from - the adapter. Normally you will set the desired locale within the - translation adapter before you add it to the registry. But you can also - set the locale from within the helper: - - - Change locale statically - - - translate()->setLocale('it'); -$this->translate("Today is %1\$s in %2\$s. Actual time: %3\$s", $date); -]]> - - - - The above example sets 'it' as the new default locale which - will be used for all further translations. - - - - Of course there is also a getLocale() method to get the - currently set locale. - - - Get the currently set locale - - - translate()->getLocale(); - -$this->translate()->setLocale('it'); -$this->translate("Today is %1\$s in %2\$s. Actual time: %3\$s", $date); - -// returns 'it' as new set default locale -$this->translate()->getLocale(); -]]> - -
diff --git a/documentation/manual/en/module_specs/zend.db.adapter.xml b/documentation/manual/en/module_specs/zend.db.adapter.xml new file mode 100644 index 00000000000..e6278146057 --- /dev/null +++ b/documentation/manual/en/module_specs/zend.db.adapter.xml @@ -0,0 +1,397 @@ + +
Zend\Db\Adapter + + + The Adapter object is the most important sub-component of Zend\Db. + It is responsible for adapting any code written in or for Zend\Db + to the targeted php extensions and vendor databases. In doing this, + it creates an abstraction layer for the PHP extensions, which is called + the "Driver" portion of the Zend\Db adapter. It also creates a lightweight + abstraction layer for the various idiosyncrasies that each vendor specific + platform might have in it's SQL/RDBMS implementation which is called the + "Platform" portion of the adapter. + + +
Creating an Adapter (Quickstart) + + + Creating an adapter can simply be done by instantiating the + Zend\Db\Adapter\Adapter class. The most common use case, while not the + most explicit, is to pass an array of information to the Adapter. + + + + + + This driver array is an abstraction for the extension level required + parameters. Here is a table for the + + + Connection Array Keys + + + + Name + Required + Notes + + + + + + driver + + + required + + + Mysqli, Sqlsrv, Pdo_Sqlite, Pdo_Mysql, Pdo-OtherPdoDriver + + + + + database + + + generally required + + + the name of the database (schema) + + + + + username + + + generally required + + + the connection username + + + + + password + + + generally required + + + the connection password + + + + + hostname + + + not generally required + + + the IP address or hostname to connect to + + + + + port + + + not generally required + + + not generally required the port to connect to (if applicable) + + + + + characterset + + + not generally required + + + not generally required the character set to use + + + + +
+ + + * other names will work as well. Effectively, if the PHP manual + uses a particular naming, this naming will be supported by our Driver. + For example, dbname in most cases will also work for 'database'. Another + example is that in the case of Sqlsrv, UID will work in place of username. + Which format you chose is up to you, but the above table represents the + official abstraction names. + + + + So, for example, a MySQL connection using ext/mysqli: + + + 'Mysqli', + 'database' => 'zend_db_example', + 'username' => 'developer', + 'password' => 'developer-password' +)); +]]> + + + Another example, of a Sqlite connection via PDO: + + + 'Pdo_Sqlite', + 'database' => 'path/to/sqlite.db' + )); +]]> + + + It is important to know that by using this style of adapter creation, the Adapter + will attempt to create any dependencies that were not explicitly provided. A Driver + object will be created from the contents of the $driver array provided in the + constructor. A Platform object will be created based off the type of Driver object + that was instantiated. And lastly, a default ResultSet object is created and utilized. + Any of these objects can be injected, to do this, see the next section. + + + +
+ +
Creating an Adapter (By Injecting Dependencies) + + + The more expressive and explicit way of creating an adapter is by injecting all your + dependencies up front. Zend\Db\Adapter\Adapter uses constructor injection, and all + required dependencies are injected through the constructor, which has the following + signature (in pseudo-code): + + + + + + + What can be injected: + + + + $driver - an array or an instance of Zend\Db\Adapter\Driver\DriverInterface + $platform - (optional) an instance of Zend\Db\Platform\PlatformInterface, the default will be created based off the driver implementation + $queryResultSetPrototype - (optional) an instance of Zend\Db\ResultSet\ResultSet, to understand this object's role, see the section below on querying through the adapter + + +
+ +
Query Preparation Through <classname>Zend\Db\Adapter\Adapter</classname>::query() + + + By default, query() prefers that you use "preparation" as a means for processing SQL + statements. This generally means that you will supply a SQL statement with the values + substituted by placeholders, and then the parameters for those placeholders are + supplied separately. An example of this workflow with Zend\Db\Adapter\Adapter is: + + + query('SELECT * FROM `artist` WHERE `id` = ?', array(5)); +]]> + + + The above example will go through the following steps: + + + + + + create a new Statement object + + + + + prepare an array into a ParameterContainer if necessary + + + + + inject the ParameterContainer into the Statement object + + + + + execute the Statement object, producing a Result object + + + + + check the Result object to check if the supplied sql was a "query", or a result set producing statement + + + + + if it is a result set producing query, clone the ResultSet prototype, inject Result as datasource, return it + + + + + else, return the Result + + + + + +
+ + +
Query Execution Through Zend\Db\Adapter\Adapter::query() + + + In some cases, you have to execute statements directly. The primary purpose for + needing to execute sql instead of prepare and execute a sql statement, might be + because you are attempting to execute a DDL statement (which in most extensions + and vendor platforms), are un-preparable. An example of executing: + + + + query('ALTER TABLE ADD INDEX(`foo_index`) ON (`foo_column`))', Adapter::QUERY_MODE_EXECUTE); +]]> + + + The primary difference to notice is that you must provide the Adapter::QUERY_MODE_EXECUTE + (execute) as the second parameter. + + +
+ + +
Creating Statements + + + While query() is highly useful for one-off and quick querying of a + database through Adapter, it generally makes more sense to create a + statement and interact with it directly, so that you have greater control + over the prepare-then-execute workflow. To do this, Adapter gives you a + routine called createStatement() that allows you to create a Driver + specific Statement to use so you can manage your own prepare-then-execute workflow. + + + createStatement($sql, $optionalParameters); +$result = $statement->execute(); +]]> + +
+ + +
Using The Platform Object + + + The Platform object provides an API to assist in crafting queries in a way that + is specific to the SQL implementation of a particular vendor. Nuances such + as how identifiers or values are quoted, or what the identifier separator + character is are handled by this object. To get an idea of the capabilities, + the interface for a platform object looks like this: + + + + + + For example, to quote a column name, specific to MySQL's way of quoting: + + + quoteIdentifier('first_name'); // returns `first_name` +]]> + + + Generally speaking, it is easier to get the proper Platform instance from the adapter: + + + getPlatform(); +// or +$platform = $adapter->platform; // magic property access +]]> + +
+ + +
Using The Parameter Container + + + The ParameterContainer object is a container for the various parameters that + need to be passed into a Statement object to fulfill all the various + parameterized parts of the SQL statement. This object implements the + ArrayAccess interface. + + +
+ +
Examples + + + Creating a Driver and Vendor portable Query, Preparing and Iterating Result + + + platform->quoteIdentifier($name); }; +$fp = function($name) use ($adapter) { return $adapter->driver->formatParameterName($name); }; + +$sql = 'UPDATE ' . $qi('artist') + . ' SET ' . $qi('name') . ' = ' . $fp('name') + . ' WHERE ' . $qi('id') . ' = ' . $fp('id'); + +/* @var $statement Zend\Db\Adapter\DriverStatementInterface */ +$statement = $adapter->query($sql); + +$parameters = array( + 'name' => 'Updated Artist', + 'id' => 1 +); + +$statement->execute($parameters); + +// DATA INSERTED, NOW CHECK + +/* @var $statement Zend\Db\Adapter\DriverStatementInterface */ +$statement = $adapter->query('SELECT * FROM ' + . $qi('artist') + . ' WHERE id = ' . $fp('id')); + +/* @var $results Zend\Db\ResultSet\ResultSet */ +$results = $statement->execute(array('id' => 1)); + +$row = $results->current(); +$name = $row['name']; +]]> + +
+ +
diff --git a/documentation/manual/en/module_specs/zend.db.metadata.xml b/documentation/manual/en/module_specs/zend.db.metadata.xml new file mode 100644 index 00000000000..471007c13fd --- /dev/null +++ b/documentation/manual/en/module_specs/zend.db.metadata.xml @@ -0,0 +1,251 @@ + +
+ Zend\Db\Metadata + + + Zend\Db\Metadata is as sub-component of Zend\Db that makes it possible + to get metadata information about tables, columns, constraints, triggers, + and other information from a database in a standardized way. The primary + interface for the Metadata objects is: + + + + +
+ Basic Usage + + + Usage of Zend\Db\Metadata is very straight forward. The top level + class Zend\Db\Metadata\Metadata will, given an adapter, choose the + best strategy (based on the database platform being used) for + retrieving metadata. In most cases, information will come from + querying the INFORMATION_SCHEMA tables generally accessible to + all database connections about the currently accessible schema. + + + + Metadata::get*Names() methods will return an array of strings, while + the other methods will return specific value objects with the + containing information. This is best demonstrated by the script below. + + + getTableNames(); + +foreach ($tableNames as $tableName) { + echo 'In Table ' . $tableName . PHP_EOL; + + /** @var $table Zend\Db\Metadata\Object\TableObject */ + $table = $metadata->getTable($tableName); + + echo ' With columns: ' . PHP_EOL; + foreach ($table->getColumns() as $column) { + /** @var $column Zend\Db\Metadata\Object\ColumnObject */ + echo ' ' . $column->getName() + . ' -> ' . $column->getDataType() + . PHP_EOL; + } + + echo PHP_EOL; + echo ' With constraints: ' . PHP_EOL; + + foreach ($metadata->getConstraints($tableName) as $constraint) { + /** @var $constraint Zend\Db\Metadata\Object\ConstraintObject */ + echo ' ' . $constraint->getName() + . ' -> ' . $constraint->getType() + . PHP_EOL; + if (!$constraint->hasColumns()) { + continue; + } + echo ' column: ' . implode(', ', $constraint->getColumns()); + if ($constraint->isForeignKey()) { + $fkCols = array(); + foreach ($constraint->getReferencedColumns() as $refColumn) { + $fkCols[] = $constraint->getReferencedTableName() . '.' . $refColumn; + } + echo ' => ' . implode(', ', $fkCols); + } + echo PHP_EOL; + + } + + echo '----' . PHP_EOL; +} +]]> + + + Metadata returns value objects that provide an interface to help + developers better explore the metadata. Below is the API for the + various value objects: + + + + The TableObject: + + + + + + The ColumnObject: + + + + + + The ConstraintObject: + + + + + + The TriggerObject: + + + + +
+ +
\ No newline at end of file diff --git a/documentation/manual/en/module_specs/zend.db.result-set.xml b/documentation/manual/en/module_specs/zend.db.result-set.xml new file mode 100644 index 00000000000..3dd8ac69858 --- /dev/null +++ b/documentation/manual/en/module_specs/zend.db.result-set.xml @@ -0,0 +1,116 @@ + +
+ Zend\Db\ResultSet + + + Zend\Db\ResultSet is a sub-component of Zend\Db for abstracting + the iteration of rowset producing queries. While data sources for + this can be anything that is iterable, generally a + Zend\Db\Adpater\Driver\ResultInterface based object is the primary + source for retrieving data. + + + + Zend\Db\ResultSet's must implement the Zend\Db\ResultSet\ResultSetInterface + and all sub-components of Zend\Db that return a ResultSet as part + of their API will assume an instance of a ResultSetInterface should be + returned. In most casts, the Prototype pattern will be used by consuming + object to clone a prototype of a ResultSet and return a specialized + ResultSet with a specific data source injected. The interface of + ResultSetInterface looks like this: + + + + +
+ Quickstart + + + Zend\Db\ResultSet\ResultSet is the most basic form of a ResultSet + object that will expose each row as either an ArrayObject-like object + or an array of row data. The following workflow is based on that + inside Zend\Db\Adapter\Adapter::query(): + + + createStatement($sql); +$stmt->prepare($parameters); +$result = $stmt->execute(); + +if ($result instanceof ResultInterface && $result->isQueryResult()) { + $resultSet = new ResultSet + $resultSet->initialize($result); + + foreach ($resultSet as $row) { + echo $row->my_column . PHP_EOL; + } +} +]]> + +
+ +
+ Zend\Db\ResultSet\HydratingResultSet + + + Zend\Db\ResultSet\HydratingResultSet is a more flexible ResultSet + object that allows the developer to choose an appropriate + "hydration strategy" for getting row data into a target object. + While iterating, HydratingResultSet will take a prototype of a + target object and clone it for each successive new row it iterates. + With this newly cloned row, HydratingResultSet will hydrate + the target object with the row data. + + + + In the example below, rows from the database will be iterated, and + during iteration, HydratingRowSet will use the Reflection based + hydrator to inject the row data directly into the protected members + of the cloned UserEntity object: + + + first_name; } + public function getLastName() { return $this->last_name; } +} + +$stmt = $driver->createStatement($sql); +$stmt->prepare($parameters); +$result = $stmt->execute(); + +if ($result instanceof ResultInterface && $result->isQueryResult()) { + $resultSet = new HydratingResultSet(new ReflectionHydrator, new UserEntity); + $resultSet->initialize($result); + + foreach ($resultSet as $user) { + echo $user->getFirstName() . ' ' . $user->getLastName() . PHP_EOL; + } +} +]]> + + + For more information, see the Zend\Stdlib\Hydrator documentation + to get a better sense of the different strategies that can be + employed in order to populate a target object. + + +
+ +
\ No newline at end of file diff --git a/documentation/manual/en/module_specs/zend.db.row-gateway.xml b/documentation/manual/en/module_specs/zend.db.row-gateway.xml new file mode 100644 index 00000000000..489129b3c7d --- /dev/null +++ b/documentation/manual/en/module_specs/zend.db.row-gateway.xml @@ -0,0 +1,86 @@ + +
+ Zend\Db\RowGateway + + + Zend\Db\RowGateway is a sub-component of Zend\Db + that implements the Row Gateway pattern from PoEAA. This effectively + means that Row Gateway objects primarily model a row in a database, and + have methods such as save() and delete() that will help persist this + row-as-an-object in the database itself. Likewise, after a row from the + database is retrieved, it can then be manipulated and save()'d back to + the database in the same position (row), or it can be delete()'d from the + table. + + + + The interface for a Row Gateway object simply adds save() and delete() + and this is the interface that should be assumed when a component has a + dependency that is expected to be an instance of a RowGateway object: + + + + +
+ Quickstart + + + While most of the time, RowGateway will be used in conjucntion with + other Zend\Db\ResultSet producing objects, it is possible to use it + standalone. To use it standalone, you simply need an Adapter and a + set of data to work with. The following use case demonstrates + Zend\Db\RowGateway\RowGateway usage in its simplest form: + + + query('SELECT * FROM "user" WHERE "id" = 2'); + +// get array of data +$rowData = $resultSet->current()->toArray(); + +// row gateway +$rowGateway = new RowGateway('id', 'my_table', $adapter); +$rowGateway->populate($rowData); + +$rowGateway->first_name = 'New Name'; +$rowGateway->save(); + +// or delete this row: +$rowGateway->delete(); +]]> + + + The workflow described above is greatly simplified when RowGateway + is used in conjunction with the TableGateway feature. What this + achieves is a Table Gateway object that when select()'ing from a + table, will produce a ResultSet that is then capable of producing + valid Row Gateway objects. Its usage looks like this: + + + select(array('id' => 2)); + +$artistRow = $results->current(); // Zend\Db\RowGateway\RowGateway +$artistRow->name = 'New Name'; +$artistRow->save(); +]]> + + + +
+ +
\ No newline at end of file diff --git a/documentation/manual/en/module_specs/zend.db.sql.xml b/documentation/manual/en/module_specs/zend.db.sql.xml new file mode 100644 index 00000000000..05fe97764e4 --- /dev/null +++ b/documentation/manual/en/module_specs/zend.db.sql.xml @@ -0,0 +1,628 @@ + +
+ Zend\Db\Sql + + + Zend\Db\Sql is a SQL abstraction layer for building platform specific + SQL queries via a object-oriented API. The end result of an Zend\Db\Sql + object will be to either produce a Statement and Parameter container that + represents the target query, or a full string that can be directly executed + against the database platform. To achieve this, there is Zend\Db\Sql + objects require a Zend\Db\Adapter\Adapter object in order to produce + the desired results. + + +
+ Zend\Db\Sql\Sql (Quickstart) + + + As there are for primary tasks associated with interacting with a database + (from the DML, or Data Manipulation Language): selecting, inserting, updating + and deleting. As such, there are four primary objects that developers can + interact or building queries, Zend\Db\Sql\Select, + Insert, Update and Delete. + + + + Since these four tasks are so closely related, and generally used together + within the same application, Zend\Db\Sql\Sql objects help you create them + and produce the result you are attempting to achieve. + + + select(); // @return Zend\Db\Sql\Select +$insert = $sql->insert(); // @return Zend\Db\Sql\Insert +$update = $sql->update(); // @return Zend\Db\Sql\Update +$delete = $sql->delete(); // @return Zend\Db\Sql\Delete +]]> + + + As a developer, you can now interact with these objects, as described in + the sections below, to specialize each query. Once they have been populated + with values, they are ready to either be prepared or executed. + + + + To prepare (using a Select object): + + + from('foo'); +$select->where(array('id' => 2)); + +$statement = $sql->prepareStatementForSqlObject($select); +$results = $statement->execute(); +]]> + + + To execute (using a Select object) + + + from('foo'); +$select->where(array('id' => 2)); + +$selectString = $sql->getSqlStringForSqlObject($select); +$results = $adapter->query($selectString, $adapter::QUERY_MODE_EXECUTE); +]]> + + + Zend\Db\Sql\Sql objects can also be bound to a particular table so that in + getting a select, insert, update, or delete object, they are all primarily + seeded with the same table when produced. + + + where(array('id' => 2)); // $select already has the from('foo') applied +]]> + +
+ +
+ Zend\Db\Sql's Select, Insert, Update and Delete + + + Each of these objects implement the following (2) interfaces: + + + + + + These are the functions you can call to either produce (a) a prepared statement, + or (b) a string to be executed. + + +
+ +
+ Zend\Db\Sql\Select + + + Zend\Db\Sql\Select is an object who's primary function is to present a unified + API for building platform specific SQL SELECT queries. The object can be + instantiated and consumed without Zend\Db\Sql\Sql: + + + + + + If a table is provided to the Select object, then from() cannot be called later + to change the name of the table. + + + + Once you have a valid Select object, the following API can be used to further + specify various select statement parts: + + + + + + from(): + + + from('foo'); + +// as an array to specify an alias: +// produces SELECT "t".* FROM "table" AS "t" + +$select->from(array('t' => 'table')); + +// using a Sql\TableIdentifier: +// same output as above + +$select->from(new TableIdentifier(array('t' => 'table'))); +]]> + + + columns(): + + + columns(array('foo', 'bar')); + +// as an associative array with aliases as the keys: +// produces 'bar' AS 'foo', 'bax' AS 'baz' + +$select->columns(array('foo' => 'bar', 'baz' => 'bax')); +]]> + + + join(): + + + join( + 'foo' // table name, + 'id = bar.id', // expression to join on (will be quoted by platform object before insertion), + array('bar', 'baz'), // (optional) list of columns, same requiremetns as columns() above + $select::JOIN_OUTER // (optional), one of inner, outer, left, right also represtned by constants in the API +); + +$select->from(array('f' => 'foo')) // base table + ->join(array('b' => 'bar'), // join table with alias + 'f.foo_id = b.foo_id'); // join expression +]]> + + + where(), having(): + + + + + + order(): + + + order('id DESC'); // produces 'id' DESC + +$select = new Select; +$select->order('id DESC') + ->order('name ASC, age DESC'); // produces 'id' DESC, 'name' ASC, 'age' DESC + +$select = new Select; +$select->order(array('name ASC', 'age DESC')); // produces 'name' ASC, 'age' DESC +]]> + + + limit() and offset(): + + + limit(5); // always takes an integer/numeric +$select->offset(10); // similarly takes an integer/numeric +]]> + +
+ +
+ Zend\Db\Sql\Insert + + + The Insert API: + + + + + + Similarly to Select objects, the table can be set at construction time + or via into(). + + + + columns(): + + + columns(array('foo', 'bar')); // set the valid columns +]]> + + + values(): + + + values(array( + 'col_1' => 'value1', + 'col_2' => 'value2' +)); +]]> + + values(array('col_2' => 'value2'), $insert::VALUES); +]]> + +
+ +
+ Zend\Db\Sql\Update + + + + + set(): + + + set(array('foo' => 'bar', 'baz' => bax')); +]]> + + + where(): + + + + +
+ +
+ Zend\Db\Sql\Delete + + + + + where(): + + + + +
+ +
+ Zend\Db\Sql\Where & Zend\Db\Sql\Having + + + In the following, we will talk about Where, Having is implies as being the same API. + + + + + Effectively, Where and Having extend from the same base object, a + Predicate (and PredicateSet). All of the parts that make up a where + or having that are and'ed or or'd together are called predicates. The full + set of predicates is called a PredicateSet. This object set generally contains + the values (and identifiers) separate from the fragment they belong to until + the last possible moment when the statement is either used to be prepared + (parameteritized), or executed. In parameterization, the parameters will be + replaced with their proper placeholder (a named or positional parameter), and + the values stored inside a Adapter\ParameterContainer. When executed, the values + will be interpolated into the fragments they belong to and properly quoted. + + + + It is important to know that in this API, a distinction is made between what + elements are considered identifiers (TYPE_IDENTIFIER) and which of those is + a value (TYPE_VALUE). There is also a special use case type for literal values + (TYPE_LITERAL). These are all exposed via the Zend\Db\Sql\ExpressionInterface + interface. + + + + The Zend\Db\Sql\Where (Predicate/PredicateSet) API: + + + + + + Each method in the Where API will produce a coresponding Predicate object of a similarly + named type, described below, with the full API of the object: + + + + equalTo(), lessThan(), greaterThan(), lessThanOrEqualTo(), greaterThanOrEqualTo(): + + + equalTo('id', 5); + +// same as the following workflow +$where->addPredicate( + new Predicate\Operator($left, Operator::OPERATOR_EQUAL_TO, $right, $leftType, $rightType) +); + +class Operator implements PredicateInterface +{ + const OPERATOR_EQUAL_TO = '='; + const OP_EQ = '='; + const OPERATOR_NOT_EQUAL_TO = '!='; + const OP_NE = '!='; + const OPERATOR_LESS_THAN = '<'; + const OP_LT = '<'; + const OPERATOR_LESS_THAN_OR_EQUAL_TO = '<='; + const OP_LTE = '<='; + const OPERATOR_GREATER_THAN = '>'; + const OP_GT = '>'; + const OPERATOR_GREATER_THAN_OR_EQUAL_TO = '>='; + const OP_GTE = '>='; + + public function __construct($left = null, $operator = self::OPERATOR_EQUAL_TO, $right = null, $leftType = self::TYPE_IDENTIFIER, $rightType = self::TYPE_VALUE); + public function setLeft($left); + public function getLeft(); + public function setLeftType($type); + public function getLeftType(); + public function setOperator($operator); + public function getOperator(); + public function setRight($value); + public function getRight(); + public function setRightType($type); + public function getRightType(); + public function getExpressionData(); +} +]]> + + + like($identifier, $like): + + + like($identifier, $like): + +// same as +$where->addPredicate( + new Predicate\Like($identifier, $like) +); + +// full API + +class Like implements PredicateInterface +{ + public function __construct($identifier = null, $like = null); + public function setIdentifier($identifier); + public function getIdentifier(); + public function setLike($like); + public function getLike(); +} +]]> + + + literal($literal, $parameter); + + + literal($literal, $parameter); + +// same as +$where->addPredicate( + new Predicate\Expression($literal, $parameter) +); + +// full API +class Expression implements ExpressionInterface, PredicateInterface +{ + const PLACEHOLDER = '?'; + public function __construct($expression = null, $valueParameter = null /*[, $valueParameter, ... ]*/); + public function setExpression($expression); + public function getExpression(); + public function setParameters($parameters); + public function getParameters(); + public function setTypes(array $types); + public function getTypes(); +} +]]> + + + isNull($identifier); + + + isNull($identifier); + +// same as +$where->addPredicate( + new Predicate\IsNull($identifier) +); + +// full API +class IsNull implements PredicateInterface +{ + public function __construct($identifier = null); + public function setIdentifier($identifier); + public function getIdentifier(); +} +]]> + + + isNotNull($identifier); + + + isNotNull($identifier); + +// same as +$where->addPredicate( + new Predicate\IsNotNull($identifier) +); + +// full API +class IsNotNull implements PredicateInterface +{ + public function __construct($identifier = null); + public function setIdentifier($identifier); + public function getIdentifier(); +} +]]> + + + in($identifier, array $valueSet = array()); + + + in($identifier, array $valueSet = array()); + +// same as +$where->addPredicate( + new Predicate\In($identifier, $valueSet) +); + +// full API +class In implements PredicateInterface +{ + public function __construct($identifier = null, array $valueSet = array()); + public function setIdentifier($identifier); + public function getIdentifier(); + public function setValueSet(array $valueSet); + public function getValueSet(); +} +]]> + + + between($identifier, $minValue, $maxValue); + + + between($identifier, $minValue, $maxValue); + +// same as +$where->addPredicate( + new Predicate\Between($identifier, $minValue, $maxValue) +); + +// full API +class Between implements PredicateInterface +{ + public function __construct($identifier = null, $minValue = null, $maxValue = null); + public function setIdentifier($identifier); + public function getIdentifier(); + public function setMinValue($minValue); + public function getMinValue(); + public function setMaxValue($maxValue); + public function getMaxValue(); + public function setSpecification($specification); +} +]]> + +
+
+ + + + + + + + + diff --git a/documentation/manual/en/module_specs/zend.db.table-gateway.xml b/documentation/manual/en/module_specs/zend.db.table-gateway.xml new file mode 100644 index 00000000000..a3b3e4eed2c --- /dev/null +++ b/documentation/manual/en/module_specs/zend.db.table-gateway.xml @@ -0,0 +1,242 @@ + +
+ Zend\Db\TableGateway + + + The Table Gateway object is intended to provide an object + that represents a table in a database, and the methods of + this object mirror the most common operations on a database + table. In code, the interface for such an object looks like this: + + + + + + There are two primary implementations of the TableGatewayInterface + that are of the most useful: AbstractTableGateway and TableGateway. + The AbstractTableGateway is an abstract basic implementation that provides + functionality for select(), insert(), update(), delete(), as well as an + additional API for doing these same kinds of tasks with explicit SQL + objects. These methods are selectWith(), insertWith(), updateWith() + and deleteWith(). In addition, AbstracTableGateway also implements + a "Feature" API, that allows for expanding the behaviors of the + base TableGateway implementation without having to extend the + class with this new functionality. The TableGateway concrete + implementation simply adds a sensible constructor to the AbstractTableGateway + class so that out-of-the-box, TableGateway does not need to be extended + in order to be consumed and utilized to its fullest. + + + +
+ Basic Usage + + + The quickest way to get up and running with Zend\Db\TableGateway is + to configure and utilize the concrete implementation of the TableGateway. + The API of the concrete TableGateway is: + + + + + + The concrete TableGateway object practices constructor injection for + getting dependencies and options into the instance. The table name + and an instance of an Adapter are all that is needed to setup a working + TableGateway object. + + + + Out of the box, this implementation makes no assumptions about table + structure or metadata, and when select() is executed, a simple ResultSet + object with the populated Adapter's Result (the datasource) will be returned + and ready for iteration. + + + select(array('type' => 'PHP')); + +echo 'Projects of type PHP: ' . +foreach ($rowset as $projectRow) { + echo $projectRow['name'] . PHP_EOL; +} + +// or, when expecting a single row: +$artistTable = new TableGateway('artist', $adapter); +$rowset = $artistTable->select(array('id' => 2)); +$artistRow = $rowset->current(); + +var_dump($artistRow->toArray()); +]]> + + + The select() method takes the same arguments as Zend\Db\Sql\Select::where() + with the addition of also being able to accept a closure, which in turn, will + be passed the current Select object that is being used to build the SELECT + query. The following usage is possible: + + + select(function (Select $select) { + $select->where->like('name', 'Brit%'); + $select->order('name ASC')->limit(2); +}); +]]> + +
+ +
+ TableGateway Features + + + The Features API allows for extending the functionality of the base TableGateway + object without having to polymorphically extend the base class. This allows for + a wider array of possible mixing and matching of features to achieve a particular + behiavior that needs to be attained to make the base implementation of TableGateway + useful for a particular problem. + + + + With the TableGateway object, features should be injected though the constructor. + The constructor can take Features in 3 different forms: as a single feature object, + as a FeatureSet object, or as an array of Feature objects. + + + + There are a number of features built-in and shipped with Zend\Db: + + + + + + GlobalAdapterFeature: the ability to use a global/static adapter without needing + to inject it into a TableGateway instance. This is more useful when you are + extending the AbstractTableGateway implementation: + + + AbstractTableGateway +{ + public function __construct() + { + $this->table = 'my_table'; + $this->featureSet = new Feature\FeatureSet(); + $this->featureSet->addFeature(new Feature\GlobalAdapterFeature()); + $this->initialize(); + } +} + +// elsewhere in code, in a bootstrap +Zend\Db\TableGateway\Feature\GlobalAdapterFeature::setStaticAdapter($adapter); + +// in a controller, or model somewhere +$table = new MyTableGateway(); // adapter is statially loaded +]]> + + + + + MasterSlaveFeature: the ability to use a master adapter for insert(), update(), + and delete() while using a slave adapter for all select() operations. + + + + + + + + + MetadataFeature: the ability populate TableGateway with column information from + a Metadata object. It will also store the primary key information in case + RowGatewayFeature needs to consume this information. + + + + + + + + + EventFeature: the ability utilize a TableGateway object with Zend\EventManager + and to be able to subscribe to various events in a TableGateway lifecycle. + + + + + + + + + RowGatewayFeature: the ability for select() to return a ResultSet object that + upon iteration will + + + select(array('id' => 2)); + +$artistRow = $results->current(); +$artistRow->name = 'New Name'; +$artistRow->save(); +]]> + + + + + +
+ +
diff --git a/documentation/manual/en/module_specs/zend.form.element.captcha.xml b/documentation/manual/en/module_specs/zend.form.element.captcha.xml new file mode 100644 index 00000000000..9fe2abb55f5 --- /dev/null +++ b/documentation/manual/en/module_specs/zend.form.element.captcha.xml @@ -0,0 +1,100 @@ + +
+ Zend\Form\Element\Captcha + + + The Captcha element can be used with forms + where authenticated users are not necessary, but you want to prevent + spam submissions. It is pairs with one of the + Zend/Form/View/Helper/Captcha/* view helpers + that matches the type of CAPTCHA adapter in use. + + + + Basic Usage of Zend\Form\Element\Captcha + + + A CAPTCHA adapter must be attached + in order for validation to be included in the element's input filter specification. + See the section on Zend CAPTCHA Adapters + for more information on what adapters are available. + + + setCaptcha(new Captcha\Dumb()) + ->setLabel('Please verify you are human'); + +$form = new Form('my-form'); +$form->add($captcha); +]]> + + +
+ Available Methods + + + The following methods are in addition to the inherited + methods of + Zend\Form\Element. + + + + + setCaptcha + + + setCaptcha + + array|Zend\Captcha\AdapterInterface $captcha + + + + Set the CAPTCHA adapter for this element. + If $captcha is an array, + Zend\Captcha\Factory::factory() will + be run to create the adapter from the array configuration. + + Returns Zend\Form\Element\Captcha + + + + + getCaptcha + + + getCaptcha + + + + Return the CAPTCHA adapter for this element. + + Returns Zend\Captcha\AdapterInterface + + + + + getInputSpecification + + + getInputSpecification + + + + Returns a input filter specification, which includes a + Zend\Filter\StringTrim filter, + and a CAPTCHA validator. + + Returns array + + + +
+ +
diff --git a/documentation/manual/en/module_specs/zend.form.element.color.xml b/documentation/manual/en/module_specs/zend.form.element.color.xml new file mode 100644 index 00000000000..b82064b63d7 --- /dev/null +++ b/documentation/manual/en/module_specs/zend.form.element.color.xml @@ -0,0 +1,69 @@ + +
+ Zend\Form\Element\Color + + + The Color element is meant to be paired with the + Zend/Form/View/Helper/FormColor for + HTML5 inputs with type color. + This element adds filters and a Regex + validator to it's input filter specification in order to validate a + + HTML5 valid simple color value on the server. + + + + Basic Usage of Zend\Form\Element\Color + + + This element automatically adds a "type" + attribute of value "color". + + + setLabel('Background color'); + +$form = new Form('my-form'); +$form->add($color); +]]> + + +
+ Available Methods + + + The following methods are in addition to the inherited + methods of + Zend\Form\Element. + + + + + getInputSpecification + + + getInputSpecification + + + + Returns a input filter specification, which includes + Zend\Filter\StringTrim and + Zend\Filter\StringToLower filters, + and a Zend\Validator\Regex to validate + the RGB hex format. + + Returns array + + + +
+ +
diff --git a/documentation/manual/en/module_specs/zend.form.element.csrf.xml b/documentation/manual/en/module_specs/zend.form.element.csrf.xml new file mode 100644 index 00000000000..1da93bf4934 --- /dev/null +++ b/documentation/manual/en/module_specs/zend.form.element.csrf.xml @@ -0,0 +1,63 @@ + +
+ Zend\Form\Element\Csrf + + + The Csrf element pairs with the + Zend/Form/View/Helper/FormHidden to + provide protection from CSRF attacks on forms, + ensuring the data is submitted by the user session that generated the form + and not by a rogue script. Protection is achieved by adding a hash element + to a form and verifying it when the form is submitted. + + + + Basic Usage of Zend\Form\Element\Csrf + + + This element automatically adds a "type" attribute + of value "hidden". + + + add($csrf); +]]> + + +
+ Available Methods + + + The following methods are in addition to the inherited + methods of + Zend\Form\Element. + + + + + getInputSpecification + + + getInputSpecification + + + + Returns a input filter specification, which includes a + Zend\Filter\StringTrim filter + and a Zend\Validator\Csrf to validate + the CSRF value. + + Returns array + + + +
+ +
diff --git a/documentation/manual/en/module_specs/zend.form.element.date-time-local.xml b/documentation/manual/en/module_specs/zend.form.element.date-time-local.xml new file mode 100644 index 00000000000..8309a5fc615 --- /dev/null +++ b/documentation/manual/en/module_specs/zend.form.element.date-time-local.xml @@ -0,0 +1,85 @@ + +
+ Zend\Form\Element\DateTimeLocal + + + The DateTimeLocal element is meant to be paired with the + Zend/Form/View/Helper/FormDateTimeLocal for + HTML5 inputs with type datetime-local. + This element adds filters and validators to it's input filter specification + in order to validate HTML5 a local datetime input values on the server. + + + + Basic Usage of Zend\Form\Element\DateTimeLocal + + + This element automatically adds a "type" + attribute of value "datetime-local". + + + setLabel('Appointment Date') + ->setAttributes(array( + 'min' => '2010-01-01T00:00:00', + 'max' => '2020-01-01T00:00:00', + 'step' => '1', // minutes; default step interval is 1 min + )); + +$form = new Form('my-form'); +$form->add($dateTimeLocal); +]]> + + + + Note: the min, max, and + step attributes should be set prior to calling + Zend\Form::prepare(). Otherwise, the default input specification for + the element may not contain the correct validation rules. + + + + +
+ Available Methods + + + The following methods are in addition to the inherited + methods of + Zend\Form\Element\DateTime. + + + + + getInputSpecification + + + getInputSpecification + + + + Returns a input filter specification, which includes + Zend\Filter\StringTrim and + will add the appropriate validators + based on the values from the min, + max, and step attributes. + See getInputSpecification + in Zend\Form\Element\DateTime + for more information. + + Returns array + + + +
+ +
diff --git a/documentation/manual/en/module_specs/zend.form.element.date-time.xml b/documentation/manual/en/module_specs/zend.form.element.date-time.xml new file mode 100644 index 00000000000..758b1ec60e1 --- /dev/null +++ b/documentation/manual/en/module_specs/zend.form.element.date-time.xml @@ -0,0 +1,100 @@ + +
+ Zend\Form\Element\DateTime + + + The DateTime element is meant to be paired with the + Zend/Form/View/Helper/FormDateTime for + HTML5 inputs with type datetime. + This element adds filters and validators to it's input filter specification + in order to validate HTML5 datetime input values on the server. + + + + Basic Usage of Zend\Form\Element\DateTime + + + This element automatically adds a "type" + attribute of value "datetime". + + + setLabel('Appointment Date/Time') + ->setAttributes(array( + 'min' => '2010-01-01T00:00:00Z', + 'max' => '2020-01-01T00:00:00Z', + 'step' => '1', // minutes; default step interval is 1 min + )); + +$form = new Form('my-form'); +$form->add($dateTime); +]]> + + + + Note: the min, max, and + step attributes should be set prior to calling + Zend\Form::prepare(). Otherwise, the default input specification for + the element may not contain the correct validation rules. + + + + +
+ Available Methods + + + The following methods are in addition to the inherited + methods of + Zend\Form\Element. + + + + + getInputSpecification + + + getInputSpecification + + + + Returns a input filter specification, which includes + Zend\Filter\StringTrim and + will add the appropriate validators + based on the values from the min, + max, and step attributes. + + + If the min attribute is set, + a Zend\Validator\GreaterThan validator + will be added to ensure the date value is greater than the + minimum value. + + + If the max attribute is set, + a Zend\Validator\LessThanValidator validator + will be added to ensure the date value is less than the + maximum value. + + + If the step attribute is set to "any", + step validations will be skipped. Otherwise, a + a Zend\Validator\DateStep validator + will be added to ensure the date value is within a certain + interval of minutes (default is 1 minute). + + Returns array + + + +
+ +
diff --git a/documentation/manual/en/module_specs/zend.form.element.date.xml b/documentation/manual/en/module_specs/zend.form.element.date.xml new file mode 100644 index 00000000000..f15a8113b59 --- /dev/null +++ b/documentation/manual/en/module_specs/zend.form.element.date.xml @@ -0,0 +1,91 @@ + +
+ Zend\Form\Element\Date + + + The Date element is meant to be paired with the + Zend/Form/View/Helper/FormDate for + HTML5 inputs with type date. + This element adds filters and validators to it's input filter specification + in order to validate HTML5 date input values on the server. + + + + Basic Usage of Zend\Form\Element\Date + + + This element automatically adds a "type" + attribute of value "date". + + + setLabel('Appointment Date') + ->setAttributes(array( + 'min' => '2012-01-01', + 'max' => '2020-01-01', + 'step' => '1', // days; default step interval is 1 day + )); + +$form = new Form('my-form'); +$form->add($date); +]]> + + + + Note: the min, max, and + step attributes should be set prior to calling + Zend\Form::prepare(). Otherwise, the default input specification for + the element may not contain the correct validation rules. + + + + +
+ Available Methods + + + The following methods are in addition to the inherited + methods of + Zend\Form\Element\DateTime. + + + + + getInputSpecification + + + getInputSpecification + + + + Returns a input filter specification, which includes + Zend\Filter\StringTrim and + will add the appropriate validators + based on the values from the min, + max, and step attributes. + See getInputSpecification + in Zend\Form\Element\DateTime + for more information. + + + One difference from Zend\Form\Element\DateTime + is that the Zend\Validator\DateStep validator + will expect the step attribute to use an interval + of days (default is 1 day). + + Returns array + + + +
+ +
diff --git a/documentation/manual/en/module_specs/zend.form.element.email.xml b/documentation/manual/en/module_specs/zend.form.element.email.xml new file mode 100644 index 00000000000..fd1ae9f79ec --- /dev/null +++ b/documentation/manual/en/module_specs/zend.form.element.email.xml @@ -0,0 +1,94 @@ + +
+ Zend\Form\Element\Email + + + The Email element is meant to be paired with the + Zend/Form/View/Helper/FormEmail for + HTML5 inputs with type email. + This element adds filters and validators to it's input filter specification + in order to validate + HTML5 valid email address on the server. + + + + Basic Usage of Zend\Form\Element\Email + + + This element automatically adds a "type" + attribute of value "email". + + + setLabel('Email Address') +$form->add($email); + +// Comma separated list of emails +$emails = new Element\Email('emails'); +$emails + ->setLabel('Email Addresses') + ->setAttribute('multiple', true); +$form->add($emails); +]]> + + + + Note: the multiple attribute should be set prior + to calling Zend\Form::prepare(). Otherwise, the default input + specification for the element may not contain the correct validation rules. + + + + +
+ Available Methods + + + The following methods are in addition to the inherited + methods of + Zend\Form\Element. + + + + + getInputSpecification + + + getInputSpecification + + + + Returns a input filter specification, which includes + a Zend\Filter\StringTrim filter, + and a validator based on the multiple + attribute. + + + If the multiple attribute is unset or false, + a Zend\Validator\Regex validator + will be added to validate a single email address. + + + If the multiple attribute is true, + a Zend\Validator\Explode validator + will be added to ensure the input string value is split by commas before + validating each email address with Zend\Validator\Regex. + + Returns array + + + +
+ +
diff --git a/documentation/manual/en/module_specs/zend.form.element.month.xml b/documentation/manual/en/module_specs/zend.form.element.month.xml new file mode 100644 index 00000000000..38e01675eb3 --- /dev/null +++ b/documentation/manual/en/module_specs/zend.form.element.month.xml @@ -0,0 +1,91 @@ + +
+ Zend\Form\Element\Month + + + The Month element is meant to be paired with the + Zend/Form/View/Helper/FormMonth for + HTML5 inputs with type month. + This element adds filters and validators to it's input filter specification + in order to validate HTML5 month input values on the server. + + + + Basic Usage of Zend\Form\Element\Month + + + This element automatically adds a "type" + attribute of value "month". + + + setLabel('Month') + ->setAttributes(array( + 'min' => '2012-01', + 'max' => '2020-01', + 'step' => '1', // months; default step interval is 1 month + )); + +$form = new Form('my-form'); +$form->add($month); +]]> + + + + Note: the min, max, and + step attributes should be set prior to calling + Zend\Form::prepare(). Otherwise, the default input specification for + the element may not contain the correct validation rules. + + + + +
+ Available Methods + + + The following methods are in addition to the inherited + methods of + Zend\Form\Element\DateTime. + + + + + getInputSpecification + + + getInputSpecification + + + + Returns a input filter specification, which includes + Zend\Filter\StringTrim and + will add the appropriate validators + based on the values from the min, + max, and step attributes. + See getInputSpecification + in Zend\Form\Element\DateTime + for more information. + + + One difference from Zend\Form\Element\DateTime + is that the Zend\Validator\DateStep validator + will expect the step attribute to use an interval + of months (default is 1 month). + + Returns array + + + +
+ +
diff --git a/documentation/manual/en/module_specs/zend.form.element.number.xml b/documentation/manual/en/module_specs/zend.form.element.number.xml new file mode 100644 index 00000000000..fe09aa31560 --- /dev/null +++ b/documentation/manual/en/module_specs/zend.form.element.number.xml @@ -0,0 +1,109 @@ + +
+ Zend\Form\Element\Number + + + The Number element is meant to be paired with the + Zend/Form/View/Helper/FormNumber for + HTML5 inputs with type number. + This element adds filters and validators to it's input filter specification + in order to validate HTML5 number input values on the server. + + + + Basic Usage of Zend\Form\Element\Number + + + This element automatically adds a "type" + attribute of value "number". + + + setLabel('Quantity') + ->setAttributes(array( + 'min' => '0', + 'max' => '10', + 'step' => '1', // default step interval is 1 + )); + +$form = new Form('my-form'); +$form->add($number); +]]> + + + + Note: the min, max, and + step attributes should be set prior to calling + Zend\Form::prepare(). Otherwise, the default input specification for + the element may not contain the correct validation rules. + + + + +
+ Available Methods + + + The following methods are in addition to the inherited + methods of + Zend\Form\Element. + + + + + getInputSpecification + + + getInputSpecification + + + + Returns a input filter specification, which includes + Zend\Filter\StringTrim and + will add the appropriate validators + based on the values from the min, + max, and step attributes. + + + If the min attribute is set, + a Zend\Validator\GreaterThan validator + will be added to ensure the number value is greater than the + minimum value. The min value should be a + valid floating point number. + + + If the max attribute is set, + a Zend\Validator\LessThanValidator validator + will be added to ensure the number value is less than the + maximum value. The max value should be a + valid floating point number. + + + If the step attribute is set to "any", + step validations will be skipped. Otherwise, a + a Zend\Validator\Step validator + will be added to ensure the number value is within a certain + interval (default is 1). The step value should + be either "any" or a valid floating point number. + + Returns array + + + +
+ +
diff --git a/documentation/manual/en/module_specs/zend.form.element.range.xml b/documentation/manual/en/module_specs/zend.form.element.range.xml new file mode 100644 index 00000000000..f4b6026444e --- /dev/null +++ b/documentation/manual/en/module_specs/zend.form.element.range.xml @@ -0,0 +1,91 @@ + +
+ Zend\Form\Element\Range + + + The Range element is meant to be paired with the + Zend/Form/View/Helper/FormRange for + HTML5 inputs with type range. + This element adds filters and validators to it's input filter specification + in order to validate HTML5 range values on the server. + + + + Basic Usage of Zend\Form\Element\Range + + + This element automatically adds a "type" + attribute of value "range". + + + setLabel('Minimum and Maximum Amount') + ->setAttributes(array( + 'min' => '0', // default minimum is 0 + 'max' => '100', // default maximum is 100 + 'step' => '1', // default interval is 1 + )); + +$form = new Form('my-form'); +$form->add($range); +]]> + + + + Note: the min, max, and + step attributes should be set prior to calling + Zend\Form::prepare(). Otherwise, the default input specification for + the element may not contain the correct validation rules. + + + + +
+ Available Methods + + + The following methods are in addition to the inherited + methods of + Zend\Form\Element\Number. + + + + + getInputSpecification + + + getInputSpecification + + + + Returns a input filter specification, which includes + Zend\Filter\StringTrim and + will add the appropriate validators + based on the values from the min, + max, and step attributes. + See getInputSpecification + in Zend\Form\Element\Number + for more information. + + + The Range element differs from Zend\Form\Element\Number + in that the Zend\Validator\GreaterThan and + Zend\Validator\LessThan validators will always be + present. The default minimum is 1, and the default maximum is 100. + + Returns array + + + +
+ +
diff --git a/documentation/manual/en/module_specs/zend.form.element.time.xml b/documentation/manual/en/module_specs/zend.form.element.time.xml new file mode 100644 index 00000000000..c812659279b --- /dev/null +++ b/documentation/manual/en/module_specs/zend.form.element.time.xml @@ -0,0 +1,91 @@ + +
+ Zend\Form\Element\Time + + + The Time element is meant to be paired with the + Zend/Form/View/Helper/FormTime for + HTML5 inputs with type time. + This element adds filters and validators to it's input filter specification + in order to validate HTML5 time input values on the server. + + + + Basic Usage of Zend\Form\Element\Time + + + This element automatically adds a "type" + attribute of value "time". + + + setLabel('Time') + ->setAttributes(array( + 'min' => '00:00:00', + 'max' => '23:59:59', + 'step' => '60', // seconds; default step interval is 60 seconds + )); + +$form = new Form('my-form'); +$form->add($time); +]]> + + + + Note: the min, max, and + step attributes should be set prior to calling + Zend\Form::prepare(). Otherwise, the default input specification for + the element may not contain the correct validation rules. + + + + +
+ Available Methods + + + The following methods are in addition to the inherited + methods of + Zend\Form\Element\DateTime. + + + + + getInputSpecification + + + getInputSpecification + + + + Returns a input filter specification, which includes + Zend\Filter\StringTrim and + will add the appropriate validators + based on the values from the min, + max, and step attributes. + See getInputSpecification + in Zend\Form\Element\DateTime + for more information. + + + One difference from Zend\Form\Element\DateTime + is that the Zend\Validator\DateStep validator + will expect the step attribute to use an interval + of seconds (default is 60 seconds). + + Returns array + + + +
+ +
diff --git a/documentation/manual/en/module_specs/zend.form.element.url.xml b/documentation/manual/en/module_specs/zend.form.element.url.xml new file mode 100644 index 00000000000..4bf37322e4b --- /dev/null +++ b/documentation/manual/en/module_specs/zend.form.element.url.xml @@ -0,0 +1,66 @@ + +
+ Zend\Form\Element\Url + + + The Url element is meant to be paired with the + Zend/Form/View/Helper/FormUrl for + HTML5 inputs with type url. + This element adds filters and a Zend\Validator\Uri + validator to it's input filter specification + for validating HTML5 URL input values on the server. + + + + Basic Usage of Zend\Form\Element\Url + + + This element automatically adds a "type" + attribute of value "url". + + + setLabel('Webpage URL'); + +$form = new Form('my-form'); +$form->add($url); +]]> + + +
+ Available Methods + + + The following methods are in addition to the inherited + methods of + Zend\Form\Element. + + + + + getInputSpecification + + + getInputSpecification + + + + Returns a input filter specification, which includes a + Zend\Filter\StringTrim filter, + and a Zend\Validator\Uri to validate + the URI string. + + Returns array + + + +
+ +
diff --git a/documentation/manual/en/module_specs/zend.form.element.week.xml b/documentation/manual/en/module_specs/zend.form.element.week.xml new file mode 100644 index 00000000000..86368fa7b69 --- /dev/null +++ b/documentation/manual/en/module_specs/zend.form.element.week.xml @@ -0,0 +1,91 @@ + +
+ Zend\Form\Element\Week + + + The Week element is meant to be paired with the + Zend/Form/View/Helper/FormWeek for + HTML5 inputs with type week. + This element adds filters and validators to it's input filter specification + in order to validate HTML5 week input values on the server. + + + + Basic Usage of Zend\Form\Element\Week + + + This element automatically adds a "type" + attribute of value "week". + + + setLabel('Week') + ->setAttributes(array( + 'min' => '2012-W01', + 'max' => '2020-W01', + 'step' => '1', // weeks; default step interval is 1 week + )); + +$form = new Form('my-form'); +$form->add($week); +]]> + + + + Note: the min, max, and + step attributes should be set prior to calling + Zend\Form::prepare(). Otherwise, the default input specification for + the element may not contain the correct validation rules. + + + + +
+ Available Methods + + + The following methods are in addition to the inherited + methods of + Zend\Form\Element\DateTime. + + + + + getInputSpecification + + + getInputSpecification + + + + Returns a input filter specification, which includes + Zend\Filter\StringTrim and + will add the appropriate validators + based on the values from the min, + max, and step attributes. + See getInputSpecification + in Zend\Form\Element\DateTime + for more information. + + + One difference from Zend\Form\Element\DateTime + is that the Zend\Validator\DateStep validator + will expect the step attribute to use an interval + of weeks (default is 1 week). + + Returns array + + + +
+ +
diff --git a/documentation/manual/en/module_specs/zend.form.element.xml b/documentation/manual/en/module_specs/zend.form.element.xml new file mode 100644 index 00000000000..29d268d70bf --- /dev/null +++ b/documentation/manual/en/module_specs/zend.form.element.xml @@ -0,0 +1,289 @@ + +
+ Zend\Form\Element + + + Zend\Form\Element is a base class for all + specialized elements and Zend\Form\Fieldset, but can also be used + for all generic text, select, + radio, etc. type form inputs which + do not have a specialized element available. + + + + Basic Usage of Zend\Form\Element + + + At the bare minimum, each element or fieldset requires a name. + You will also typically provide some attributes to hint to the view + layer how it might render the item. + + + setLabel('Username'); + ->setAttributes(array( + 'type' => 'text', + 'class' => 'username', + 'size' => '30', + )); + +$password = new Element('password'); +$password + ->setLabel('Password'); + ->setAttributes(array( + 'type' => 'password', + 'size' => '30', + )); + +$form = new Form('my-form'); +$form + ->add($username) + ->add($password); +]]> + + +
+ Available Methods + + + + setName + + + setName + + string $name + + + + Set the name for this element. + + Returns Zend\Form\Element + + + + + getName + + + getName + + + + Return the name for this element. + + Returns string + + + + + setLabel + + + setLabel + + string $label + + + + Set the label content for this element. + + Returns Zend\Form\Element + + + + + getLabel + + + getLabel + + + + Return the label content for this element. + + Returns string + + + + + setLabelAttributes + + + setLabelAttributes + + array $labelAttributes + + + + Set the attributes to use with the label. + + Returns Zend\Form\Element + + + + + getLabelAttributes + + + getLabelAttributes + + + + Return the attributes to use with the label. + + Returns array + + + + + setOptions + + + setOptions + + array $options + + + + Set options for an element. Accepted options are: + "label" and "label_attributes", + which call setLabel + and setLabelAttributes, respectively. + + Returns Zend\Form\Element + + + + + setAttribute + + + setAttribute + + string $key, mixed $value + + + + Set a single element attribute. + + Returns Zend\Form\Element + + + + + getAttribute + + + getAttribute + + string $key + + + + Retrieve a single element attribute. + + Returns mixed + + + + + hasAttribute + + + hasAttribute + + string $key + + + + Check if a specific attribute exists for this element. + + Returns boolean + + + + + setAttributes + + + setAttributes + + array|Traversable $arrayOrTraversable + + + + Set many attributes at once. + Implementation will decide if this will overwrite or merge. + + Returns Zend\Form\Element + + + + + getAttributes + + + getAttributes + + + + Retrieve all attributes at once. + + Returns array|Traversable + + + + + clearAttributes + + + clearAttributes + + + + Clear all attributes for this element. + + Returns Zend\Form\Element + + + + + setMessages + + + setMessages + + array|Traversable $messages + + + + Set a list of messages to report when validation fails. + + Returns Zend\Form\Element + + + + + setMessages + + + getMessages + + + + Returns a list of validation failure messages, if any. + + Returns array|Traversable + + + +
+ +
diff --git a/documentation/manual/en/module_specs/zend.form.elements.xml b/documentation/manual/en/module_specs/zend.form.elements.xml new file mode 100644 index 00000000000..6de969b8d2e --- /dev/null +++ b/documentation/manual/en/module_specs/zend.form.elements.xml @@ -0,0 +1,40 @@ + +
+ Zend\Form\Element + +
+ Introduction + + + A set of specialized elements are provided for accomplishing application-centric + tasks. These include several HTML5 input elements with matching server-side + validators, the Csrf element (to prevent Cross Site + Request Forgery attacks), and the Captcha element + (to display and validate CAPTCHAs). + + + + A Factory is provided to facilitate creation of elements, + fieldsets, forms, and the related input filter. See the + Zend\Form Quick Start + for more information. + +
+ + + + + + + + + + + + + + + + +
diff --git a/documentation/manual/en/module_specs/zend.form.intro.xml b/documentation/manual/en/module_specs/zend.form.intro.xml index 9ad416bbc16..918b36265aa 100644 --- a/documentation/manual/en/module_specs/zend.form.intro.xml +++ b/documentation/manual/en/module_specs/zend.form.intro.xml @@ -1,10 +1,10 @@ -
- Zend\Form + Introduction to Zend\Form Zend\Form is intended primarily as a bridge between your domain @@ -55,9 +55,19 @@ - Finally, a Factory is provided to facilitate creation of elements, + A Factory is provided to facilitate creation of elements, fieldsets, forms, and the related input filter. The default Form implementation is backed by a factory to facilitate extension and ease the process of form creation. + + + The code related to forms can often spread between a variety of concerns: a form definition, + an input filter definition, a domain model class, and one or more hydrator implementations. + As such, finding the various bits of code and how they relate can become tedious. To + simplify the situation, you can also annotate your domain model class, detailing the various + input filter definitions, attributes, and hydrators that should all be used together. + Zend\Form\Annotation\AnnotationBuilder can then be used to build the + various objects you need. +
diff --git a/documentation/manual/en/module_specs/zend.form.quick-start.xml b/documentation/manual/en/module_specs/zend.form.quick-start.xml index ebb788ee81b..4ab5d6e1e2b 100644 --- a/documentation/manual/en/module_specs/zend.form.quick-start.xml +++ b/documentation/manual/en/module_specs/zend.form.quick-start.xml @@ -818,4 +818,221 @@ use Zend\Form\FormInterface; $form->setValidationGroup(FormInterface::VALIDATE_ALL); ]]>
+ + + Using Annotations + + + Creating a complete forms solution can often be tedious: you'll create some domain model + object, an input filter for validating it, a form object for providing a representation + for it, and potentially a hydrator for mapping the form elements and fieldsets to the + domain model. Wouldn't it be nice to have a central place to define all of these? + + + + Annotations allow us to solve this problem. You can define the following behaviors with + the shipped annotations in Zend\Form: + + + + + + AllowEmpty: mark an input as allowing an empty value. This + annotation does not require a value. + + + + + + Attributes: specify the form, fieldset, or element attributes. This + annotation requires an associative array of values, in a JSON object format: + @Attributes({"class":"zend_form","type":"text"}). + + + + + + ComposedObject: specify another object with annotations to parse. + Typically, this is used if a property references another object, which will then + be added to your form as an additional fieldset. Expects a string value + indicating the class for the object being composed. + + + + + + ErrorMessage: specify the error message to return for an element in + the case of a failed validation. Expects a string value. + + + + + + Exclude: mark a property to exclude from the form or fieldset. This + annotation does not require a value. + + + + + + Filter: provide a specification for a filter to use on a given + element. Expects an associative array of values, with a "name" key pointing to a + string filter name, and an "options" key pointing to an associatve array of + filter options for the constructor: @Filter({"name": "Boolean", "options": + {"casting":true}}). This annotation may be specified multiple times. + + + + + + Flags: flags to pass to the fieldset or form composing an element + or fieldset; these are usually used to specify the name or priority. The + annotation expects an associative array: @Flags({"priority": 100}). + + + + + + Hydrator: specify the hydrator class to use for this given form or + fieldset. A string value is expected. + + + + + + InputFilter: specify the input filter class to use for this given + form or fieldset. A string value is expected. + + + + + + Input: specify the input class to use for this given element. A + string value is expected. + + + + + + Name: specify the name of the current element, fieldset, or form. A + string value is expected. + + + + + + Options: options to pass to the fieldset or form that are used to + inform behavior -- things that are not attributes; e.g. labels, CAPTCHA + adapters, etc. The annotation expects an associative array: + @Options({"label": "Username:"}). + + + + + + Required: indicate whether an element is required. A boolean value + is expected. By default, all elements are required, so this annotation is mainly + present to allow disabling a requirement. + + + + + + Type: indicate the class to use for the current element, fieldset, + or form. A string value is expected. + + + + + + Validator: provide a specification for a validator to use on a given + element. Expects an associative array of values, with a "name" key pointing to a + string validator name, and an "options" key pointing to an associatve array of + validator options for the constructor: @Validator({"name": "StringLength", "options": + {"min":3, "max": 25}}). This annotation may be specified multiple times. + + + + + + To use annotations, you simply include them in your class and/or property docblocks. + Annotation names will be resolved according to the import statements in your class; as + such, you can make them as long or as short as you want depending on what you import. + + + + Here's a simple example. + + + + + + The above will hint to the annotation build to create a form with name "user", which + uses the hydrator Zend\Stdlib\Hydrator\ObjectProperty. That form + will have two elements, "username" and "email". The "username" element will have an + associated input that has a StringTrim filter, and two + validators: a StringLength validator indicating the username is + between 1 and 25 characters, and a Regex validator asserting it + follows a specific accepted pattern. The form element itself will have an attribute + "type" with value "text" (a text element), and a label "Username:". The "email" element + will be of type Zend\Form\Element\Email, and have the label "Your + email address:". + + + + To use the above, we need Zend\Form\Annotation\AnnotationBuilder: + + + createForm('User'); +]]> + + + At this point, you have a form with the appropriate hydrator attached, an input filter + with the appropriate inputs, and all elements. + + + + You're not done + + + In all liklihood, you'll need to add some more elements to the form you construct. + For example, you'll want a submit button, and likely a CSRF-protection element. We + recommend creating a fieldset with common elements such as these that you can then + attach to the form you build via annotations. + + +
diff --git a/documentation/manual/en/module_specs/zend.i18n.filter.alnum.xml b/documentation/manual/en/module_specs/zend.i18n.filter.alnum.xml new file mode 100644 index 00000000000..15301e845e6 --- /dev/null +++ b/documentation/manual/en/module_specs/zend.i18n.filter.alnum.xml @@ -0,0 +1,81 @@ + +
+ Alnum Filter + + + The Alnum filter can be used to return + only alphabetic characters and digits in the + unicode "letter" and "number" categories, respectively. + All other characters are supressed. + + + + Supported options for Alnum Filter + + + The following options are supported for Alnum: + + + + Alnum([ boolean $allowWhiteSpace [, string $locale ]]) + + + + + + $allowWhiteSpace : If set to true then + whitespace characters are allowed. Otherwise they are + suppressed. Default is "false" (whitespace is not allowed). + + + Methods for getting/setting the allowWhiteSpace option + are also available: + getAllowWhiteSpace() and + setAllowWhiteSpace() + + + + + $locale : The locale string used in + identifying the characters to filter + (locale name, e.g. en_US). If unset, it will use the + default locale + (Locale::getDefault()). + + + Methods for getting/setting the locale are also available: + getLocale() and + setLocale() + + + + + + + Alnum Filter Usage + + filter("This is (my) content: 123"); +// Returns "Thisismycontent123" + +// First param in constructor is $allowWhiteSpace +$filter = \Zend\I18n\Filter\Alnum(true); +echo $filter->filter("This is (my) content: 123"); +// Returns "This is my content 123" +]]> + + + + Note: Alnum works on almost all + languages, except: Chinese, Japanese and Korean. + Within these languages the english alphabet is used + instead of the characters from these languages. + The language itself is detected using the + Locale. + + + + +
diff --git a/documentation/manual/en/module_specs/zend.i18n.filter.alpha.xml b/documentation/manual/en/module_specs/zend.i18n.filter.alpha.xml new file mode 100644 index 00000000000..ae610bce81a --- /dev/null +++ b/documentation/manual/en/module_specs/zend.i18n.filter.alpha.xml @@ -0,0 +1,81 @@ + +
+ Alpha Filter + + + The Alpha filter can be used to return + only alphabetic characters in the unicode "letter" category. + All other characters are supressed. + + + + Supported options for Alpha Filter + + + The following options are supported for Alpha: + + + + Alpha([ boolean $allowWhiteSpace [, string $locale ]]) + + + + + + $allowWhiteSpace : If set to true then + whitespace characters are allowed. Otherwise they are + suppressed. Default is "false" (whitespace is not allowed). + + + Methods for getting/setting the allowWhiteSpace option + are also available: + getAllowWhiteSpace() and + setAllowWhiteSpace() + + + + + $locale : The locale string used in + identifying the characters to filter + (locale name, e.g. en_US). If unset, it will use the + default locale + (Locale::getDefault()). + + + Methods for getting/setting the locale are also available: + getLocale() and + setLocale() + + + + + + + Alpha Filter Usage + + filter("This is (my) content: 123"); +// Returns "Thisismycontent" + +// Allow whitespace +$filter = \Zend\I18n\Filter\Alpha(true); +echo $filter->filter("This is (my) content: 123"); +// Returns "This is my content " +]]> + + + + Note: Alpha works on almost all + languages, except: Chinese, Japanese and Korean. + Within these languages the english alphabet is used + instead of the characters from these languages. + The language itself is detected using the + Locale. + + + + + +
diff --git a/documentation/manual/en/module_specs/zend.i18n.filter.number-format.xml b/documentation/manual/en/module_specs/zend.i18n.filter.number-format.xml new file mode 100644 index 00000000000..33d338202b8 --- /dev/null +++ b/documentation/manual/en/module_specs/zend.i18n.filter.number-format.xml @@ -0,0 +1,86 @@ + +
+ NumberFormat Filter + + + The NumberFormat filter can be used to return + locale-specific number and percentage strings. + It acts as a wrapper for the NumberFormatter + class within the Internationalization extension (Intl). + + + + Supported options for NumberFormat Filter + + + The following options are supported for NumberFormat: + + + + NumberFormat([ string $locale [, int $style [, int $type ]]]) + + + + + + $locale : (Optional) Locale in which the number would be formatted (locale name, e.g. en_US). + If unset, it will use the default locale (Locale::getDefault()) + + + + Methods for getting/setting the locale are also available: + getLocale() and + setLocale() + + + + + $style : (Optional) Style of the formatting, one of the + format style constants. + If unset, it will use NumberFormatter::DEFAULT_STYLE as the default style. + + + Methods for getting/setting the format style are also available: + getStyle() and + setStyle() + + + + + $type : (Optional) The + formatting type to use. + If unset, it will use NumberFormatter::TYPE_DOUBLE as the default type. + + + Methods for getting/setting the format type are also available: + getType() and + setType() + + + + + + + + NumberFormat Filter Usage + + filter(1234567.8912346); +// Returns "1.234.567,891" + +$filter = \Zend\I18n\Filter\NumberFormat("en_US", NumberFormatter::PERCENT); +echo $filter->filter(0.80); +// Returns "80%" + +$filter = \Zend\I18n\Filter\NumberFormat("fr_FR", NumberFormatter::SCIENTIFIC); +echo $filter->filter(0.00123456789); +// Returns "1,23456789E-3" +]]> + + +
diff --git a/documentation/manual/en/module_specs/zend.i18n.filters.xml b/documentation/manual/en/module_specs/zend.i18n.filters.xml new file mode 100644 index 00000000000..fc01c09ac7d --- /dev/null +++ b/documentation/manual/en/module_specs/zend.i18n.filters.xml @@ -0,0 +1,13 @@ + +
+ I18n Filters + + + Zend Framework comes with a set of filters related to Internationalization. + + + + + +
diff --git a/documentation/manual/en/module_specs/zend.i18n.view.helper.currency-format.xml b/documentation/manual/en/module_specs/zend.i18n.view.helper.currency-format.xml new file mode 100644 index 00000000000..fa37b1a7db0 --- /dev/null +++ b/documentation/manual/en/module_specs/zend.i18n.view.helper.currency-format.xml @@ -0,0 +1,63 @@ + +
CurrencyFormat Helper + + + The CurrencyFormat view helper can be used to simplify rendering + of localized currency values. It acts as a wrapper for the NumberFormatter + class within the Internationalization extension (Intl). + + + + Basic Usage of CurrencyFormat + currencyFormat(1234.56, "USD", "en_US"); +// This returns: "$1,234.56" + +echo $this->currencyFormat(1234.56, "EUR", "de_DE"); +// This returns: "1.234,56 ā‚¬" +]]> + + + currencyFormat(float $number , string $currencyCode [, string $locale ]) + + + + + + $number : The numeric currency value. + + + + + $currencyCode : The 3-letter ISO 4217 currency code indicating the currency to use. + + + + + $locale : (Optional) Locale in which the currency would be formatted (locale name, e.g. en_US). + If unset, it will use the default locale (Locale::getDefault()) + + + + + + + + CurrencyFormat Setters + + The $currencyCode and $locale options can be set prior to formatting + and will be applied each time the helper is used: + + + plugin("currencyformat")->setCurrencyCode("USD")->setLocale("en_US"); + +echo $this->currencyFormat(1234.56); // "$1,234.56" +echo $this->currencyFormat(5678.90); // "$5,678.90" +]]> + + +
diff --git a/documentation/manual/en/module_specs/zend.i18n.view.helper.date-format.xml b/documentation/manual/en/module_specs/zend.i18n.view.helper.date-format.xml new file mode 100644 index 00000000000..b6ff58a0487 --- /dev/null +++ b/documentation/manual/en/module_specs/zend.i18n.view.helper.date-format.xml @@ -0,0 +1,105 @@ + +
DateFormat Helper + + + The DateFormat view helper can be used to simplify rendering + of localized date/time values. It acts as a wrapper for the IntlDateFormatter + class within the Internationalization extension (Intl). + + + + Basic Usage of DateFormat + dateFormat( + new DateTime(), + IntlDateFormatter::MEDIUM, // date + IntlDateFormatter::MEDIUM, // time + "en_US" +); +// This returns: "Jul 2, 2012 6:44:03 PM" + +// Date Only +echo $this->dateFormat( + new DateTime(), + IntlDateFormatter::LONG, // date + IntlDateFormatter::NONE, // time + "en_US" +); +// This returns: "July 2, 2012" + +// Time Only +echo $this->dateFormat( + new DateTime(), + IntlDateFormatter::NONE, // date + IntlDateFormatter::SHORT, // time + "en_US" +); +// This returns: "6:44 PM" +]]> + + + dateFormat(mixed $date [, int $dateType [, int $timeType [, string $locale ]]]) + + + + + + $date : The value to format. This may be a + DateTime object, an integer representing a Unix timestamp + value or an array in the format output by localtime(). + + + + + $dateType : (Optional) Date type to use (none, short, medium, long, full). + This is one of the IntlDateFormatter constants. Defaults to IntlDateFormatter::NONE. + + + + + $timeType : (Optional) Time type to use (none, short, medium, long, full). + This is one of the IntlDateFormatter constants. Defaults to IntlDateFormatter::NONE. + + + + + $locale : (Optional) Locale in which the date would be formatted (locale name, e.g. en_US). + If unset, it will use the default locale (Locale::getDefault()) + + + + + + + + DateFormat Setters + + The $locale option can be set prior to formatting + with the setLocale() method + and will be applied each time the helper is used. + + + + By default, the system's default timezone will be used when formatting. + This overrides any timezone that may be set inside a DateTime object. + To change the timezone when formatting, use the + setTimezone method. + + + plugin("dateFormat")->setTimezone("America/New_York")->setLocale("en_US"); + +echo $this->dateFormat(new DateTime(), IntlDateFormatter::MEDIUM); // "Jul 2, 2012" +echo $this->dateFormat(new DateTime(), IntlDateFormatter::SHORT); // "7/2/12" +]]> + + +
diff --git a/documentation/manual/en/module_specs/zend.i18n.view.helper.number-format.xml b/documentation/manual/en/module_specs/zend.i18n.view.helper.number-format.xml new file mode 100644 index 00000000000..bc0df3a070d --- /dev/null +++ b/documentation/manual/en/module_specs/zend.i18n.view.helper.number-format.xml @@ -0,0 +1,103 @@ + +
NumberFormat Helper + + + The NumberFormat view helper can be used to simplify rendering + of locale-specific number and percentage strings. + It acts as a wrapper for the NumberFormatter + class within the Internationalization extension (Intl). + + + + Basic Usage of NumberFormat + numberFormat( + 1234567.891234567890000, + NumberFormatter::DECIMAL, + NumberFormatter::TYPE_DEFAULT, + "de_DE" +); +// This returns: "1.234.567,891" + +// Example of Percent formatting: +echo $this->numberFormat( + 0.80, + NumberFormatter::PERCENT, + NumberFormatter::TYPE_DEFAULT, + "en_US" +); +// This returns: "80%" + +// Example of Scientific notation formatting: +echo $this->numberFormat( + 0.00123456789, + NumberFormatter::SCIENTIFIC, + NumberFormatter::TYPE_DEFAULT, + "fr_FR" +); +// This returns: "1,23456789E-3" +]]> + + + numberFormat(number $number [, int $formatStyle [, int $formatType [, string $locale ]]]) + + + + + + $number : The numeric value. + + + + + $formatStyle : (Optional) Style of the formatting, one of the + format style constants. + If unset, it will use NumberFormatter::DECIMAL as the default style. + + + + + + $formatType : (Optional) The + formatting type to use. + If unset, it will use NumberFormatter::TYPE_DEFAULT as the default type. + + + + + $locale : (Optional) Locale in which the number would be formatted (locale name, e.g. en_US). + If unset, it will use the default locale (Locale::getDefault()) + + + + + + + + NumberFormat Setters + + The $formatStyle, $formatType, and + $locale options can be set prior to formatting and will be applied + each time the helper is used. + + + plugin("numberformat") + ->setFormatStyle(NumberFormatter::PERCENT) + ->setFormatType(NumberFormatter::TYPE_DOUBLE) + ->setLocale("en_US"); + +echo $this->numberFormat(0.56); // "56%" +echo $this->numberFormat(0.90); // "90%" +]]> + + +
diff --git a/documentation/manual/en/module_specs/zend.i18n.view.helper.translate-plural.xml b/documentation/manual/en/module_specs/zend.i18n.view.helper.translate-plural.xml new file mode 100644 index 00000000000..00867812c77 --- /dev/null +++ b/documentation/manual/en/module_specs/zend.i18n.view.helper.translate-plural.xml @@ -0,0 +1,91 @@ + +
TranslatePlural Helper + + + The TranslatePlural view helper can be used to + translate words which take into account numeric meanings. English, + for example, has a singular definition of "car", for one car. + And has the plural definition, "cars", meaning zero "cars" or + more than one car. Other languages like Russian or Polish have more + plurals with different rules. + + + + The viewhelper acts as a wrapper for the + Zend\I18n\Translator\Translator class. + + + + TranslatePlural Setup + + + Before using the TranslatePlural view helper, + you must have first created a Translator object + and have attached it to the view helper. + If you use the Zend\I18n\Translator\TranslatorServiceFactory + to create your Translator object, this will be + done automatically for you. + + + + If you are not using the TranslatorServiceFactory, + then you will need to manually attach your + Translator object, such as: + + get('ViewHelperManager')->get('translateplural')->setTranslator($translator); +]]> + + + + Basic Usage of TranslatePlural + + translatePlural("car", "cars", $num); + +// Use a custom domain +echo $this->translatePlural("monitor", "monitors", $num, "customDomain"); + +// Change locale +echo $this->translate("locale", "locales", $num, "default", "de_DE"); +]]> + + + translatePlural(string $singular, string $plural, int $number [, string $textDomain [, string $locale ]]) + + + + + + $singular : The singular message to be translated. + + + + + $plural : The plural message to be translated. + + + + + $number : The number to evaluate and determine which message to use. + + + + + $textDomain : (Optional) The text domain where this translation lives. + Defaults to the value "default". + + + + + $locale : (Optional) Locale in which the message would be translated (locale name, e.g. en_US). + If unset, it will use the default locale (Locale::getDefault()) + + + + + + +
diff --git a/documentation/manual/en/module_specs/zend.i18n.view.helper.translate.xml b/documentation/manual/en/module_specs/zend.i18n.view.helper.translate.xml new file mode 100644 index 00000000000..00a4e5437f6 --- /dev/null +++ b/documentation/manual/en/module_specs/zend.i18n.view.helper.translate.xml @@ -0,0 +1,72 @@ + +
Translate Helper + + + The Translate view helper can be used to + translate content. It acts as a wrapper for the + Zend\I18n\Translator\Translator class. + + + + Translate Setup + + Before using the Translate view helper, + you must have first created a Translator object + and have attached it to the view helper. + If you use the Zend\I18n\Translator\TranslatorServiceFactory + to create your Translator object, this will be + done automatically for you. + + + + If you are not using the TranslatorServiceFactory, then you will need + to manually attach your Translator object, such as: + + get('ViewHelperManager')->get('translate')->setTranslator($translator); +]]> + + + + Basic Usage of Translate + + translate("Some translated text."); + +echo $this->translate("Translated text from a custom text domain.", "customDomain"); + +echo sprintf($this->translate("The current time is %s."), $currentTime); + +echo $this->translate("Translate in a specific locale", "default", "de_DE"); +]]> + + + translate(string $message [, string $textDomain [, string $locale ]]) + + + + + + $message : The message to be translated. + + + + + $textDomain : (Optional) The text domain where this translation lives. + Defaults to the value "default". + + + + + $locale : (Optional) Locale in which the message would be translated (locale name, e.g. en_US). + If unset, it will use the default locale (Locale::getDefault()) + + + + + + +
diff --git a/documentation/manual/en/module_specs/zend.i18n.view.helpers.xml b/documentation/manual/en/module_specs/zend.i18n.view.helpers.xml new file mode 100644 index 00000000000..511a20fe96e --- /dev/null +++ b/documentation/manual/en/module_specs/zend.i18n.view.helpers.xml @@ -0,0 +1,26 @@ + +
+ I18n View Helpers + +
+ Introduction + + + Zend Framework comes with an initial set of helper classes related to Internationalization: + e.g., formatting a date, formatting currency, or displaying translated content. You can + use helper, or plugin, classes to perform these behaviors for you. + + + + See the section on view helpers for more information. + +
+ + + + + + + +
diff --git a/documentation/manual/en/module_specs/zend.module-manager.module-manager.xml b/documentation/manual/en/module_specs/zend.module-manager.module-manager.xml index 3953e711178..4b5396f53b0 100644 --- a/documentation/manual/en/module_specs/zend.module-manager.module-manager.xml +++ b/documentation/manual/en/module_specs/zend.module-manager.module-manager.xml @@ -1,12 +1,12 @@ -
- + The Module Manager - + The module manager, Zend\ModuleManager\ModuleManager, is a very @@ -16,23 +16,24 @@
- + Module Manager Events - + Events triggered by <classname>Zend\ModuleManager\ModuleManager</classname> - loadModules.pre + loadModules - Triggered prior to any modules being loaded. This event is useful for - registering a module autoloader. ZF2 ships with a default module autoloader - which is automatically attached to this event if you are using - Zend\ModuleManager\Listener\DefaultListenerAggregate, both - of which are covered in detail later. + This event is primarily used internally to help encapsulate the work of + loading modules in event listeners, and allow the loadModules.post event to + be more user-friendly. Internal listeners will attach to this event with a + negative priority instead of loadModules.post so that users can safely + assume things like config merging have been done once loadModules.post is + triggered, without having to worry about priorities at all. @@ -91,16 +92,16 @@
- +
- + Module Manager Listeners - + By default, Zend Framework provides several useful module manager listeners. - + Provided Module Manager Listeners @@ -123,7 +124,7 @@ - This listener checks each module to see if it has implemented + This listener checks each module to see if it has implemented Zend\ModuleManager\Feature\AutoloaderProviderInterface or simply defined the getAutoloaderConfig() method. If so, it calls the getAutoloaderConfig() method on @@ -145,7 +146,7 @@ - + Zend\ModuleManager\Listener\InitTrigger @@ -164,7 +165,7 @@ - + Zend\ModuleManager\Listener\LocatorRegistrationListener @@ -179,7 +180,7 @@ - + Zend\ModuleManager\Listener\ModuleResolverListener @@ -191,7 +192,7 @@ - + Zend\ModuleManager\Listener\OnBootstrapListener @@ -217,7 +218,7 @@ - + Zend\ModuleManager\Listener\ServiceListener diff --git a/documentation/manual/en/module_specs/zend.timesync.working.xml b/documentation/manual/en/module_specs/zend.timesync.working.xml new file mode 100644 index 00000000000..c1c9cb461ce --- /dev/null +++ b/documentation/manual/en/module_specs/zend.timesync.working.xml @@ -0,0 +1,269 @@ + +
Working with Zend_TimeSync + + + Zend\TimeSync\TimeSync can return the actual time from any given + NTP or SNTP time server. + It can automatically handle multiple servers and provides a simple interface. + + + + + All examples in this chapter use a public, generic time server: + 0.europe.pool.ntp.org. You should use a public, generic time server + which is close to your application server. See http://www.pool.ntp.org for information. + + + +
Generic Time Server Request + + + Requesting the time from a time server is simple. First, you provide the time server + from which you want to request the time. + + + getDate()->format(DateTime::ISO8601); +]]> + + + So what is happening in the background of Zend\TimeSync\TimeSync? First + the syntax of the time server is checked. In our example, + '0.pool.ntp.org' is checked and recognised as a possible address + for a time server. Then when calling getDate() the actual set + time server is requested and it will return its own time. + Zend\TimeSync\TimeSync then calculates the difference to the actual time + of the server running the script and returns a DateTime object + with the correct time. + + + + For details about DateTime and its methods see the + + DateTimedocumentation. + +
+ +
Multiple Time Servers + + + Not all time servers are always available to return their time. Servers may be + unavailable during maintenance, for example. When the time cannot be requested from the + time server, you will get an exception. + + + + Zend\TimeSync\TimeSync is a simple solution that can handle multiple time + servers and supports an automatic fallback mechanism. There are two supported ways; you + can either specify an array of time servers when creating the instance, or you can add + additional time servers to the instance using the addServer() + method. + + + addServer('3.pool.ntp.org'); + +print $server->getDate()->format(DateTime::ISO8601); +]]> + + + There is no limit to the number of time servers you can add. When a time server can not + be reached, Zend\TimeSync\TimeSync will fallback and try to connect to the + next time server. + + + + When you supply more than one time server- which is considered a best practice for + Zend\TimeSync\TimeSync- you should name each server. You can name your + servers with array keys, with the second parameter at instantiation, or with the second + parameter when adding another time server. + + + '0.pool.ntp.org', + 'fallback' => '1.pool.ntp.org', + 'reserve' => '2.pool.ntp.org')); +$server->addServer('3.pool.ntp.org', 'additional'); + +print $server->getDate()->format(DateTime::ISO8601); +]]> + + + Naming the time servers allows you to request a specific time server as we will see + later in this chapter. + +
+ +
Protocols of Time Servers + + + There are different types of time servers. Most public time servers use the + NTP protocol. But there are other time synchronization + protocols available. + + + + You set the proper protocol in the address of the time server. There are two + protocols which are supported by Zend\TimeSync\TimeSync: + NTP and SNTP. The default protocol is + NTP. If you are using NTP, you can omit the + protocol in the address as demonstrated in the previous examples. + + + 'ntp://0.pool.ntp.org', + 'fallback' => 'ntp://1.pool.ntp.org', + 'reserve' => 'ntp://2.pool.ntp.org')); +$server->addServer('sntp://internal.myserver.com', 'additional'); + +print $server->getDate()->format(DateTime::ISO8601); +]]> + + + Zend\TimeSync\TimeSync can handle mixed time servers. So you are not + restricted to only one protocol; you can add any server independently from its protocol. + +
+ +
Using Ports for Time Servers + + + As with every protocol within the world wide web, the NTP and + SNTP protocols use standard ports. NTP uses port + 123 and SNTP uses port 37. + + + + But sometimes the port that the protocols use differs from the standard one. You can + define the port which has to be used for each server within the address. Just add the + number of the port after the address. If no port is defined, then + Zend\TimeSync\TimeSync will use the standard port. + + + 'ntp://0.pool.ntp.org:200', + 'fallback' => 'ntp://1.pool.ntp.org')); +$server->addServer('sntp://internal.myserver.com:399', 'additional'); + +print $server->getDate()->format(DateTime::ISO8601); +]]> +
+ +
Time Servers Options + + + There is only one option within Zend\TimeSync\TimeSync which will be used + internally: timeout. You can set any self-defined option you are in + need of and request it, however. + + + + The option timeout defines the number of seconds after which + a connection is detected as broken when there was no response. The default value is + 1, which means that Zend\TimeSync\TimeSync will + fallback to the next time server if the requested time server does not respond in one + second. + + + + With the setOptions() method, you can set any option. This + function accepts an array where the key is the option to set and the value is the value + of that option. Any previously set option will be overwritten by the new value. If you + want to know which options are set, use the getOptions() + method. It accepts either a key which returns the given option if specified, or, if no + key is set, it will return all set options. + + + 3, 'myoption' => 'timesync')); +$server = new Zend\TimeSync\TimeSync(array('generic' => 'ntp://0.pool.ntp.org', + 'fallback' => 'ntp://1.pool.ntp.org')); +$server->addServer('sntp://internal.myserver.com', 'additional'); + +print $server->getDate()->format(DateTime::ISO8601); +print_r(Zend\TimeSync\TimeSync::getOptions(); +print "Timeout = " . Zend\TimeSync\TimeSync::getOptions('timeout'); +]]> + + + As you can see, the options for Zend\TimeSync\TimeSync are static. Each + instance of Zend\TimeSync\TimeSync will use the same options. + +
+ +
Using Different Time Servers + + + Zend\TimeSync\TimeSync's default behavior for requesting a time is to + request it from the first given server. But sometimes it is useful to set a different + time server from which to request the time. This can be done with the + setServer() method. To define the used time server set the + alias as a parameter within the method. To get the actual used time server call the + getServer() method. It accepts an alias as a parameter which + defines the time server to be returned. If no parameter is given, the current time + server will be returned. + + + 'ntp://0.pool.ntp.org', + 'fallback' => 'ntp://1.pool.ntp.org')); +$server->addServer('sntp://internal.myserver.com', 'additional'); + +$actual = $server->getServer(); +$server = $server->setServer('additional'); +]]> +
+ +
Information from Time Servers + + + Time servers not only offer the time itself, but also additional information. You can + get this information with the getInfo() method. + + + 'ntp://0.pool.ntp.org', + 'fallback' => 'ntp://1.pool.ntp.org')); + +print_r ($server->getInfo()); +]]> + + + The returned information differs with the protocol used and can also differ with the + server used. + +
+ +
Handling Exceptions + + + Exceptions are collected for all time servers and returned as an array. So you can + iterate through all thrown exceptions as shown in the following example: + + + 'ntp://a.foo.bar.org', + 'invalid_b' => 'sntp://b.foo.bar.org', +); + +$server = new Zend\TimeSync\TimeSync($serverlist); + +try { + $result = $server->getDate(); + echo $result->format(DateTime::ISO8601); +} catch (Zend\TimeSync\Exception\RuntimeException $e) { + while ($e = $e->getPrevious()) { + echo $e->getMessage(); + echo '
'; + } +} +]]>
+
+
diff --git a/documentation/manual/en/module_specs/zend.timesync.xml b/documentation/manual/en/module_specs/zend.timesync.xml new file mode 100644 index 00000000000..e565ca5c323 --- /dev/null +++ b/documentation/manual/en/module_specs/zend.timesync.xml @@ -0,0 +1,193 @@ + +
Introduction + + + Zend_TimeSync is able to receive internet or network time from a time + server using the NTP or SNTP protocol. + With Zend_TimeSync, Zend Framework is able to act independently from + the time settings of the server where it is running. + + + + To be independent from the actual time of the server, Zend_TimeSync + works with the difference of the real time which is sent through NTP or SNTP and the + internal server's time. + + + Background + + + Zend_TimeSync is not able to change the server's time, but it + will return a DateTime instance from + which the difference from the server's time can be worked with. + + + +
Why Zend_TimeSync ? + + + So why would someone use Zend_TimeSync ? + + + + Normally every server within a multi-server farm will have a service running which + synchronizes its own time with a time server. So within a standard environment it should + not be necessary to use Zend_TimeSync. But it can become handy if + there is no service available and if you don't have the right to install such a service. + + + + Here are some example use cases, for which Zend_TimeSync is + perfect suited: + + + + + + Server without time service + + + + If your application is running on a server and this server does not have any + time service running, it may make sense to use + Zend_TimeSync in your application. + + + + + + Separate database server + + + + If your database is running on a different server and this server is not + connected with NTP or SNTP + to the application server, you might have problems using storing and using time + stamp data. + + + + + + Multiple servers + + + + If your application is running on more than one server and these servers' time + bases are not synchronized, you can expect problems within your application when + part of the application is coming from one server and another part from another + server. + + + + + + Batch processing + + + + If you want to work with a time service within a batch file or within a + command line application, Zend_TimeSync may be of use. + + + + + + Zend_TimeSync may provide a good solution in all of these cases + and can be used if you are unable to run any services on your server. + +
+ +
What is NTP ? + + + The Network Time Protocol (NTP) is a protocol + for synchronizing multiple systems' clocks over packet-switched, variable-latency data + networks. NTP uses UDP port 123 as its transport layer. See the wikipedia article + for details about this protocol. + +
+ +
What is SNTP? + + + The Simple Network Time Protocol (SNTP) is a + protocol synchronizing multiple systems' clocks over packet-switched, variable-latency + data networks. SNTP uses UDP port 37 as its transport layer. It is closely related to + the Network Time Protocol, but simpler. + +
+ +
Problematic usage + + + Be warned that when you are using Zend_TimeSync you will have to + think about some details related to the structure of time sync and the internet itself. + Correct usage and best practices will be described here. Read carefully before you begin + using Zend_TimeSync. + +
+ +
Decide which server to use + + + You should select the time server that you want to use very carefully according to the + following criteria: + + + + + + Distance + + + + The distance from your application server to the time server. If your server is + in Europe, it would make little sense to select a time server in Tahiti. Always + select a server which is not far away. This reduces the request time and overall + network load. + + + + + + Speed + + + + How long it takes to receive the request is also relevant. Try different servers + to get the best result. If you are requesting a server which is never + accessible, you will always have an unnecessary delay. + + + + + + Splitting + + + + Do not always use the same server. All time servers will lock out requests from + servers that are flooding the server. If your application requires heavy use of + time servers, you should consider one of the pools described later. + + + + + + So where can you find a time server? Generally you can use any timeserver you can + connect to. This can be a time server within your LAN or any public time server you have + access to. If you decide to use a public time server, you should consider using a server + pool. Server pools are public addresses from which you will get a random, pooled time + server by requesting the time. This way you will not have to split your requests. There + are public server pools available for many regions which you may use to avoid problems + mentioned above. + + + + See pool.ntp.org to find your nearest + server pool. For example, if your server is located within Germany you can connect to + 0.europe.pool.ntp.org. + +
+
diff --git a/documentation/manual/en/module_specs/zend.validator.iban.xml b/documentation/manual/en/module_specs/zend.validator.iban.xml index dcbdfdd2b46..41ee100e903 100644 --- a/documentation/manual/en/module_specs/zend.validator.iban.xml +++ b/documentation/manual/en/module_specs/zend.validator.iban.xml @@ -46,7 +46,7 @@ isValid('AT611904300234573201')) { Of course this works only when an application wide locale was set within the - registry previously. Otherwise Zend\Locale\Locale will try to + registry previously. Otherwise Locale will try to use the locale which the client sends or, when non has been send, it uses the environment locale. Be aware that this can lead to unwanted behaviour within the validation. diff --git a/documentation/manual/en/module_specs/zend.validator.messages.xml b/documentation/manual/en/module_specs/zend.validator.messages.xml index 539161b6316..8684ee39ac3 100644 --- a/documentation/manual/en/module_specs/zend.validator.messages.xml +++ b/documentation/manual/en/module_specs/zend.validator.messages.xml @@ -80,26 +80,16 @@ $validator->setMessage( 'array', - 'content' => '/resources/languages', - 'locale' => $language, - 'scan' => Zend\Translator\Tranlator::LOCALE_DIRECTORY - ) +$translator = new Zend\I18n\Translator\Translator(); +$translator->addTranslationFile( + 'phpArray' + 'resources/languages/en.php', + 'default', + 'en_US ); Zend\Validator\AbstractValidator::setDefaultTranslator($translator); ]]> - Used translation adapter - - - - As translation adapter Zend Framework chose the array adapter. It is simple to - edit and created very fast. - - - Supported languages diff --git a/documentation/manual/en/module_specs/zend.validator.postCode.xml b/documentation/manual/en/module_specs/zend.validator.postCode.xml index b10e69f1cbb..9fea2cc4dd8 100644 --- a/documentation/manual/en/module_specs/zend.validator.postCode.xml +++ b/documentation/manual/en/module_specs/zend.validator.postCode.xml @@ -30,13 +30,12 @@ $validator = new Zend\Validator\PostCode('de_AT'); When you don't set a locale yourself, then Zend\Validator\PostCode will use the application wide set locale, or, when there is none, the locale returned by - Zend\Locale\Locale. + Locale. @@ -82,8 +81,8 @@ $validator->setFormat('AT-\d{5}'); - At it's most basic, you may pass either a Zend\Locale\Locale object or a - string representing a fully qualified locale to the constructor of + At it's most basic, you may pass a string representing a fully + qualified locale to the constructor of Zend\Validator\PostCode. diff --git a/documentation/manual/en/module_specs/zend.validator.xml b/documentation/manual/en/module_specs/zend.validator.xml index c4506a64e7d..c21c946e162 100644 --- a/documentation/manual/en/module_specs/zend.validator.xml +++ b/documentation/manual/en/module_specs/zend.validator.xml @@ -177,44 +177,31 @@ if (!validator->isValid('word')) { Validator classes provide a setTranslator() method with - which you can specify a instance of Zend\Translator\Translator which + which you can specify a instance of Zend\I18n\Translator\Translator which will translate the messages in case of a validation failure. The getTranslator() method returns the set translator instance. 8, 'max' => 12)); -$translate = new Zend\Translator\Translator( - array( - 'adapter' => 'array', - 'content' => array( - Zend\Validator\StringLength::TOO_SHORT => 'Translated \'%value%\'' - ), - 'locale' => 'en' - ) -); +$translate = new Zend\I18n\Translator\Translator(); +// configure the translator... $validator->setTranslator($translate); ]]> With the static setDefaultTranslator() method you can set - a instance of Zend\Translator\Translator which will be used for all + a instance of Zend\I18n\Translator\Translator which will be used for all validation classes, and can be retrieved with getDefaultTranslator(). This prevents you from setting a translator manually for all validator classes, and simplifies your code. 'array', - 'content' => array( - Zend\Validator\StringLength::TOO_SHORT => 'Translated \'%value%\'' - ), - 'locale' => 'en' - ) -); +$translate = new Zend\I18n\Translator\Translator(); +// configure the translator... + Zend\Validator\AbstractValidator::setDefaultTranslator($translate); ]]> diff --git a/documentation/manual/en/module_specs/zend.view.helpers.xml b/documentation/manual/en/module_specs/zend.view.helpers.xml index e9eb4c2f985..4f41b8985b3 100644 --- a/documentation/manual/en/module_specs/zend.view.helpers.xml +++ b/documentation/manual/en/module_specs/zend.view.helpers.xml @@ -97,7 +97,6 @@ $filtered = $view->lowercase('some value'); - @@ -111,7 +110,6 @@ $filtered = $view->lowercase('some value'); -
@@ -281,7 +279,7 @@ I have seen 'The Jerk' 3 time(s). script as part of your helper. This is why we define the setView() and getView() methods. As an example, we could rewrite the SpecialPurpose helper as follows to - take advantage of the Escape helper: + take advantage of the EscapeHtml helper: count++; $output = sprintf("I have seen 'The Jerk' %d time(s).", $this->count); - $escaper = $this->getView()->plugin('escape'); + $escaper = $this->getView()->plugin('escapehtml'); return $escaper($output); } } diff --git a/documentation/manual/en/module_specs/zend.view.php-renderer.scripts.xml b/documentation/manual/en/module_specs/zend.view.php-renderer.scripts.xml index c8d9a1688cd..dc0d5cb7bcf 100644 --- a/documentation/manual/en/module_specs/zend.view.php-renderer.scripts.xml +++ b/documentation/manual/en/module_specs/zend.view.php-renderer.scripts.xml @@ -69,8 +69,8 @@ books as $key => $val): ?> - escape($val['author']) ?> - escape($val['title']) ?> + escapeHtml($val['author']) ?> + escapeHtml($val['title']) ?> @@ -90,12 +90,17 @@ One of the most important tasks to perform in a view script is to make sure that output is escaped properly; among other things, this helps to avoid cross-site scripting attacks. Unless you are using a function, method, or helper that does escaping on its - own, you should always escape variables when you output them. + own, you should always escape variables when you output them and pay careful attention + to applying the correct escaping strategy to each HTML context you use. - The PhpRenderer includes an Escape helper - you can utilize for this purpose. + The PhpRenderer includes a selection of helpers you can use for + this purpose: EscapeHtml, EscapeHtmlAttr + EscapeJs, EscapeCss, and + EscapeUrl. Matching the correct helper (or combination of + helpers) to the context into which you are injecting untrusted variables will ensure + that you are protected against Cross-Site Scripting (XSS) vulnerabilities. variable; // good view-script practice: -echo $this->escape($this->variable); -]]> - - - By default, the escape() method uses the PHP - htmlspecialchars() function for escaping, using UTF-8 as the - characterset, and the ENT_QUOTES setting. However, depending on - your environment, you may wish for escaping to occur in a different way. You may change - either the encoding or callback used, using the setEncoding() - or setCallback() method of the helper. - - - plugin('escape'); +echo $this->escapeHtml($this->variable); -// specify a different encoding to use for the default htmlspecialchars usage -$escaper->setEncoding('ISO-8859-1'); - -// tell it to use htmlentities as the escaping callback -$escaper->setCallback('htmlentities'); - -// or tell it to use a static class method as the callback -$escaper->setCallback(array('SomeClass', 'methodName')); - -// or an instance method -$obj = new SomeClass(); -$escaper->setCallback(array($obj, 'methodName')); - -// or use a closure to curry arguments to another function, -// or inline an escaping mechanism. -$escaper->setCallback(function ($value) { - $value = str_rot13($value); - return base64_encode($value); -}); +// and remember context is always relevant! + ]]> - - The callback function or method should take the value to be escaped as its first - parameter, and all other parameters should be optional. -
diff --git a/documentation/manual/en/module_specs/zend.view.quick-start.xml b/documentation/manual/en/module_specs/zend.view.quick-start.xml index 5a782dc8c20..9e73d946569 100644 --- a/documentation/manual/en/module_specs/zend.view.quick-start.xml +++ b/documentation/manual/en/module_specs/zend.view.quick-start.xml @@ -424,7 +424,7 @@ class ArticleController extends AbstractActionController
- escape('article') ?> + escapeHtml('article') ?>
@@ -987,7 +987,7 @@ class AcceptStrategy implements ListenerAggregate public function selectRenderer($e) { $request = $e->getRequest(); - $headers = $request->headers(); + $headers = $request->getHeaders(); // No Accept header? return PhpRenderer if (!$headers->has('accept')) { @@ -1022,13 +1022,13 @@ class AcceptStrategy implements ListenerAggregate if ($renderer === $this->jsonRenderer) { // JSON Renderer; set content-type header - $headers = $response->headers(); + $headers = $response->getHeaders(); $headers->addHeaderLine('content-type', 'application/json'); } elseif ($renderer === $this->feedRenderer) { // Feed Renderer; set content-type header, and export the feed if // necessary $feedType = $this->feedRenderer->getFeedType(); - $headers = $response->headers(); + $headers = $response->getHeaders(); $mediatype = 'application/' . (('rss' == $feedType) ? 'rss' : 'atom') . '+xml'; diff --git a/documentation/manual/en/module_specs/zend.view.renderer.php-renderer.xml b/documentation/manual/en/module_specs/zend.view.renderer.php-renderer.xml index 102570356af..de812bd13b2 100644 --- a/documentation/manual/en/module_specs/zend.view.renderer.php-renderer.xml +++ b/documentation/manual/en/module_specs/zend.view.renderer.php-renderer.xml @@ -292,8 +292,8 @@ $renderer->render($model); books as $key => $val): ?> - escape($val['author']) ?> - escape($val['title']) ?> + escapeHtml($val['author']) ?> + escapeHtml($val['title']) ?> @@ -309,17 +309,31 @@ $renderer->render($model); Escape Output + + The security mantra is "Filter input, escape output." If you are unsure of the source of a given variable -- which is likely most of the time -- you should escape - it. + it based on which HTML context it is being injected into. The primary contexts to + be aware of are HTML Body, HTML Attribute, Javascript, CSS and URI. Each context + has a dedicated helper available to apply the escaping strategy most appropriate to + each context. You should be aware that escaping does vary significantly between + contexts - there is no one single escaping strategy that can be globally applied. - In the example above, there are calls to an escape() + In the example above, there are calls to an escapeHtml() method. The method is actually a helper, - a plugin available via method overloading, but the salient point is: use it to - escape your output, and thus help prevent cross-site scripting (XSS) attacks. + a plugin available via method overloading. Additional escape helpers provide the + escapeHtmlAttr(), escapeJs(), + escapeCss(), and escapeUrl() + methods for each of the HTML contexts you are most likely to encounter. + + + + By using the provided helpers and being aware of your variables' contexts, you + will prevent your templates from running afoul of Cross-Site Scripting (XSS) + vulnerabilities. diff --git a/documentation/manual/en/module_specs/zend.xmlrpc.client.xml b/documentation/manual/en/module_specs/zend.xmlrpc.client.xml index 0f2ee2a045f..7c697db152b 100644 --- a/documentation/manual/en/module_specs/zend.xmlrpc.client.xml +++ b/documentation/manual/en/module_specs/zend.xmlrpc.client.xml @@ -174,7 +174,7 @@ $result = $client->call('test.sayHello', array($arg1, $arg2)); - Zend\Date\Date + DateTime dateTime.iso8601 diff --git a/documentation/manual/en/ref/requirements-dependencies-table.xml b/documentation/manual/en/ref/requirements-dependencies-table.xml index e1fb7225a57..b875d8b84ca 100644 --- a/documentation/manual/en/ref/requirements-dependencies-table.xml +++ b/documentation/manual/en/ref/requirements-dependencies-table.xml @@ -4471,21 +4471,6 @@
- - - - - Zend_Service_Yahoo - - - - &requirements.hard; - - - Zend_Exception - - - diff --git a/documentation/manual/en/ref/requirements-php-extensions-table.xml b/documentation/manual/en/ref/requirements-php-extensions-table.xml index daeb6d2518e..7e5869a3d19 100644 --- a/documentation/manual/en/ref/requirements-php-extensions-table.xml +++ b/documentation/manual/en/ref/requirements-php-extensions-table.xml @@ -295,13 +295,6 @@ - - - - Zend_Service_Yahoo - - - diff --git a/documentation/manual/en/ref/requirements-zendcomponents-table.xml b/documentation/manual/en/ref/requirements-zendcomponents-table.xml index e63fa699023..7c25b9f0d61 100644 --- a/documentation/manual/en/ref/requirements-zendcomponents-table.xml +++ b/documentation/manual/en/ref/requirements-zendcomponents-table.xml @@ -941,19 +941,6 @@ --- --- - - - - - Zend_Service_Yahoo - - - - &requirements.hard; - - dom - - libxml diff --git a/library/Zend/Acl/Acl.php b/library/Zend/Acl/Acl.php index 06d57ee1a44..85af27275af 100644 --- a/library/Zend/Acl/Acl.php +++ b/library/Zend/Acl/Acl.php @@ -1,21 +1,11 @@ =5.3.3" + } +} \ No newline at end of file diff --git a/library/Zend/Amf/AbstractAuthentication.php b/library/Zend/Amf/AbstractAuthentication.php index 2ee345564aa..d9d7b198dc5 100644 --- a/library/Zend/Amf/AbstractAuthentication.php +++ b/library/Zend/Amf/AbstractAuthentication.php @@ -1,21 +1,11 @@ =5.3.3" + } +} \ No newline at end of file diff --git a/library/Zend/Authentication/Adapter/AdapterInterface.php b/library/Zend/Authentication/Adapter/AdapterInterface.php index d5584d5bf66..e85a20226fd 100644 --- a/library/Zend/Authentication/Adapter/AdapterInterface.php +++ b/library/Zend/Authentication/Adapter/AdapterInterface.php @@ -1,22 +1,11 @@ _challengeClient(); } - $password = $this->_basicResolver->resolve($creds[0], $this->_realm); - if ($password && - $this->_secureStringCompare($password, $creds[1])) { + $result = $this->_basicResolver->resolve($creds[0], $this->_realm, $creds[1]); + + if ($result + && !is_array($result) + && $this->_secureStringCompare($result, $creds[1]) + ) { $identity = array('username'=>$creds[0], 'realm'=>$this->_realm); return new Authentication\Result(Authentication\Result::SUCCESS, $identity); - } else { - return $this->_challengeClient(); + } elseif (is_array($result)) { + return new Authentication\Result(Authentication\Result::SUCCESS, $result); } + + return $this->_challengeClient(); } /** diff --git a/library/Zend/Authentication/Adapter/Http/Exception/ExceptionInterface.php b/library/Zend/Authentication/Adapter/Http/Exception/ExceptionInterface.php index 2998aadfce6..738ba5767a1 100644 --- a/library/Zend/Authentication/Adapter/Http/Exception/ExceptionInterface.php +++ b/library/Zend/Authentication/Adapter/Http/Exception/ExceptionInterface.php @@ -1,22 +1,11 @@ =5.3.3" + }, + "suggest": { + "zendframework/zend-db": "Zend\\Db component", + "zendframework/zend-uri": "Zend\\Uri component", + "zendframework/zend-session": "Zend\\Session component" + } +} \ No newline at end of file diff --git a/library/Zend/Barcode/Barcode.php b/library/Zend/Barcode/Barcode.php index b6883bd8a03..9e6defcceba 100644 --- a/library/Zend/Barcode/Barcode.php +++ b/library/Zend/Barcode/Barcode.php @@ -1,36 +1,24 @@ =5.3.3", + "zendframework/zend-stdlib": "self.version" + }, + "suggest": { + "zendframework/zend-validator": "Zend\\Validator component" + } +} \ No newline at end of file diff --git a/library/Zend/Cache/Exception/BadMethodCallException.php b/library/Zend/Cache/Exception/BadMethodCallException.php index 4aa41fa93fb..50602b63490 100644 --- a/library/Zend/Cache/Exception/BadMethodCallException.php +++ b/library/Zend/Cache/Exception/BadMethodCallException.php @@ -1,21 +1,11 @@ 1, 'maxTtl' => 0, 'staticTtl' => true, 'ttlPrecision' => 1, diff --git a/library/Zend/Cache/Storage/Adapter/ApcIterator.php b/library/Zend/Cache/Storage/Adapter/ApcIterator.php index 08f97a83337..80f2576c18e 100644 --- a/library/Zend/Cache/Storage/Adapter/ApcIterator.php +++ b/library/Zend/Cache/Storage/Adapter/ApcIterator.php @@ -1,36 +1,22 @@ _close(); + + parent::__destruct(); + } + + /* options */ + + /** + * Set options. + * + * @param array|Traversable|DbaOptions $options + * @return Apc + * @see getOptions() + */ + public function setOptions($options) + { + if (!$options instanceof DbaOptions) { + $options = new DbaOptions($options); + } + + return parent::setOptions($options); + } + + /** + * Get options. + * + * @return DbaOptions + * @see setOptions() + */ + public function getOptions() + { + if (!$this->options) { + $this->setOptions(new DbaOptions()); + } + return $this->options; + } + + /* TotalSpaceCapableInterface */ + + /** + * Get total space in bytes + * + * @return int|float + */ + public function getTotalSpace() + { + if ($this->totalSpace !== null) { + $pathname = $this->getOptions()->getPathname(); + + if ($pathname === '') { + throw new Exception\LogicException('No pathname to database file'); + } + + ErrorHandler::start(); + $total = disk_total_space($pathname); + $error = ErrorHandler::stop(); + if ($total === false) { + throw new Exception\RuntimeException("Can't detect total space of '{$pathname}'", 0, $error); + } + + // clean total space buffer on change pathname + $events = $this->getEventManager(); + $handle = null; + $totalSpace = & $this->totalSpace; + $callback = function ($event) use (& $events, & $handle, & $totalSpace) { + $params = $event->getParams(); + if (isset($params['pathname'])) { + $totalSpace = null; + $events->detach($handle); + } + }; + $handle = $events->attach($callback); + } + + return $this->totalSpace; + } + + /* AvailableSpaceCapableInterface */ + + /** + * Get available space in bytes + * + * @return int|float + */ + public function getAvailableSpace() + { + $pathname = $this->getOptions()->getPathname(); + + if ($pathname === '') { + throw new Exception\LogicException('No pathname to database file'); + } + + ErrorHandler::start(); + $avail = disk_free_space($pathname); + $error = ErrorHandler::stop(); + if ($avail === false) { + throw new Exception\RuntimeException("Can't detect free space of '{$pathname}'", 0, $error); + } + + return $avail; + } + + /* FlushableInterface */ + + /** + * Flush the whole storage + * + * @return boolean + */ + public function flush() + { + $pathname = $this->getOptions()->getPathname(); + + if ($pathname === '') { + throw new Exception\LogicException('No pathname to database file'); + } + + if (file_exists($pathname)) { + + // close the dba file before delete + // and reopen (create) on next use + $this->_close(); + + ErrorHandler::start(); + $result = unlink($pathname); + $error = ErrorHandler::stop(); + if (!$result) { + throw new Exception\RuntimeException("unlink('{$pathname}') failed", 0, $error); + } + } + + return true; + } + + /* ClearByNamespaceInterface */ + + /** + * Remove items by given namespace + * + * @param string $prefix + * @return boolean + */ + public function clearByNamespace($namespace) + { + $prefix = $namespace . $this->getOptions()->getNamespaceSeparator(); + $prefixl = strlen($prefix); + $result = true; + + $this->_open(); + + do { // Workaround for PHP-Bug #62491 & #62492 + $recheck = false; + $internalKey = dba_firstkey($this->handle); + while ($internalKey !== false && $internalKey !== null) { + if (substr($internalKey, 0, $prefixl) === $prefix) { + $result = dba_delete($internalKey, $this->handle) && $result; + } + + $internalKey = dba_nextkey($this->handle); + } + } while ($recheck); + + return $result; + } + + /* ClearByPrefixInterface */ + + /** + * Remove items matching given prefix + * + * @param string $prefix + * @return boolean + */ + public function clearByPrefix($prefix) + { + $options = $this->getOptions(); + $prefix = $options->getNamespace() . $options->getNamespaceSeparator() . $prefix; + $prefixl = strlen($prefix); + $result = true; + + $this->_open(); + + do { // Workaround for PHP-Bug #62491 & #62492 + $recheck = false; + $internalKey = dba_firstkey($this->handle); + while ($internalKey !== false && $internalKey !== null) { + if (substr($internalKey, 0, $prefixl) === $prefix) { + $result = dba_delete($internalKey, $this->handle) && $result; + $recheck = true; + } + + $internalKey = dba_nextkey($this->handle); + } + } while ($recheck); + + return $result; + } + + /* IterableInterface */ + + /** + * Get the storage iterator + * + * @return ApcIterator + */ + public function getIterator() + { + $options = $this->getOptions(); + $prefix = $options->getNamespace() . $options->getNamespaceSeparator(); + + return new DbaIterator($this, $this->handle, $prefix); + } + + /* OptimizableInterface */ + + /** + * Optimize the storage + * + * @return boolean + * @return Exception\RuntimeException + */ + public function optimize() + { + $this->_open(); + if (!dba_optimize($this->handle)) { + throw new Exception\RuntimeException('dba_optimize failed'); + } + return true; + } + + /* reading */ + + /** + * Internal method to get an item. + * + * @param string $normalizedKey + * @param boolean $success + * @param mixed $casToken + * @return mixed Data on success, null on failure + * @throws Exception\ExceptionInterface + */ + protected function internalGetItem(& $normalizedKey, & $success = null, & $casToken = null) + { + $options = $this->getOptions(); + $prefix = $options->getNamespace() . $options->getNamespaceSeparator(); + $internalKey = $prefix . $normalizedKey; + + $this->_open(); + $value = dba_fetch($internalKey, $this->handle); + + if ($value === false) { + $success = false; + return null; + } + + $success = true; + $casToken = $value; + return $value; + } + + /** + * Internal method to test if an item exists. + * + * @param string $normalizedKey + * @return boolean + * @throws Exception\ExceptionInterface + */ + protected function internalHasItem(& $normalizedKey) + { + $options = $this->getOptions(); + $prefix = $options->getNamespace() . $options->getNamespaceSeparator(); + $internalKey = $prefix . $normalizedKey; + + $this->_open(); + return dba_exists($internalKey, $this->handle); + } + + /* writing */ + + /** + * Internal method to store an item. + * + * @param string $normalizedKey + * @param mixed $value + * @return boolean + * @throws Exception\ExceptionInterface + */ + protected function internalSetItem(& $normalizedKey, & $value) + { + $options = $this->getOptions(); + $prefix = $options->getNamespace() . $options->getNamespaceSeparator(); + $internalKey = $prefix . $normalizedKey; + + $this->_open(); + if (!dba_replace($internalKey, $value, $this->handle)) { + throw new Exception\RuntimeException("dba_replace('{$internalKey}', ...) failed"); + } + + return true; + } + + /** + * Add an item. + * + * @param string $normalizedKey + * @param mixed $value + * @return boolean + * @throws Exception\ExceptionInterface + */ + protected function internalAddItem(& $normalizedKey, & $value) + { + $options = $this->getOptions(); + $prefix = $options->getNamespace() . $options->getNamespaceSeparator(); + $internalKey = $prefix . $normalizedKey; + + $this->_open(); + + // Workaround for PHP-Bug #54242 & #62489 + if (dba_exists($internalKey, $this->handle)) { + return false; + } + + // Workaround for PHP-Bug #54242 & #62489 + // dba_insert returns true if key already exists + ErrorHandler::start(); + $result = dba_insert($internalKey, $value, $this->handle); + $error = ErrorHandler::stop(); + if (!$result || $error) { + return false; + } + + return true; + } + + /** + * Internal method to remove an item. + * + * @param string $normalizedKey + * @return boolean + * @throws Exception\ExceptionInterface + */ + protected function internalRemoveItem(& $normalizedKey) + { + $options = $this->getOptions(); + $prefix = $options->getNamespace() . $options->getNamespaceSeparator(); + $internalKey = $prefix . $normalizedKey; + + $this->_open(); + + // Workaround for PHP-Bug #62490 + if (!dba_exists($internalKey, $this->handle)) { + return false; + } + + return dba_delete($internalKey, $this->handle); + } + + /* status */ + + /** + * Internal method to get capabilities of this adapter + * + * @return Capabilities + */ + protected function internalGetCapabilities() + { + if ($this->capabilities === null) { + $marker = new stdClass(); + $capabilities = new Capabilities( + $this, + $marker, + array( + 'supportedDatatypes' => array( + 'NULL' => 'string', + 'boolean' => 'string', + 'integer' => 'string', + 'double' => 'string', + 'string' => true, + 'array' => false, + 'object' => false, + 'resource' => false, + ), + 'minTtl' => 0, + 'supportedMetadata' => array(), + 'maxKeyLength' => 0, // TODO: maxKeyLength ???? + 'namespaceIsPrefix' => true, + 'namespaceSeparator' => $this->getOptions()->getNamespaceSeparator(), + ) + ); + + // update namespace separator on change option + $this->getEventManager()->attach('option', function ($event) use ($capabilities, $marker) { + $params = $event->getParams(); + + if (isset($params['namespace_separator'])) { + $capabilities->setNamespaceSeparator($marker, $params['namespace_separator']); + } + }); + + $this->capabilities = $capabilities; + $this->capabilityMarker = $marker; + } + + return $this->capabilities; + } + + /** + * Open the database if not already done. + * + * @return void + * @throws Exception\LogicException + * @throws Exception\RuntimeException + */ + protected function _open() + { + if (!$this->handle) { + $options = $this->getOptions(); + $pathname = $options->getPathname(); + $mode = $options->getMode(); + $handler = $options->getHandler(); + + if ($pathname === '') { + throw new Exception\LogicException('No pathname to database file'); + } + + ErrorHandler::start(); + $dba = dba_open($pathname, $mode, $handler); + $err = ErrorHandler::stop(); + if (!$dba) { + throw new Exception\RuntimeException( + "dba_open('{$pathname}', '{$mode}', '{$handler}') failed", 0, $err + ); + } + $this->handle = $dba; + } + } + + /** + * Close database file if opend + * + * @return void + */ + protected function _close() + { + if ($this->handle) { + @dba_close($this->handle); + $this->handle = null; + } + } +} diff --git a/library/Zend/Cache/Storage/Adapter/DbaIterator.php b/library/Zend/Cache/Storage/Adapter/DbaIterator.php new file mode 100644 index 00000000000..67e0cfe9dce --- /dev/null +++ b/library/Zend/Cache/Storage/Adapter/DbaIterator.php @@ -0,0 +1,197 @@ +storage = $storage; + $this->handle = $handle; + $this->prefixLength = strlen($prefix); + + $this->rewind(); + } + + /** + * Get storage instance + * + * @return Dba + */ + public function getStorage() + { + return $this->storage; + } + + /** + * Get iterator mode + * + * @return int Value of IteratorInterface::CURRENT_AS_* + */ + public function getMode() + { + return $this->mode; + } + + /** + * Set iterator mode + * + * @param int $mode + * @return ApcIterator Fluent interface + */ + public function setMode($mode) + { + $this->mode = (int) $mode; + return $this; + } + + /* Iterator */ + + /** + * Get current key, value or metadata. + * + * @return mixed + * @throws Exception\RuntimeException + */ + public function current() + { + if ($this->mode == IteratorInterface::CURRENT_AS_SELF) { + return $this; + } + + $key = $this->key(); + + if ($this->mode == IteratorInterface::CURRENT_AS_VALUE) { + return $this->storage->getItem($key); + } elseif ($this->mode == IteratorInterface::CURRENT_AS_METADATA) { + return $this->storage->getMetadata($key); + } + + return $key; + } + + /** + * Get current key + * + * @return string + * @throws Exception\RuntimeException + */ + public function key() + { + if ($this->currentInternalKey === false) { + throw new Exception\RuntimeException("Iterater is on an invalid state"); + } + + // remove namespace prefix + return substr($this->currentInternalKey, $this->prefixLength); + } + + /** + * Move forward to next element + * + * @return void + * @throws Exception\RuntimeException + */ + public function next() + { + if ($this->currentInternalKey === false) { + throw new Exception\RuntimeException("Iterater is on an invalid state"); + } + + $this->currentInternalKey = dba_nextkey($this->handle); + + // Workaround for PHP-Bug #62492 + if ($this->currentInternalKey === null) { + $this->currentInternalKey = false; + } + } + + /** + * Checks if current position is valid + * + * @return boolean + */ + public function valid() + { + return ($this->currentInternalKey !== false); + } + + /** + * Rewind the Iterator to the first element. + * + * @return void + * @throws Exception\RuntimeException + */ + public function rewind() + { + if ($this->currentInternalKey === false) { + throw new Exception\RuntimeException("Iterater is on an invalid state"); + } + + $this->currentInternalKey = dba_firstkey($this->handle); + + // Workaround for PHP-Bug #62492 + if ($this->currentInternalKey === null) { + $this->currentInternalKey = false; + } + } +} diff --git a/library/Zend/Cache/Storage/Adapter/DbaOptions.php b/library/Zend/Cache/Storage/Adapter/DbaOptions.php new file mode 100644 index 00000000000..ebadc0f3176 --- /dev/null +++ b/library/Zend/Cache/Storage/Adapter/DbaOptions.php @@ -0,0 +1,134 @@ +triggerOptionEvent('namespace_separator', $separator); + $this->namespaceSeparator = $separator; + return $this; + } + + /** + * Get namespace separator + * + * @return string + */ + public function getNamespaceSeparator() + { + return $this->namespaceSeparator; + } + + /** + * Set pathname to database file + * + * @param string $pathname + * @return DbaOptions + */ + public function setPathname($pathname) + { + $this->pathname = (string) $pathname; + $this->triggerOptionEvent('pathname', $pathname); + return $this; + } + + /** + * Get pathname to database file + * + * @return string + */ + public function getPathname() + { + return $this->pathname; + } + + /** + * + * + * @param unknown_type $mode + * @return \Zend\Cache\Storage\Adapter\DbaOptions + */ + public function setMode($mode) + { + $this->mode = (string) $mode; + $this->triggerOptionEvent('mode', $mode); + return $this; + } + + public function getMode() + { + return $this->mode; + } + + public function setHandler($handler) + { + $handler = (string) $handler; + + if (!function_exists('dba_handlers') || !in_array($handler, dba_handlers())) { + throw new Exception\ExtensionNotLoadedException("DBA-Handler '{$handler}' not supported"); + } + + $this->triggerOptionEvent('handler', $handler); + $this->handler = $handler; + return $this; + } + + public function getHandler() + { + return $this->handler; + } +} diff --git a/library/Zend/Cache/Storage/Adapter/Filesystem.php b/library/Zend/Cache/Storage/Adapter/Filesystem.php index aca2d6dbe0d..30fa8017311 100644 --- a/library/Zend/Cache/Storage/Adapter/Filesystem.php +++ b/library/Zend/Cache/Storage/Adapter/Filesystem.php @@ -1,51 +1,38 @@ detach($handle); } }; - $handle = $this->getEventManager()->attach($callback); + $handle = $events->attach($callback); } + return $this->totalSpace; } @@ -1188,6 +1176,7 @@ protected function internalGetCapabilities() 'resource' => false, ), 'supportedMetadata' => $metadata, + 'minTtl' => 1, 'maxTtl' => 0, 'staticTtl' => false, 'ttlPrecision' => 1, diff --git a/library/Zend/Cache/Storage/Adapter/FilesystemIterator.php b/library/Zend/Cache/Storage/Adapter/FilesystemIterator.php index b8e37619953..c745ac03358 100644 --- a/library/Zend/Cache/Storage/Adapter/FilesystemIterator.php +++ b/library/Zend/Cache/Storage/Adapter/FilesystemIterator.php @@ -1,36 +1,22 @@ false, ), 'supportedMetadata' => array(), + 'minTtl' => 1, 'maxTtl' => 0, 'staticTtl' => true, 'ttlPrecision' => 1, diff --git a/library/Zend/Cache/Storage/Adapter/MemcachedOptions.php b/library/Zend/Cache/Storage/Adapter/MemcachedOptions.php index e04271ede73..89c627786bf 100644 --- a/library/Zend/Cache/Storage/Adapter/MemcachedOptions.php +++ b/library/Zend/Cache/Storage/Adapter/MemcachedOptions.php @@ -1,29 +1,18 @@ true, 'resource' => true, ), - 'supportedMetadata' => array('mtime'), + 'supportedMetadata' => array('mtime'), + 'minTtl' => 1, 'maxTtl' => PHP_INT_MAX, 'staticTtl' => false, 'ttlPrecision' => 0.05, diff --git a/library/Zend/Cache/Storage/Adapter/MemoryOptions.php b/library/Zend/Cache/Storage/Adapter/MemoryOptions.php index 534974b03e3..ce871fc12ad 100644 --- a/library/Zend/Cache/Storage/Adapter/MemoryOptions.php +++ b/library/Zend/Cache/Storage/Adapter/MemoryOptions.php @@ -1,22 +1,11 @@ array( 'internal_key', 'ttl', 'hits', 'size' ), + 'minTtl' => 1, 'maxTtl' => 0, 'staticTtl' => true, 'ttlPrecision' => 1, diff --git a/library/Zend/Cache/Storage/Adapter/WinCacheOptions.php b/library/Zend/Cache/Storage/Adapter/WinCacheOptions.php index 09db0faddc0..e8547c98198 100644 --- a/library/Zend/Cache/Storage/Adapter/WinCacheOptions.php +++ b/library/Zend/Cache/Storage/Adapter/WinCacheOptions.php @@ -1,22 +1,11 @@ setCapability($marker, 'supportedMetadata', $metadata); } + /** + * Get minimum supported time-to-live + * + * @return int 0 means items never expire + */ + public function getMinTtl() + { + return $this->getCapability('minTtl', 0); + } + + /** + * Set minimum supported time-to-live + * + * @param stdClass $marker + * @param int $minTtl + * @return Capabilities Fluent interface + */ + public function setMinTtl(stdClass $marker, $minTtl) + { + $minTtl = (int) $minTtl; + if ($minTtl < 0) { + throw new Exception\InvalidArgumentException('$minTtl must be greater or equal 0'); + } + return $this->setCapability($marker, 'minTtl', $minTtl); + } + /** * Get maximum supported time-to-live * @@ -254,7 +322,7 @@ public function getMaxTtl() */ public function setMaxTtl(stdClass $marker, $maxTtl) { - $maxTtl = (int)$maxTtl; + $maxTtl = (int) $maxTtl; if ($maxTtl < 0) { throw new Exception\InvalidArgumentException('$maxTtl must be greater or equal 0'); } diff --git a/library/Zend/Cache/Storage/ClearByNamespaceInterface.php b/library/Zend/Cache/Storage/ClearByNamespaceInterface.php index 6d1e886444c..c1b1eb8d5c8 100644 --- a/library/Zend/Cache/Storage/ClearByNamespaceInterface.php +++ b/library/Zend/Cache/Storage/ClearByNamespaceInterface.php @@ -1,22 +1,11 @@ =5.3.3" + }, + "suggest": { + "zendframework/zend-log": "Zend\\Log component" + } +} \ No newline at end of file diff --git a/library/Zend/Captcha/AbstractAdapter.php b/library/Zend/Captcha/AbstractAdapter.php index 67373f01997..f4c7279d5e2 100644 --- a/library/Zend/Captcha/AbstractAdapter.php +++ b/library/Zend/Captcha/AbstractAdapter.php @@ -1,22 +1,11 @@ =5.3.3" + } +} \ No newline at end of file diff --git a/library/Zend/Cloud/AbstractFactory.php b/library/Zend/Cloud/AbstractFactory.php index 731ae0b41b4..9ad95a832ba 100644 --- a/library/Zend/Cloud/AbstractFactory.php +++ b/library/Zend/Cloud/AbstractFactory.php @@ -1,21 +1,11 @@ =5.3.3" + }, + "suggest": { + "zendframework/zend-service-amazon": "Zend\\Service\\Amazon component", + "zendframework/zend-service-rackspace": "Zend\\Service\\Rackspace component", + "zendframework/zend-service-gogrid": "Zend\\Service\\GoGrid component", + "zendframework/zend-service-windowsazure": "Zend\\Service\\WindowsAzure component" + } +} \ No newline at end of file diff --git a/library/Zend/Code/Annotation/AnnotationCollection.php b/library/Zend/Code/Annotation/AnnotationCollection.php index 6caf15ab944..1318a8a6a9e 100644 --- a/library/Zend/Code/Annotation/AnnotationCollection.php +++ b/library/Zend/Code/Annotation/AnnotationCollection.php @@ -1,4 +1,12 @@ url . ' ' . $this->description . self::LINE_FEED; return $output; } diff --git a/library/Zend/Code/Generator/DocBlock/Tag/ParamTag.php b/library/Zend/Code/Generator/DocBlock/Tag/ParamTag.php index 7ca8130fd79..9b040180d60 100644 --- a/library/Zend/Code/Generator/DocBlock/Tag/ParamTag.php +++ b/library/Zend/Code/Generator/DocBlock/Tag/ParamTag.php @@ -1,22 +1,11 @@ getName() . ' ]' . PHP_EOL; } -} \ No newline at end of file +} diff --git a/library/Zend/Code/Reflection/DocBlock/Tag/ParamTag.php b/library/Zend/Code/Reflection/DocBlock/Tag/ParamTag.php index 60275353396..66aa01d4094 100644 --- a/library/Zend/Code/Reflection/DocBlock/Tag/ParamTag.php +++ b/library/Zend/Code/Reflection/DocBlock/Tag/ParamTag.php @@ -1,21 +1,11 @@ =5.3.3" + }, + "require-dev": { + "doctrine/common": ">=2.1" + }, + "suggest": { + "doctrine/common": "Doctrine\\Common >=2.1 for annotation features" + } +} \ No newline at end of file diff --git a/library/Zend/Config/Config.php b/library/Zend/Config/Config.php index 70fa03a1b4b..ece2b095b84 100644 --- a/library/Zend/Config/Config.php +++ b/library/Zend/Config/Config.php @@ -10,9 +10,9 @@ namespace Zend\Config; +use ArrayAccess; use Countable; use Iterator; -use ArrayAccess; use Zend\Stdlib\ArrayUtils; /** diff --git a/library/Zend/Config/Processor/Queue.php b/library/Zend/Config/Processor/Queue.php index e3691495116..fb276ba22b4 100644 --- a/library/Zend/Config/Processor/Queue.php +++ b/library/Zend/Config/Processor/Queue.php @@ -11,8 +11,8 @@ namespace Zend\Config\Processor; use Zend\Config\Config; -use Zend\Stdlib\PriorityQueue; use Zend\Config\Exception; +use Zend\Stdlib\PriorityQueue; /** * @category Zend diff --git a/library/Zend/Config/Processor/Token.php b/library/Zend/Config/Processor/Token.php index cf725ba97d0..022daf5f4ec 100644 --- a/library/Zend/Config/Processor/Token.php +++ b/library/Zend/Config/Processor/Token.php @@ -10,9 +10,9 @@ namespace Zend\Config\Processor; +use Traversable; use Zend\Config\Config; use Zend\Config\Exception; -use Traversable; /** * @category Zend diff --git a/library/Zend/Config/Reader/Json.php b/library/Zend/Config/Reader/Json.php index 01a5f9ed80f..a84b7e49914 100644 --- a/library/Zend/Config/Reader/Json.php +++ b/library/Zend/Config/Reader/Json.php @@ -11,8 +11,8 @@ namespace Zend\Config\Reader; use Zend\Config\Exception; -use Zend\Json\Json as JsonFormat; use Zend\Json\Exception as JsonException; +use Zend\Json\Json as JsonFormat; /** * JSON config reader. diff --git a/library/Zend/Config/ReaderPluginManager.php b/library/Zend/Config/ReaderPluginManager.php index 008bd0d5800..c059725de3c 100644 --- a/library/Zend/Config/ReaderPluginManager.php +++ b/library/Zend/Config/ReaderPluginManager.php @@ -1,21 +1,11 @@ =5.3.3" + } +} \ No newline at end of file diff --git a/library/Zend/Console/Exception/ExceptionInterface.php b/library/Zend/Console/Exception/ExceptionInterface.php index e1cb31dd8a2..e67f6916cad 100644 --- a/library/Zend/Console/Exception/ExceptionInterface.php +++ b/library/Zend/Console/Exception/ExceptionInterface.php @@ -1,21 +1,11 @@ =5.3.3" + } +} \ No newline at end of file diff --git a/library/Zend/Crypt/BlockCipher.php b/library/Zend/Crypt/BlockCipher.php index 44f5884b017..f32620cafdd 100644 --- a/library/Zend/Crypt/BlockCipher.php +++ b/library/Zend/Crypt/BlockCipher.php @@ -10,10 +10,10 @@ namespace Zend\Crypt; -use Zend\Crypt\Symmetric\SymmetricInterface; use Zend\Crypt\Hmac; -use Zend\Crypt\Utils; use Zend\Crypt\Key\Derivation\Pbkdf2; +use Zend\Crypt\Symmetric\SymmetricInterface; +use Zend\Crypt\Utils; use Zend\Math\Math; /** diff --git a/library/Zend/Crypt/Exception/ExceptionInterface.php b/library/Zend/Crypt/Exception/ExceptionInterface.php index f8f067f91a4..dc7ce3bf107 100644 --- a/library/Zend/Crypt/Exception/ExceptionInterface.php +++ b/library/Zend/Crypt/Exception/ExceptionInterface.php @@ -13,8 +13,6 @@ /** * @category Zend * @package Zend_Crypt - * @copyright Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com) - * @license http://framework.zend.com/license/new-bsd New BSD License */ interface ExceptionInterface { diff --git a/library/Zend/Crypt/Exception/InvalidArgumentException.php b/library/Zend/Crypt/Exception/InvalidArgumentException.php index a36a0798d95..611ad147a7c 100644 --- a/library/Zend/Crypt/Exception/InvalidArgumentException.php +++ b/library/Zend/Crypt/Exception/InvalidArgumentException.php @@ -7,6 +7,7 @@ * @license http://framework.zend.com/license/new-bsd New BSD License * @package Zend_Crypt */ + namespace Zend\Crypt\Exception; /** @@ -15,8 +16,6 @@ * @category Zend * @package Zend_Crypt * @subpackage Exception - * @copyright Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com) - * @license http://framework.zend.com/license/new-bsd New BSD License */ class InvalidArgumentException extends \InvalidArgumentException diff --git a/library/Zend/Crypt/Exception/RuntimeException.php b/library/Zend/Crypt/Exception/RuntimeException.php index cd889deac90..5b51426a263 100644 --- a/library/Zend/Crypt/Exception/RuntimeException.php +++ b/library/Zend/Crypt/Exception/RuntimeException.php @@ -7,6 +7,7 @@ * @license http://framework.zend.com/license/new-bsd New BSD License * @package Zend_Crypt */ + namespace Zend\Crypt\Exception; /** @@ -15,8 +16,6 @@ * @category Zend * @package Zend_Crypt * @subpackage Exception - * @copyright Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com) - * @license http://framework.zend.com/license/new-bsd New BSD License */ class RuntimeException extends \RuntimeException diff --git a/library/Zend/Crypt/Key/Derivation/Exception/ExceptionInterface.php b/library/Zend/Crypt/Key/Derivation/Exception/ExceptionInterface.php index fe14dd150a2..57c95836485 100644 --- a/library/Zend/Crypt/Key/Derivation/Exception/ExceptionInterface.php +++ b/library/Zend/Crypt/Key/Derivation/Exception/ExceptionInterface.php @@ -7,6 +7,7 @@ * @license http://framework.zend.com/license/new-bsd New BSD License * @package Zend_Crypt */ + namespace Zend\Crypt\Key\Derivation\Exception; use Zend\Crypt\Exception\ExceptionInterface as Exception; @@ -14,8 +15,6 @@ /** * @category Zend * @package Zend_Crypt - * @copyright Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com) - * @license http://framework.zend.com/license/new-bsd New BSD License */ interface ExceptionInterface extends Exception -{} \ No newline at end of file +{} diff --git a/library/Zend/Crypt/Key/Derivation/Exception/InvalidArgumentException.php b/library/Zend/Crypt/Key/Derivation/Exception/InvalidArgumentException.php index 56b418a3441..6982dd6bddf 100644 --- a/library/Zend/Crypt/Key/Derivation/Exception/InvalidArgumentException.php +++ b/library/Zend/Crypt/Key/Derivation/Exception/InvalidArgumentException.php @@ -7,6 +7,7 @@ * @license http://framework.zend.com/license/new-bsd New BSD License * @package Zend_Crypt */ + namespace Zend\Crypt\Key\Derivation\Exception; use Zend\Crypt\Exception; @@ -17,8 +18,6 @@ * @category Zend * @package Zend_Crypt * @subpackage Exception - * @copyright Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com) - * @license http://framework.zend.com/license/new-bsd New BSD License */ class InvalidArgumentException extends Exception\InvalidArgumentException implements ExceptionInterface diff --git a/library/Zend/Crypt/Key/Derivation/Exception/RuntimeException.php b/library/Zend/Crypt/Key/Derivation/Exception/RuntimeException.php index 4806cedd783..a7bedfcbfa4 100644 --- a/library/Zend/Crypt/Key/Derivation/Exception/RuntimeException.php +++ b/library/Zend/Crypt/Key/Derivation/Exception/RuntimeException.php @@ -18,8 +18,6 @@ * @category Zend * @package Zend_Crypt * @subpackage Exception - * @copyright Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com) - * @license http://framework.zend.com/license/new-bsd New BSD License */ class RuntimeException extends Exception\RuntimeException implements ExceptionInterface diff --git a/library/Zend/Crypt/Key/Derivation/SaltedS2k.php b/library/Zend/Crypt/Key/Derivation/SaltedS2k.php index 16f260df99a..8e4b4ed3e7d 100644 --- a/library/Zend/Crypt/Key/Derivation/SaltedS2k.php +++ b/library/Zend/Crypt/Key/Derivation/SaltedS2k.php @@ -7,6 +7,7 @@ * @license http://framework.zend.com/license/new-bsd New BSD License * @package Zend_Crypt */ + namespace Zend\Crypt\Key\Derivation; /** @@ -14,8 +15,6 @@ * * @category Zend * @package Zend_Crypt - * @copyright Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com) - * @license http://framework.zend.com/license/new-bsd New BSD License */ class SaltedS2k { diff --git a/library/Zend/Crypt/Password/Bcrypt.php b/library/Zend/Crypt/Password/Bcrypt.php index 1446dd090c4..c8607bf7884 100644 --- a/library/Zend/Crypt/Password/Bcrypt.php +++ b/library/Zend/Crypt/Password/Bcrypt.php @@ -7,20 +7,19 @@ * @license http://framework.zend.com/license/new-bsd New BSD License * @package Zend_Crypt */ + namespace Zend\Crypt\Password; -use Zend\Math\Math; use Traversable; -use Zend\Stdlib\ArrayUtils; use Zend\Math\Exception as MathException; +use Zend\Math\Math; +use Zend\Stdlib\ArrayUtils; /** * Bcrypt algorithm using crypt() function of PHP * * @category Zend * @package Zend_Crypt - * @copyright Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com) - * @license http://framework.zend.com/license/new-bsd New BSD License */ class Bcrypt implements PasswordInterface { diff --git a/library/Zend/Crypt/Password/Exception/ExceptionInterface.php b/library/Zend/Crypt/Password/Exception/ExceptionInterface.php index 306a06b42f5..2b9716771b8 100644 --- a/library/Zend/Crypt/Password/Exception/ExceptionInterface.php +++ b/library/Zend/Crypt/Password/Exception/ExceptionInterface.php @@ -7,6 +7,7 @@ * @license http://framework.zend.com/license/new-bsd New BSD License * @package Zend_Crypt */ + namespace Zend\Crypt\Password\Exception; use Zend\Crypt\Exception\ExceptionInterface as Exception; @@ -14,8 +15,6 @@ /** * @category Zend * @package Zend_Crypt - * @copyright Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com) - * @license http://framework.zend.com/license/new-bsd New BSD License */ interface ExceptionInterface extends Exception -{} \ No newline at end of file +{} diff --git a/library/Zend/Crypt/Password/Exception/InvalidArgumentException.php b/library/Zend/Crypt/Password/Exception/InvalidArgumentException.php index 77480002a9a..7525d27461d 100644 --- a/library/Zend/Crypt/Password/Exception/InvalidArgumentException.php +++ b/library/Zend/Crypt/Password/Exception/InvalidArgumentException.php @@ -7,6 +7,7 @@ * @license http://framework.zend.com/license/new-bsd New BSD License * @package Zend_Crypt */ + namespace Zend\Crypt\Password\Exception; use Zend\Crypt\Exception; @@ -17,8 +18,6 @@ * @category Zend * @package Zend_Crypt * @subpackage Exception - * @copyright Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com) - * @license http://framework.zend.com/license/new-bsd New BSD License */ class InvalidArgumentException extends Exception\InvalidArgumentException implements ExceptionInterface diff --git a/library/Zend/Crypt/Password/Exception/RuntimeException.php b/library/Zend/Crypt/Password/Exception/RuntimeException.php index 340b33e9073..7f8d7f3116b 100644 --- a/library/Zend/Crypt/Password/Exception/RuntimeException.php +++ b/library/Zend/Crypt/Password/Exception/RuntimeException.php @@ -18,8 +18,6 @@ * @category Zend * @package Zend_Crypt * @subpackage Exception - * @copyright Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com) - * @license http://framework.zend.com/license/new-bsd New BSD License */ class RuntimeException extends Exception\RuntimeException implements ExceptionInterface diff --git a/library/Zend/Crypt/Password/PasswordInterface.php b/library/Zend/Crypt/Password/PasswordInterface.php index 66cbdfed02e..122f4ef6757 100644 --- a/library/Zend/Crypt/Password/PasswordInterface.php +++ b/library/Zend/Crypt/Password/PasswordInterface.php @@ -7,6 +7,7 @@ * @license http://framework.zend.com/license/new-bsd New BSD License * @package Zend_Crypt */ + namespace Zend\Crypt\Password; interface PasswordInterface diff --git a/library/Zend/Crypt/PublicKey/DiffieHellman.php b/library/Zend/Crypt/PublicKey/DiffieHellman.php index b6e31364b69..ce26a21c294 100644 --- a/library/Zend/Crypt/PublicKey/DiffieHellman.php +++ b/library/Zend/Crypt/PublicKey/DiffieHellman.php @@ -7,6 +7,7 @@ * @license http://framework.zend.com/license/new-bsd New BSD License * @package Zend_Crypt */ + namespace Zend\Crypt\PublicKey; use Zend\Crypt\Exception; @@ -19,8 +20,6 @@ * * @category Zend * @package Zend_Crypt - * @copyright Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com) - * @license http://framework.zend.com/license/new-bsd New BSD License */ class DiffieHellman { diff --git a/library/Zend/Crypt/PublicKey/Rsa.php b/library/Zend/Crypt/PublicKey/Rsa.php index 9588aefee8f..a76eaa09159 100644 --- a/library/Zend/Crypt/PublicKey/Rsa.php +++ b/library/Zend/Crypt/PublicKey/Rsa.php @@ -10,10 +10,10 @@ namespace Zend\Crypt\PublicKey; +use Traversable; use Zend\Crypt\PublicKey\RsaOptions; use Zend\Crypt\PublicKey\Rsa\Exception; use Zend\Stdlib\ArrayUtils; -use Traversable; /** * Implementation of the RSA public key encryption algorithm. diff --git a/library/Zend/Crypt/PublicKey/Rsa/AbstractKey.php b/library/Zend/Crypt/PublicKey/Rsa/AbstractKey.php index 002e912f5a5..ce09506ef1e 100644 --- a/library/Zend/Crypt/PublicKey/Rsa/AbstractKey.php +++ b/library/Zend/Crypt/PublicKey/Rsa/AbstractKey.php @@ -13,8 +13,6 @@ /** * @category Zend * @package Zend_Crypt - * @copyright Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com) - * @license http://framework.zend.com/license/new-bsd New BSD License */ abstract class AbstractKey { diff --git a/library/Zend/Crypt/PublicKey/Rsa/Exception/ExceptionInterface.php b/library/Zend/Crypt/PublicKey/Rsa/Exception/ExceptionInterface.php index 1bd30556857..ce72eae4cdc 100644 --- a/library/Zend/Crypt/PublicKey/Rsa/Exception/ExceptionInterface.php +++ b/library/Zend/Crypt/PublicKey/Rsa/Exception/ExceptionInterface.php @@ -18,4 +18,4 @@ * @subpackage PublicKey */ interface ExceptionInterface extends Exception -{} \ No newline at end of file +{} diff --git a/library/Zend/Crypt/PublicKey/RsaOptions.php b/library/Zend/Crypt/PublicKey/RsaOptions.php index 4cdfaf75b26..75613f0c06e 100644 --- a/library/Zend/Crypt/PublicKey/RsaOptions.php +++ b/library/Zend/Crypt/PublicKey/RsaOptions.php @@ -10,10 +10,10 @@ namespace Zend\Crypt\PublicKey; -use Zend\Stdlib\AbstractOptions; +use Traversable; use Zend\Crypt\PublicKey\Rsa\Exception; +use Zend\Stdlib\AbstractOptions; use Zend\Stdlib\ArrayUtils; -use Traversable; /** * RSA instance options diff --git a/library/Zend/Crypt/Symmetric/.Mcrypt.php.swp b/library/Zend/Crypt/Symmetric/.Mcrypt.php.swp deleted file mode 100644 index 4b70ca0926f..00000000000 Binary files a/library/Zend/Crypt/Symmetric/.Mcrypt.php.swp and /dev/null differ diff --git a/library/Zend/Crypt/Symmetric/Exception/ExceptionInterface.php b/library/Zend/Crypt/Symmetric/Exception/ExceptionInterface.php index 4caac25851d..1c1bb74dddc 100644 --- a/library/Zend/Crypt/Symmetric/Exception/ExceptionInterface.php +++ b/library/Zend/Crypt/Symmetric/Exception/ExceptionInterface.php @@ -15,8 +15,6 @@ /** * @category Zend * @package Zend_Crypt - * @copyright Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com) - * @license http://framework.zend.com/license/new-bsd New BSD License */ interface ExceptionInterface extends Exception -{} \ No newline at end of file +{} diff --git a/library/Zend/Crypt/Symmetric/Exception/InvalidArgumentException.php b/library/Zend/Crypt/Symmetric/Exception/InvalidArgumentException.php index 4e6e49a72db..b5505508ad2 100644 --- a/library/Zend/Crypt/Symmetric/Exception/InvalidArgumentException.php +++ b/library/Zend/Crypt/Symmetric/Exception/InvalidArgumentException.php @@ -7,6 +7,7 @@ * @license http://framework.zend.com/license/new-bsd New BSD License * @package Zend_Crypt */ + namespace Zend\Crypt\Symmetric\Exception; use Zend\Crypt\Exception; @@ -17,8 +18,6 @@ * @category Zend * @package Zend_Crypt * @subpackage Exception - * @copyright Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com) - * @license http://framework.zend.com/license/new-bsd New BSD License */ class InvalidArgumentException extends Exception\InvalidArgumentException implements ExceptionInterface diff --git a/library/Zend/Crypt/Symmetric/Exception/RuntimeException.php b/library/Zend/Crypt/Symmetric/Exception/RuntimeException.php index 973f457e654..7e82cf881e6 100644 --- a/library/Zend/Crypt/Symmetric/Exception/RuntimeException.php +++ b/library/Zend/Crypt/Symmetric/Exception/RuntimeException.php @@ -18,8 +18,6 @@ * @category Zend * @package Zend_Crypt * @subpackage Exception - * @copyright Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com) - * @license http://framework.zend.com/license/new-bsd New BSD License */ class RuntimeException extends Exception\RuntimeException implements ExceptionInterface diff --git a/library/Zend/Crypt/Symmetric/Padding/PaddingInterface.php b/library/Zend/Crypt/Symmetric/Padding/PaddingInterface.php index c2bf015f65b..77e67eb26cd 100644 --- a/library/Zend/Crypt/Symmetric/Padding/PaddingInterface.php +++ b/library/Zend/Crypt/Symmetric/Padding/PaddingInterface.php @@ -7,6 +7,7 @@ * @license http://framework.zend.com/license/new-bsd New BSD License * @package Zend_Crypt */ + namespace Zend\Crypt\Symmetric\Padding; interface PaddingInterface diff --git a/library/Zend/Crypt/Symmetric/Padding/Pkcs7.php b/library/Zend/Crypt/Symmetric/Padding/Pkcs7.php index a3cb3c0222a..1ae5a2b893d 100644 --- a/library/Zend/Crypt/Symmetric/Padding/Pkcs7.php +++ b/library/Zend/Crypt/Symmetric/Padding/Pkcs7.php @@ -7,6 +7,7 @@ * @license http://framework.zend.com/license/new-bsd New BSD License * @package Zend_Crypt */ + namespace Zend\Crypt\Symmetric\Padding; /** @@ -14,8 +15,6 @@ * * @category Zend * @package Zend_Crypt - * @copyright Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com) - * @license http://framework.zend.com/license/new-bsd New BSD License */ class Pkcs7 implements PaddingInterface { diff --git a/library/Zend/Crypt/Symmetric/PaddingPluginManager.php b/library/Zend/Crypt/Symmetric/PaddingPluginManager.php index 703077a3287..7f4ec9b4675 100644 --- a/library/Zend/Crypt/Symmetric/PaddingPluginManager.php +++ b/library/Zend/Crypt/Symmetric/PaddingPluginManager.php @@ -1,22 +1,11 @@ =5.3.3", + "zendframework/zend-math": "self.version", + "zendframework/zend-stdlib": "self.version" + } +} \ No newline at end of file diff --git a/library/Zend/Currency/Currency.php b/library/Zend/Currency/Currency.php deleted file mode 100644 index dc255b8814e..00000000000 --- a/library/Zend/Currency/Currency.php +++ /dev/null @@ -1,866 +0,0 @@ - Position for the currency sign - * 'script' => Script for the output - * 'format' => Locale for numeric output - * 'display' => Currency detail to show - * 'precision' => Precision for the currency - * 'name' => Name for this currency - * 'currency' => 3 lettered international abbreviation - * 'symbol' => Currency symbol - * 'locale' => Locale for this currency - * 'value' => Money value - * 'service' => Exchange service to use - * - * @var array - * @see Zend_Locale - */ - protected $_options = array( - 'position' => self::STANDARD, - 'script' => null, - 'format' => null, - 'display' => self::NO_SYMBOL, - 'precision' => 2, - 'name' => null, - 'currency' => null, - 'symbol' => null, - 'locale' => null, - 'value' => 0, - 'service' => null, - 'tag' => 'Zend_Locale' - ); - - /** - * Creates a currency instance. Every supressed parameter is used from the actual or the given locale. - * - * @param string|array $options OPTIONAL Options array or currency short name - * when string is given - * @param string|\Zend\Locale\Locale $locale OPTIONAL locale name - * @throws Exception\InvalidArgumentException When currency is invalid - */ - public function __construct($options = null, $locale = null) - { - if (is_array($options)) { - $this->setLocale($locale); - $this->setFormat($options); - } else if (Locale\Locale::isLocale($options, false)) { - $this->setLocale($options); - $options = $locale; - } else { - $this->setLocale($locale); - } - - // Get currency details - if (!isset($this->_options['currency']) || !is_array($options)) { - $this->_options['currency'] = self::getShortName($options, $this->_options['locale']); - } - - if (!isset($this->_options['name']) || !is_array($options)) { - $this->_options['name'] = self::getName($options, $this->_options['locale']); - } - - if (!isset($this->_options['symbol']) || !is_array($options)) { - $this->_options['symbol'] = self::getSymbol($options, $this->_options['locale']); - } - - if (($this->_options['currency'] === null) and ($this->_options['name'] === null)) { - throw new Exception\InvalidArgumentException("Currency '$options' not found"); - } - - // Get the format - if (!empty($this->_options['symbol'])) { - $this->_options['display'] = self::USE_SYMBOL; - } else if (!empty($this->_options['currency'])) { - $this->_options['display'] = self::USE_SHORTNAME; - } - } - - /** - * Returns a localized currency string - * - * @param integer|float $value OPTIONAL Currency value - * @param array $options OPTIONAL options to set temporary - * @throws Exception\InvalidArgumentException When the value is not a number - * @return string - */ - public function toCurrency($value = null, array $options = array()) - { - if ($value === null) { - if (is_array($options) && isset($options['value'])) { - $value = $options['value']; - } else { - $value = $this->_options['value']; - } - } - - if (is_array($value)) { - $options += $value; - if (isset($options['value'])) { - $value = $options['value']; - } - } - - // Validate the passed number - if (!(isset($value)) or (is_numeric($value) === false)) { - throw new Exception\InvalidArgumentException("Value '$value' has to be numeric"); - } - - if (isset($options['currency'])) { - if (!isset($options['locale'])) { - $options['locale'] = $this->_options['locale']; - } - - $options['currency'] = self::getShortName($options['currency'], $options['locale']); - $options['name'] = self::getName($options['currency'], $options['locale']); - $options['symbol'] = self::getSymbol($options['currency'], $options['locale']); - } - - $options = $this->_checkOptions($options) + $this->_options; - - // Format the number - $format = $options['format']; - $locale = $options['locale']; - if (empty($format)) { - $format = Cldr::getContent($locale, 'currencynumber'); - } else if (Locale\Locale::isLocale($format, true)) { - $locale = $format; - $format = Cldr::getContent($format, 'currencynumber'); - } - - $original = $value; - $value = Locale\Format::toNumber($value, array('locale' => $locale, - 'number_format' => $format, - 'precision' => $options['precision'])); - - if ($options['position'] !== self::STANDARD) { - $value = str_replace('Ā¤', '', $value); - $space = ''; - if (iconv_strpos($value, 'Ā ') !== false) { - $value = str_replace('Ā ', '', $value); - $space = 'Ā '; - } - - if ($options['position'] == self::LEFT) { - $value = 'Ā¤' . $space . $value; - } else { - $value = $value . $space . 'Ā¤'; - } - } - - // Localize the number digits - if (empty($options['script']) === false) { - $value = Locale\Format::convertNumerals($value, 'Latn', $options['script']); - } - - // Get the sign to be placed next to the number - if (is_numeric($options['display']) === false) { - $sign = $options['display']; - } else { - switch($options['display']) { - case self::USE_SYMBOL: - $sign = $this->_extractPattern($options['symbol'], $original); - break; - - case self::USE_SHORTNAME: - $sign = $options['currency']; - break; - - case self::USE_NAME: - $sign = $options['name']; - break; - - default: - $sign = ''; - $value = str_replace('Ā ', '', $value); - break; - } - } - - $value = str_replace('Ā¤', $sign, $value); - return $value; - } - - /** - * Internal method to extract the currency pattern - * when a choice is given based on the given value - * - * @param string $pattern - * @param float|integer $value - * @return string - */ - private function _extractPattern($pattern, $value) - { - if (strpos($pattern, '|') === false) { - return $pattern; - } - - $patterns = explode('|', $pattern); - $token = $pattern; - $value = trim(str_replace('Ā¤', '', $value)); - krsort($patterns); - foreach($patterns as $content) { - if (strpos($content, '<') !== false) { - $check = iconv_substr($content, 0, iconv_strpos($content, '<')); - $token = iconv_substr($content, iconv_strpos($content, '<') + 1); - if ($check < $value) { - return $token; - } - } else { - $check = iconv_substr($content, 0, iconv_strpos($content, 'ā‰¤')); - $token = iconv_substr($content, iconv_strpos($content, 'ā‰¤') + 1); - if ($check <= $value) { - return $token; - } - } - - } - - return $token; - } - - /** - * Sets the formating options of the localized currency string - * If no parameter is passed, the standard setting of the - * actual set locale will be used - * - * @param array $options (Optional) Options to set - * @return Currency - */ - public function setFormat(array $options = array()) - { - $this->_options = $this->_checkOptions($options) + $this->_options; - return $this; - } - - /** - * Internal function for checking static given locale parameter - * - * @param string $currency (Optional) Currency name - * @param string|\Zend\Locale\Locale $locale (Optional) Locale to display informations - * @throws Exception\InvalidArgumentException When locale contains no region - * @return string The extracted locale representation as string - */ - private function _checkParams($currency = null, $locale = null) - { - // Manage the params - if ((empty($locale)) and (!empty($currency)) and - (Locale\Locale::isLocale($currency, true))) { - $locale = $currency; - $currency = null; - } - - // Validate the locale and get the country short name - $country = null; - if ((Locale\Locale::isLocale($locale, true)) and (strlen($locale) > 4)) { - $country = substr($locale, (strpos($locale, '_') + 1)); - } else { - throw new Exception\InvalidArgumentException("No region found within the locale '" . (string) $locale . "'"); - } - - // Get the available currencies for this country - $data = Cldr::getContent($locale, 'currencytoregion', $country); - if ((empty($currency) === false) and (empty($data) === false)) { - $abbreviation = $currency; - } else { - $abbreviation = $data; - } - - return array('locale' => $locale, 'currency' => $currency, 'name' => $abbreviation, 'country' => $country); - } - - /** - * Returns the actual or details of other currency symbols, - * when no symbol is available it returns the currency shortname (f.e. FIM for Finnian Mark) - * - * @param string $currency (Optional) Currency name - * @param string|\Zend\Locale\Locale $locale (Optional) Locale to display informations - * @return string - */ - public function getSymbol($currency = null, $locale = null) - { - if (($currency === null) and ($locale === null)) { - return $this->_options['symbol']; - } - - $params = self::_checkParams($currency, $locale); - - // Get the symbol - $symbol = Cldr::getContent($params['locale'], 'currencysymbol', $params['currency']); - if (empty($symbol) === true) { - $symbol = Cldr::getContent($params['locale'], 'currencysymbol', $params['name']); - } - - if (empty($symbol) === true) { - return null; - } - - return $symbol; - } - - /** - * Returns the actual or details of other currency shortnames - * - * @param string $currency OPTIONAL Currency's name - * @param string|\Zend\Locale\Locale $locale OPTIONAL The locale - * @return string - */ - public function getShortName($currency = null, $locale = null) - { - if (($currency === null) and ($locale === null)) { - return $this->_options['currency']; - } - - $params = self::_checkParams($currency, $locale); - - // Get the shortname - if (empty($params['currency']) === true) { - return $params['name']; - } - - $list = Cldr::getContent($params['locale'], 'currencytoname', $params['currency']); - if (empty($list) === true) { - $list = Cldr::getContent($params['locale'], 'nametocurrency', $params['currency']); - if (empty($list) === false) { - $list = $params['currency']; - } - } - - if (empty($list) === true) { - return null; - } - - return $list; - } - - /** - * Returns the actual or details of other currency names - * - * @param string $currency (Optional) Currency's short name - * @param string|\Zend\Locale\Locale $locale (Optional) The locale - * @return string - */ - public function getName($currency = null, $locale = null) - { - if (($currency === null) and ($locale === null)) { - return $this->_options['name']; - } - - $params = self::_checkParams($currency, $locale); - - // Get the name - $name = Cldr::getContent($params['locale'], 'nametocurrency', $params['currency']); - if (empty($name) === true) { - $name = Cldr::getContent($params['locale'], 'nametocurrency', $params['name']); - } - - if (empty($name) === true) { - return null; - } - - return $name; - } - - /** - * Returns a list of regions where this currency is or was known - * - * @param string $currency OPTIONAL Currency's short name - * @throws Exception\InvalidArgumentException When no currency was defined - * @return array List of regions - */ - public function getRegionList($currency = null) - { - if ($currency === null) { - $currency = $this->_options['currency']; - } - - if (empty($currency) === true) { - throw new Exception\InvalidArgumentException('No currency defined'); - } - - $data = Cldr::getContent($this->_options['locale'], 'regiontocurrency', $currency); - - $result = explode(' ', $data); - return $result; - } - - /** - * Returns a list of currencies which are used in this region - * a region name should be 2 charachters only (f.e. EG, DE, US) - * If no region is given, the actual region is used - * - * @param string $region OPTIONAL Region to return the currencies for - * @return array List of currencies - */ - public function getCurrencyList($region = null) - { - if (empty($region) === true) { - if (strlen($this->_options['locale']) > 4) { - $region = substr($this->_options['locale'], (strpos($this->_options['locale'], '_') + 1)); - } - } - - $data = Cldr::getContent($this->_options['locale'], 'currencytoregion', $region); - - $result = explode(' ', $data); - return $result; - } - - /** - * Returns the actual currency name - * - * @return string - */ - public function toString() - { - return $this->toCurrency(); - } - - /** - * Returns the currency name - * - * @return string - */ - public function __toString() - { - return $this->toString(); - } - - /** - * Returns the set cache - * - * @return CacheStorage The set cache - */ - public static function getCache() - { - return Cldr::getCache(); - } - - /** - * Sets a cache for Zend_Currency - * - * @param CacheStorage $cache Cache to set - * @return void - */ - public static function setCache(CacheStorage $cache) - { - Cldr::setCache($cache); - } - - /** - * Returns true when a cache is set - * - * @return boolean - */ - public static function hasCache() - { - return Cldr::hasCache(); - } - - /** - * Removes any set cache - * - * @return void - */ - public static function removeCache() - { - Cldr::removeCache(); - } - - /** - * Sets a new locale for data retreivement - * Example: 'de_XX' will be set to 'de' because 'de_XX' does not exist - * 'xx_YY' will be set to 'root' because 'xx' does not exist - * - * @param string|\Zend\Locale\Locale $locale (Optional) Locale for parsing input - * @throws Exception\InvalidArgumentException When the given locale does not exist - * @return Currency Provides fluent interface - */ - public function setLocale($locale = null) - { - try { - $locale = Locale\Locale::findLocale($locale); - if (strlen($locale) > 4) { - $this->_options['locale'] = $locale; - } else { - throw new Exception\InvalidArgumentException("No region found within the locale '" . (string) $locale . "'"); - } - } catch (Locale\Exception\ExceptionInterface $e) { - throw new Exception\InvalidArgumentException($e->getMessage()); - } - - // Get currency details - $this->_options['currency'] = $this->getShortName(null, $this->_options['locale']); - $this->_options['name'] = $this->getName(null, $this->_options['locale']); - $this->_options['symbol'] = $this->getSymbol(null, $this->_options['locale']); - - return $this; - } - - /** - * Returns the actual set locale - * - * @return string - */ - public function getLocale() - { - return $this->_options['locale']; - } - - /** - * Returns the value - * - * @return float - */ - public function getValue() - { - return $this->_options['value']; - } - - /** - * Adds a currency - * - * @param float|integer|Currency $value Add this value to currency - * @param string|Currency $currency The currency to add - * @return Currency - */ - public function setValue($value, $currency = null) - { - $this->_options['value'] = $this->_exchangeCurrency($value, $currency); - return $this; - } - - /** - * Adds a currency - * - * @param float|integer|Currency $value Add this value to currency - * @param string|Currency $currency The currency to add - * @return Currency - */ - public function add($value, $currency = null) - { - $value = $this->_exchangeCurrency($value, $currency); - $this->_options['value'] += (float) $value; - return $this; - } - - /** - * Substracts a currency - * - * @param float|integer|Currency $value Substracts this value from currency - * @param string|Currency $currency The currency to substract - * @return Currency - */ - public function sub($value, $currency = null) - { - $value = $this->_exchangeCurrency($value, $currency); - $this->_options['value'] -= (float) $value; - return $this; - } - - /** - * Divides a currency - * - * @param float|integer|Currency $value Divides this value from currency - * @param string|Currency $currency The currency to divide - * @return Currency - */ - public function div($value, $currency = null) - { - $value = $this->_exchangeCurrency($value, $currency); - $this->_options['value'] /= (float) $value; - return $this; - } - - /** - * Multiplies a currency - * - * @param float|integer|Currency $value Multiplies this value from currency - * @param string|Currency $currency The currency to multiply - * @return Currency - */ - public function mul($value, $currency = null) - { - $value = $this->_exchangeCurrency($value, $currency); - $this->_options['value'] *= (float) $value; - return $this; - } - - /** - * Calculates the modulo from a currency - * - * @param float|integer|Currency $value Calculate modulo from this value - * @param string|Currency $currency The currency to calculate the modulo - * @return Currency - */ - public function mod($value, $currency = null) - { - $value = $this->_exchangeCurrency($value, $currency); - $this->_options['value'] %= (float) $value; - return $this; - } - - /** - * Compares two currencies - * - * @param float|integer|Currency $value Compares the currency with this value - * @param string|Currency $currency The currency to compare this value from - * @return Currency - */ - public function compare($value, $currency = null) - { - $value = $this->_exchangeCurrency($value, $currency); - $value = $this->_options['value'] - $value; - if ($value < 0) { - return -1; - } else if ($value > 0) { - return 1; - } - - return 0; - } - - /** - * Returns true when the two currencies are equal - * - * @param float|integer|Currency $value Compares the currency with this value - * @param string|Currency $currency The currency to compare this value from - * @return boolean - */ - public function equals($value, $currency = null) - { - $value = $this->_exchangeCurrency($value, $currency); - if ($this->_options['value'] == $value) { - return true; - } - - return false; - } - - /** - * Returns true when the currency is more than the given value - * - * @param float|integer|Currency $value Compares the currency with this value - * @param string|Currency $currency The currency to compare this value from - * @return boolean - */ - public function isMore($value, $currency = null) - { - $value = $this->_exchangeCurrency($value, $currency); - if ($this->_options['value'] > $value) { - return true; - } - - return false; - } - - /** - * Returns true when the currency is less than the given value - * - * @param float|integer|Currency $value Compares the currency with this value - * @param string|Currency $currency The currency to compare this value from - * @return boolean - */ - public function isLess($value, $currency = null) - { - $value = $this->_exchangeCurrency($value, $currency); - if ($this->_options['value'] < $value) { - return true; - } - - return false; - - } - - /** - * Internal method which calculates the exchanges currency - * - * @param float|integer|Currency $value Compares the currency with this value - * @param string|Currency $currency The currency to compare this value from - * @return float - */ - protected function _exchangeCurrency($value, $currency) - { - if ($value instanceof Currency) { - $currency = $value->getShortName(); - $value = $value->getValue(); - } else { - $currency = $this->getShortName($currency, $this->getLocale()); - } - - $rate = 1; - if ($currency !== $this->getShortName()) { - $service = $this->getService(); - if (!($service instanceof CurrencyService)) { - throw new Exception\RuntimeException('No exchange service applied'); - } - - $rate = $service->getRate($currency, $this->getShortName()); - } - - $value *= $rate; - return $value; - } - - /** - * Returns the set service class - * - * @return CurrencyService - */ - public function getService() - { - return $this->_options['service']; - } - - /** - * Sets a new exchange service - * - * @param string|CurrencyService $service Service class - * @return Currency - */ - public function setService($service) - { - if (is_string($service)) { - if (!class_exists($service)) { - throw new Exception\InvalidArgumentException('A currency service by class name "' . $service . '" does not exist'); - } - $service = new $service; - } - - if (!($service instanceof CurrencyService)) { - throw new Exception\InvalidArgumentException('A currency service must implement Zend\Currency\CurrencyService'); - } - - $this->_options['service'] = $service; - return $this; - } - - /** - * Internal method for checking the options array - * - * @param array $options Options to check - * @throws Exception\InvalidArgumentException On unknown position - * @throws Exception\InvalidArgumentException On unknown locale - * @throws Exception\InvalidArgumentException On unknown display - * @throws Exception\InvalidArgumentException On precision not between -1 and 30 - * @throws Exception\InvalidArgumentException On problem with script conversion - * @throws Exception\InvalidArgumentException On unknown options - * @return array - */ - protected function _checkOptions(array $options = array()) - { - if (count($options) === 0) { - return $this->_options; - } - - foreach ($options as $name => $value) { - $name = strtolower($name); - if ($name !== 'format' && $name !== 'locale') { - if (gettype($value) === 'string') { - $value = strtolower($value); - } - } - - switch($name) { - case 'locale': - $this->setLocale($value); - break; - - case 'position': - if (($value !== self::STANDARD) and ($value !== self::RIGHT) and ($value !== self::LEFT)) { - throw new Exception\InvalidArgumentException("Unknown position '" . $value . "'"); - } - - break; - - case 'format': - if ((empty($value) === false) and (Locale\Locale::isLocale($value) === false)) { - if (!is_string($value) || (strpos($value, '0') === false)) { - throw new Exception\InvalidArgumentException('\'' - . ((gettype($value) === 'object') ? get_class($value) : $value) - . '\' is no format token'); - } - } - break; - - case 'display': - if (is_numeric($value) and ($value !== self::NO_SYMBOL) and ($value !== self::USE_SYMBOL) and - ($value !== self::USE_SHORTNAME) and ($value !== self::USE_NAME)) { - throw new Exception\InvalidArgumentException("Unknown display '$value'"); - } - break; - - case 'precision': - if ($value === null) { - $value = -1; - } - - if (($value < -1) or ($value > 30)) { - throw new Exception\InvalidArgumentException("'$value' precision has to be between -1 and 30."); - } - break; - - case 'script': - try { - Locale\Format::convertNumerals(0, $options['script']); - } catch (Locale\Exception\ExceptionInterface $e) { - throw new Exception\InvalidArgumentException($e->getMessage()); - } - break; - - default: - break; - } - } - - return $options; - } -} diff --git a/library/Zend/Currency/CurrencyService.php b/library/Zend/Currency/CurrencyService.php deleted file mode 100644 index 5fb233de5e6..00000000000 --- a/library/Zend/Currency/CurrencyService.php +++ /dev/null @@ -1,40 +0,0 @@ - array('latitude' => 5.3411111, 'longitude' => -4.0280556), - 'Abu Dhabi' => array('latitude' => 24.4666667, 'longitude' => 54.3666667), - 'Abuja' => array('latitude' => 9.1758333, 'longitude' => 7.1808333), - 'Accra' => array('latitude' => 5.55, 'longitude' => -0.2166667), - 'Adamstown' => array('latitude' => -25.0666667, 'longitude' => -130.0833333), - 'Addis Ababa' => array('latitude' => 9.0333333, 'longitude' => 38.7), - 'Adelaide' => array('latitude' => -34.9333333, 'longitude' => 138.6), - 'Algiers' => array('latitude' => 36.7630556, 'longitude' => 3.0505556), - 'Alofi' => array('latitude' => -19.0166667, 'longitude' => -169.9166667), - 'Amman' => array('latitude' => 31.95, 'longitude' => 35.9333333), - 'Amsterdam' => array('latitude' => 52.35, 'longitude' => 4.9166667), - 'Andorra la Vella' => array('latitude' => 42.5, 'longitude' => 1.5166667), - 'Ankara' => array('latitude' => 39.9272222, 'longitude' => 32.8644444), - 'Antananarivo' => array('latitude' => -18.9166667, 'longitude' => 47.5166667), - 'Apia' => array('latitude' => -13.8333333, 'longitude' => -171.7333333), - 'Ashgabat' => array('latitude' => 37.95, 'longitude' => 58.3833333), - 'Asmara' => array('latitude' => 15.3333333, 'longitude' => 38.9333333), - 'Astana' => array('latitude' => 51.1811111, 'longitude' => 71.4277778), - 'AsunciĆ³n' => array('latitude' => -25.2666667, 'longitude' => -57.6666667), - 'Athens' => array('latitude' => 37.9833333, 'longitude' => 23.7333333), - 'Auckland' => array('latitude' => -36.8666667, 'longitude' => 174.7666667), - 'Avarua' => array('latitude' => -21.2, 'longitude' => -159.7666667), - 'Baghdad' => array('latitude' => 33.3386111, 'longitude' => 44.3938889), - 'Baku' => array('latitude' => 40.3952778, 'longitude' => 49.8822222), - 'Bamako' => array('latitude' => 12.65, 'longitude' => -8), - 'Bandar Seri Begawan' => array('latitude' => 4.8833333, 'longitude' => 114.9333333), - 'Bankok' => array('latitude' => 13.5833333, 'longitude' => 100.2166667), - 'Bangui' => array('latitude' => 4.3666667, 'longitude' => 18.5833333), - 'Banjul' => array('latitude' => 13.4530556, 'longitude' => -16.5775), - 'Basel' => array('latitude' => 47.5666667, 'longitude' => 7.6), - 'Basseterre' => array('latitude' => 17.3, 'longitude' => -62.7166667), - 'Beijing' => array('latitude' => 39.9288889, 'longitude' => 116.3883333), - 'Beirut' => array('latitude' => 33.8719444, 'longitude' => 35.5097222), - 'Belgrade' => array('latitude' => 44.8186111, 'longitude' => 20.4680556), - 'Belmopan' => array('latitude' => 17.25, 'longitude' => -88.7666667), - 'Berlin' => array('latitude' => 52.5166667, 'longitude' => 13.4), - 'Bern' => array('latitude' => 46.9166667, 'longitude' => 7.4666667), - 'Bishkek' => array('latitude' => 42.8730556, 'longitude' => 74.6002778), - 'Bissau' => array('latitude' => 11.85, 'longitude' => -15.5833333), - 'Bloemfontein' => array('latitude' => -29.1333333, 'longitude' => 26.2), - 'BogotĆ”' => array('latitude' => 4.6, 'longitude' => -74.0833333), - 'Brasilia' => array('latitude' => -15.7833333, 'longitude' => -47.9166667), - 'Bratislava' => array('latitude' => 48.15, 'longitude' => 17.1166667), - 'Brazzaville' => array('latitude' => -4.2591667, 'longitude' => 15.2847222), - 'Bridgetown' => array('latitude' => 13.1, 'longitude' => -59.6166667), - 'Brisbane' => array('latitude' => -27.5, 'longitude' => 153.0166667), - 'Brussels' => array('latitude' => 50.8333333, 'longitude' => 4.3333333), - 'Bucharest' => array('latitude' => 44.4333333, 'longitude' => 26.1), - 'Budapest' => array('latitude' => 47.5, 'longitude' => 19.0833333), - 'Buenos Aires' => array('latitude' => -34.5875, 'longitude' => -58.6725), - 'Bujumbura' => array('latitude' => -3.3761111, 'longitude' => 29.36), - 'Cairo' => array('latitude' => 30.05, 'longitude' => 31.25), - 'Calgary' => array('latitude' => 51.0833333, 'longitude' => -114.0833333), - 'Canberra' => array('latitude' => -35.2833333, 'longitude' => 149.2166667), - 'Cape Town' => array('latitude' => -33.9166667, 'longitude' => 18.4166667), - 'Caracas' => array('latitude' => 10.5, 'longitude' => -66.9166667), - 'Castries' => array('latitude' => 14, 'longitude' => -61), - 'Charlotte Amalie' => array('latitude' => 18.34389, 'longitude' => -64.93111), - 'Chicago' => array('latitude' => 41.85, 'longitude' => -87.65), - 'Chisinau' => array('latitude' => 47.055556, 'longitude' => 28.8575), - 'Cockburn Town' => array('latitude' => 21.4666667, 'longitude' => -71.1333333), - 'Colombo' => array('latitude' => 6.9319444, 'longitude' => 79.8477778), - 'Conakry' => array('latitude' => 9.5091667, 'longitude' => -13.7122222), - 'Copenhagen' => array('latitude' => 55.6666667, 'longitude' => 12.5833333), - 'Cotonou' => array('latitude' => 6.35, 'longitude' => 2.4333333), - 'Dakar' => array('latitude' => 14.6708333, 'longitude' => -17.4380556), - 'Damascus' => array('latitude' => 33.5, 'longitude' => 36.3), - 'Dar es Salaam' => array('latitude' => -6.8, 'longitude' => 39.2833333), - 'Dhaka' => array('latitude' => 23.7230556, 'longitude' => 90.4086111), - 'Dili' => array('latitude' => -8.5586111, 'longitude' => 125.5736111), - 'Djibouti' => array('latitude' => 11.595, 'longitude' => 43.1480556), - 'Dodoma' => array('latitude' => -6.1833333, 'longitude' => 35.75), - 'Doha' => array('latitude' => 25.2866667, 'longitude' => 51.5333333), - 'Dubai' => array('latitude' => 25.2522222, 'longitude' => 55.28), - 'Dublin' => array('latitude' => 53.3330556, 'longitude' => -6.2488889), - 'Dushanbe' => array('latitude' => 38.56, 'longitude' => 68.7738889 ), - 'Fagatogo' => array('latitude' => -14.2825, 'longitude' => -170.69), - 'Fongafale' => array('latitude' => -8.5166667, 'longitude' => 179.2166667), - 'Freetown' => array('latitude' => 8.49, 'longitude' => -13.2341667), - 'Gaborone' => array('latitude' => -24.6463889, 'longitude' => 25.9119444), - 'Geneva' => array('latitude' => 46.2, 'longitude' => 6.1666667), - 'George Town' => array('latitude' => 19.3, 'longitude' => -81.3833333), - 'Georgetown' => array('latitude' => 6.8, 'longitude' => -58.1666667), - 'Gibraltar' => array('latitude' => 36.1333333, 'longitude' => -5.35), - 'Glasgow' => array('latitude' => 55.8333333, 'longitude' => -4.25), - 'Guatemala la Nueva' => array('latitude' => 14.6211111, 'longitude' => -90.5269444), - 'Hagatna' => array('latitude' => 13.47417, 'longitude' => 144.74778), - 'The Hague' => array('latitude' => 52.0833333, 'longitude' => 4.3), - 'Hamilton' => array('latitude' => 32.2941667, 'longitude' => -64.7838889), - 'Hanoi' => array('latitude' => 21.0333333, 'longitude' => 105.85), - 'Harare' => array('latitude' => -17.8177778, 'longitude' => 31.0447222), - 'Havana' => array('latitude' => 23.1319444, 'longitude' => -82.3641667), - 'Helsinki' => array('latitude' => 60.1755556, 'longitude' => 24.9341667), - 'Honiara' => array('latitude' => -9.4333333, 'longitude' => 159.95), - 'Islamabad' => array('latitude' => 30.8486111, 'longitude' => 72.4944444), - 'Istanbul' => array('latitude' => 41.0186111, 'longitude' => 28.9647222), - 'Jakarta' => array('latitude' => -6.1744444, 'longitude' => 106.8294444), - 'Jamestown' => array('latitude' => -15.9333333, 'longitude' => -5.7166667), - 'Jerusalem' => array('latitude' => 31.7666667, 'longitude' => 35.2333333), - 'Johannesburg' => array('latitude' => -26.2, 'longitude' => 28.0833333), - 'Kabul' => array('latitude' => 34.5166667, 'longitude' => 69.1833333), - 'Kampala' => array('latitude' => 0.3155556, 'longitude' => 32.5655556), - 'Kathmandu' => array('latitude' => 27.7166667, 'longitude' => 85.3166667), - 'Khartoum' => array('latitude' => 15.5880556, 'longitude' => 32.5341667), - 'Kigali' => array('latitude' => -1.9536111, 'longitude' => 30.0605556), - 'Kingston' => array('latitude' => -29.05, 'longitude' => 167.95), - 'Kingstown' => array('latitude' => 13.1333333, 'longitude' => -61.2166667), - 'Kinshasa' => array('latitude' => -4.3, 'longitude' => 15.3), - 'Kolkata' => array('latitude' => 22.5697222, 'longitude' => 88.3697222), - 'Kuala Lumpur' => array('latitude' => 3.1666667, 'longitude' => 101.7), - 'Kuwait City' => array('latitude' => 29.3697222, 'longitude' => 47.9783333), - 'Kiev' => array('latitude' => 50.4333333, 'longitude' => 30.5166667), - 'La Paz' => array('latitude' => -16.5, 'longitude' => -68.15), - 'Libreville' => array('latitude' => 0.3833333, 'longitude' => 9.45), - 'Lilongwe' => array('latitude' => -13.9833333, 'longitude' => 33.7833333), - 'Lima' => array('latitude' => -12.05, 'longitude' => -77.05), - 'Lisbon' => array('latitude' => 38.7166667, 'longitude' => -9.1333333), - 'Ljubljana' => array('latitude' => 46.0552778, 'longitude' => 14.5144444), - 'Lobamba' => array('latitude' => -26.4666667, 'longitude' => 31.2), - 'LomĆ©' => array('latitude' => 9.7166667, 'longitude' => 38.3), - 'London' => array('latitude' => 51.5, 'longitude' => -0.1166667), - 'Los Angeles' => array('latitude' => 34.05222, 'longitude' => -118.24278), - 'Luanda' => array('latitude' => -8.8383333, 'longitude' => 13.2344444), - 'Lusaka' => array('latitude' => -15.4166667, 'longitude' => 28.2833333), - 'Luxembourg' => array('latitude' => 49.6116667, 'longitude' => 6.13), - 'Madrid' => array('latitude' => 40.4, 'longitude' => -3.6833333), - 'Majuro' => array('latitude' => 7.1, 'longitude' => 171.3833333), - 'Malabo' => array('latitude' => 3.75, 'longitude' => 8.7833333), - 'Managua' => array('latitude' => 12.1508333, 'longitude' => -86.2683333), - 'Manama' => array('latitude' => 26.2361111, 'longitude' => 50.5830556), - 'Manila' => array('latitude' => 14.6041667, 'longitude' => 120.9822222), - 'Maputo' => array('latitude' => -25.9652778, 'longitude' => 32.5891667), - 'Maseru' => array('latitude' => -29.3166667, 'longitude' => 27.4833333), - 'Mbabane' => array('latitude' => -26.3166667, 'longitude' => 31.1333333), - 'Melbourne' => array('latitude' => -37.8166667, 'longitude' => 144.9666667), - 'Melekeok' => array('latitude' => 7.4933333, 'longitude' => 134.6341667), - 'Mexiko City' => array('latitude' => 19.4341667, 'longitude' => -99.1386111), - 'Minsk' => array('latitude' => 53.9, 'longitude' => 27.5666667), - 'Mogadishu' => array('latitude' => 2.0666667, 'longitude' => 45.3666667), - 'Monaco' => array('latitude' => 43.7333333, 'longitude' => 7.4166667), - 'Monrovia' => array('latitude' => 6.3105556, 'longitude' => -10.8047222), - 'Montevideo' => array('latitude' => -34.8580556, 'longitude' => -56.1708333), - 'Montreal' => array('latitude' => 45.5, 'longitude' => -73.5833333), - 'Moroni' => array('latitude' => -11.7041667, 'longitude' => 43.2402778), - 'Moscow' => array('latitude' => 55.7522222, 'longitude' => 37.6155556), - 'Muscat' => array('latitude' => 23.6133333, 'longitude' => 58.5933333), - 'Nairobi' => array('latitude' => -1.3166667, 'longitude' => 36.8333333), - 'Nassau' => array('latitude' => 25.0833333, 'longitude' => -77.35), - 'NĀ“Djamena' => array('latitude' => 12.1130556, 'longitude' => 15.0491667), - 'New Dehli' => array('latitude' => 28.6, 'longitude' => 77.2), - 'New York' => array('latitude' => 40.71417, 'longitude' => -74.00639), - 'Newcastle' => array('latitude' => -32.9166667, 'longitude' => 151.75), - 'Niamey' => array('latitude' => 13.6666667, 'longitude' => 1.7833333), - 'Nicosia' => array('latitude' => 35.1666667, 'longitude' => 33.3666667), - 'Nouakchott' => array('latitude' => 18.0863889, 'longitude' => -15.9752778), - 'Noumea' => array('latitude' => -22.2666667, 'longitude' => 166.45), - 'NukuĀ“alofa' => array('latitude' => -21.1333333, 'longitude' => -175.2), - 'Nuuk' => array('latitude' => 64.1833333, 'longitude' => -51.75), - 'Oranjestad' => array('latitude' => 12.5166667, 'longitude' => -70.0333333), - 'Oslo' => array('latitude' => 59.9166667, 'longitude' => 10.75), - 'Ouagadougou' => array('latitude' => 12.3702778, 'longitude' => -1.5247222), - 'Palikir' => array('latitude' => 6.9166667, 'longitude' => 158.15), - 'Panama City' => array('latitude' => 8.9666667, 'longitude' => -79.5333333), - 'Papeete' => array('latitude' => -17.5333333, 'longitude' => -149.5666667), - 'Paramaribo' => array('latitude' => 5.8333333, 'longitude' => -55.1666667), - 'Paris' => array('latitude' => 48.8666667, 'longitude' => 2.3333333), - 'Perth' => array('latitude' => -31.9333333, 'longitude' => 115.8333333), - 'Phnom Penh' => array('latitude' => 11.55, 'longitude' => 104.9166667), - 'Podgorica' => array('latitude' => 43.7752778, 'longitude' => 19.6827778), - 'Port Louis' => array('latitude' => -20.1666667, 'longitude' => 57.5), - 'Port Moresby' => array('latitude' => -9.4647222, 'longitude' => 147.1925), - 'Port-au-Prince' => array('latitude' => 18.5391667, 'longitude' => -72.335), - 'Port of Spain' => array('latitude' => 10.6666667, 'longitude' => -61.5), - 'Porto-Novo' => array('latitude' => 6.4833333, 'longitude' => 2.6166667), - 'Prague' => array('latitude' => 50.0833333, 'longitude' => 14.4666667), - 'Praia' => array('latitude' => 14.9166667, 'longitude' => -23.5166667), - 'Pretoria' => array('latitude' => -25.7069444, 'longitude' => 28.2294444), - 'Pyongyang' => array('latitude' => 39.0194444, 'longitude' => 125.7547222), - 'Quito' => array('latitude' => -0.2166667, 'longitude' => -78.5), - 'Rabat' => array('latitude' => 34.0252778, 'longitude' => -6.8361111), - 'Reykjavik' => array('latitude' => 64.15, 'longitude' => -21.95), - 'Riga' => array('latitude' => 56.95, 'longitude' => 24.1), - 'Rio de Janero' => array('latitude' => -22.9, 'longitude' => -43.2333333), - 'Road Town' => array('latitude' => 18.4166667, 'longitude' => -64.6166667), - 'Rome' => array('latitude' => 41.9, 'longitude' => 12.4833333), - 'Roseau' => array('latitude' => 15.3, 'longitude' => -61.4), - 'Rotterdam' => array('latitude' => 51.9166667, 'longitude' => 4.5), - 'Salvador' => array('latitude' => -12.9833333, 'longitude' => -38.5166667), - 'San JosĆ©' => array('latitude' => 9.9333333, 'longitude' => -84.0833333), - 'San Juan' => array('latitude' => 18.46833, 'longitude' => -66.10611), - 'San Marino' => array('latitude' => 43.5333333, 'longitude' => 12.9666667), - 'San Salvador' => array('latitude' => 13.7086111, 'longitude' => -89.2030556), - 'SanaĆ”' => array('latitude' => 15.3547222, 'longitude' => 44.2066667), - 'Santa Cruz' => array('latitude' => -17.8, 'longitude' => -63.1666667), - 'Santiago' => array('latitude' => -33.45, 'longitude' => -70.6666667), - 'Santo Domingo' => array('latitude' => 18.4666667, 'longitude' => -69.9), - 'Sao Paulo' => array('latitude' => -23.5333333, 'longitude' => -46.6166667), - 'Sarajevo' => array('latitude' => 43.85, 'longitude' => 18.3833333), - 'Seoul' => array('latitude' => 37.5663889, 'longitude' => 126.9997222), - 'Shanghai' => array('latitude' => 31.2222222, 'longitude' => 121.4580556), - 'Sydney' => array('latitude' => -33.8833333, 'longitude' => 151.2166667), - 'Singapore' => array('latitude' => 1.2930556, 'longitude' => 103.8558333), - 'Skopje' => array('latitude' => 42, 'longitude' => 21.4333333), - 'Sofia' => array('latitude' => 42.6833333, 'longitude' => 23.3166667), - 'St. GeorgeĀ“s' => array('latitude' => 12.05, 'longitude' => -61.75), - 'St. JohnĀ“s' => array('latitude' => 17.1166667, 'longitude' => -61.85), - 'Stanley' => array('latitude' => -51.7, 'longitude' => -57.85), - 'Stockholm' => array('latitude' => 59.3333333, 'longitude' => 18.05), - 'Suva' => array('latitude' => -18.1333333, 'longitude' => 178.4166667), - 'Taipei' => array('latitude' => 25.0166667, 'longitude' => 121.45), - 'Tallinn' => array('latitude' => 59.4338889, 'longitude' => 24.7280556), - 'Tashkent' => array('latitude' => 41.3166667, 'longitude' => 69.25), - 'Tbilisi' => array('latitude' => 41.725, 'longitude' => 44.7908333), - 'Tegucigalpa' => array('latitude' => 14.1, 'longitude' => -87.2166667), - 'Tehran' => array('latitude' => 35.6719444, 'longitude' => 51.4244444), - 'The Hague' => array('latitude' => 52.0833333, 'longitude' => 4.3), - 'Thimphu' => array('latitude' => 27.4833333, 'longitude' => 89.6), - 'Tirana' => array('latitude' => 41.3275, 'longitude' => 19.8188889), - 'Tiraspol' => array('latitude' => 46.8402778, 'longitude' => 29.6433333), - 'Tokyo' => array('latitude' => 35.685, 'longitude' => 139.7513889), - 'Toronto' => array('latitude' => 43.6666667, 'longitude' => -79.4166667), - 'TĆ³rshavn' => array('latitude' => 62.0166667, 'longitude' => -6.7666667), - 'Tripoli' => array('latitude' => 32.8925, 'longitude' => 13.18), - 'Tunis' => array('latitude' => 36.8027778, 'longitude' => 10.1797222), - 'Ulaanbaatar' => array('latitude' => 47.9166667, 'longitude' => 106.9166667), - 'Vaduz' => array('latitude' => 47.1333333, 'longitude' => 9.5166667), - 'Valletta' => array('latitude' => 35.8997222, 'longitude' => 14.5147222), - 'Valparaiso' => array('latitude' => -33.0477778, 'longitude' => -71.6011111), - 'Vancouver' => array('latitude' => 49.25, 'longitude' => -123.1333333), - 'Vatican City' => array('latitude' => 41.9, 'longitude' => 12.4833333), - 'Victoria' => array('latitude' => -4.6166667, 'longitude' => 55.45), - 'Vienna' => array('latitude' => 48.2, 'longitude' => 16.3666667), - 'Vientaine' => array('latitude' => 17.9666667, 'longitude' => 102.6), - 'Vilnius' => array('latitude' => 54.6833333, 'longitude' => 25.3166667), - 'Warsaw' => array('latitude' => 52.25, 'longitude' => 21), - 'Washington dc' => array('latitude' => 38.895, 'longitude' => -77.03667), - 'Wellington' => array('latitude' => -41.3, 'longitude' => 174.7833333), - 'Willemstad' => array('latitude' => 12.1, 'longitude' => -68.9166667), - 'Windhoek' => array('latitude' => -22.57, 'longitude' => 17.0836111), - 'Yamoussoukro' => array('latitude' => 6.8166667, 'longitude' => -5.2833333), - 'YaoundĆ©' => array('latitude' => 3.8666667, 'longitude' => 11.5166667), - 'Yerevan' => array('latitude' => 40.1811111, 'longitude' => 44.5136111), - 'ZĆ¼rich' => array('latitude' => 47.3666667, 'longitude' => 8.55), - 'Zagreb' => array('latitude' => 45.8, 'longitude' => 16) - ); - - /** - * Returns the location from the selected city - * - * @param string $city City to get location for - * @param string $horizon Horizon to use : - * default: effective - * others are civil, nautic, astronomic - * @return array - * @throws \Zend\Date\Exception When city is unknown - */ - public static function City($city, $horizon = false) - { - foreach (self::$cities as $key => $value) { - if (strtolower($key) === strtolower($city)) { - $return = $value; - $return['horizon'] = $horizon; - return $return; - } - } - throw new Exception\InvalidArgumentException('unknown city'); - } - - /** - * Return a list with all known cities - * - * @return array - */ - public static function getCityList() - { - return array_keys(self::$cities); - } -} - - -/** - - - - - */ diff --git a/library/Zend/Date/Date.php b/library/Zend/Date/Date.php deleted file mode 100644 index 58ddd8a839f..00000000000 --- a/library/Zend/Date/Date.php +++ /dev/null @@ -1,4870 +0,0 @@ - 'iso', // format for date strings 'iso' or 'php' - 'fix_dst' => true, // fix dst on summer/winter time change - 'extend_month' => false, // false - addMonth like SQL, true like excel - 'cache' => null, // cache to set - 'timesync' => null // timesync server to set - ); - - // Class wide Date Constants - const DAY = 'dd'; - const DAY_SHORT = 'd'; - const DAY_SUFFIX = 'SS'; - const DAY_OF_YEAR = 'D'; - const WEEKDAY = 'EEEE'; - const WEEKDAY_SHORT = 'EEE'; - const WEEKDAY_NARROW = 'E'; - const WEEKDAY_NAME = 'EE'; - const WEEKDAY_8601 = 'eee'; - const WEEKDAY_DIGIT = 'e'; - const WEEK = 'ww'; - const MONTH = 'MM'; - const MONTH_SHORT = 'M'; - const MONTH_DAYS = 'ddd'; - const MONTH_NAME = 'MMMM'; - const MONTH_NAME_SHORT = 'MMM'; - const MONTH_NAME_NARROW = 'MMMMM'; - const YEAR = 'y'; - const YEAR_SHORT = 'yy'; - const YEAR_8601 = 'Y'; - const YEAR_SHORT_8601 = 'YY'; - const LEAPYEAR = 'l'; - const MERIDIEM = 'a'; - const SWATCH = 'B'; - const HOUR = 'HH'; - const HOUR_SHORT = 'H'; - const HOUR_AM = 'hh'; - const HOUR_SHORT_AM = 'h'; - const MINUTE = 'mm'; - const MINUTE_SHORT = 'm'; - const SECOND = 'ss'; - const SECOND_SHORT = 's'; - const MILLISECOND = 'S'; - const TIMEZONE_NAME = 'zzzz'; - const DAYLIGHT = 'I'; - const GMT_DIFF = 'Z'; - const GMT_DIFF_SEP = 'ZZZZ'; - const TIMEZONE = 'z'; - const TIMEZONE_SECS = 'X'; - const ISO_8601 = 'c'; - const RFC_2822 = 'r'; - const TIMESTAMP = 'U'; - const ERA = 'G'; - const ERA_NAME = 'GGGG'; - const ERA_NARROW = 'GGGGG'; - const DATES = 'F'; - const DATE_FULL = 'FFFFF'; - const DATE_LONG = 'FFFF'; - const DATE_MEDIUM = 'FFF'; - const DATE_SHORT = 'FF'; - const TIMES = 'WW'; - const TIME_FULL = 'TTTTT'; - const TIME_LONG = 'TTTT'; - const TIME_MEDIUM = 'TTT'; - const TIME_SHORT = 'TT'; - const DATETIME = 'K'; - const DATETIME_FULL = 'KKKKK'; - const DATETIME_LONG = 'KKKK'; - const DATETIME_MEDIUM = 'KKK'; - const DATETIME_SHORT = 'KK'; - const ATOM = 'OOO'; - const COOKIE = 'CCC'; - const RFC_822 = 'R'; - const RFC_850 = 'RR'; - const RFC_1036 = 'RRR'; - const RFC_1123 = 'RRRR'; - const RFC_3339 = 'RRRRR'; - const RSS = 'SSS'; - const W3C = 'WWW'; - - /** - * Generates the standard date object, could be a unix timestamp, localized date, - * string, integer, array and so on. Also parts of dates or time are supported - * Always set the default timezone: http://php.net/date_default_timezone_set - * For example, in your bootstrap: date_default_timezone_set('America/Los_Angeles'); - * For detailed instructions please look in the docu. - * - * @param string|integer|\Zend\Date\Date|array $date OPTIONAL Date value or value of date part to set - * ,depending on $part. If null the actual time is set - * @param string $part OPTIONAL Defines the input format of $date - * @param string|\Zend\Locale\Locale $locale OPTIONAL Locale for parsing input - * @return \Zend\Date\Date - * @throws \Zend\Date\Exception - */ - public function __construct($date = null, $part = null, $locale = null) - { - if (is_object($date) and !($date instanceof TimeSync\AbstractProtocol) and - !($date instanceof Date)) { - if ($locale instanceof Locale) { - $locale = $date; - $date = null; - $part = null; - } else { - $date = (string) $date; - } - } - - if (($date !== null) and !is_array($date) and !($date instanceof TimeSync\AbstractProtocol) and - !($date instanceof Date) and !defined($date) and Locale::isLocale($date, true)) { - $locale = $date; - $date = null; - $part = null; - } else if (($part !== null) and !defined($part) and Locale::isLocale($part, true)) { - $locale = $part; - $part = null; - } - - $this->setLocale($locale); - if (is_string($date) && ($part === null) && (strlen($date) <= 5)) { - $part = $date; - $date = null; - } - - if ($date === null) { - if ($part === null) { - $date = time(); - } else if ($part !== self::TIMESTAMP) { - $date = self::now($locale); - $date = $date->get($part); - } - } - - if ($date instanceof TimeSync\AbstractProtocol) { - $date = $date->getInfo(); - $date = $this->_getTime($date['offset']); - $part = null; - } else if (parent::$_defaultOffset != 0) { - $date = $this->_getTime(parent::$_defaultOffset); - } - - // set the timezone and offset for $this - $zone = @date_default_timezone_get(); - $this->setTimezone($zone); - - // try to get timezone from date-string - if (!is_int($date)) { - $zone = $this->getTimezoneFromString($date); - $this->setTimezone($zone); - } - - // set datepart - if (($part !== null && $part !== self::TIMESTAMP) or (!is_numeric($date))) { - // switch off dst handling for value setting - $this->setUnixTimestamp($this->getGmtOffset()); - $this->set($date, $part, $this->_locale); - - // DST fix - if (is_array($date) === true) { - if (!isset($date['hour'])) { - $date['hour'] = 0; - } - - $hour = $this->toString('H', 'iso', true); - $hour = $date['hour'] - $hour; - switch ($hour) { - case 1 : - case -23 : - $this->addTimestamp(3600); - break; - case -1 : - case 23 : - $this->subTimestamp(3600); - break; - case 2 : - case -22 : - $this->addTimestamp(7200); - break; - case -2 : - case 22 : - $this->subTimestamp(7200); - break; - } - } - } else { - $this->setUnixTimestamp($date); - } - } - - /** - * Sets class wide options, if no option was given, the actual set options will be returned - * - * @param array $options Options to set - * @throws \Zend\Date\Exception - * @return Options array if no option was given - */ - public static function setOptions(array $options = array()) - { - if (empty($options)) { - return self::$_options; - } - - foreach ($options as $name => $value) { - $name = strtolower($name); - - if (array_key_exists($name, self::$_options)) { - switch($name) { - case 'format_type' : - if ((strtolower($value) != 'php') && (strtolower($value) != 'iso')) { - throw new Exception\InvalidArgumentException("Unknown format type ($value) for dates, only 'iso' and 'php' supported"); /*, 0, null, $value */ - } - break; - case 'fix_dst' : - if (!is_bool($value)) { - throw new Exception\InvalidArgumentException("'fix_dst' has to be boolean"); /* , 0, null, $value */ - } - break; - case 'extend_month' : - if (!is_bool($value)) { - throw new Exception\InvalidArgumentException("'extend_month' has to be boolean"); /* ); */ - } - break; - case 'cache' : - if ($value === null) { - parent::$_cache = null; - } else { - if (!$value instanceof CacheStorage) { - throw new Exception\InvalidArgumentException("Instance of Zend\Cache\Storage\StorageInterface expected"); - } - - parent::$_cache = $value; - Cldr::setCache($value); - } - break; - case 'timesync' : - if ($value === null) { - parent::$_defaultOffset = 0; - } else { - if (!$value instanceof TimeSync\AbstractProtocol) { - throw new Exception\InvalidArgumentException("Instance of Zend_TimeSync expected for option timesync"); - } - - $date = $value->getInfo(); - parent::$_defaultOffset = $date['offset']; - } - break; - } - self::$_options[$name] = $value; - } - else { - throw new Exception\InvalidArgumentException("Unknown option: $name = $value"); - } - } - } - - /** - * Returns this object's internal UNIX timestamp (equivalent to Zend_Date::TIMESTAMP). - * If the timestamp is too large for integers, then the return value will be a string. - * This function does not return the timestamp as an object. - * Use clone() or copyPart() instead. - * - * @return integer|string UNIX timestamp - */ - public function getTimestamp() - { - return $this->getUnixTimestamp(); - } - - /** - * Returns the calculated timestamp - * HINT: timestamps are always GMT - * - * @param string $calc Type of calculation to make - * @param string|integer|array|\Zend\Date\Date $stamp Timestamp to calculate, when null the actual timestamp is calculated - * @return \Zend\Date\Date|integer - * @throws \Zend\Date\Exception - */ - private function _timestamp($calc, $stamp) - { - if ($stamp instanceof Date) { - // extract timestamp from object - $stamp = $stamp->getTimestamp(); - } - - if (is_array($stamp)) { - if (isset($stamp['timestamp']) === true) { - $stamp = $stamp['timestamp']; - } else { - throw new Exception\RuntimeException('no timestamp given in array'); - } - } - - if ($calc === 'set') { - $return = $this->setUnixTimestamp($stamp); - } else { - $return = $this->_calcdetail($calc, $stamp, self::TIMESTAMP, null); - } - if ($calc != 'cmp') { - return $this; - } - return $return; - } - - /** - * Sets a new timestamp - * - * @param integer|string|array|\Zend\Date\Date $timestamp Timestamp to set - * @return \Zend\Date\Date Provides fluid interface - * @throws \Zend\Date\Exception - */ - public function setTimestamp($timestamp) - { - return $this->_timestamp('set', $timestamp); - } - - /** - * Adds a timestamp - * - * @param integer|string|array|\Zend\Date\Date $timestamp Timestamp to add - * @return \Zend\Date\Date Provides fluid interface - * @throws \Zend\Date\Exception - */ - public function addTimestamp($timestamp) - { - return $this->_timestamp('add', $timestamp); - } - - /** - * Subtracts a timestamp - * - * @param integer|string|array|\Zend\Date\Date $timestamp Timestamp to sub - * @return \Zend\Date\Date Provides fluid interface - * @throws \Zend\Date\Exception - */ - public function subTimestamp($timestamp) - { - return $this->_timestamp('sub', $timestamp); - } - - /** - * Compares two timestamps, returning the difference as integer - * - * @param integer|string|array|\Zend\Date\Date $timestamp Timestamp to compare - * @return integer 0 = equal, 1 = later, -1 = earlier - * @throws \Zend\Date\Exception - */ - public function compareTimestamp($timestamp) - { - return $this->_timestamp('cmp', $timestamp); - } - - /** - * Returns a string representation of the object - * Supported format tokens are: - * G - era, y - year, Y - ISO year, M - month, w - week of year, D - day of year, d - day of month - * E - day of week, e - number of weekday (1-7), h - hour 1-12, H - hour 0-23, m - minute, s - second - * A - milliseconds of day, z - timezone, Z - timezone offset, S - fractional second, a - period of day - * - * Additionally format tokens but non ISO conform are: - * SS - day suffix, eee - php number of weekday(0-6), ddd - number of days per month - * l - Leap year, B - swatch internet time, I - daylight saving time, X - timezone offset in seconds - * r - RFC2822 format, U - unix timestamp - * - * Not supported ISO tokens are - * u - extended year, Q - quarter, q - quarter, L - stand alone month, W - week of month - * F - day of week of month, g - modified julian, c - stand alone weekday, k - hour 0-11, K - hour 1-24 - * v - wall zone - * - * @param string $format OPTIONAL Rule for formatting output. If null the default date format is used - * @param string $type OPTIONAL Type for the format string which overrides the standard setting - * @param string|\Zend\Locale\Locale $locale OPTIONAL Locale for parsing input - * @return string - */ - public function toString($format = null, $type = null, $locale = null) - { - if (is_object($format)) { - if ($format instanceof Locale) { - $locale = $format; - $format = null; - } else { - $format = (string) $format; - } - } - - if (is_object($type)) { - if ($type instanceof Locale) { - $locale = $type; - $type = null; - } else { - $type = (string) $type; - } - } - - if (($format !== null) && !defined($format) - && ($format != 'ee') && ($format != 'ss') && ($format != 'GG') && ($format != 'MM') && ($format != 'EE') && ($format != 'TT') - && Locale::isLocale($format) - ) { - $locale = $format; - $format = null; - } - - if (($type !== null) and ($type != 'php') and ($type != 'iso') and - Locale::isLocale($type)) { - $locale = $type; - $type = null; - } - - if ($locale === null) { - $locale = $this->getLocale(); - } - - if ($format === null) { - $format = Format::getDateFormat($locale) . ' ' . Format::getTimeFormat($locale); - } else if (((self::$_options['format_type'] == 'php') && ($type === null)) or ($type == 'php')) { - $format = Format::convertPhpToIsoFormat($format); - } - - return $this->date($this->_toToken($format, $locale), $this->getUnixTimestamp(), false); - } - - /** - * Returns a string representation of the date which is equal with the timestamp - * - * @return string - */ - public function __toString() - { - return $this->toString(null, $this->_locale); - } - - /** - * Returns a integer representation of the object - * But returns false when the given part is no value f.e. Month-Name - * - * @param string|integer|\Zend\Date\Date $part OPTIONAL Defines the date or datepart to return as integer - * @return integer|false - */ - public function toValue($part = null) - { - $result = $this->get($part); - if (is_numeric($result)) { - return intval("$result"); - } else { - return false; - } - } - - /** - * Returns an array representation of the object - * - * @return array - */ - public function toArray() - { - return array('day' => $this->toString(self::DAY_SHORT, 'iso'), - 'month' => $this->toString(self::MONTH_SHORT, 'iso'), - 'year' => $this->toString(self::YEAR, 'iso'), - 'hour' => $this->toString(self::HOUR_SHORT, 'iso'), - 'minute' => $this->toString(self::MINUTE_SHORT, 'iso'), - 'second' => $this->toString(self::SECOND_SHORT, 'iso'), - 'timezone' => $this->toString(self::TIMEZONE, 'iso'), - 'timestamp' => $this->toString(self::TIMESTAMP, 'iso'), - 'weekday' => $this->toString(self::WEEKDAY_8601, 'iso'), - 'dayofyear' => $this->toString(self::DAY_OF_YEAR, 'iso'), - 'week' => $this->toString(self::WEEK, 'iso'), - 'gmtsecs' => $this->toString(self::TIMEZONE_SECS, 'iso')); - } - - /** - * Returns a representation of a date or datepart - * This could be for example a localized monthname, the time without date, - * the era or only the fractional seconds. There are about 50 different supported date parts. - * For a complete list of supported datepart values look into the docu - * - * @param string $part OPTIONAL Part of the date to return, if null the timestamp is returned - * @param string|\Zend\Locale\Locale $locale OPTIONAL Locale for parsing input - * @return string date or datepart - */ - public function get($part = null, $locale = null) - { - if ($locale === null) { - $locale = $this->getLocale(); - } - - if (($part !== null) && !defined($part) - && ($part != 'ee') && ($part != 'ss') && ($part != 'GG') && ($part != 'MM') && ($part != 'EE') && ($part != 'TT') - && Locale::isLocale($part) - ) { - $locale = $part; - $part = null; - } - - if ($part === null) { - $part = self::TIMESTAMP; - } else if (self::$_options['format_type'] == 'php') { - $part = Format::convertPhpToIsoFormat($part); - } - - return $this->date($this->_toToken($part, $locale), $this->getUnixTimestamp(), false); - } - - /** - * Internal method to apply tokens - * - * @param string $part - * @param string $locale - * @return string - */ - private function _toToken($part, $locale) { - // get format tokens - $comment = false; - $format = ''; - $orig = ''; - for ($i = 0; isset($part[$i]); ++$i) { - if ($part[$i] == "'") { - $comment = $comment ? false : true; - if (isset($part[$i+1]) && ($part[$i+1] == "'")) { - $comment = $comment ? false : true; - $format .= "\\'"; - ++$i; - } - - $orig = ''; - continue; - } - - if ($comment) { - $format .= '\\' . $part[$i]; - $orig = ''; - } else { - $orig .= $part[$i]; - if (!isset($part[$i+1]) || (isset($orig[0]) && ($orig[0] != $part[$i+1]))) { - $format .= $this->_parseIsoToDate($orig, $locale); - $orig = ''; - } - } - } - - return $format; - } - - /** - * Internal parsing method - * - * @param string $token - * @param string $locale - * @return string - */ - private function _parseIsoToDate($token, $locale) { - switch($token) { - case self::DAY : - return 'd'; - break; - - case self::WEEKDAY_SHORT : - $weekday = strtolower($this->date('D', $this->getUnixTimestamp(), false)); - $day = Cldr::getContent($locale, 'day', array('gregorian', 'format', 'wide', $weekday)); - return $this->_toComment(iconv_substr($day, 0, 3, 'UTF-8')); - break; - - case self::DAY_SHORT : - return 'j'; - break; - - case self::WEEKDAY : - $weekday = strtolower($this->date('D', $this->getUnixTimestamp(), false)); - return $this->_toComment(Cldr::getContent($locale, 'day', array('gregorian', 'format', 'wide', $weekday))); - break; - - case self::WEEKDAY_8601 : - return 'N'; - break; - - case 'ee' : - return $this->_toComment(str_pad($this->date('N', $this->getUnixTimestamp(), false), 2, '0', STR_PAD_LEFT)); - break; - - case self::DAY_SUFFIX : - return 'S'; - break; - - case self::WEEKDAY_DIGIT : - return 'w'; - break; - - case self::DAY_OF_YEAR : - return 'z'; - break; - - case 'DDD' : - return $this->_toComment(str_pad($this->date('z', $this->getUnixTimestamp(), false), 3, '0', STR_PAD_LEFT)); - break; - - case 'DD' : - return $this->_toComment(str_pad($this->date('z', $this->getUnixTimestamp(), false), 2, '0', STR_PAD_LEFT)); - break; - - case self::WEEKDAY_NARROW : - case 'EEEEE' : - $weekday = strtolower($this->date('D', $this->getUnixTimestamp(), false)); - $day = Cldr::getContent($locale, 'day', array('gregorian', 'format', 'abbreviated', $weekday)); - return $this->_toComment(iconv_substr($day, 0, 1, 'UTF-8')); - break; - - case self::WEEKDAY_NAME : - $weekday = strtolower($this->date('D', $this->getUnixTimestamp(), false)); - return $this->_toComment(Cldr::getContent($locale, 'day', array('gregorian', 'format', 'abbreviated', $weekday))); - break; - - case 'w' : - $week = $this->date('W', $this->getUnixTimestamp(), false); - return $this->_toComment(($week[0] == '0') ? $week[1] : $week); - break; - - case self::WEEK : - return 'W'; - break; - - case self::MONTH_NAME : - $month = $this->date('n', $this->getUnixTimestamp(), false); - return $this->_toComment(Cldr::getContent($locale, 'month', array('gregorian', 'format', 'wide', $month))); - break; - - case self::MONTH : - return 'm'; - break; - - case self::MONTH_NAME_SHORT : - $month = $this->date('n', $this->getUnixTimestamp(), false); - return $this->_toComment(Cldr::getContent($locale, 'month', array('gregorian', 'format', 'abbreviated', $month))); - break; - - case self::MONTH_SHORT : - return 'n'; - break; - - case self::MONTH_DAYS : - return 't'; - break; - - case self::MONTH_NAME_NARROW : - $month = $this->date('n', $this->getUnixTimestamp(), false); - $mon = Cldr::getContent($locale, 'month', array('gregorian', 'format', 'abbreviated', $month)); - return $this->_toComment(iconv_substr($mon, 0, 1, 'UTF-8')); - break; - - case self::LEAPYEAR : - return 'L'; - break; - - case self::YEAR_8601 : - return 'o'; - break; - - case self::YEAR : - return 'Y'; - break; - - case self::YEAR_SHORT : - return 'y'; - break; - - case self::YEAR_SHORT_8601 : - return $this->_toComment(substr($this->date('o', $this->getUnixTimestamp(), false), -2, 2)); - break; - - case self::MERIDIEM : - $am = $this->date('a', $this->getUnixTimestamp(), false); - if ($am == 'am') { - return $this->_toComment(Cldr::getContent($locale, 'am')); - } - - return $this->_toComment(Cldr::getContent($locale, 'pm')); - break; - - case self::SWATCH : - return 'B'; - break; - - case self::HOUR_SHORT_AM : - return 'g'; - break; - - case self::HOUR_SHORT : - return 'G'; - break; - - case self::HOUR_AM : - return 'h'; - break; - - case self::HOUR : - return 'H'; - break; - - case self::MINUTE : - return $this->_toComment(str_pad($this->date('i', $this->getUnixTimestamp(), false), 2, '0', STR_PAD_LEFT)); - break; - - case self::SECOND : - return $this->_toComment(str_pad($this->date('s', $this->getUnixTimestamp(), false), 2, '0', STR_PAD_LEFT)); - break; - - case self::MINUTE_SHORT : - return 'i'; - break; - - case self::SECOND_SHORT : - return 's'; - break; - - case self::MILLISECOND : - return $this->_toComment($this->getMilliSecond()); - break; - - case self::TIMEZONE_NAME : - case 'vvvv' : - return 'e'; - break; - - case self::DAYLIGHT : - return 'I'; - break; - - case self::GMT_DIFF : - case 'ZZ' : - case 'ZZZ' : - return 'O'; - break; - - case self::GMT_DIFF_SEP : - return 'P'; - break; - - case self::TIMEZONE : - case 'v' : - case 'zz' : - case 'zzz' : - return 'T'; - break; - - case self::TIMEZONE_SECS : - return 'Z'; - break; - - case self::ISO_8601 : - return 'c'; - break; - - case self::RFC_2822 : - return 'r'; - break; - - case self::TIMESTAMP : - return 'U'; - break; - - case self::ERA : - case 'GG' : - case 'GGG' : - $year = $this->date('Y', $this->getUnixTimestamp(), false); - if ($year < 0) { - return $this->_toComment(Cldr::getContent($locale, 'era', array('gregorian', 'Abbr', '0'))); - } - - return $this->_toComment(Cldr::getContent($locale, 'era', array('gregorian', 'Abbr', '1'))); - break; - - case self::ERA_NARROW : - $year = $this->date('Y', $this->getUnixTimestamp(), false); - if ($year < 0) { - return $this->_toComment(iconv_substr(Cldr::getContent($locale, 'era', array('gregorian', 'Abbr', '0')), 0, 1, 'UTF-8')) . '.'; - } - - return $this->_toComment(iconv_substr(Cldr::getContent($locale, 'era', array('gregorian', 'Abbr', '1')), 0, 1, 'UTF-8')) . '.'; - break; - - case self::ERA_NAME : - $year = $this->date('Y', $this->getUnixTimestamp(), false); - if ($year < 0) { - return $this->_toComment(Cldr::getContent($locale, 'era', array('gregorian', 'Names', '0'))); - } - - return $this->_toComment(Cldr::getContent($locale, 'era', array('gregorian', 'Names', '1'))); - break; - - case self::DATES : - return $this->_toToken(Format::getDateFormat($locale), $locale); - break; - - case self::DATE_FULL : - return $this->_toToken(Cldr::getContent($locale, 'date', array('gregorian', 'full')), $locale); - break; - - case self::DATE_LONG : - return $this->_toToken(Cldr::getContent($locale, 'date', array('gregorian', 'long')), $locale); - break; - - case self::DATE_MEDIUM : - return $this->_toToken(Cldr::getContent($locale, 'date', array('gregorian', 'medium')), $locale); - break; - - case self::DATE_SHORT : - return $this->_toToken(Cldr::getContent($locale, 'date', array('gregorian', 'short')), $locale); - break; - - case self::TIMES : - return $this->_toToken(Format::getTimeFormat($locale), $locale); - break; - - case self::TIME_FULL : - return $this->_toToken(Cldr::getContent($locale, 'time', 'full'), $locale); - break; - - case self::TIME_LONG : - return $this->_toToken(Cldr::getContent($locale, 'time', 'long'), $locale); - break; - - case self::TIME_MEDIUM : - return $this->_toToken(Cldr::getContent($locale, 'time', 'medium'), $locale); - break; - - case self::TIME_SHORT : - return $this->_toToken(Cldr::getContent($locale, 'time', 'short'), $locale); - break; - - case self::DATETIME : - return $this->_toToken(Format::getDateTimeFormat($locale), $locale); - break; - - case self::DATETIME_FULL : - return $this->_toToken(Cldr::getContent($locale, 'datetime', array('gregorian', 'full')), $locale); - break; - - case self::DATETIME_LONG : - return $this->_toToken(Cldr::getContent($locale, 'datetime', array('gregorian', 'long')), $locale); - break; - - case self::DATETIME_MEDIUM : - return $this->_toToken(Cldr::getContent($locale, 'datetime', array('gregorian', 'medium')), $locale); - break; - - case self::DATETIME_SHORT : - return $this->_toToken(Cldr::getContent($locale, 'datetime', array('gregorian', 'short')), $locale); - break; - - case self::ATOM : - return 'Y\-m\-d\TH\:i\:sP'; - break; - - case self::COOKIE : - return 'l\, d\-M\-y H\:i\:s e'; - break; - - case self::RFC_822 : - return 'D\, d M y H\:i\:s O'; - break; - - case self::RFC_850 : - return 'l\, d\-M\-y H\:i\:s e'; - break; - - case self::RFC_1036 : - return 'D\, d M y H\:i\:s O'; - break; - - case self::RFC_1123 : - return 'D\, d M Y H\:i\:s O'; - break; - - case self::RFC_3339 : - return 'Y\-m\-d\TH\:i\:sP'; - break; - - case self::RSS : - return 'D\, d M Y H\:i\:s O'; - break; - - case self::W3C : - return 'Y\-m\-d\TH\:i\:sP'; - break; - } - - if ($token == '') { - return ''; - } - - switch ($token[0]) { - case 'y' : - if ((strlen($token) == 4) && (abs($this->getUnixTimestamp()) <= 0x7FFFFFFF)) { - return 'Y'; - } - - $length = iconv_strlen($token, 'UTF-8'); - return $this->_toComment(str_pad($this->date('Y', $this->getUnixTimestamp(), false), $length, '0', STR_PAD_LEFT)); - break; - - case 'Y' : - if ((strlen($token) == 4) && (abs($this->getUnixTimestamp()) <= 0x7FFFFFFF)) { - return 'o'; - } - - $length = iconv_strlen($token, 'UTF-8'); - return $this->_toComment(str_pad($this->date('o', $this->getUnixTimestamp(), false), $length, '0', STR_PAD_LEFT)); - break; - - case 'A' : - $length = iconv_strlen($token, 'UTF-8'); - $result = substr($this->getMilliSecond(), 0, 3); - $result += $this->date('s', $this->getUnixTimestamp(), false) * 1000; - $result += $this->date('i', $this->getUnixTimestamp(), false) * 60000; - $result += $this->date('H', $this->getUnixTimestamp(), false) * 3600000; - - return $this->_toComment(str_pad($result, $length, '0', STR_PAD_LEFT)); - break; - } - - return $this->_toComment($token); - } - - /** - * Private function to make a comment of a token - * - * @param string $token - * @return string - */ - private function _toComment($token) - { - $token = str_split($token); - $result = ''; - foreach ($token as $tok) { - $result .= '\\' . $tok; - } - - return $result; - } - - /** - * Return digit from standard names (english) - * Faster implementation than locale aware searching - * - * @param string $name - * @return integer Number of this month - * @throws \Zend\Date\Exception - */ - private function _getDigitFromName($name) - { - switch($name) { - case "Jan": - return 1; - - case "Feb": - return 2; - - case "Mar": - return 3; - - case "Apr": - return 4; - - case "May": - return 5; - - case "Jun": - return 6; - - case "Jul": - return 7; - - case "Aug": - return 8; - - case "Sep": - return 9; - - case "Oct": - return 10; - - case "Nov": - return 11; - - case "Dec": - return 12; - - default: - throw new Exception\InvalidArgumentException('Month ($name) is not a known month'); - } - } - - /** - * Counts the exact year number - * < 70 - 2000 added, >70 < 100 - 1900, others just returned - * - * @param integer $value year number - * @return integer Number of year - */ - public static function getFullYear($value) - { - if ($value >= 0) { - if ($value < 70) { - $value += 2000; - } else if ($value < 100) { - $value += 1900; - } - } - return $value; - } - - /** - * Sets the given date as new date or a given datepart as new datepart returning the new datepart - * This could be for example a localized dayname, the date without time, - * the month or only the seconds. There are about 50 different supported date parts. - * For a complete list of supported datepart values look into the docu - * - * @param string|integer|array|\Zend\Date\Date $date Date or datepart to set - * @param string $part OPTIONAL Part of the date to set, if null the timestamp is set - * @param string|\Zend\Locale\Locale $locale OPTIONAL Locale for parsing input - * @return \Zend\Date\Date Provides fluid interface - * @throws \Zend\Date\Exception - */ - public function set($date, $part = null, $locale = null) - { - if (self::$_options['format_type'] == 'php') { - $part = Format::convertPhpToIsoFormat($part); - } - - $zone = $this->getTimezoneFromString($date); - $this->setTimezone($zone); - - $this->_calculate('set', $date, $part, $locale); - return $this; - } - - /** - * Adds a date or datepart to the existing date, by extracting $part from $date, - * and modifying this object by adding that part. The $part is then extracted from - * this object and returned as an integer or numeric string (for large values, or $part's - * corresponding to pre-defined formatted date strings). - * This could be for example a ISO 8601 date, the hour the monthname or only the minute. - * There are about 50 different supported date parts. - * For a complete list of supported datepart values look into the docu. - * - * @param string|integer|array|\Zend\Date\Date $date Date or datepart to add - * @param string $part OPTIONAL Part of the date to add, if null the timestamp is added - * @param string|\Zend\Locale\Locale $locale OPTIONAL Locale for parsing input - * @return \Zend\Date\Date Provides fluid interface - * @throws \Zend\Date\Exception - */ - public function add($date, $part = self::TIMESTAMP, $locale = null) - { - if (self::$_options['format_type'] == 'php') { - $part = Format::convertPhpToIsoFormat($part); - } - - $this->_calculate('add', $date, $part, $locale); - return $this; - } - - /** - * Subtracts a date from another date. - * This could be for example a RFC2822 date, the time, - * the year or only the timestamp. There are about 50 different supported date parts. - * For a complete list of supported datepart values look into the docu - * Be aware: Adding -2 Months is not equal to Subtracting 2 Months !!! - * - * @param string|integer|array|\Zend\Date\Date $date Date or datepart to subtract - * @param string $part OPTIONAL Part of the date to sub, if null the timestamp is subtracted - * @param string|\Zend\Locale\Locale $locale OPTIONAL Locale for parsing input - * @return \Zend\Date\Date Provides fluid interface - * @throws \Zend\Date\Exception - */ - public function sub($date, $part = self::TIMESTAMP, $locale = null) - { - if (self::$_options['format_type'] == 'php') { - $part = Format::convertPhpToIsoFormat($part); - } - - $this->_calculate('sub', $date, $part, $locale); - return $this; - } - - /** - * Compares a date or datepart with the existing one. - * Returns -1 if earlier, 0 if equal and 1 if later. - * - * @param string|integer|array|\Zend\Date\Date $date Date or datepart to compare with the date object - * @param string $part OPTIONAL Part of the date to compare, if null the timestamp is subtracted - * @param string|\Zend\Locale\Locale $locale OPTIONAL Locale for parsing input - * @return integer 0 = equal, 1 = later, -1 = earlier - * @throws \Zend\Date\Exception - */ - public function compare($date, $part = self::TIMESTAMP, $locale = null) - { - if (self::$_options['format_type'] == 'php') { - $part = Format::convertPhpToIsoFormat($part); - } - - $compare = $this->_calculate('cmp', $date, $part, $locale); - - if ($compare > 0) { - return 1; - } else if ($compare < 0) { - return -1; - } - return 0; - } - - /** - * Returns a new instance of Zend_Date with the selected part copied. - * To make an exact copy, use PHP's clone keyword. - * For a complete list of supported date part values look into the docu. - * If a date part is copied, all other date parts are set to standard values. - * For example: If only YEAR is copied, the returned date object is equal to - * 01-01-YEAR 00:00:00 (01-01-1970 00:00:00 is equal to timestamp 0) - * If only HOUR is copied, the returned date object is equal to - * 01-01-1970 HOUR:00:00 (so $this contains a timestamp equal to a timestamp of 0 plus HOUR). - * - * @param string $part Part of the date to compare, if null the timestamp is subtracted - * @param string|\Zend\Locale\Locale $locale OPTIONAL New object's locale. No adjustments to timezone are made. - * @return \Zend\Date\Date New clone with requested part - */ - public function copyPart($part, $locale = null) - { - $clone = clone $this; // copy all instance variables - $clone->setUnixTimestamp(0); // except the timestamp - if ($locale != null) { - $clone->setLocale($locale); // set an other locale if selected - } - $clone->set($this, $part); - return $clone; - } - - /** - * Internal function, returns the offset of a given timezone - * - * @param string $zone - * @return integer - */ - public function getTimezoneFromString($zone) - { - if (is_array($zone)) { - return $this->getTimezone(); - } - - if ($zone instanceof Date) { - return $zone->getTimezone(); - } - - $match = array(); - preg_match('/\dZ$/', $zone, $match); - if (!empty($match)) { - return "Etc/UTC"; - } - - preg_match('/([+-]\d{2}):{0,1}\d{2}/', $zone, $match); - if (!empty($match) and ($match[count($match) - 1] <= 12) and ($match[count($match) - 1] >= -12)) { - $zone = "Etc/GMT"; - $zone .= ($match[count($match) - 1] < 0) ? "+" : "-"; - $zone .= (int) abs($match[count($match) - 1]); - return $zone; - } - - preg_match('/([[:alpha:]\/]{3,30})(?!.*([[:alpha:]\/]{3,30}))/', $zone, $match); - try { - if (!empty($match) and (!is_int($match[count($match) - 1]))) { - $oldzone = $this->getTimezone(); - $this->setTimezone($match[count($match) - 1]); - $result = $this->getTimezone(); - $this->setTimezone($oldzone); - if ($result !== $oldzone) { - return $match[count($match) - 1]; - } - } - } catch (\Exception $e) { - // fall through - } - - return $this->getTimezone(); - } - - /** - * Calculates the date or object - * - * @param string $calc Calculation to make - * @param string|integer $date Date for calculation - * @param string|integer $comp Second date for calculation - * @param boolean|integer $dst Use dst correction if option is set - * @return integer|string|\Zend\Date\Date new timestamp or \Zend\Date\Date depending on calculation - */ - private function _assign($calc, $date, $comp = 0, $dst = false) - { - switch ($calc) { - case 'set' : - if (!empty($comp)) { - $this->setUnixTimestamp(call_user_func(Math::$sub, $this->getUnixTimestamp(), $comp)); - } - $this->setUnixTimestamp(call_user_func(Math::$add, $this->getUnixTimestamp(), $date)); - $value = $this->getUnixTimestamp(); - break; - case 'add' : - $this->setUnixTimestamp(call_user_func(Math::$add, $this->getUnixTimestamp(), $date)); - $value = $this->getUnixTimestamp(); - break; - case 'sub' : - $this->setUnixTimestamp(call_user_func(Math::$sub, $this->getUnixTimestamp(), $date)); - $value = $this->getUnixTimestamp(); - break; - default : - // cmp - compare - return call_user_func(Math::$comp, $comp, $date); - break; - } - - // dst-correction if 'fix_dst' = true and dst !== false but only for non UTC and non GMT - if ((self::$_options['fix_dst'] === true) and ($dst !== false) and ($this->_dst === true)) { - $hour = $this->toString(self::HOUR, 'iso'); - if ($hour != $dst) { - if (($dst == ($hour + 1)) or ($dst == ($hour - 23))) { - $value += 3600; - } else if (($dst == ($hour - 1)) or ($dst == ($hour + 23))) { - $value -= 3600; - } - $this->setUnixTimestamp($value); - } - } - return $this->getUnixTimestamp(); - } - - - /** - * Calculates the date or object - * - * @param string $calc Calculation to make, one of: 'add'|'sub'|'cmp'|'copy'|'set' - * @param string|integer|array|\Zend\Date\Date $date Date or datepart to calculate with - * @param string $part Part of the date to calculate, if null the timestamp is used - * @param string|\Zend\Locale\Locale $locale Locale for parsing input - * @return integer|string|\Zend\Date\Date new timestamp - * @throws \Zend\Date\Exception - */ - private function _calculate($calc, $date, $part, $locale) - { - if ($date === null) { - throw new Exception\RuntimeException('parameter $date must be set, null is not allowed'); - } - - if (($part !== null) && (strlen($part) !== 2) && (Locale::isLocale($part))) { - $locale = $part; - $part = null; - } - - if ($locale === null) { - $locale = $this->getLocale(); - } - - $locale = (string) $locale; - - // Create date parts - $year = $this->toString(self::YEAR, 'iso'); - $month = $this->toString(self::MONTH_SHORT, 'iso'); - $day = $this->toString(self::DAY_SHORT, 'iso'); - $hour = $this->toString(self::HOUR_SHORT, 'iso'); - $minute = $this->toString(self::MINUTE_SHORT, 'iso'); - $second = $this->toString(self::SECOND_SHORT, 'iso'); - // If object extract value - if ($date instanceof Date) { - $date = $date->toString($part, 'iso', $locale); - } - - if (is_array($date) === true) { - if (empty($part) === false) { - switch($part) { - // Fall through - case self::DAY: - case self::DAY_SHORT: - if (isset($date['day']) === true) { - $date = $date['day']; - } - break; - // Fall through - case self::WEEKDAY_SHORT: - case self::WEEKDAY: - case self::WEEKDAY_8601: - case self::WEEKDAY_DIGIT: - case self::WEEKDAY_NARROW: - case self::WEEKDAY_NAME: - if (isset($date['weekday']) === true) { - $date = $date['weekday']; - $part = self::WEEKDAY_DIGIT; - } - break; - case self::DAY_OF_YEAR: - if (isset($date['day_of_year']) === true) { - $date = $date['day_of_year']; - } - break; - // Fall through - case self::MONTH: - case self::MONTH_SHORT: - case self::MONTH_NAME: - case self::MONTH_NAME_SHORT: - case self::MONTH_NAME_NARROW: - if (isset($date['month']) === true) { - $date = $date['month']; - } - break; - // Fall through - case self::YEAR: - case self::YEAR_SHORT: - case self::YEAR_8601: - case self::YEAR_SHORT_8601: - if (isset($date['year']) === true) { - $date = $date['year']; - } - break; - // Fall through - case self::HOUR: - case self::HOUR_AM: - case self::HOUR_SHORT: - case self::HOUR_SHORT_AM: - if (isset($date['hour']) === true) { - $date = $date['hour']; - } - break; - // Fall through - case self::MINUTE: - case self::MINUTE_SHORT: - if (isset($date['minute']) === true) { - $date = $date['minute']; - } - break; - // Fall through - case self::SECOND: - case self::SECOND_SHORT: - if (isset($date['second']) === true) { - $date = $date['second']; - } - break; - // Fall through - case self::TIMEZONE: - case self::TIMEZONE_NAME: - if (isset($date['timezone']) === true) { - $date = $date['timezone']; - } - break; - case self::TIMESTAMP: - if (isset($date['timestamp']) === true) { - $date = $date['timestamp']; - } - break; - case self::WEEK: - if (isset($date['week']) === true) { - $date = $date['week']; - } - break; - case self::TIMEZONE_SECS: - if (isset($date['gmtsecs']) === true) { - $date = $date['gmtsecs']; - } - break; - default: - throw new Exception\RuntimeException("datepart for part ($part) not found in array"); - break; - } - } else { - $hours = 0; - if (isset($date['hour']) === true) { - $hours = $date['hour']; - } - $minutes = 0; - if (isset($date['minute']) === true) { - $minutes = $date['minute']; - } - $seconds = 0; - if (isset($date['second']) === true) { - $seconds = $date['second']; - } - $months = 0; - if (isset($date['month']) === true) { - $months = $date['month']; - } - $days = 0; - if (isset($date['day']) === true) { - $days = $date['day']; - } - $years = 0; - if (isset($date['year']) === true) { - $years = $date['year']; - } - return $this->_assign($calc, $this->mktime($hours, $minutes, $seconds, $months, $days, $years, true), - $this->mktime($hour, $minute, $second, $month, $day, $year, true), $hour); - } - } - - // $date as object, part of foreign date as own date - switch($part) { - - // day formats - case self::DAY: - if (is_numeric($date)) { - return $this->_assign($calc, $this->mktime(0, 0, 0, 1, 1 + intval($date), 1970, true), - $this->mktime(0, 0, 0, 1, 1 + intval($day), 1970, true), $hour); - } - - throw new Exception\RuntimeException("invalid date ($date) operand, day expected"); - break; - - case self::WEEKDAY_SHORT: - $daylist = Cldr::getList($locale, 'day'); - $weekday = (int) $this->toString(self::WEEKDAY_DIGIT, 'iso', $locale); - $cnt = 0; - - foreach ($daylist as $key => $value) { - if (strtoupper(iconv_substr($value, 0, 3, 'UTF-8')) == strtoupper($date)) { - $found = $cnt; - break; - } - ++$cnt; - } - - // Weekday found - if ($cnt < 7) { - return $this->_assign($calc, $this->mktime(0, 0, 0, 1, 1 + $found, 1970, true), - $this->mktime(0, 0, 0, 1, 1 + $weekday, 1970, true), $hour); - } - - // Weekday not found - throw new Exception\RuntimeException("invalid date ($date) operand, weekday expected"); - break; - - case self::DAY_SHORT: - if (is_numeric($date)) { - return $this->_assign($calc, $this->mktime(0, 0, 0, 1, 1 + intval($date), 1970, true), - $this->mktime(0, 0, 0, 1, 1 + intval($day), 1970, true), $hour); - } - - throw new Exception\RuntimeException("invalid date ($date) operand, day expected"); - break; - - case self::WEEKDAY: - $daylist = Cldr::getList($locale, 'day'); - $weekday = (int) $this->toString(self::WEEKDAY_DIGIT, 'iso', $locale); - $cnt = 0; - - foreach ($daylist as $key => $value) { - if (strtoupper($value) == strtoupper($date)) { - $found = $cnt; - break; - } - ++$cnt; - } - - // Weekday found - if ($cnt < 7) { - return $this->_assign($calc, $this->mktime(0, 0, 0, 1, 1 + $found, 1970, true), - $this->mktime(0, 0, 0, 1, 1 + $weekday, 1970, true), $hour); - } - - // Weekday not found - throw new Exception\RuntimeException("invalid date ($date) operand, weekday expected"); - break; - - case self::WEEKDAY_8601: - $weekday = (int) $this->toString(self::WEEKDAY_8601, 'iso', $locale); - if ((intval($date) > 0) and (intval($date) < 8)) { - return $this->_assign($calc, $this->mktime(0, 0, 0, 1, 1 + intval($date), 1970, true), - $this->mktime(0, 0, 0, 1, 1 + $weekday, 1970, true), $hour); - } - - // Weekday not found - throw new Exception\RuntimeException("invalid date ($date) operand, weekday expected"); - break; - - case self::DAY_SUFFIX: - throw new Exception\RuntimeException('day suffix not supported'); - break; - - case self::WEEKDAY_DIGIT: - $weekday = (int) $this->toString(self::WEEKDAY_DIGIT, 'iso', $locale); - if (is_numeric($date) and (intval($date) >= 0) and (intval($date) < 7)) { - return $this->_assign($calc, $this->mktime(0, 0, 0, 1, 1 + $date, 1970, true), - $this->mktime(0, 0, 0, 1, 1 + $weekday, 1970, true), $hour); - } - - // Weekday not found - throw new Exception\RuntimeException("invalid date ($date) operand, weekday expected"); - break; - - case self::DAY_OF_YEAR: - if (is_numeric($date)) { - if (($calc == 'add') || ($calc == 'sub')) { - $year = 1970; - ++$date; - ++$day; - } - - return $this->_assign($calc, $this->mktime(0, 0, 0, 1, $date, $year, true), - $this->mktime(0, 0, 0, $month, $day, $year, true), $hour); - } - - throw new Exception\RuntimeException("invalid date ($date) operand, day expected"); - break; - - case self::WEEKDAY_NARROW: - $daylist = Cldr::getList($locale, 'day', array('gregorian', 'format', 'abbreviated')); - $weekday = (int) $this->toString(self::WEEKDAY_DIGIT, 'iso', $locale); - $cnt = 0; - foreach ($daylist as $key => $value) { - if (strtoupper(iconv_substr($value, 0, 1, 'UTF-8')) == strtoupper($date)) { - $found = $cnt; - break; - } - ++$cnt; - } - - // Weekday found - if ($cnt < 7) { - return $this->_assign($calc, $this->mktime(0, 0, 0, 1, 1 + $found, 1970, true), - $this->mktime(0, 0, 0, 1, 1 + $weekday, 1970, true), $hour); - } - - // Weekday not found - throw new Exception\RuntimeException("invalid date ($date) operand, weekday expected"); - break; - - case self::WEEKDAY_NAME: - $daylist = Cldr::getList($locale, 'day', array('gregorian', 'format', 'abbreviated')); - $weekday = (int) $this->toString(self::WEEKDAY_DIGIT, 'iso', $locale); - $cnt = 0; - foreach ($daylist as $key => $value) { - if (strtoupper($value) == strtoupper($date)) { - $found = $cnt; - break; - } - ++$cnt; - } - - // Weekday found - if ($cnt < 7) { - return $this->_assign($calc, $this->mktime(0, 0, 0, 1, 1 + $found, 1970, true), - $this->mktime(0, 0, 0, 1, 1 + $weekday, 1970, true), $hour); - } - - // Weekday not found - throw new Exception\RuntimeException("invalid date ($date) operand, weekday expected"); - break; - - // week formats - case self::WEEK: - if (is_numeric($date)) { - $week = (int) $this->toString(self::WEEK, 'iso', $locale); - return $this->_assign($calc, parent::mktime(0, 0, 0, 1, 1 + ($date * 7), 1970, true), - parent::mktime(0, 0, 0, 1, 1 + ($week * 7), 1970, true), $hour); - } - - throw new Exception\RuntimeException("invalid date ($date) operand, week expected"); - break; - - // month formats - case self::MONTH_NAME: - $monthlist = Cldr::getList($locale, 'month'); - $cnt = 0; - foreach ($monthlist as $key => $value) { - if (strtoupper($value) == strtoupper($date)) { - $found = $key; - break; - } - ++$cnt; - } - $date = array_search($date, $monthlist); - - // Monthname found - if ($cnt < 12) { - $fixday = 0; - if ($calc == 'add') { - $date += $found; - $calc = 'set'; - if (self::$_options['extend_month'] == false) { - $parts = $this->getDateParts($this->mktime($hour, $minute, $second, $date, $day, $year, false)); - if ($parts['mday'] != $day) { - $fixday = ($parts['mday'] < $day) ? -$parts['mday'] : ($parts['mday'] - $day); - } - } - } else if ($calc == 'sub') { - $date = $month - $found; - $calc = 'set'; - if (self::$_options['extend_month'] == false) { - $parts = $this->getDateParts($this->mktime($hour, $minute, $second, $date, $day, $year, false)); - if ($parts['mday'] != $day) { - $fixday = ($parts['mday'] < $day) ? -$parts['mday'] : ($parts['mday'] - $day); - } - } - } - return $this->_assign($calc, $this->mktime(0, 0, 0, $date, $day + $fixday, $year, true), - $this->mktime(0, 0, 0, $month, $day, $year, true), $hour); - } - - // Monthname not found - throw new Exception\RuntimeException("invalid date ($date) operand, month expected"); - break; - - case self::MONTH: - if (is_numeric($date)) { - $fixday = 0; - if ($calc == 'add') { - $date += $month; - $calc = 'set'; - if (self::$_options['extend_month'] == false) { - $parts = $this->getDateParts($this->mktime($hour, $minute, $second, $date, $day, $year, false)); - if ($parts['mday'] != $day) { - $fixday = ($parts['mday'] < $day) ? -$parts['mday'] : ($parts['mday'] - $day); - } - } - } else if ($calc == 'sub') { - $date = $month - $date; - $calc = 'set'; - if (self::$_options['extend_month'] == false) { - $parts = $this->getDateParts($this->mktime($hour, $minute, $second, $date, $day, $year, false)); - if ($parts['mday'] != $day) { - $fixday = ($parts['mday'] < $day) ? -$parts['mday'] : ($parts['mday'] - $day); - } - } - } - return $this->_assign($calc, $this->mktime(0, 0, 0, $date, $day + $fixday, $year, true), - $this->mktime(0, 0, 0, $month, $day, $year, true), $hour); - } - - throw new Exception\RuntimeException("invalid date ($date) operand, month expected"); - break; - - case self::MONTH_NAME_SHORT: - $monthlist = Cldr::getList($locale, 'month', array('gregorian', 'format', 'abbreviated')); - $cnt = 0; - foreach ($monthlist as $key => $value) { - if (strtoupper($value) == strtoupper($date)) { - $found = $key; - break; - } - ++$cnt; - } - $date = array_search($date, $monthlist); - - // Monthname found - if ($cnt < 12) { - $fixday = 0; - if ($calc == 'add') { - $date += $found; - $calc = 'set'; - if (self::$_options['extend_month'] === false) { - $parts = $this->getDateParts($this->mktime($hour, $minute, $second, $date, $day, $year, false)); - if ($parts['mday'] != $day) { - $fixday = ($parts['mday'] < $day) ? -$parts['mday'] : ($parts['mday'] - $day); - } - } - } else if ($calc == 'sub') { - $date = $month - $found; - $calc = 'set'; - if (self::$_options['extend_month'] === false) { - $parts = $this->getDateParts($this->mktime($hour, $minute, $second, $date, $day, $year, false)); - if ($parts['mday'] != $day) { - $fixday = ($parts['mday'] < $day) ? -$parts['mday'] : ($parts['mday'] - $day); - } - } - } - return $this->_assign($calc, $this->mktime(0, 0, 0, $date, $day + $fixday, $year, true), - $this->mktime(0, 0, 0, $month, $day, $year, true), $hour); - } - - // Monthname not found - throw new Exception\RuntimeException("invalid date ($date) operand, month expected"); - break; - - case self::MONTH_SHORT: - if (is_numeric($date) === true) { - $fixday = 0; - if ($calc === 'add') { - $date += $month; - $calc = 'set'; - if (self::$_options['extend_month'] === false) { - $parts = $this->getDateParts($this->mktime($hour, $minute, $second, $date, $day, $year, false)); - if ($parts['mday'] != $day) { - $fixday = ($parts['mday'] < $day) ? -$parts['mday'] : ($parts['mday'] - $day); - } - } - } else if ($calc === 'sub') { - $date = $month - $date; - $calc = 'set'; - if (self::$_options['extend_month'] === false) { - $parts = $this->getDateParts($this->mktime($hour, $minute, $second, $date, $day, $year, false)); - if ($parts['mday'] != $day) { - $fixday = ($parts['mday'] < $day) ? -$parts['mday'] : ($parts['mday'] - $day); - } - } - } - - return $this->_assign($calc, $this->mktime(0, 0, 0, $date, $day + $fixday, $year, true), - $this->mktime(0, 0, 0, $month, $day, $year, true), $hour); - } - - throw new Exception\RuntimeException("invalid date ($date) operand, month expected"); - break; - - case self::MONTH_DAYS: - throw new Exception\RuntimeException('month days not supported'); - break; - - case self::MONTH_NAME_NARROW: - $monthlist = Cldr::getList($locale, 'month', array('gregorian', 'stand-alone', 'narrow')); - $cnt = 0; - foreach ($monthlist as $key => $value) { - if (strtoupper($value) === strtoupper($date)) { - $found = $key; - break; - } - ++$cnt; - } - $date = array_search($date, $monthlist); - - // Monthname found - if ($cnt < 12) { - $fixday = 0; - if ($calc === 'add') { - $date += $found; - $calc = 'set'; - if (self::$_options['extend_month'] === false) { - $parts = $this->getDateParts($this->mktime($hour, $minute, $second, $date, $day, $year, false)); - if ($parts['mday'] != $day) { - $fixday = ($parts['mday'] < $day) ? -$parts['mday'] : ($parts['mday'] - $day); - } - } - } else if ($calc === 'sub') { - $date = $month - $found; - $calc = 'set'; - if (self::$_options['extend_month'] === false) { - $parts = $this->getDateParts($this->mktime($hour, $minute, $second, $date, $day, $year, false)); - if ($parts['mday'] != $day) { - $fixday = ($parts['mday'] < $day) ? -$parts['mday'] : ($parts['mday'] - $day); - } - } - } - return $this->_assign($calc, $this->mktime(0, 0, 0, $date, $day + $fixday, $year, true), - $this->mktime(0, 0, 0, $month, $day, $year, true), $hour); - } - - // Monthname not found - throw new Exception\RuntimeException("invalid date ($date) operand, month expected"); - break; - - // year formats - case self::LEAPYEAR: - throw new Exception\RuntimeException('leap year not supported'); - break; - - case self::YEAR_8601: - if (is_numeric($date)) { - if ($calc === 'add') { - $date += $year; - $calc = 'set'; - } else if ($calc === 'sub') { - $date = $year - $date; - $calc = 'set'; - } - - return $this->_assign($calc, $this->mktime(0, 0, 0, $month, $day, intval($date), true), - $this->mktime(0, 0, 0, $month, $day, $year, true), false); - } - - throw new Exception\RuntimeException("invalid date ($date) operand, year expected"); - break; - - case self::YEAR: - if (is_numeric($date)) { - if ($calc === 'add') { - $date += $year; - $calc = 'set'; - } else if ($calc === 'sub') { - $date = $year - $date; - $calc = 'set'; - } - - return $this->_assign($calc, $this->mktime(0, 0, 0, $month, $day, intval($date), true), - $this->mktime(0, 0, 0, $month, $day, $year, true), false); - } - - throw new Exception\RuntimeException("invalid date ($date) operand, year expected"); - break; - - case self::YEAR_SHORT: - if (is_numeric($date)) { - $date = intval($date); - if (($calc == 'set') || ($calc == 'cmp')) { - $date = self::getFullYear($date); - } - if ($calc === 'add') { - $date += $year; - $calc = 'set'; - } else if ($calc === 'sub') { - $date = $year - $date; - $calc = 'set'; - } - - return $this->_assign($calc, $this->mktime(0, 0, 0, $month, $day, $date, true), - $this->mktime(0, 0, 0, $month, $day, $year, true), false); - } - - throw new Exception\RuntimeException("invalid date ($date) operand, year expected"); - break; - - case self::YEAR_SHORT_8601: - if (is_numeric($date)) { - $date = intval($date); - if (($calc === 'set') || ($calc === 'cmp')) { - $date = self::getFullYear($date); - } - if ($calc === 'add') { - $date += $year; - $calc = 'set'; - } else if ($calc === 'sub') { - $date = $year - $date; - $calc = 'set'; - } - - return $this->_assign($calc, $this->mktime(0, 0, 0, $month, $day, $date, true), - $this->mktime(0, 0, 0, $month, $day, $year, true), false); - } - - throw new Exception\RuntimeException("invalid date ($date) operand, year expected"); - break; - - // time formats - case self::MERIDIEM: - throw new Exception\RuntimeException('meridiem not supported'); - break; - - case self::SWATCH: - if (is_numeric($date)) { - $rest = intval($date); - $hours = floor($rest * 24 / 1000); - $rest = $rest - ($hours * 1000 / 24); - $minutes = floor($rest * 1440 / 1000); - $rest = $rest - ($minutes * 1000 / 1440); - $seconds = floor($rest * 86400 / 1000); - return $this->_assign($calc, $this->mktime($hours, $minutes, $seconds, 1, 1, 1970, true), - $this->mktime($hour, $minute, $second, 1, 1, 1970, true), false); - } - - throw new Exception\RuntimeException("invalid date ($date) operand, swatchstamp expected"); - break; - - case self::HOUR_SHORT_AM: - if (is_numeric($date)) { - return $this->_assign($calc, $this->mktime(intval($date), 0, 0, 1, 1, 1970, true), - $this->mktime($hour, 0, 0, 1, 1, 1970, true), false); - } - - throw new Exception\RuntimeException("invalid date ($date) operand, hour expected"); - break; - - case self::HOUR_SHORT: - if (is_numeric($date)) { - return $this->_assign($calc, $this->mktime(intval($date), 0, 0, 1, 1, 1970, true), - $this->mktime($hour, 0, 0, 1, 1, 1970, true), false); - } - - throw new Exception\RuntimeException("invalid date ($date) operand, hour expected"); - break; - - case self::HOUR_AM: - if (is_numeric($date)) { - return $this->_assign($calc, $this->mktime(intval($date), 0, 0, 1, 1, 1970, true), - $this->mktime($hour, 0, 0, 1, 1, 1970, true), false); - } - - throw new Exception\RuntimeException("invalid date ($date) operand, hour expected"); - break; - - case self::HOUR: - if (is_numeric($date)) { - return $this->_assign($calc, $this->mktime(intval($date), 0, 0, 1, 1, 1970, true), - $this->mktime($hour, 0, 0, 1, 1, 1970, true), false); - } - - throw new Exception\RuntimeException("invalid date ($date) operand, hour expected"); - break; - - case self::MINUTE: - if (is_numeric($date)) { - return $this->_assign($calc, $this->mktime(0, intval($date), 0, 1, 1, 1970, true), - $this->mktime(0, $minute, 0, 1, 1, 1970, true), false); - } - - throw new Exception\RuntimeException("invalid date ($date) operand, minute expected"); - break; - - case self::SECOND: - if (is_numeric($date)) { - return $this->_assign($calc, $this->mktime(0, 0, intval($date), 1, 1, 1970, true), - $this->mktime(0, 0, $second, 1, 1, 1970, true), false); - } - - throw new Exception\RuntimeException("invalid date ($date) operand, second expected"); - break; - - case self::MILLISECOND: - if (is_numeric($date)) { - switch($calc) { - case 'set' : - return $this->setMillisecond($date); - break; - case 'add' : - return $this->addMillisecond($date); - break; - case 'sub' : - return $this->subMillisecond($date); - break; - } - - return $this->compareMillisecond($date); - } - - throw new Exception\RuntimeException("invalid date ($date) operand, milliseconds expected"); - break; - - case self::MINUTE_SHORT: - if (is_numeric($date)) { - return $this->_assign($calc, $this->mktime(0, intval($date), 0, 1, 1, 1970, true), - $this->mktime(0, $minute, 0, 1, 1, 1970, true), false); - } - - throw new Exception\RuntimeException("invalid date ($date) operand, minute expected"); - break; - - case self::SECOND_SHORT: - if (is_numeric($date)) { - return $this->_assign($calc, $this->mktime(0, 0, intval($date), 1, 1, 1970, true), - $this->mktime(0, 0, $second, 1, 1, 1970, true), false); - } - - throw new Exception\RuntimeException("invalid date ($date) operand, second expected"); - break; - - // timezone formats - // break intentionally omitted - case self::TIMEZONE_NAME: - case self::TIMEZONE: - case self::TIMEZONE_SECS: - throw new Exception\RuntimeException('timezone not supported'); - break; - - case self::DAYLIGHT: - throw new Exception\RuntimeException('daylight not supported'); - break; - - case self::GMT_DIFF: - case self::GMT_DIFF_SEP: - throw new Exception\RuntimeException('gmtdiff not supported'); - break; - - // date strings - case self::ISO_8601: - // (-)YYYY-MM-dd - preg_match('/^(-{0,1}\d{4})-(\d{2})-(\d{2})/', $date, $datematch); - // (-)YY-MM-dd - if (empty($datematch)) { - preg_match('/^(-{0,1}\d{2})-(\d{2})-(\d{2})/', $date, $datematch); - } - // (-)YYYYMMdd - if (empty($datematch)) { - preg_match('/^(-{0,1}\d{4})(\d{2})(\d{2})/', $date, $datematch); - } - // (-)YYMMdd - if (empty($datematch)) { - preg_match('/^(-{0,1}\d{2})(\d{2})(\d{2})/', $date, $datematch); - } - $tmpdate = $date; - if (!empty($datematch)) { - $dateMatchCharCount = iconv_strlen($datematch[0], 'UTF-8'); - $tmpdate = iconv_substr($date, - $dateMatchCharCount, - iconv_strlen($date, 'UTF-8') - $dateMatchCharCount, - 'UTF-8'); - } - // (T)hh:mm:ss - preg_match('/[T,\s]{0,1}(\d{2}):(\d{2}):(\d{2})/', $tmpdate, $timematch); - if (empty($timematch)) { - preg_match('/[T,\s]{0,1}(\d{2})(\d{2})(\d{2})/', $tmpdate, $timematch); - } - if (empty($datematch) and empty($timematch)) { - throw new Exception\RuntimeException("unsupported ISO8601 format ($date)"); - } - if (!empty($timematch)) { - $timeMatchCharCount = iconv_strlen($timematch[0], 'UTF-8'); - $tmpdate = iconv_substr($tmpdate, - $timeMatchCharCount, - iconv_strlen($tmpdate, 'UTF-8') - $timeMatchCharCount, - 'UTF-8'); - } - if (empty($datematch)) { - $datematch[1] = 1970; - $datematch[2] = 1; - $datematch[3] = 1; - } else if (iconv_strlen($datematch[1], 'UTF-8') == 2) { - $datematch[1] = self::getFullYear($datematch[1]); - } - if (empty($timematch)) { - $timematch[1] = 0; - $timematch[2] = 0; - $timematch[3] = 0; - } - - if (($calc == 'set') || ($calc == 'cmp')) { - --$datematch[2]; - --$month; - --$datematch[3]; - --$day; - $datematch[1] -= 1970; - $year -= 1970; - } - return $this->_assign($calc, $this->mktime($timematch[1], $timematch[2], $timematch[3], 1 + $datematch[2], 1 + $datematch[3], 1970 + $datematch[1], false), - $this->mktime($hour, $minute, $second, 1 + $month, 1 + $day, 1970 + $year, false), false); - break; - - case self::RFC_2822: - $result = preg_match('/^\w{3},\s(\d{1,2})\s(\w{3})\s(\d{4})\s(\d{2}):(\d{2}):{0,1}(\d{0,2})\s([+-]{1}\d{4})$/', $date, $match); - if (!$result) { - throw new Exception\RuntimeException("no RFC 2822 format ($date)"); - } - - $months = $this->_getDigitFromName($match[2]); - - if (($calc == 'set') || ($calc == 'cmp')) { - --$months; - --$month; - --$match[1]; - --$day; - $match[3] -= 1970; - $year -= 1970; - } - return $this->_assign($calc, $this->mktime($match[4], $match[5], $match[6], 1 + $months, 1 + $match[1], 1970 + $match[3], false), - $this->mktime($hour, $minute, $second, 1 + $month, 1 + $day, 1970 + $year, false), false); - break; - - case self::TIMESTAMP: - if (is_numeric($date)) { - return $this->_assign($calc, $date, $this->getUnixTimestamp()); - } - - throw new Exception\RuntimeException("invalid date ($date) operand, timestamp expected"); - break; - - // additional formats - // break intentionally omitted - case self::ERA: - case self::ERA_NAME: - throw new Exception\RuntimeException('era not supported'); - break; - - case self::DATES: - try { - $parsed = Format::getDate($date, array('locale' => $locale, 'format_type' => 'iso', 'fix_date' => true)); - - if (($calc == 'set') || ($calc == 'cmp')) { - --$parsed['month']; - --$month; - --$parsed['day']; - --$day; - $parsed['year'] -= 1970; - $year -= 1970; - } - - return $this->_assign($calc, $this->mktime(0, 0, 0, 1 + $parsed['month'], 1 + $parsed['day'], 1970 + $parsed['year'], true), - $this->mktime(0, 0, 0, 1 + $month, 1 + $day, 1970 + $year, true), $hour); - } catch (\Zend\Locale\Exception\ExceptionInterface $e) { - throw new Exception\RuntimeException($e->getMessage()); - } - break; - - case self::DATE_FULL: - try { - $format = Cldr::getContent($locale, 'date', array('gregorian', 'full')); - $parsed = Format::getDate($date, array('date_format' => $format, 'format_type' => 'iso', 'locale' => $locale)); - - if (($calc == 'set') || ($calc == 'cmp')) { - --$parsed['month']; - --$month; - --$parsed['day']; - --$day; - $parsed['year'] -= 1970; - $year -= 1970; - } - return $this->_assign($calc, $this->mktime(0, 0, 0, 1 + $parsed['month'], 1 + $parsed['day'], 1970 + $parsed['year'], true), - $this->mktime(0, 0, 0, 1 + $month, 1 + $day, 1970 + $year, true), $hour); - } catch (\Zend\Locale\Exception\ExceptionInterface $e) { - throw new Exception\RuntimeException($e->getMessage()); - } - break; - - case self::DATE_LONG: - try { - $format = Cldr::getContent($locale, 'date', array('gregorian', 'long')); - $parsed = Format::getDate($date, array('date_format' => $format, 'format_type' => 'iso', 'locale' => $locale)); - - if (($calc == 'set') || ($calc == 'cmp')){ - --$parsed['month']; - --$month; - --$parsed['day']; - --$day; - $parsed['year'] -= 1970; - $year -= 1970; - } - return $this->_assign($calc, $this->mktime(0, 0, 0, 1 + $parsed['month'], 1 + $parsed['day'], 1970 + $parsed['year'], true), - $this->mktime(0, 0, 0, 1 + $month, 1 + $day, 1970 + $year, true), $hour); - } catch (\Zend\Locale\Exception\ExceptionInterface $e) { - throw new Exception\RuntimeException($e->getMessage()); - } - break; - - case self::DATE_MEDIUM: - try { - $format = Cldr::getContent($locale, 'date', array('gregorian', 'medium')); - $parsed = Format::getDate($date, array('date_format' => $format, 'format_type' => 'iso', 'locale' => $locale)); - - if (($calc == 'set') || ($calc == 'cmp')) { - --$parsed['month']; - --$month; - --$parsed['day']; - --$day; - $parsed['year'] -= 1970; - $year -= 1970; - } - return $this->_assign($calc, $this->mktime(0, 0, 0, 1 + $parsed['month'], 1 + $parsed['day'], 1970 + $parsed['year'], true), - $this->mktime(0, 0, 0, 1 + $month, 1 + $day, 1970 + $year, true), $hour); - } catch (\Zend\Locale\Exception\ExceptionInterface $e) { - throw new Exception\RuntimeException($e->getMessage()); - } - break; - - case self::DATE_SHORT: - try { - $format = Cldr::getContent($locale, 'date', array('gregorian', 'short')); - $parsed = Format::getDate($date, array('date_format' => $format, 'format_type' => 'iso', 'locale' => $locale)); - - $parsed['year'] = self::getFullYear($parsed['year']); - - if (($calc == 'set') || ($calc == 'cmp')) { - --$parsed['month']; - --$month; - --$parsed['day']; - --$day; - $parsed['year'] -= 1970; - $year -= 1970; - } - return $this->_assign($calc, $this->mktime(0, 0, 0, 1 + $parsed['month'], 1 + $parsed['day'], 1970 + $parsed['year'], true), - $this->mktime(0, 0, 0, 1 + $month, 1 + $day, 1970 + $year, true), $hour); - } catch (\Zend\Locale\Exception\ExceptionInterface $e) { - throw new Exception\RuntimeException($e->getMessage()); - } - break; - - case self::TIMES: - try { - if ($calc != 'set') { - $month = 1; - $day = 1; - $year = 1970; - } - $parsed = Format::getTime($date, array('locale' => $locale, 'format_type' => 'iso', 'fix_date' => true)); - return $this->_assign($calc, $this->mktime($parsed['hour'], $parsed['minute'], $parsed['second'], $month, $day, $year, true), - $this->mktime($hour, $minute, $second, $month, $day, $year, true), false); - } catch (\Zend\Locale\Exception\ExceptionInterface $e) { - throw new Exception\RuntimeException($e->getMessage()); - } - break; - - case self::TIME_FULL: - try { - $format = Cldr::getContent($locale, 'time', array('gregorian', 'full')); - $parsed = Format::getTime($date, array('date_format' => $format, 'format_type' => 'iso', 'locale' => $locale)); - if ($calc != 'set') { - $month = 1; - $day = 1; - $year = 1970; - } - - if (!isset($parsed['second'])) { - $parsed['second'] = 0; - } - - return $this->_assign($calc, $this->mktime($parsed['hour'], $parsed['minute'], $parsed['second'], $month, $day, $year, true), - $this->mktime($hour, $minute, $second, $month, $day, $year, true), false); - } catch (\Zend\Locale\Exception\ExceptionInterface $e) { - throw new Exception\RuntimeException($e->getMessage()); - } - break; - - case self::TIME_LONG: - try { - $format = Cldr::getContent($locale, 'time', array('gregorian', 'long')); - $parsed = Format::getTime($date, array('date_format' => $format, 'format_type' => 'iso', 'locale' => $locale)); - if ($calc != 'set') { - $month = 1; - $day = 1; - $year = 1970; - } - return $this->_assign($calc, $this->mktime($parsed['hour'], $parsed['minute'], $parsed['second'], $month, $day, $year, true), - $this->mktime($hour, $minute, $second, $month, $day, $year, true), false); - } catch (\Zend\Locale\Exception\ExceptionInterface $e) { - throw new Exception\RuntimeException($e->getMessage()); - } - break; - - case self::TIME_MEDIUM: - try { - $format = Cldr::getContent($locale, 'time', array('gregorian', 'medium')); - $parsed = Format::getTime($date, array('date_format' => $format, 'format_type' => 'iso', 'locale' => $locale)); - if ($calc != 'set') { - $month = 1; - $day = 1; - $year = 1970; - } - return $this->_assign($calc, $this->mktime($parsed['hour'], $parsed['minute'], $parsed['second'], $month, $day, $year, true), - $this->mktime($hour, $minute, $second, $month, $day, $year, true), false); - } catch (\Zend\Locale\Exception\ExceptionInterface $e) { - throw new Exception\RuntimeException($e->getMessage()); - } - break; - - case self::TIME_SHORT: - try { - $format = Cldr::getContent($locale, 'time', array('gregorian', 'short')); - $parsed = Format::getTime($date, array('date_format' => $format, 'format_type' => 'iso', 'locale' => $locale)); - if ($calc != 'set') { - $month = 1; - $day = 1; - $year = 1970; - } - - if (!isset($parsed['second'])) { - $parsed['second'] = 0; - } - - return $this->_assign($calc, $this->mktime($parsed['hour'], $parsed['minute'], $parsed['second'], $month, $day, $year, true), - $this->mktime($hour, $minute, $second, $month, $day, $year, true), false); - } catch (\Zend\Locale\Exception\ExceptionInterface $e) { - throw new Exception\RuntimeException($e->getMessage()); - } - break; - - case self::DATETIME: - try { - $parsed = Format::getDateTime($date, array('locale' => $locale, 'format_type' => 'iso', 'fix_date' => true)); - if (($calc == 'set') || ($calc == 'cmp')) { - --$parsed['month']; - --$month; - --$parsed['day']; - --$day; - $parsed['year'] -= 1970; - $year -= 1970; - } - return $this->_assign($calc, $this->mktime($parsed['hour'], $parsed['minute'], $parsed['second'], 1 + $parsed['month'], 1 + $parsed['day'], 1970 + $parsed['year'], true), - $this->mktime($hour, $minute, $second, 1 + $month, 1 + $day, 1970 + $year, true), $hour); - } catch (\Zend\Locale\Exception\ExceptionInterface $e) { - throw new Exception\RuntimeException($e->getMessage()); - } - break; - - case self::DATETIME_FULL: - try { - $format = Cldr::getContent($locale, 'datetime', array('gregorian', 'full')); - $parsed = Format::getDateTime($date, array('date_format' => $format, 'format_type' => 'iso', 'locale' => $locale)); - - if (($calc == 'set') || ($calc == 'cmp')) { - --$parsed['month']; - --$month; - --$parsed['day']; - --$day; - $parsed['year'] -= 1970; - $year -= 1970; - } - - if (!isset($parsed['second'])) { - $parsed['second'] = 0; - } - - return $this->_assign($calc, $this->mktime($parsed['hour'], $parsed['minute'], $parsed['second'], 1 + $parsed['month'], 1 + $parsed['day'], 1970 + $parsed['year'], true), - $this->mktime($hour, $minute, $second, 1 + $month, 1 + $day, 1970 + $year, true), $hour); - } catch (\Zend\Locale\Exception\ExceptionInterface $e) { - throw new Exception\RuntimeException($e->getMessage()); - } - break; - - case self::DATETIME_LONG: - try { - $format = Cldr::getContent($locale, 'datetime', array('gregorian', 'long')); - $parsed = Format::getDateTime($date, array('date_format' => $format, 'format_type' => 'iso', 'locale' => $locale)); - - if (($calc == 'set') || ($calc == 'cmp')){ - --$parsed['month']; - --$month; - --$parsed['day']; - --$day; - $parsed['year'] -= 1970; - $year -= 1970; - } - return $this->_assign($calc, $this->mktime($parsed['hour'], $parsed['minute'], $parsed['second'], 1 + $parsed['month'], 1 + $parsed['day'], 1970 + $parsed['year'], true), - $this->mktime($hour, $minute, $second, 1 + $month, 1 + $day, 1970 + $year, true), $hour); - } catch (\Zend\Locale\Exception\ExceptionInterface $e) { - throw new Exception\RuntimeException($e->getMessage()); - } - break; - - case self::DATETIME_MEDIUM: - try { - $format = Cldr::getContent($locale, 'datetime', array('gregorian', 'medium')); - $parsed = Format::getDateTime($date, array('date_format' => $format, 'format_type' => 'iso', 'locale' => $locale)); - if (($calc == 'set') || ($calc == 'cmp')) { - --$parsed['month']; - --$month; - --$parsed['day']; - --$day; - $parsed['year'] -= 1970; - $year -= 1970; - } - return $this->_assign($calc, $this->mktime($parsed['hour'], $parsed['minute'], $parsed['second'], 1 + $parsed['month'], 1 + $parsed['day'], 1970 + $parsed['year'], true), - $this->mktime($hour, $minute, $second, 1 + $month, 1 + $day, 1970 + $year, true), $hour); - } catch (\Zend\Locale\Exception\ExceptionInterface $e) { - throw new Exception\RuntimeException($e->getMessage()); - } - break; - - case self::DATETIME_SHORT: - try { - $format = Cldr::getContent($locale, 'datetime', array('gregorian', 'short')); - $parsed = Format::getDateTime($date, array('date_format' => $format, 'format_type' => 'iso', 'locale' => $locale)); - - $parsed['year'] = self::getFullYear($parsed['year']); - - if (($calc == 'set') || ($calc == 'cmp')) { - --$parsed['month']; - --$month; - --$parsed['day']; - --$day; - $parsed['year'] -= 1970; - $year -= 1970; - } - - if (!isset($parsed['second'])) { - $parsed['second'] = 0; - } - - return $this->_assign($calc, $this->mktime($parsed['hour'], $parsed['minute'], $parsed['second'], 1 + $parsed['month'], 1 + $parsed['day'], 1970 + $parsed['year'], true), - $this->mktime($hour, $minute, $second, 1 + $month, 1 + $day, 1970 + $year, true), $hour); - } catch (\Zend\Locale\Exception\ExceptionInterface $e) { - throw new Exception\RuntimeException($e->getMessage()); - } - break; - - // ATOM and RFC_3339 are identical - case self::ATOM: - case self::RFC_3339: - $result = preg_match('/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})\d{0,4}([+-]{1}\d{2}:\d{2}|Z)$/', $date, $match); - if (!$result) { - throw new Exception\RuntimeException("invalid date ($date) operand, ATOM format expected"); - } - - if (($calc == 'set') || ($calc == 'cmp')) { - --$match[2]; - --$month; - --$match[3]; - --$day; - $match[1] -= 1970; - $year -= 1970; - } - return $this->_assign($calc, $this->mktime($match[4], $match[5], $match[6], 1 + $match[2], 1 + $match[3], 1970 + $match[1], true), - $this->mktime($hour, $minute, $second, 1 + $month, 1 + $day, 1970 + $year, true), false); - break; - - case self::COOKIE: - $result = preg_match("/^\w{6,9},\s(\d{2})-(\w{3})-(\d{2})\s(\d{2}):(\d{2}):(\d{2})\s.{3,20}$/", $date, $match); - if (!$result) { - throw new Exception\RuntimeException("invalid date ($date) operand, COOKIE format expected"); - } - $matchStartPos = iconv_strpos($match[0], ' ', 0, 'UTF-8') + 1; - $match[0] = iconv_substr($match[0], - $matchStartPos, - iconv_strlen($match[0], 'UTF-8') - $matchStartPos, - 'UTF-8'); - - $months = $this->_getDigitFromName($match[2]); - $match[3] = self::getFullYear($match[3]); - - if (($calc == 'set') || ($calc == 'cmp')) { - --$months; - --$month; - --$match[1]; - --$day; - $match[3] -= 1970; - $year -= 1970; - } - return $this->_assign($calc, $this->mktime($match[4], $match[5], $match[6], 1 + $months, 1 + $match[1], 1970 + $match[3], true), - $this->mktime($hour, $minute, $second, 1 + $month, 1 + $day, 1970 + $year, true), false); - break; - - case self::RFC_822: - case self::RFC_1036: - // new RFC 822 format, identical to RFC 1036 standard - $result = preg_match('/^\w{0,3},{0,1}\s{0,1}(\d{1,2})\s(\w{3})\s(\d{2})\s(\d{2}):(\d{2}):{0,1}(\d{0,2})\s([+-]{1}\d{4}|\w{1,20})$/', $date, $match); - if (!$result) { - throw new Exception\RuntimeException("invalid date ($date) operand, RFC 822 date format expected"); - } - - $months = $this->_getDigitFromName($match[2]); - $match[3] = self::getFullYear($match[3]); - - if (($calc == 'set') || ($calc == 'cmp')) { - --$months; - --$month; - --$match[1]; - --$day; - $match[3] -= 1970; - $year -= 1970; - } - return $this->_assign($calc, $this->mktime($match[4], $match[5], $match[6], 1 + $months, 1 + $match[1], 1970 + $match[3], false), - $this->mktime($hour, $minute, $second, 1 + $month, 1 + $day, 1970 + $year, false), false); - break; - - case self::RFC_850: - $result = preg_match('/^\w{6,9},\s(\d{2})-(\w{3})-(\d{2})\s(\d{2}):(\d{2}):(\d{2})\s.{3,21}$/', $date, $match); - if (!$result) { - throw new Exception\RuntimeException("invalid date ($date) operand, RFC 850 date format expected"); - } - - $months = $this->_getDigitFromName($match[2]); - $match[3] = self::getFullYear($match[3]); - - if (($calc == 'set') || ($calc == 'cmp')) { - --$months; - --$month; - --$match[1]; - --$day; - $match[3] -= 1970; - $year -= 1970; - } - return $this->_assign($calc, $this->mktime($match[4], $match[5], $match[6], 1 + $months, 1 + $match[1], 1970 + $match[3], true), - $this->mktime($hour, $minute, $second, 1 + $month, 1 + $day, 1970 + $year, true), false); - break; - - case self::RFC_1123: - $result = preg_match('/^\w{0,3},{0,1}\s{0,1}(\d{1,2})\s(\w{3})\s(\d{2,4})\s(\d{2}):(\d{2}):{0,1}(\d{0,2})\s([+-]{1}\d{4}|\w{1,20})$/', $date, $match); - if (!$result) { - throw new Exception\RuntimeException("invalid date ($date) operand, RFC 1123 date format expected"); - } - - $months = $this->_getDigitFromName($match[2]); - - if (($calc == 'set') || ($calc == 'cmp')) { - --$months; - --$month; - --$match[1]; - --$day; - $match[3] -= 1970; - $year -= 1970; - } - return $this->_assign($calc, $this->mktime($match[4], $match[5], $match[6], 1 + $months, 1 + $match[1], 1970 + $match[3], true), - $this->mktime($hour, $minute, $second, 1 + $month, 1 + $day, 1970 + $year, true), false); - break; - - case self::RSS: - $result = preg_match('/^\w{3},\s(\d{2})\s(\w{3})\s(\d{2,4})\s(\d{1,2}):(\d{2}):(\d{2})\s.{1,21}$/', $date, $match); - if (!$result) { - throw new Exception\RuntimeException("invalid date ($date) operand, RSS date format expected"); - } - - $months = $this->_getDigitFromName($match[2]); - $match[3] = self::getFullYear($match[3]); - - if (($calc == 'set') || ($calc == 'cmp')) { - --$months; - --$month; - --$match[1]; - --$day; - $match[3] -= 1970; - $year -= 1970; - } - return $this->_assign($calc, $this->mktime($match[4], $match[5], $match[6], 1 + $months, 1 + $match[1], 1970 + $match[3], true), - $this->mktime($hour, $minute, $second, 1 + $month, 1 + $day, 1970 + $year, true), false); - break; - - case self::W3C: - $result = preg_match('/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})[+-]{1}\d{2}:\d{2}$/', $date, $match); - if (!$result) { - throw new Exception\RuntimeException("invalid date ($date) operand, W3C date format expected"); - } - - if (($calc == 'set') || ($calc == 'cmp')) { - --$match[2]; - --$month; - --$match[3]; - --$day; - $match[1] -= 1970; - $year -= 1970; - } - return $this->_assign($calc, $this->mktime($match[4], $match[5], $match[6], 1 + $match[2], 1 + $match[3], 1970 + $match[1], true), - $this->mktime($hour, $minute, $second, 1 + $month, 1 + $day, 1970 + $year, true), false); - break; - - default: - if (!is_numeric($date) || !empty($part)) { - try { - if (empty($part)) { - $part = Format::getDateFormat($locale) . " "; - $part .= Format::getTimeFormat($locale); - } - - $parsed = Format::getDate($date, array('date_format' => $part, 'locale' => $locale, 'fix_date' => true, 'format_type' => 'iso')); - if ((strpos(strtoupper($part), 'YY') !== false) and (strpos(strtoupper($part), 'YYYY') === false)) { - $parsed['year'] = self::getFullYear($parsed['year']); - } - - if (($calc == 'set') || ($calc == 'cmp')) { - if (isset($parsed['month'])) { - --$parsed['month']; - } else { - $parsed['month'] = 0; - } - - if (isset($parsed['day'])) { - --$parsed['day']; - } else { - $parsed['day'] = 0; - } - - if (isset($parsed['year'])) { - $parsed['year'] -= 1970; - } else { - $parsed['year'] = 0; - } - } - - return $this->_assign($calc, $this->mktime( - isset($parsed['hour']) ? $parsed['hour'] : 0, - isset($parsed['minute']) ? $parsed['minute'] : 0, - isset($parsed['second']) ? $parsed['second'] : 0, - isset($parsed['month']) ? (1 + $parsed['month']) : 1, - isset($parsed['day']) ? (1 + $parsed['day']) : 1, - isset($parsed['year']) ? (1970 + $parsed['year']) : 1970, - false), $this->getUnixTimestamp(), false); - } catch (\Zend\Locale\Exception\ExceptionInterface $e) { - if (!is_numeric($date)) { - throw new Exception\RuntimeException($e->getMessage(), 0, $e); - } - } - } - - return $this->_assign($calc, $date, $this->getUnixTimestamp(), false); - break; - } - } - - /** - * Returns true when both date objects or date parts are equal. - * For example: - * 15.May.2000 <-> 15.June.2000 Equals only for Day or Year... all other will return false - * - * @param string|integer|array|\Zend\Date\Date $date Date or datepart to equal with - * @param string $part OPTIONAL Part of the date to compare, if null the timestamp is used - * @param string|\Zend\Locale\Locale $locale OPTIONAL Locale for parsing input - * @return boolean - * @throws \Zend\Date\Exception - */ - public function equals($date, $part = self::TIMESTAMP, $locale = null) - { - $result = $this->compare($date, $part, $locale); - - if ($result == 0) { - return true; - } - - return false; - } - - /** - * Returns if the given date or datepart is earlier - * For example: - * 15.May.2000 <-> 13.June.1999 will return true for day, year and date, but not for month - * - * @param string|integer|array|\Zend\Date\Date $date Date or datepart to compare with - * @param string $part OPTIONAL Part of the date to compare, if null the timestamp is used - * @param string|\Zend\Locale\Locale $locale OPTIONAL Locale for parsing input - * @return boolean - * @throws \Zend\Date\Exception - */ - public function isEarlier($date, $part = null, $locale = null) - { - $result = $this->compare($date, $part, $locale); - - if ($result == -1) { - return true; - } - - return false; - } - - /** - * Returns if the given date or datepart is later - * For example: - * 15.May.2000 <-> 13.June.1999 will return true for month but false for day, year and date - * Returns if the given date is later - * - * @param string|integer|array|\Zend\Date\Date $date Date or datepart to compare with - * @param string $part OPTIONAL Part of the date to compare, if null the timestamp is used - * @param string|\Zend\Locale\Locale $locale OPTIONAL Locale for parsing input - * @return boolean - * @throws \Zend\Date\Exception - */ - public function isLater($date, $part = null, $locale = null) - { - $result = $this->compare($date, $part, $locale); - - if ($result == 1) { - return true; - } - - return false; - } - - /** - * Returns only the time of the date as new Zend_Date object - * For example: - * 15.May.2000 10:11:23 will return a dateobject equal to 01.Jan.1970 10:11:23 - * - * @param string|\Zend\Locale\Locale $locale OPTIONAL Locale for parsing input - * @return \Zend\Date\Date - */ - public function getTime($locale = null) - { - if (self::$_options['format_type'] == 'php') { - $format = 'H:i:s'; - } else { - $format = self::TIME_MEDIUM; - } - - return $this->copyPart($format, $locale); - } - - /** - * Returns the calculated time - * - * @param string $calc Calculation to make - * @param string|integer|array|\Zend\Date\Date $time Time to calculate with, if null the actual time is taken - * @param string $format Timeformat for parsing input - * @param string|\Zend\Locale\Locale $locale Locale for parsing input - * @return integer|\Zend\Date\Date new time - * @throws \Zend\Date\Exception - */ - private function _time($calc, $time, $format, $locale) - { - if ($time === null) { - throw new Exception\InvalidArgumentException('parameter $time must be set, null is not allowed'); - } - - if ($time instanceof Date) { - // extract time from object - $time = $time->toString('HH:mm:ss', 'iso'); - } else { - if (is_array($time)) { - if ((isset($time['hour']) === true) or (isset($time['minute']) === true) or - (isset($time['second']) === true)) { - $parsed = $time; - } else { - throw new Exception\InvalidArgumentException("no hour, minute or second given in array"); - } - } else { - if (self::$_options['format_type'] == 'php') { - $format = Format::convertPhpToIsoFormat($format); - } - try { - if ($locale === null) { - $locale = $this->getLocale(); - } - - $parsed = Format::getTime($time, array('date_format' => $format, 'locale' => $locale, 'format_type' => 'iso')); - } catch (\Zend\Locale\Exception\ExceptionInterface $e) { - throw new Exception\InvalidArgumentException($e->getMessage(), 0, $e); - } - } - - if (!array_key_exists('hour', $parsed)) { - $parsed['hour'] = 0; - } - - if (!array_key_exists('minute', $parsed)) { - $parsed['minute'] = 0; - } - - if (!array_key_exists('second', $parsed)) { - $parsed['second'] = 0; - } - - $time = str_pad($parsed['hour'], 2, '0', STR_PAD_LEFT) . ":"; - $time .= str_pad($parsed['minute'], 2, '0', STR_PAD_LEFT) . ":"; - $time .= str_pad($parsed['second'], 2, '0', STR_PAD_LEFT); - } - - $return = $this->_calcdetail($calc, $time, self::TIMES, 'de'); - if ($calc != 'cmp') { - return $this; - } - - return $return; - } - - - /** - * Sets a new time for the date object. Format defines how to parse the time string. - * Also a complete date can be given, but only the time is used for setting. - * For example: dd.MMMM.yyTHH:mm' and 'ss sec'-> 10.May.07T25:11 and 44 sec => 1h11min44sec + 1 day - * Returned is the new date object and the existing date is left as it was before - * - * @param string|integer|array|\Zend\Date\Date $time Time to set - * @param string $format OPTIONAL Timeformat for parsing input - * @param string|\Zend\Locale\Locale $locale OPTIONAL Locale for parsing input - * @return \Zend\Date\Date Provides fluid interface - * @throws \Zend\Date\Exception - */ - public function setTime($time, $format = null, $locale = null) - { - return $this->_time('set', $time, $format, $locale); - } - - - /** - * Adds a time to the existing date. Format defines how to parse the time string. - * If only parts are given the other parts are set to 0. - * If no format is given, the standardformat of this locale is used. - * For example: HH:mm:ss -> 10 -> +10 hours - * - * @param string|integer|array|\Zend\Date\Date $time Time to add - * @param string $format OPTIONAL Timeformat for parsing input - * @param string|\Zend\Locale\Locale $locale OPTIONAL Locale for parsing input - * @return \Zend\Date\Date Provides fluid interface - * @throws \Zend\Date\Exception - */ - public function addTime($time, $format = null, $locale = null) - { - return $this->_time('add', $time, $format, $locale); - } - - - /** - * Subtracts a time from the existing date. Format defines how to parse the time string. - * If only parts are given the other parts are set to 0. - * If no format is given, the standardformat of this locale is used. - * For example: HH:mm:ss -> 10 -> -10 hours - * - * @param string|integer|array|\Zend\Date\Date $time Time to sub - * @param string $format OPTIONAL Timeformat for parsing input - * @param string|\Zend\Locale\Locale $locale OPTIONAL Locale for parsing input - * @return \Zend\Date\Date Provides fluid inteface - * @throws \Zend\Date\Exception - */ - public function subTime($time, $format = null, $locale = null) - { - return $this->_time('sub', $time, $format, $locale); - } - - - /** - * Compares the time from the existing date. Format defines how to parse the time string. - * If only parts are given the other parts are set to default. - * If no format us given, the standardformat of this locale is used. - * For example: HH:mm:ss -> 10 -> 10 hours - * - * @param string|integer|array|\Zend\Date\Date $time Time to compare - * @param string $format OPTIONAL Timeformat for parsing input - * @param string|\Zend\Locale\Locale $locale OPTIONAL Locale for parsing input - * @return integer 0 = equal, 1 = later, -1 = earlier - * @throws \Zend\Date\Exception - */ - public function compareTime($time, $format = null, $locale = null) - { - return $this->_time('cmp', $time, $format, $locale); - } - - /** - * Returns a clone of $this, with the time part set to 00:00:00. - * - * @param string|\Zend\Locale\Locale $locale OPTIONAL Locale for parsing input - * @return \Zend\Date\Date - */ - public function getDate($locale = null) - { - $orig = self::$_options['format_type']; - if (self::$_options['format_type'] == 'php') { - self::$_options['format_type'] = 'iso'; - } - - $date = $this->copyPart(self::DATE_MEDIUM, $locale); - $date->addTimestamp($this->getGmtOffset()); - self::$_options['format_type'] = $orig; - - return $date; - } - - /** - * Returns the calculated date - * - * @param string $calc Calculation to make - * @param string|integer|array|\Zend\Date\Date $date Date to calculate with, if null the actual date is taken - * @param string $format Date format for parsing - * @param string|\Zend\Locale\Locale $locale Locale for parsing input - * @return integer|\Zend\Date\Date new date - * @throws \Zend\Date\Exception - */ - private function _date($calc, $date, $format, $locale) - { - if ($date === null) { - throw new Exception\InvalidArgumentException('parameter $date must be set, null is not allowed'); - } - - if ($date instanceof Date) { - // extract date from object - $date = $date->toString('d.M.y', 'iso'); - } else { - if (is_array($date)) { - if ((isset($date['year']) === true) or (isset($date['month']) === true) or - (isset($date['day']) === true)) { - $parsed = $date; - } else { - throw new Exception\InvalidArgumentException("no day,month or year given in array"); - } - } else { - if ((self::$_options['format_type'] == 'php') && !defined($format)) { - $format = Format::convertPhpToIsoFormat($format); - } - try { - if ($locale === null) { - $locale = $this->getLocale(); - } - - $parsed = Format::getDate($date, array('date_format' => $format, 'locale' => $locale, 'format_type' => 'iso')); - if ((strpos(strtoupper($format), 'YY') !== false) and (strpos(strtoupper($format), 'YYYY') === false)) { - $parsed['year'] = self::getFullYear($parsed['year']); - } - } catch (\Zend\Locale\Exception\ExceptionInterface $e) { - throw new Exception\InvalidArgumentException($e->getMessage(), 0, $e); - } - } - - if (!array_key_exists('day', $parsed)) { - $parsed['day'] = 1; - } - - if (!array_key_exists('month', $parsed)) { - $parsed['month'] = 1; - } - - if (!array_key_exists('year', $parsed)) { - $parsed['year'] = 0; - } - - $date = $parsed['day'] . "." . $parsed['month'] . "." . $parsed['year']; - } - - $return = $this->_calcdetail($calc, $date, self::DATE_MEDIUM, 'de'); - if ($calc != 'cmp') { - return $this; - } - return $return; - } - - - /** - * Sets a new date for the date object. Format defines how to parse the date string. - * Also a complete date with time can be given, but only the date is used for setting. - * For example: MMMM.yy HH:mm-> May.07 22:11 => 01.May.07 00:00 - * Returned is the new date object and the existing time is left as it was before - * - * @param string|integer|array|\Zend\Date\Date $date Date to set - * @param string $format OPTIONAL Date format for parsing - * @param string|\Zend\Locale\Locale $locale OPTIONAL Locale for parsing input - * @return \Zend\Date\Date Provides fluid interface - * @throws \Zend\Date\Exception - */ - public function setDate($date, $format = null, $locale = null) - { - return $this->_date('set', $date, $format, $locale); - } - - - /** - * Adds a date to the existing date object. Format defines how to parse the date string. - * If only parts are given the other parts are set to 0. - * If no format is given, the standardformat of this locale is used. - * For example: MM.dd.YYYY -> 10 -> +10 months - * - * @param string|integer|array|\Zend\Date\Date $date Date to add - * @param string $format OPTIONAL Date format for parsing input - * @param string|\Zend\Locale\Locale $locale OPTIONAL Locale for parsing input - * @return \Zend\Date\Date Provides fluid interface - * @throws \Zend\Date\Exception - */ - public function addDate($date, $format = null, $locale = null) - { - return $this->_date('add', $date, $format, $locale); - } - - - /** - * Subtracts a date from the existing date object. Format defines how to parse the date string. - * If only parts are given the other parts are set to 0. - * If no format is given, the standardformat of this locale is used. - * For example: MM.dd.YYYY -> 10 -> -10 months - * Be aware: Subtracting 2 months is not equal to Adding -2 months !!! - * - * @param string|integer|array|\Zend\Date\Date $date Date to sub - * @param string $format OPTIONAL Date format for parsing input - * @param string|\Zend\Locale\Locale $locale OPTIONAL Locale for parsing input - * @return \Zend\Date\Date Provides fluid interface - * @throws \Zend\Date\Exception - */ - public function subDate($date, $format = null, $locale = null) - { - return $this->_date('sub', $date, $format, $locale); - } - - - /** - * Compares the date from the existing date object, ignoring the time. - * Format defines how to parse the date string. - * If only parts are given the other parts are set to 0. - * If no format is given, the standardformat of this locale is used. - * For example: 10.01.2000 => 10.02.1999 -> false - * - * @param string|integer|array|\Zend\Date\Date $date Date to compare - * @param string $format OPTIONAL Date format for parsing input - * @param string|\Zend\Locale\Locale $locale OPTIONAL Locale for parsing input - * @return integer 0 = equal, 1 = later, -1 = earlier - * @throws \Zend\Date\Exception - */ - public function compareDate($date, $format = null, $locale = null) - { - return $this->_date('cmp', $date, $format, $locale); - } - - - /** - * Returns the full ISO 8601 date from the date object. - * Always the complete ISO 8601 specifiction is used. If an other ISO date is needed - * (ISO 8601 defines several formats) use toString() instead. - * This function does not return the ISO date as object. Use copy() instead. - * - * @param string|\Zend\Locale\Locale $locale OPTIONAL Locale for parsing input - * @return string - */ - public function getIso($locale = null) - { - return $this->toString(self::ISO_8601, 'iso', $locale); - } - - - /** - * Sets a new date for the date object. Not given parts are set to default. - * Only supported ISO 8601 formats are accepted. - * For example: 050901 -> 01.Sept.2005 00:00:00, 20050201T10:00:30 -> 01.Feb.2005 10h00m30s - * Returned is the new date object - * - * @param string|integer|\Zend\Date\Date $date ISO Date to set - * @param string|\Zend\Locale\Locale $locale OPTIONAL Locale for parsing input - * @return \Zend\Date\Date Provides fluid interface - * @throws \Zend\Date\Exception - */ - public function setIso($date, $locale = null) - { - return $this->_calcvalue('set', $date, 'iso', self::ISO_8601, $locale); - } - - - /** - * Adds a ISO date to the date object. Not given parts are set to default. - * Only supported ISO 8601 formats are accepted. - * For example: 050901 -> + 01.Sept.2005 00:00:00, 10:00:00 -> +10h - * Returned is the new date object - * - * @param string|integer|\Zend\Date\Date $date ISO Date to add - * @param string|\Zend\Locale\Locale $locale OPTIONAL Locale for parsing input - * @return \Zend\Date\Date Provides fluid interface - * @throws \Zend\Date\Exception - */ - public function addIso($date, $locale = null) - { - return $this->_calcvalue('add', $date, 'iso', self::ISO_8601, $locale); - } - - - /** - * Subtracts a ISO date from the date object. Not given parts are set to default. - * Only supported ISO 8601 formats are accepted. - * For example: 050901 -> - 01.Sept.2005 00:00:00, 10:00:00 -> -10h - * Returned is the new date object - * - * @param string|integer|\Zend\Date\Date $date ISO Date to sub - * @param string|\Zend\Locale\Locale $locale OPTIONAL Locale for parsing input - * @return \Zend\Date\Date Provides fluid interface - * @throws \Zend\Date\Exception - */ - public function subIso($date, $locale = null) - { - return $this->_calcvalue('sub', $date, 'iso', self::ISO_8601, $locale); - } - - - /** - * Compares a ISO date with the date object. Not given parts are set to default. - * Only supported ISO 8601 formats are accepted. - * For example: 050901 -> - 01.Sept.2005 00:00:00, 10:00:00 -> -10h - * Returns if equal, earlier or later - * - * @param string|integer|\Zend\Date\Date $date ISO Date to sub - * @param string|\Zend\Locale\Locale $locale OPTIONAL Locale for parsing input - * @return integer 0 = equal, 1 = later, -1 = earlier - * @throws \Zend\Date\Exception - */ - public function compareIso($date, $locale = null) - { - return $this->_calcvalue('cmp', $date, 'iso', self::ISO_8601, $locale); - } - - - /** - * Returns a RFC 822 compilant datestring from the date object. - * This function does not return the RFC date as object. Use copy() instead. - * - * @param string|\Zend\Locale\Locale $locale OPTIONAL Locale for parsing input - * @return string - */ - public function getArpa($locale = null) - { - if (self::$_options['format_type'] == 'php') { - $format = 'D\, d M y H\:i\:s O'; - } else { - $format = self::RFC_822; - } - - return $this->toString($format, 'iso', $locale); - } - - - /** - * Sets a RFC 822 date as new date for the date object. - * Only RFC 822 compilant date strings are accepted. - * For example: Sat, 14 Feb 09 00:31:30 +0100 - * Returned is the new date object - * - * @param string|integer|\Zend\Date\Date $date RFC 822 to set - * @param string|\Zend\Locale\Locale $locale OPTIONAL Locale for parsing input - * @return \Zend\Date\Date Provides fluid interface - * @throws \Zend\Date\Exception - */ - public function setArpa($date, $locale = null) - { - return $this->_calcvalue('set', $date, 'arpa', self::RFC_822, $locale); - } - - - /** - * Adds a RFC 822 date to the date object. - * ARPA messages are used in emails or HTTP Headers. - * Only RFC 822 compilant date strings are accepted. - * For example: Sat, 14 Feb 09 00:31:30 +0100 - * Returned is the new date object - * - * @param string|integer|\Zend\Date\Date $date RFC 822 Date to add - * @param string|\Zend\Locale\Locale $locale OPTIONAL Locale for parsing input - * @return \Zend\Date\Date Provides fluid interface - * @throws \Zend\Date\Exception - */ - public function addArpa($date, $locale = null) - { - return $this->_calcvalue('add', $date, 'arpa', self::RFC_822, $locale); - } - - - /** - * Subtracts a RFC 822 date from the date object. - * ARPA messages are used in emails or HTTP Headers. - * Only RFC 822 compilant date strings are accepted. - * For example: Sat, 14 Feb 09 00:31:30 +0100 - * Returned is the new date object - * - * @param string|integer|\Zend\Date\Date $date RFC 822 Date to sub - * @param string|\Zend\Locale\Locale $locale OPTIONAL Locale for parsing input - * @return \Zend\Date\Date Provides fluid interface - * @throws \Zend\Date\Exception - */ - public function subArpa($date, $locale = null) - { - return $this->_calcvalue('sub', $date, 'arpa', self::RFC_822, $locale); - } - - - /** - * Compares a RFC 822 compilant date with the date object. - * ARPA messages are used in emails or HTTP Headers. - * Only RFC 822 compilant date strings are accepted. - * For example: Sat, 14 Feb 09 00:31:30 +0100 - * Returns if equal, earlier or later - * - * @param string|integer|\Zend\Date\Date $date RFC 822 Date to sub - * @param string|\Zend\Locale\Locale $locale OPTIONAL Locale for parsing input - * @return integer 0 = equal, 1 = later, -1 = earlier - * @throws \Zend\Date\Exception - */ - public function compareArpa($date, $locale = null) - { - return $this->_calcvalue('cmp', $date, 'arpa', self::RFC_822, $locale); - } - - - /** - * Check if location is supported - * - * @param array $location Locations array - * @return float Horizon - */ - private function _checkLocation($location) - { - if (!isset($location['longitude']) or !isset($location['latitude'])) { - throw new Exception\InvalidArgumentException('Location must include \'longitude\' and \'latitude\''); - } - if (($location['longitude'] > 180) or ($location['longitude'] < -180)) { - throw new Exception\InvalidArgumentException('Longitude must be between -180 and 180'); - } - if (($location['latitude'] > 90) or ($location['latitude'] < -90)) { - throw new Exception\InvalidArgumentException('Latitude must be between -90 and 90'); - } - - if (!isset($location['horizon'])){ - $location['horizon'] = 'effective'; - } - - switch ($location['horizon']) { - case 'civil' : - return -0.104528; - break; - case 'nautic' : - return -0.207912; - break; - case 'astronomic' : - return -0.309017; - break; - default : - return -0.0145439; - break; - } - } - - - /** - * Returns the time of sunrise for this date and a given location as new date object - * For a list of cities and correct locations use the class Zend_Date_Cities - * - * @param array $location Location of sunrise - * ['horizon'] -> civil, nautic, astronomical, effective (default) - * ['longitude'] -> longitude of location - * ['latitude'] -> latitude of location - * @return \Zend\Date\Date - * @throws \Zend\Date\Exception - */ - public function getSunrise($location) - { - $horizon = $this->_checkLocation($location); - $result = clone $this; - $result->set($this->calcSun($location, $horizon, true), self::TIMESTAMP); - return $result; - } - - - /** - * Returns the time of sunset for this date and a given location as new date object - * For a list of cities and correct locations use the class Zend_Date_Cities - * - * @param array $location Location of sunset - * ['horizon'] -> civil, nautic, astronomical, effective (default) - * ['longitude'] -> longitude of location - * ['latitude'] -> latitude of location - * @return \Zend\Date\Date - * @throws \Zend\Date\Exception - */ - public function getSunset($location) - { - $horizon = $this->_checkLocation($location); - $result = clone $this; - $result->set($this->calcSun($location, $horizon, false), self::TIMESTAMP); - return $result; - } - - - /** - * Returns an array with the sunset and sunrise dates for all horizon types - * For a list of cities and correct locations use the class Zend_Date_Cities - * - * @param array $location Location of suninfo - * ['horizon'] -> civil, nautic, astronomical, effective (default) - * ['longitude'] -> longitude of location - * ['latitude'] -> latitude of location - * @return array - [sunset|sunrise][effective|civil|nautic|astronomic] - * @throws \Zend\Date\Exception - */ - public function getSunInfo($location) - { - $suninfo = array(); - for ($i = 0; $i < 4; ++$i) { - switch ($i) { - case 0 : - $location['horizon'] = 'effective'; - break; - case 1 : - $location['horizon'] = 'civil'; - break; - case 2 : - $location['horizon'] = 'nautic'; - break; - case 3 : - $location['horizon'] = 'astronomic'; - break; - } - $horizon = $this->_checkLocation($location); - $result = clone $this; - $result->set($this->calcSun($location, $horizon, true), self::TIMESTAMP); - $suninfo['sunrise'][$location['horizon']] = $result; - $result = clone $this; - $result->set($this->calcSun($location, $horizon, false), self::TIMESTAMP); - $suninfo['sunset'][$location['horizon']] = $result; - } - return $suninfo; - } - - - /** - * Check a given year for leap year. - * - * @param integer|array|\Zend\Date\Date $year Year to check - * @return boolean - */ - public static function checkLeapYear($year) - { - if ($year instanceof Date) { - $year = (int) $year->toString(self::YEAR, 'iso'); - } - - if (is_array($year)) { - if (isset($year['year']) === true) { - $year = $year['year']; - } else { - throw new Exception\InvalidArgumentException("no year given in array"); - } - } - - if (!is_numeric($year)) { - throw new Exception\InvalidArgumentException("year ($year) has to be integer for checkLeapYear()"); - } - - return (bool) parent::isYearLeapYear($year); - } - - - /** - * Returns true, if the year is a leap year. - * - * @return boolean - */ - public function isLeapYear() - { - return self::checkLeapYear($this); - } - - - /** - * Returns if the set date is todays date - * - * @return boolean - */ - public function isToday() - { - $today = $this->date('Ymd', $this->_getTime()); - $day = $this->date('Ymd', $this->getUnixTimestamp()); - return ($today == $day); - } - - - /** - * Returns if the set date is yesterdays date - * - * @return boolean - */ - public function isYesterday() - { - list($year, $month, $day) = explode('-', $this->date('Y-m-d', $this->_getTime())); - // adjusts for leap days and DST changes that are timezone specific - $yesterday = $this->date('Ymd', $this->mktime(0, 0, 0, $month, $day -1, $year)); - $day = $this->date('Ymd', $this->getUnixTimestamp()); - return $day == $yesterday; - } - - - /** - * Returns if the set date is tomorrows date - * - * @return boolean - */ - public function isTomorrow() - { - list($year, $month, $day) = explode('-', $this->date('Y-m-d', $this->_getTime())); - // adjusts for leap days and DST changes that are timezone specific - $tomorrow = $this->date('Ymd', $this->mktime(0, 0, 0, $month, $day +1, $year)); - $day = $this->date('Ymd', $this->getUnixTimestamp()); - return $day == $tomorrow; - } - - /** - * Returns the actual date as new date object - * - * @param string|\Zend\Locale\Locale $locale OPTIONAL Locale for parsing input - * @return \Zend\Date\Date - */ - public static function now($locale = null) - { - return new Date(time(), self::TIMESTAMP, $locale); - } - - /** - * Calculate date details - * - * @param string $calc Calculation to make - * @param string|integer|array|\Zend\Date\Date $date Date or Part to calculate - * @param string $part Datepart for Calculation - * @param string|\Zend\Locale\Locale $locale Locale for parsing input - * @return integer|string new date - * @throws \Zend\Date\Exception - */ - private function _calcdetail($calc, $date, $type, $locale) - { - $old = false; - if (self::$_options['format_type'] == 'php') { - self::$_options['format_type'] = 'iso'; - $old = true; - } - - switch($calc) { - case 'set' : - $return = $this->set($date, $type, $locale); - break; - case 'add' : - $return = $this->add($date, $type, $locale); - break; - case 'sub' : - $return = $this->sub($date, $type, $locale); - break; - default : - $return = $this->compare($date, $type, $locale); - break; - } - - if ($old) { - self::$_options['format_type'] = 'php'; - } - - return $return; - } - - /** - * Internal calculation, returns the requested date type - * - * @param string $calc Calculation to make - * @param string|integer|\Zend\Date\Date $value Datevalue to calculate with, if null the actual value is taken - * @param string|\Zend\Locale\Locale $locale Locale for parsing input - * @return integer|\Zend\Date\Date new date - * @throws \Zend\Date\Exception - */ - private function _calcvalue($calc, $value, $type, $parameter, $locale) - { - if ($value === null) { - throw new Exception\InvalidArgumentException("parameter $type must be set, null is not allowed"); - } - - if ($locale === null) { - $locale = $this->getLocale(); - } - - if ($value instanceof Date) { - // extract value from object - $value = $value->toString($parameter, 'iso', $locale); - } else if (!is_array($value) && !is_numeric($value) && ($type != 'iso') && ($type != 'arpa')) { - throw new Exception\InvalidArgumentException("invalid $type ($value) operand"); - } - - $return = $this->_calcdetail($calc, $value, $parameter, $locale); - if ($calc != 'cmp') { - return $this; - } - return $return; - } - - - /** - * Returns only the year from the date object as new object. - * For example: 10.May.2000 10:30:00 -> 01.Jan.2000 00:00:00 - * - * @param string|\Zend\Locale\Locale $locale OPTIONAL Locale for parsing input - * @return \Zend\Date\Date - */ - public function getYear($locale = null) - { - if (self::$_options['format_type'] == 'php') { - $format = 'Y'; - } else { - $format = self::YEAR; - } - - return $this->copyPart($format, $locale); - } - - - /** - * Sets a new year - * If the year is between 0 and 69, 2000 will be set (2000-2069) - * If the year if between 70 and 99, 1999 will be set (1970-1999) - * 3 or 4 digit years are set as expected. If you need to set year 0-99 - * use set() instead. - * Returned is the new date object - * - * @param string|integer|array|\Zend\Date\Date $date Year to set - * @param string|\Zend\Locale\Locale $locale OPTIONAL Locale for parsing input - * @return \Zend\Date\Date Provides fluid interface - * @throws \Zend\Date\Exception - */ - public function setYear($year, $locale = null) - { - return $this->_calcvalue('set', $year, 'year', self::YEAR, $locale); - } - - - /** - * Adds the year to the existing date object - * If the year is between 0 and 69, 2000 will be added (2000-2069) - * If the year if between 70 and 99, 1999 will be added (1970-1999) - * 3 or 4 digit years are added as expected. If you need to add years from 0-99 - * use add() instead. - * Returned is the new date object - * - * @param string|integer|array|\Zend\Date\Date $date Year to add - * @param string|\Zend\Locale\Locale $locale OPTIONAL Locale for parsing input - * @return \Zend\Date\Date Provides fluid interface - * @throws \Zend\Date\Exception - */ - public function addYear($year, $locale = null) - { - return $this->_calcvalue('add', $year, 'year', self::YEAR, $locale); - } - - - /** - * Subs the year from the existing date object - * If the year is between 0 and 69, 2000 will be subtracted (2000-2069) - * If the year if between 70 and 99, 1999 will be subtracted (1970-1999) - * 3 or 4 digit years are subtracted as expected. If you need to subtract years from 0-99 - * use sub() instead. - * Returned is the new date object - * - * @param string|integer|array|\Zend\Date\Date $date Year to sub - * @param string|\Zend\Locale\Locale $locale OPTIONAL Locale for parsing input - * @return \Zend\Date\Date Provides fluid interface - * @throws \Zend\Date\Exception - */ - public function subYear($year, $locale = null) - { - return $this->_calcvalue('sub', $year, 'year', self::YEAR, $locale); - } - - - /** - * Compares the year with the existing date object, ignoring other date parts. - * For example: 10.03.2000 -> 15.02.2000 -> true - * Returns if equal, earlier or later - * - * @param string|integer|array|\Zend\Date\Date $year Year to compare - * @param string|\Zend\Locale\Locale $locale OPTIONAL Locale for parsing input - * @return integer 0 = equal, 1 = later, -1 = earlier - * @throws \Zend\Date\Exception - */ - public function compareYear($year, $locale = null) - { - return $this->_calcvalue('cmp', $year, 'year', self::YEAR, $locale); - } - - - /** - * Returns only the month from the date object as new object. - * For example: 10.May.2000 10:30:00 -> 01.May.1970 00:00:00 - * - * @param string|\Zend\Locale\Locale $locale OPTIONAL Locale for parsing input - * @return \Zend\Date\Date - */ - public function getMonth($locale = null) - { - if (self::$_options['format_type'] == 'php') { - $format = 'm'; - } else { - $format = self::MONTH; - } - - return $this->copyPart($format, $locale); - } - - - /** - * Returns the calculated month - * - * @param string $calc Calculation to make - * @param string|integer|array|\Zend\Date\Date $month Month to calculate with, if null the actual month is taken - * @param string|\Zend\Locale\Locale $locale Locale for parsing input - * @return integer|\Zend\Date\Date new time - * @throws \Zend\Date\Exception - */ - private function _month($calc, $month, $locale) - { - if ($month === null) { - throw new Exception\InvalidArgumentException('parameter $month must be set, null is not allowed'); - } - - if ($locale === null) { - $locale = $this->getLocale(); - } - - if ($month instanceof Date) { - // extract month from object - $found = $month->toString(self::MONTH_SHORT, 'iso', $locale); - } else { - if (is_numeric($month)) { - $found = $month; - } else if (is_array($month)) { - if (isset($month['month']) === true) { - $month = $month['month']; - } else { - throw new Exception\InvalidArgumentException("no month given in array"); - } - } else { - $monthlist = Cldr::getList($locale, 'month'); - $monthlist2 = Cldr::getList($locale, 'month', array('gregorian', 'format', 'abbreviated')); - - $monthlist = array_merge($monthlist, $monthlist2); - $found = 0; - $cnt = 0; - foreach ($monthlist as $key => $value) { - if (strtoupper($value) == strtoupper($month)) { - $found = ($key % 12) + 1; - break; - } - ++$cnt; - } - if ($found == 0) { - foreach ($monthlist2 as $key => $value) { - if (strtoupper(iconv_substr($value, 0, 1, 'UTF-8')) == strtoupper($month)) { - $found = $key + 1; - break; - } - ++$cnt; - } - } - if ($found == 0) { - throw new Exception\InvalidArgumentException("unknown month name ($month)"); - } - } - } - $return = $this->_calcdetail($calc, $found, self::MONTH_SHORT, $locale); - if ($calc != 'cmp') { - return $this; - } - return $return; - } - - - /** - * Sets a new month - * The month can be a number or a string. Setting months lower then 0 and greater then 12 - * will result in adding or subtracting the relevant year. (12 months equal one year) - * If a localized monthname is given it will be parsed with the default locale or the optional - * set locale. - * Returned is the new date object - * - * @param string|integer|array|\Zend\Date\Date $month Month to set - * @param string|\Zend\Locale\Locale $locale OPTIONAL Locale for parsing input - * @return \Zend\Date\Date Provides fluid interface - * @throws \Zend\Date\Exception - */ - public function setMonth($month, $locale = null) - { - return $this->_month('set', $month, $locale); - } - - - /** - * Adds months to the existing date object. - * The month can be a number or a string. Adding months lower then 0 and greater then 12 - * will result in adding or subtracting the relevant year. (12 months equal one year) - * If a localized monthname is given it will be parsed with the default locale or the optional - * set locale. - * Returned is the new date object - * - * @param string|integer|array|\Zend\Date\Date $month Month to add - * @param string|\Zend\Locale\Locale $locale OPTIONAL Locale for parsing input - * @return \Zend\Date\Date Provides fluid interface - * @throws \Zend\Date\Exception - */ - public function addMonth($month, $locale = null) - { - return $this->_month('add', $month, $locale); - } - - - /** - * Subtracts months from the existing date object. - * The month can be a number or a string. Subtracting months lower then 0 and greater then 12 - * will result in adding or subtracting the relevant year. (12 months equal one year) - * If a localized monthname is given it will be parsed with the default locale or the optional - * set locale. - * Returned is the new date object - * - * @param string|integer|array|\Zend\Date\Date $month Month to sub - * @param string|\Zend\Locale\Locale $locale OPTIONAL Locale for parsing input - * @return \Zend\Date\Date Provides fluid interface - * @throws \Zend\Date\Exception - */ - public function subMonth($month, $locale = null) - { - return $this->_month('sub', $month, $locale); - } - - - /** - * Compares the month with the existing date object, ignoring other date parts. - * For example: 10.03.2000 -> 15.03.1950 -> true - * Returns if equal, earlier or later - * - * @param string|integer|array|\Zend\Date\Date $month Month to compare - * @param string|\Zend\Locale\Locale $locale OPTIONAL Locale for parsing input - * @return integer 0 = equal, 1 = later, -1 = earlier - * @throws \Zend\Date\Exception - */ - public function compareMonth($month, $locale = null) - { - return $this->_month('cmp', $month, $locale); - } - - - /** - * Returns the day as new date object - * Example: 20.May.1986 -> 20.Jan.1970 00:00:00 - * - * @param string|\Zend\Locale\Locale $locale OPTIONAL Locale for parsing input - * @return \Zend\Date\Date - */ - public function getDay($locale = null) - { - return $this->copyPart(self::DAY_SHORT, $locale); - } - - - /** - * Returns the calculated day - * - * @param string $calc Type of calculation to make - * @param string|integer|\Zend\Date\Date $day Day to calculate, when null the actual day is calculated - * @param string|\Zend\Locale\Locale $locale Locale for parsing input - * @return \Zend\Date\Date|integer - */ - private function _day($calc, $day, $locale) - { - if ($day === null) { - throw new Exception\InvalidArgumentException('parameter $day must be set, null is not allowed'); - } - - if ($locale === null) { - $locale = $this->getLocale(); - } - - if ($day instanceof Date) { - $day = $day->toString(self::DAY_SHORT, 'iso', $locale); - } - - if (is_numeric($day)) { - $type = self::DAY_SHORT; - } else if (is_array($day)) { - if (isset($day['day']) === true) { - $day = $day['day']; - $type = self::WEEKDAY; - } else { - throw new Exception\InvalidArgumentException("no day given in array"); - } - } else { - switch (iconv_strlen($day, 'UTF-8')) { - case 1 : - $type = self::WEEKDAY_NARROW; - break; - case 2: - $type = self::WEEKDAY_NAME; - break; - case 3: - $type = self::WEEKDAY_SHORT; - break; - default: - $type = self::WEEKDAY; - break; - } - } - $return = $this->_calcdetail($calc, $day, $type, $locale); - if ($calc != 'cmp') { - return $this; - } - return $return; - } - - - /** - * Sets a new day - * The day can be a number or a string. Setting days lower then 0 or greater than the number of this months days - * will result in adding or subtracting the relevant month. - * If a localized dayname is given it will be parsed with the default locale or the optional - * set locale. - * Returned is the new date object - * Example: setDay('Montag', 'de_AT'); will set the monday of this week as day. - * - * @param string|integer|array|\Zend\Date\Date $month Day to set - * @param string|\Zend\Locale\Locale $locale OPTIONAL Locale for parsing input - * @return \Zend\Date\Date Provides fluid interface - * @throws \Zend\Date\Exception - */ - public function setDay($day, $locale = null) - { - return $this->_day('set', $day, $locale); - } - - - /** - * Adds days to the existing date object. - * The day can be a number or a string. Adding days lower then 0 or greater than the number of this months days - * will result in adding or subtracting the relevant month. - * If a localized dayname is given it will be parsed with the default locale or the optional - * set locale. - * - * @param string|integer|array|\Zend\Date\Date $month Day to add - * @param string|\Zend\Locale\Locale $locale OPTIONAL Locale for parsing input - * @return \Zend\Date\Date Provides fluid interface - * @throws \Zend\Date\Exception - */ - public function addDay($day, $locale = null) - { - return $this->_day('add', $day, $locale); - } - - - /** - * Subtracts days from the existing date object. - * The day can be a number or a string. Subtracting days lower then 0 or greater than the number of this months days - * will result in adding or subtracting the relevant month. - * If a localized dayname is given it will be parsed with the default locale or the optional - * set locale. - * - * @param string|integer|array|\Zend\Date\Date $month Day to sub - * @param string|\Zend\Locale\Locale $locale OPTIONAL Locale for parsing input - * @return \Zend\Date\Date Provides fluid interface - * @throws \Zend\Date\Exception - */ - public function subDay($day, $locale = null) - { - return $this->_day('sub', $day, $locale); - } - - - /** - * Compares the day with the existing date object, ignoring other date parts. - * For example: 'Monday', 'en' -> 08.Jan.2007 -> 0 - * Returns if equal, earlier or later - * - * @param string|integer|array|\Zend\Date\Date $day Day to compare - * @param string|\Zend\Locale\Locale $locale OPTIONAL Locale for parsing input - * @return integer 0 = equal, 1 = later, -1 = earlier - * @throws \Zend\Date\Exception - */ - public function compareDay($day, $locale = null) - { - return $this->_day('cmp', $day, $locale); - } - - - /** - * Returns the weekday as new date object - * Weekday is always from 1-7 - * Example: 09-Jan-2007 -> 2 = Tuesday -> 02-Jan-1970 (when 02.01.1970 is also Tuesday) - * - * @param string|\Zend\Locale\Locale $locale OPTIONAL Locale for parsing input - * @return \Zend\Date\Date - */ - public function getWeekday($locale = null) - { - if (self::$_options['format_type'] == 'php') { - $format = 'l'; - } else { - $format = self::WEEKDAY; - } - - return $this->copyPart($format, $locale); - } - - - /** - * Returns the calculated weekday - * - * @param string $calc Type of calculation to make - * @param string|integer|array|\Zend\Date\Date $weekday Weekday to calculate, when null the actual weekday is calculated - * @param string|\Zend\Locale\Locale $locale Locale for parsing input - * @return \Zend\Date\Date|integer - * @throws \Zend\Date\Exception - */ - private function _weekday($calc, $weekday, $locale) - { - if ($weekday === null) { - throw new Exception\InvalidArgumentException('parameter $weekday must be set, null is not allowed'); - } - - if ($locale === null) { - $locale = $this->getLocale(); - } - - if ($weekday instanceof Date) { - $weekday = $weekday->toString(self::WEEKDAY_8601, 'iso', $locale); - } - - if (is_numeric($weekday)) { - $type = self::WEEKDAY_8601; - } else if (is_array($weekday)) { - if (isset($weekday['weekday']) === true) { - $weekday = $weekday['weekday']; - $type = self::WEEKDAY; - } else { - throw new Exception\InvalidArgumentException("no weekday given in array"); - } - } else { - switch(iconv_strlen($weekday, 'UTF-8')) { - case 1: - $type = self::WEEKDAY_NARROW; - break; - case 2: - $type = self::WEEKDAY_NAME; - break; - case 3: - $type = self::WEEKDAY_SHORT; - break; - default: - $type = self::WEEKDAY; - break; - } - } - $return = $this->_calcdetail($calc, $weekday, $type, $locale); - if ($calc != 'cmp') { - return $this; - } - return $return; - } - - - /** - * Sets a new weekday - * The weekday can be a number or a string. If a localized weekday name is given, - * then it will be parsed as a date in $locale (defaults to the same locale as $this). - * Returned is the new date object. - * Example: setWeekday(3); will set the wednesday of this week as day. - * - * @param string|integer|array|\Zend\Date\Date $month Weekday to set - * @param string|\Zend\Locale\Locale $locale OPTIONAL Locale for parsing input - * @return \Zend\Date\Date Provides fluid interface - * @throws \Zend\Date\Exception - */ - public function setWeekday($weekday, $locale = null) - { - return $this->_weekday('set', $weekday, $locale); - } - - - /** - * Adds weekdays to the existing date object. - * The weekday can be a number or a string. - * If a localized dayname is given it will be parsed with the default locale or the optional - * set locale. - * Returned is the new date object - * Example: addWeekday(3); will add the difference of days from the begining of the month until - * wednesday. - * - * @param string|integer|array|\Zend\Date\Date $month Weekday to add - * @param string|\Zend\Locale\Locale $locale OPTIONAL Locale for parsing input - * @return \Zend\Date\Date Provides fluid interface - * @throws \Zend\Date\Exception - */ - public function addWeekday($weekday, $locale = null) - { - return $this->_weekday('add', $weekday, $locale); - } - - - /** - * Subtracts weekdays from the existing date object. - * The weekday can be a number or a string. - * If a localized dayname is given it will be parsed with the default locale or the optional - * set locale. - * Returned is the new date object - * Example: subWeekday(3); will subtract the difference of days from the begining of the month until - * wednesday. - * - * @param string|integer|array|\Zend\Date\Date $month Weekday to sub - * @param string|\Zend\Locale\Locale $locale OPTIONAL Locale for parsing input - * @return \Zend\Date\Date Provides fluid interface - * @throws \Zend\Date\Exception - */ - public function subWeekday($weekday, $locale = null) - { - return $this->_weekday('sub', $weekday, $locale); - } - - - /** - * Compares the weekday with the existing date object, ignoring other date parts. - * For example: 'Monday', 'en' -> 08.Jan.2007 -> 0 - * Returns if equal, earlier or later - * - * @param string|integer|array|\Zend\Date\Date $weekday Weekday to compare - * @param string|\Zend\Locale\Locale $locale OPTIONAL Locale for parsing input - * @return integer 0 = equal, 1 = later, -1 = earlier - * @throws \Zend\Date\Exception - */ - public function compareWeekday($weekday, $locale = null) - { - return $this->_weekday('cmp', $weekday, $locale); - } - - - /** - * Returns the day of year as new date object - * Example: 02.Feb.1986 10:00:00 -> 02.Feb.1970 00:00:00 - * - * @param string|\Zend\Locale\Locale $locale OPTIONAL Locale for parsing input - * @return \Zend\Date\Date - */ - public function getDayOfYear($locale = null) - { - if (self::$_options['format_type'] == 'php') { - $format = 'D'; - } else { - $format = self::DAY_OF_YEAR; - } - - return $this->copyPart($format, $locale); - } - - - /** - * Sets a new day of year - * The day of year is always a number. - * Returned is the new date object - * Example: 04.May.2004 -> setDayOfYear(10) -> 10.Jan.2004 - * - * @param string|integer|array|\Zend\Date\Date $day Day of Year to set - * @param string|\Zend\Locale\Locale $locale OPTIONAL Locale for parsing input - * @return \Zend\Date\Date Provides fluid interface - * @throws \Zend\Date\Exception - */ - public function setDayOfYear($day, $locale = null) - { - return $this->_calcvalue('set', $day, 'day of year', self::DAY_OF_YEAR, $locale); - } - - - /** - * Adds a day of year to the existing date object. - * The day of year is always a number. - * Returned is the new date object - * Example: addDayOfYear(10); will add 10 days to the existing date object. - * - * @param string|integer|array|\Zend\Date\Date $day Day of Year to add - * @param string|\Zend\Locale\Locale $locale OPTIONAL Locale for parsing input - * @return \Zend\Date\Date Provides fluid interface - * @throws \Zend\Date\Exception - */ - public function addDayOfYear($day, $locale = null) - { - return $this->_calcvalue('add', $day, 'day of year', self::DAY_OF_YEAR, $locale); - } - - - /** - * Subtracts a day of year from the existing date object. - * The day of year is always a number. - * Returned is the new date object - * Example: subDayOfYear(10); will subtract 10 days from the existing date object. - * - * @param string|integer|array|\Zend\Date\Date $day Day of Year to sub - * @param string|\Zend\Locale\Locale $locale OPTIONAL Locale for parsing input - * @return \Zend\Date\Date Provides fluid interface - * @throws \Zend\Date\Exception - */ - public function subDayOfYear($day, $locale = null) - { - return $this->_calcvalue('sub', $day, 'day of year', self::DAY_OF_YEAR, $locale); - } - - - /** - * Compares the day of year with the existing date object. - * For example: compareDayOfYear(33) -> 02.Feb.2007 -> 0 - * Returns if equal, earlier or later - * - * @param string|integer|array|\Zend\Date\Date $day Day of Year to compare - * @param string|\Zend\Locale\Locale $locale OPTIONAL Locale for parsing input - * @return integer 0 = equal, 1 = later, -1 = earlier - * @throws \Zend\Date\Exception - */ - public function compareDayOfYear($day, $locale = null) - { - return $this->_calcvalue('cmp', $day, 'day of year', self::DAY_OF_YEAR, $locale); - } - - - /** - * Returns the hour as new date object - * Example: 02.Feb.1986 10:30:25 -> 01.Jan.1970 10:00:00 - * - * @param string|\Zend\Locale\Locale $locale OPTIONAL Locale for parsing input - * @return \Zend\Date\Date - */ - public function getHour($locale = null) - { - return $this->copyPart(self::HOUR, $locale); - } - - - /** - * Sets a new hour - * The hour is always a number. - * Returned is the new date object - * Example: 04.May.1993 13:07:25 -> setHour(7); -> 04.May.1993 07:07:25 - * - * @param string|integer|array|\Zend\Date\Date $hour Hour to set - * @param string|\Zend\Locale\Locale $locale OPTIONAL Locale for parsing input - * @return \Zend\Date\Date Provides fluid interface - * @throws \Zend\Date\Exception - */ - public function setHour($hour, $locale = null) - { - return $this->_calcvalue('set', $hour, 'hour', self::HOUR_SHORT, $locale); - } - - - /** - * Adds hours to the existing date object. - * The hour is always a number. - * Returned is the new date object - * Example: 04.May.1993 13:07:25 -> addHour(12); -> 05.May.1993 01:07:25 - * - * @param string|integer|array|\Zend\Date\Date $hour Hour to add - * @param string|\Zend\Locale\Locale $locale OPTIONAL Locale for parsing input - * @return \Zend\Date\Date Provides fluid interface - * @throws \Zend\Date\Exception - */ - public function addHour($hour, $locale = null) - { - return $this->_calcvalue('add', $hour, 'hour', self::HOUR_SHORT, $locale); - } - - - /** - * Subtracts hours from the existing date object. - * The hour is always a number. - * Returned is the new date object - * Example: 04.May.1993 13:07:25 -> subHour(6); -> 05.May.1993 07:07:25 - * - * @param string|integer|array|\Zend\Date\Date $hour Hour to sub - * @param string|\Zend\Locale\Locale $locale OPTIONAL Locale for parsing input - * @return \Zend\Date\Date Provides fluid interface - * @throws \Zend\Date\Exception - */ - public function subHour($hour, $locale = null) - { - return $this->_calcvalue('sub', $hour, 'hour', self::HOUR_SHORT, $locale); - } - - - /** - * Compares the hour with the existing date object. - * For example: 10:30:25 -> compareHour(10) -> 0 - * Returns if equal, earlier or later - * - * @param string|integer|array|\Zend\Date\Date $hour Hour to compare - * @param string|\Zend\Locale\Locale $locale OPTIONAL Locale for parsing input - * @return integer 0 = equal, 1 = later, -1 = earlier - * @throws \Zend\Date\Exception - */ - public function compareHour($hour, $locale = null) - { - return $this->_calcvalue('cmp', $hour, 'hour', self::HOUR_SHORT, $locale); - } - - - /** - * Returns the minute as new date object - * Example: 02.Feb.1986 10:30:25 -> 01.Jan.1970 00:30:00 - * - * @param string|\Zend\Locale\Locale $locale OPTIONAL Locale for parsing input - * @return \Zend\Date\Date - */ - public function getMinute($locale = null) - { - if (self::$_options['format_type'] == 'php') { - $format = 'i'; - } else { - $format = self::MINUTE; - } - - return $this->copyPart($format, $locale); - } - - - /** - * Sets a new minute - * The minute is always a number. - * Returned is the new date object - * Example: 04.May.1993 13:07:25 -> setMinute(29); -> 04.May.1993 13:29:25 - * - * @param string|integer|array|\Zend\Date\Date $minute Minute to set - * @param string|\Zend\Locale\Locale $locale OPTIONAL Locale for parsing input - * @return \Zend\Date\Date Provides fluid interface - * @throws \Zend\Date\Exception - */ - public function setMinute($minute, $locale = null) - { - return $this->_calcvalue('set', $minute, 'minute', self::MINUTE_SHORT, $locale); - } - - - /** - * Adds minutes to the existing date object. - * The minute is always a number. - * Returned is the new date object - * Example: 04.May.1993 13:07:25 -> addMinute(65); -> 04.May.1993 13:12:25 - * - * @param string|integer|array|\Zend\Date\Date $minute Minute to add - * @param string|\Zend\Locale\Locale $locale OPTIONAL Locale for parsing input - * @return \Zend\Date\Date Provides fluid interface - * @throws \Zend\Date\Exception - */ - public function addMinute($minute, $locale = null) - { - return $this->_calcvalue('add', $minute, 'minute', self::MINUTE_SHORT, $locale); - } - - - /** - * Subtracts minutes from the existing date object. - * The minute is always a number. - * Returned is the new date object - * Example: 04.May.1993 13:07:25 -> subMinute(9); -> 04.May.1993 12:58:25 - * - * @param string|integer|array|\Zend\Date\Date $minute Minute to sub - * @param string|\Zend\Locale\Locale $locale OPTIONAL Locale for parsing input - * @return \Zend\Date\Date Provides fluid interface - * @throws \Zend\Date\Exception - */ - public function subMinute($minute, $locale = null) - { - return $this->_calcvalue('sub', $minute, 'minute', self::MINUTE_SHORT, $locale); - } - - - /** - * Compares the minute with the existing date object. - * For example: 10:30:25 -> compareMinute(30) -> 0 - * Returns if equal, earlier or later - * - * @param string|integer|array|\Zend\Date\Date $minute Hour to compare - * @param string|\Zend\Locale\Locale $locale OPTIONAL Locale for parsing input - * @return integer 0 = equal, 1 = later, -1 = earlier - * @throws \Zend\Date\Exception - */ - public function compareMinute($minute, $locale = null) - { - return $this->_calcvalue('cmp', $minute, 'minute', self::MINUTE_SHORT, $locale); - } - - - /** - * Returns the second as new date object - * Example: 02.Feb.1986 10:30:25 -> 01.Jan.1970 00:00:25 - * - * @param string|\Zend\Locale\Locale $locale OPTIONAL Locale for parsing input - * @return \Zend\Date\Date - */ - public function getSecond($locale = null) - { - if (self::$_options['format_type'] == 'php') { - $format = 's'; - } else { - $format = self::SECOND; - } - - return $this->copyPart($format, $locale); - } - - - /** - * Sets new seconds to the existing date object. - * The second is always a number. - * Returned is the new date object - * Example: 04.May.1993 13:07:25 -> setSecond(100); -> 04.May.1993 13:08:40 - * - * @param string|integer|array|\Zend\Date\Date $second Second to set - * @param string|\Zend\Locale\Locale $locale (Optional) Locale for parsing input - * @return \Zend\Date\Date Provides fluid interface - * @throws \Zend\Date\Exception - */ - public function setSecond($second, $locale = null) - { - return $this->_calcvalue('set', $second, 'second', self::SECOND_SHORT, $locale); - } - - - /** - * Adds seconds to the existing date object. - * The second is always a number. - * Returned is the new date object - * Example: 04.May.1993 13:07:25 -> addSecond(65); -> 04.May.1993 13:08:30 - * - * @param string|integer|array|\Zend\Date\Date $second Second to add - * @param string|\Zend\Locale\Locale $locale (Optional) Locale for parsing input - * @return \Zend\Date\Date Provides fluid interface - * @throws \Zend\Date\Exception - */ - public function addSecond($second, $locale = null) - { - return $this->_calcvalue('add', $second, 'second', self::SECOND_SHORT, $locale); - } - - - /** - * Subtracts seconds from the existing date object. - * The second is always a number. - * Returned is the new date object - * Example: 04.May.1993 13:07:25 -> subSecond(10); -> 04.May.1993 13:07:15 - * - * @param string|integer|array|\Zend\Date\Date $second Second to sub - * @param string|\Zend\Locale\Locale $locale (Optional) Locale for parsing input - * @return \Zend\Date\Date Provides fluid interface - * @throws \Zend\Date\Exception - */ - public function subSecond($second, $locale = null) - { - return $this->_calcvalue('sub', $second, 'second', self::SECOND_SHORT, $locale); - } - - - /** - * Compares the second with the existing date object. - * For example: 10:30:25 -> compareSecond(25) -> 0 - * Returns if equal, earlier or later - * - * @param string|integer|array|\Zend\Date\Date $second Second to compare - * @param string|\Zend\Locale\Locale $locale (Optional) Locale for parsing input - * @return integer 0 = equal, 1 = later, -1 = earlier - * @throws \Zend\Date\Exception - */ - public function compareSecond($second, $locale = null) - { - return $this->_calcvalue('cmp', $second, 'second', self::SECOND_SHORT, $locale); - } - - - /** - * Returns the precision for fractional seconds - * - * @return integer - */ - public function getFractionalPrecision() - { - return $this->_precision; - } - - - /** - * Sets a new precision for fractional seconds - * - * @param integer $precision Precision for the fractional datepart 3 = milliseconds - * @throws \Zend\Date\Exception - * @return \Zend\Date\Date Provides fluid interface - */ - public function setFractionalPrecision($precision) - { - if (!intval($precision) or ($precision < 0) or ($precision > 9)) { - throw new Exception\InvalidArgumentException("precision ($precision) must be a positive integer less than 10"); - } - - $this->_precision = (int) $precision; - if ($this->_precision < strlen($this->_fractional)) { - $this->_fractional = substr($this->_fractional, 0, $this->_precision); - } else { - $this->_fractional = str_pad($this->_fractional, $this->_precision, '0', STR_PAD_RIGHT); - } - - return $this; - } - - - /** - * Returns the milliseconds of the date object - * - * @return string - */ - public function getMilliSecond() - { - return $this->_fractional; - } - - - /** - * Sets new milliseconds for the date object - * Example: setMilliSecond(550, 2) -> equals +5 Sec +50 MilliSec - * - * @param integer|\Zend\Date\Date $milli (Optional) Millisecond to set, when null the actual millisecond is set - * @param integer $precision (Optional) Fraction precision of the given milliseconds - * @return \Zend\Date\Date Provides fluid interface - */ - public function setMilliSecond($milli = null, $precision = null) - { - if ($milli === null) { - list($milli, $time) = explode(" ", microtime()); - $milli = intval($milli); - $precision = 6; - } else if (!is_numeric($milli)) { - throw new Exception\InvalidArgumentException("invalid milli second ($milli) operand"); - } - - if ($precision === null) { - $precision = $this->_precision; - } - - if (!is_int($precision) || $precision < 1 || $precision > 9) { - throw new Exception\InvalidArgumentException("precision ($precision) must be a positive integer less than 10"); - } - - $this->_fractional = 0; - $this->addMilliSecond($milli, $precision); - return $this; - } - - - /** - * Adds milliseconds to the date object - * - * @param integer|\Zend\Date\Date $milli (Optional) Millisecond to add, when null the actual millisecond is added - * @param integer $precision (Optional) Fractional precision for the given milliseconds - * @return \Zend\Date\Date Provides fluid interface - */ - public function addMilliSecond($milli = null, $precision = null) - { - if ($milli === null) { - list($milli, $time) = explode(" ", microtime()); - $milli = intval($milli); - } else if (!is_numeric($milli)) { - throw new Exception\InvalidArgumentException("invalid milli second ($milli) operand"); - } - - if ($precision === null) { - $precision = strlen($milli); - if ($milli < 0) { - --$precision; - } - } - - if (!is_int($precision) || $precision < 1 || $precision > 9) { - throw new Exception\InvalidArgumentException("precision ($precision) must be a positive integer less than 10"); - } - - $this->_fractional += $milli; - - // Add/sub milliseconds + add/sub seconds - $max = pow(10, $this->_precision); - // Milli includes seconds - if ($this->_fractional >= $max) { - while ($this->_fractional >= $max) { - $this->addSecond(1); - $this->_fractional -= $max; - } - } - - if ($this->_fractional < 0) { - while ($this->_fractional < 0) { - $this->subSecond(1); - $this->_fractional += $max; - } - } - - if ($this->_precision > strlen($this->_fractional)) { - $this->_fractional = str_pad($this->_fractional, $this->_precision, '0', STR_PAD_LEFT); - } - - return $this; - } - - - /** - * Subtracts a millisecond - * - * @param integer|\Zend\Date\Date $milli (Optional) Millisecond to sub, when null the actual millisecond is subtracted - * @param integer $precision (Optional) Fractional precision for the given milliseconds - * @return \Zend\Date\Date Provides fluid interface - */ - public function subMilliSecond($milli = null, $precision = null) - { - $this->addMilliSecond(0 - $milli, $precision); - return $this; - } - - /** - * Compares only the millisecond part, returning the difference - * - * @param integer|\Zend\Date\Date $milli OPTIONAL Millisecond to compare, when null the actual millisecond is compared - * @param integer $precision OPTIONAL Fractional precision for the given milliseconds - * @throws \Zend\Date\Exception On invalid input - * @return integer 0 = equal, 1 = later, -1 = earlier - */ - public function compareMilliSecond($milli = null, $precision = null) - { - if ($milli === null) { - list($milli, $time) = explode(" ", microtime()); - $milli = intval($milli); - } else if (is_numeric($milli) === false) { - throw new Exception\InvalidArgumentException("invalid milli second ($milli) operand"); - } - - if ($precision === null) { - $precision = strlen($milli); - } else if (!is_int($precision) || $precision < 1 || $precision > 9) { - throw new Exception\InvalidArgumentException("precision ($precision) must be a positive integer less than 10"); - } - - if ($precision === 0) { - throw new Exception\InvalidArgumentException('precision is 0'); - } - - if ($precision != $this->_precision) { - if ($precision > $this->_precision) { - $diff = $precision - $this->_precision; - $milli = (int) ($milli / (10 * $diff)); - } else { - $diff = $this->_precision - $precision; - $milli = (int) ($milli * (10 * $diff)); - } - } - - $comp = $this->_fractional - $milli; - if ($comp < 0) { - return -1; - } else if ($comp > 0) { - return 1; - } - return 0; - } - - /** - * Returns the week as new date object using monday as begining of the week - * Example: 12.Jan.2007 -> 08.Jan.1970 00:00:00 - * - * @param string|\Zend\Locale\Locale $locale OPTIONAL Locale for parsing input - * @return \Zend\Date\Date - */ - public function getWeek($locale = null) - { - if (self::$_options['format_type'] == 'php') { - $format = 'W'; - } else { - $format = self::WEEK; - } - - return $this->copyPart($format, $locale); - } - - /** - * Sets a new week. The week is always a number. The day of week is not changed. - * Returned is the new date object - * Example: 09.Jan.2007 13:07:25 -> setWeek(1); -> 02.Jan.2007 13:07:25 - * - * @param string|integer|array|\Zend\Date\Date $week Week to set - * @param string|\Zend\Locale\Locale $locale OPTIONAL Locale for parsing input - * @return \Zend\Date\Date Provides fluid interface - * @throws \Zend\Date\Exception - */ - public function setWeek($week, $locale = null) - { - return $this->_calcvalue('set', $week, 'week', self::WEEK, $locale); - } - - /** - * Adds a week. The week is always a number. The day of week is not changed. - * Returned is the new date object - * Example: 09.Jan.2007 13:07:25 -> addWeek(1); -> 16.Jan.2007 13:07:25 - * - * @param string|integer|array|\Zend\Date\Date $week Week to add - * @param string|\Zend\Locale\Locale $locale OPTIONAL Locale for parsing input - * @return \Zend\Date\Date Provides fluid interface - * @throws \Zend\Date\Exception - */ - public function addWeek($week, $locale = null) - { - return $this->_calcvalue('add', $week, 'week', self::WEEK, $locale); - } - - /** - * Subtracts a week. The week is always a number. The day of week is not changed. - * Returned is the new date object - * Example: 09.Jan.2007 13:07:25 -> subWeek(1); -> 02.Jan.2007 13:07:25 - * - * @param string|integer|array|\Zend\Date\Date $week Week to sub - * @param string|\Zend\Locale\Locale $locale OPTIONAL Locale for parsing input - * @return \Zend\Date\Date Provides fluid interface - * @throws \Zend\Date\Exception - */ - public function subWeek($week, $locale = null) - { - return $this->_calcvalue('sub', $week, 'week', self::WEEK, $locale); - } - - /** - * Compares only the week part, returning the difference - * Returned is the new date object - * Returns if equal, earlier or later - * Example: 09.Jan.2007 13:07:25 -> compareWeek(2); -> 0 - * - * @param string|integer|array|\Zend\Date\Date $week Week to compare - * @param string|\Zend\Locale\Locale $locale OPTIONAL Locale for parsing input - * @return integer 0 = equal, 1 = later, -1 = earlier - */ - public function compareWeek($week, $locale = null) - { - return $this->_calcvalue('cmp', $week, 'week', self::WEEK, $locale); - } - - /** - * Sets a new standard locale for the date object. - * This locale will be used for all functions - * Returned is the really set locale. - * Example: 'de_XX' will be set to 'de' because 'de_XX' does not exist - * 'xx_YY' will be set to 'root' because 'xx' does not exist - * - * @param string|\Zend\Locale\Locale $locale (Optional) Locale for parsing input - * @throws \Zend\Date\Exception When the given locale does not exist - * @return \Zend\Date\Date Provides fluent interface - */ - public function setLocale($locale = null) - { - try { - $this->_locale = Locale::findLocale($locale); - } catch (\Zend\Locale\Exception\ExceptionInterface $e) { - throw new Exception\InvalidArgumentException($e->getMessage(), 0, $e); - } - - return $this; - } - - /** - * Returns the actual set locale - * - * @return string - */ - public function getLocale() - { - return $this->_locale; - } - - /** - * Checks if the given date is a real date or datepart. - * Returns false if a expected datepart is missing or a datepart exceeds its possible border. - * But the check will only be done for the expected dateparts which are given by format. - * If no format is given the standard dateformat for the actual locale is used. - * f.e. 30.February.2007 will return false if format is 'dd.MMMM.YYYY' - * - * @param string|array|\Zend\Date\Date $date Date to parse for correctness - * @param string $format (Optional) Format for parsing the date string - * @param string|\Zend\Locale\Locale $locale (Optional) Locale for parsing date parts - * @return boolean True when all date parts are correct - */ - public static function isDate($date, $format = null, $locale = null) - { - if (!is_string($date) - && !is_numeric($date) - && !($date instanceof Date) - && !is_array($date) - ) { - return false; - } - - if (($format !== null) - && ($format != 'ee') - && ($format != 'ss') - && ($format != 'GG') - && ($format != 'MM') - && ($format != 'EE') - && ($format != 'TT') - && Locale::isLocale($format) - ) { - $locale = $format; - $format = null; - } - - $locale = Locale::findLocale($locale); - - if ($format === null) { - $format = Format::getDateFormat($locale); - } elseif ((self::$_options['format_type'] == 'php') && !defined($format)) { - $format = Format::convertPhpToIsoFormat($format); - } - - $format = self::_getLocalizedToken($format, $locale); - if ($date instanceof Date) { - $parsed = $date->toArray(); - } elseif (!is_array($date)) { - try { - $parsed = Format::getDate($date, array( - 'locale' => $locale, - 'date_format' => $format, - 'format_type' => 'iso', - 'fix_date' => false, - )); - } catch (\Zend\Locale\Exception\ExceptionInterface $e) { - // Date can not be parsed - return false; - } - } else { - $parsed = $date; - } - - if (((strpos($format, 'Y') !== false) || (strpos($format, 'y') !== false)) - && !isset($parsed['year']) - ) { - // Year expected but not found - return false; - } - - if ((strpos($format, 'M') !== false) && (!isset($parsed['month']))) { - // Month expected but not found - return false; - } - - if ((strpos($format, 'd') !== false) && (!isset($parsed['day']))) { - // Day expected but not found - return false; - } - - if (((strpos($format, 'H') !== false) || (strpos($format, 'h') !== false)) - && !isset($parsed['hour']) - ) { - // Hour expected but not found - return false; - } - - if ((strpos($format, 'm') !== false) && (!isset($parsed['minute']))) { - // Minute expected but not found - return false; - } - - if ((strpos($format, 's') !== false) && (!isset($parsed['second']))) { - // Second expected but not found - return false; - } - - // Set not given dateparts - if (isset($parsed['hour']) === false) { - $parsed['hour'] = 12; - } - - if (isset($parsed['minute']) === false) { - $parsed['minute'] = 0; - } - - if (isset($parsed['second']) === false) { - $parsed['second'] = 0; - } - - if (isset($parsed['month']) === false) { - $parsed['month'] = 1; - } - - if (isset($parsed['day']) === false) { - $parsed['day'] = 1; - } - - if (isset($parsed['year']) === false) { - $parsed['year'] = 1970; - } - - if (self::isYearLeapYear($parsed['year'])) { - $parsed['year'] = 1972; - } else { - $parsed['year'] = 1971; - } - - $date = new self($parsed, null, $locale); - $timestamp = $date->mktime($parsed['hour'], $parsed['minute'], $parsed['second'], - $parsed['month'], $parsed['day'], $parsed['year']); - - if ($parsed['year'] != $date->date('Y', $timestamp)) { - // Given year differs from parsed year - return false; - } - - if ($parsed['month'] != $date->date('n', $timestamp)) { - // Given month differs from parsed month - return false; - } - - if ($parsed['day'] != $date->date('j', $timestamp)) { - // Given day differs from parsed day - return false; - } - - if ($parsed['hour'] != $date->date('G', $timestamp)) { - // Given hour differs from parsed hour - return false; - } - - if ($parsed['minute'] != $date->date('i', $timestamp)) { - // Given minute differs from parsed minute - return false; - } - - if ($parsed['second'] != $date->date('s', $timestamp)) { - // Given second differs from parsed second - return false; - } - - return true; - } - - /** - * Returns the ISO Token for all localized constants - * - * @param string $token Token to normalize - * @param string $locale Locale to search - * @return string - */ - protected static function _getLocalizedToken($token, $locale) - { - switch($token) { - case self::ISO_8601 : - return "yyyy-MM-ddThh:mm:ss"; - break; - case self::RFC_2822 : - return "EEE, dd MMM yyyy HH:mm:ss"; - break; - case self::DATES : - return Cldr::getContent($locale, 'date'); - break; - case self::DATE_FULL : - return Cldr::getContent($locale, 'date', array('gregorian', 'full')); - break; - case self::DATE_LONG : - return Cldr::getContent($locale, 'date', array('gregorian', 'long')); - break; - case self::DATE_MEDIUM : - return Cldr::getContent($locale, 'date', array('gregorian', 'medium')); - break; - case self::DATE_SHORT : - return Cldr::getContent($locale, 'date', array('gregorian', 'short')); - break; - case self::TIMES : - return Cldr::getContent($locale, 'time'); - break; - case self::TIME_FULL : - return Cldr::getContent($locale, 'time', array('gregorian', 'full')); - break; - case self::TIME_LONG : - return Cldr::getContent($locale, 'time', array('gregorian', 'long')); - break; - case self::TIME_MEDIUM : - return Cldr::getContent($locale, 'time', array('gregorian', 'medium')); - break; - case self::TIME_SHORT : - return Cldr::getContent($locale, 'time', array('gregorian', 'short')); - break; - case self::DATETIME : - return Cldr::getContent($locale, 'datetime'); - break; - case self::DATETIME_FULL : - return Cldr::getContent($locale, 'datetime', array('gregorian', 'full')); - break; - case self::DATETIME_LONG : - return Cldr::getContent($locale, 'datetime', array('gregorian', 'long')); - break; - case self::DATETIME_MEDIUM : - return Cldr::getContent($locale, 'datetime', array('gregorian', 'medium')); - break; - case self::DATETIME_SHORT : - return Cldr::getContent($locale, 'datetime', array('gregorian', 'short')); - break; - case self::ATOM : - case self::RFC_3339 : - case self::W3C : - return "yyyy-MM-DD HH:mm:ss"; - break; - case self::COOKIE : - case self::RFC_850 : - return "EEEE, dd-MM-yyyy HH:mm:ss"; - break; - case self::RFC_822 : - case self::RFC_1036 : - case self::RFC_1123 : - case self::RSS : - return "EEE, dd MM yyyy HH:mm:ss"; - break; - } - - return $token; - } -} diff --git a/library/Zend/Date/DateObject.php b/library/Zend/Date/DateObject.php deleted file mode 100644 index 67d44aae6b9..00000000000 --- a/library/Zend/Date/DateObject.php +++ /dev/null @@ -1,1061 +0,0 @@ - 0, 1960 => -315619200, 1950 => -631152000, - 1940 => -946771200, 1930 => -1262304000, 1920 => -1577923200, - 1910 => -1893456000, 1900 => -2208988800, 1890 => -2524521600, - 1880 => -2840140800, 1870 => -3155673600, 1860 => -3471292800, - 1850 => -3786825600, 1840 => -4102444800, 1830 => -4417977600, - 1820 => -4733596800, 1810 => -5049129600, 1800 => -5364662400, - 1790 => -5680195200, 1780 => -5995814400, 1770 => -6311347200, - 1760 => -6626966400, 1750 => -6942499200, 1740 => -7258118400, - 1730 => -7573651200, 1720 => -7889270400, 1710 => -8204803200, - 1700 => -8520336000, 1690 => -8835868800, 1680 => -9151488000, - 1670 => -9467020800, 1660 => -9782640000, 1650 => -10098172800, - 1640 => -10413792000, 1630 => -10729324800, 1620 => -11044944000, - 1610 => -11360476800, 1600 => -11676096000); - - /** - * Set this object to have a new UNIX timestamp. - * - * @param string|integer $timestamp OPTIONAL timestamp; defaults to local time using time() - * @return string|integer old timestamp - * @throws \Zend\Date\Exception - */ - protected function setUnixTimestamp($timestamp = null) - { - $old = $this->_unixTimestamp; - - if (is_numeric($timestamp)) { - $this->_unixTimestamp = $timestamp; - } else if ($timestamp === null) { - $this->_unixTimestamp = time(); - } else { - throw new Exception\InvalidArgumentException('\'' . $timestamp . '\' is not a valid UNIX timestamp'); - } - - return $old; - } - - /** - * Returns this object's UNIX timestamp - * A timestamp greater then the integer range will be returned as string - * This function does not return the timestamp as object. Use copy() instead. - * - * @return integer|string timestamp - */ - protected function getUnixTimestamp() - { - if ($this->_unixTimestamp === intval($this->_unixTimestamp)) { - return (int) $this->_unixTimestamp; - } else { - return (string) $this->_unixTimestamp; - } - } - - /** - * Internal function. - * Returns time(). This method exists to allow unit tests to work-around methods that might otherwise - * be hard-coded to use time(). For example, this makes it possible to test isYesterday() in Date.php. - * - * @param integer $sync OPTIONAL time syncronisation value - * @return integer timestamp - */ - protected function _getTime($sync = null) - { - if ($sync !== null) { - $this->_syncronised = round($sync); - } - return (time() + $this->_syncronised); - } - - /** - * Internal mktime function used by Zend_Date. - * The timestamp returned by mktime() can exceed the precision of traditional UNIX timestamps, - * by allowing PHP to auto-convert to using a float value. - * - * Returns a timestamp relative to 1970/01/01 00:00:00 GMT/UTC. - * DST (Summer/Winter) is depriciated since php 5.1.0. - * Year has to be 4 digits otherwise it would be recognised as - * year 70 AD instead of 1970 AD as expected !! - * - * @param integer $hour - * @param integer $minute - * @param integer $second - * @param integer $month - * @param integer $day - * @param integer $year - * @param boolean $gmt OPTIONAL true = other arguments are for UTC time, false = arguments are for local time/date - * @return integer|float timestamp (number of seconds elapsed relative to 1970/01/01 00:00:00 GMT/UTC) - */ - protected function mktime($hour, $minute, $second, $month, $day, $year, $gmt = false) - { - // complete date but in 32bit timestamp - use PHP internal - if ((1901 < $year) and ($year < 2038)) { - - $oldzone = @date_default_timezone_get(); - // Timezone also includes DST settings, therefor substracting the GMT offset is not enough - // We have to set the correct timezone to get the right value - if (($this->_timezone != $oldzone) and ($gmt === false)) { - date_default_timezone_set($this->_timezone); - } - $result = ($gmt) ? @gmmktime($hour, $minute, $second, $month, $day, $year) - : @mktime($hour, $minute, $second, $month, $day, $year); - date_default_timezone_set($oldzone); - - return $result; - } - - if ($gmt !== true) { - $second += $this->_offset; - } - - if (isset(self::$_cache)) { - $id = strtr('Zend_DateObject_mkTime_' . $this->_offset . '_' . $year.$month.$day.'_'.$hour.$minute.$second . '_'.(int)$gmt, '-','_'); - $rs = self::$_cache->getItem($id, $success); - if ($success) { - return $rs; - } - } - - // date to integer - $day = intval($day); - $month = intval($month); - $year = intval($year); - - // correct months > 12 and months < 1 - if ($month > 12) { - $overlap = floor($month / 12); - $year += $overlap; - $month -= $overlap * 12; - } else { - $overlap = ceil((1 - $month) / 12); - $year -= $overlap; - $month += $overlap * 12; - } - - $date = 0; - if ($year >= 1970) { - - // Date is after UNIX epoch - // go through leapyears - // add months from latest given year - for ($count = 1970; $count <= $year; $count++) { - - $leapyear = self::isYearLeapYear($count); - if ($count < $year) { - - $date += 365; - if ($leapyear === true) { - $date++; - } - - } else { - - for ($mcount = 0; $mcount < ($month - 1); $mcount++) { - $date += self::$_monthTable[$mcount]; - if (($leapyear === true) and ($mcount == 1)) { - $date++; - } - - } - } - } - - $date += $day - 1; - $date = (($date * 86400) + ($hour * 3600) + ($minute * 60) + $second); - } else { - - // Date is before UNIX epoch - // go through leapyears - // add months from latest given year - for ($count = 1969; $count >= $year; $count--) { - - $leapyear = self::isYearLeapYear($count); - if ($count > $year) - { - $date += 365; - if ($leapyear === true) - $date++; - } else { - - for ($mcount = 11; $mcount > ($month - 1); $mcount--) { - $date += self::$_monthTable[$mcount]; - if (($leapyear === true) and ($mcount == 2)) { - $date++; - } - - } - } - } - - $date += (self::$_monthTable[$month - 1] - $day); - $date = -(($date * 86400) + (86400 - (($hour * 3600) + ($minute * 60) + $second))); - - // gregorian correction for 5.Oct.1582 - if ($date < -12220185600) { - $date += 864000; - } else if ($date < -12219321600) { - $date = -12219321600; - } - } - - if (isset(self::$_cache)) { - self::$_cache->setItem($id, $date); - } - - return $date; - } - - /** - * Returns true, if given $year is a leap year. - * - * @param integer $year - * @return boolean true, if year is leap year - */ - protected static function isYearLeapYear($year) - { - // all leapyears can be divided through 4 - if (($year % 4) != 0) { - return false; - } - - // all leapyears can be divided through 400 - if ($year % 400 == 0) { - return true; - } else if (($year > 1582) and ($year % 100 == 0)) { - return false; - } - - return true; - } - - /** - * Internal mktime function used by Zend_Date for handling 64bit timestamps. - * - * Returns a formatted date for a given timestamp. - * - * @param string $format format for output - * @param mixed $timestamp - * @param boolean $gmt OPTIONAL true = other arguments are for UTC time, false = arguments are for local time/date - * @return string - */ - protected function date($format, $timestamp = null, $gmt = false) - { - $oldzone = @date_default_timezone_get(); - if ($this->_timezone != $oldzone) { - date_default_timezone_set($this->_timezone); - } - - if ($timestamp === null) { - $result = ($gmt) ? @gmdate($format) : @date($format); - date_default_timezone_set($oldzone); - return $result; - } - - if (abs($timestamp) <= 0x7FFFFFFF) { - $result = ($gmt) ? @gmdate($format, $timestamp) : @date($format, $timestamp); - date_default_timezone_set($oldzone); - return $result; - } - - $jump = false; - $origstamp = $timestamp; - if (isset(self::$_cache)) { - $idstamp = strtr('Zend_DateObject_date_' . $this->_offset . '_'. $timestamp . '_'.(int)$gmt, '-','_'); - $result2 = self::$_cache->getItem($idstamp, $success); - if ($success) { - $timestamp = $result2; - $jump = true; - } - } - - // check on false or null alone fails - if (empty($gmt) and empty($jump)) { - $tempstamp = $timestamp; - if ($tempstamp > 0) { - while (abs($tempstamp) > 0x7FFFFFFF) { - $tempstamp -= (86400 * 23376); - } - - $dst = date("I", $tempstamp); - if ($dst === 1) { - $timestamp += 3600; - } - - $temp = date('Z', $tempstamp); - $timestamp += $temp; - } - - if (isset(self::$_cache)) { - self::$_cache->setItem($idstamp, $timestamp); - } - } - - if (($timestamp < 0) and ($gmt !== true)) { - $timestamp -= $this->_offset; - } - - date_default_timezone_set($oldzone); - $date = $this->getDateParts($timestamp, true); - $length = strlen($format); - $output = ''; - - for ($i = 0; $i < $length; $i++) { - switch($format[$i]) { - // day formats - case 'd': // day of month, 2 digits, with leading zero, 01 - 31 - $output .= (($date['mday'] < 10) ? '0' . $date['mday'] : $date['mday']); - break; - - case 'D': // day of week, 3 letters, Mon - Sun - $output .= date('D', 86400 * (3 + self::dayOfWeek($date['year'], $date['mon'], $date['mday']))); - break; - - case 'j': // day of month, without leading zero, 1 - 31 - $output .= $date['mday']; - break; - - case 'l': // day of week, full string name, Sunday - Saturday - $output .= date('l', 86400 * (3 + self::dayOfWeek($date['year'], $date['mon'], $date['mday']))); - break; - - case 'N': // ISO 8601 numeric day of week, 1 - 7 - $day = self::dayOfWeek($date['year'], $date['mon'], $date['mday']); - if ($day == 0) { - $day = 7; - } - $output .= $day; - break; - - case 'S': // english suffix for day of month, st nd rd th - if (($date['mday'] % 10) == 1) { - $output .= 'st'; - } else if ((($date['mday'] % 10) == 2) and ($date['mday'] != 12)) { - $output .= 'nd'; - } else if (($date['mday'] % 10) == 3) { - $output .= 'rd'; - } else { - $output .= 'th'; - } - break; - - case 'w': // numeric day of week, 0 - 6 - $output .= self::dayOfWeek($date['year'], $date['mon'], $date['mday']); - break; - - case 'z': // day of year, 0 - 365 - $output .= $date['yday']; - break; - - - // week formats - case 'W': // ISO 8601, week number of year - $output .= $this->weekNumber($date['year'], $date['mon'], $date['mday']); - break; - - - // month formats - case 'F': // string month name, january - december - $output .= date('F', mktime(0, 0, 0, $date['mon'], 2, 1971)); - break; - - case 'm': // number of month, with leading zeros, 01 - 12 - $output .= (($date['mon'] < 10) ? '0' . $date['mon'] : $date['mon']); - break; - - case 'M': // 3 letter month name, Jan - Dec - $output .= date('M',mktime(0, 0, 0, $date['mon'], 2, 1971)); - break; - - case 'n': // number of month, without leading zeros, 1 - 12 - $output .= $date['mon']; - break; - - case 't': // number of day in month - $output .= self::$_monthTable[$date['mon'] - 1]; - break; - - - // year formats - case 'L': // is leap year ? - $output .= (self::isYearLeapYear($date['year'])) ? '1' : '0'; - break; - - case 'o': // ISO 8601 year number - $week = $this->weekNumber($date['year'], $date['mon'], $date['mday']); - if (($week > 50) and ($date['mon'] == 1)) { - $output .= ($date['year'] - 1); - } else { - $output .= $date['year']; - } - break; - - case 'Y': // year number, 4 digits - $output .= $date['year']; - break; - - case 'y': // year number, 2 digits - $output .= substr($date['year'], strlen($date['year']) - 2, 2); - break; - - - // time formats - case 'a': // lower case am/pm - $output .= (($date['hours'] >= 12) ? 'pm' : 'am'); - break; - - case 'A': // upper case am/pm - $output .= (($date['hours'] >= 12) ? 'PM' : 'AM'); - break; - - case 'B': // swatch internet time - $dayseconds = ($date['hours'] * 3600) + ($date['minutes'] * 60) + $date['seconds']; - if ($gmt === true) { - $dayseconds += 3600; - } - $output .= (int) (($dayseconds % 86400) / 86.4); - break; - - case 'g': // hours without leading zeros, 12h format - if ($date['hours'] > 12) { - $hour = $date['hours'] - 12; - } else { - if ($date['hours'] == 0) { - $hour = '12'; - } else { - $hour = $date['hours']; - } - } - $output .= $hour; - break; - - case 'G': // hours without leading zeros, 24h format - $output .= $date['hours']; - break; - - case 'h': // hours with leading zeros, 12h format - if ($date['hours'] > 12) { - $hour = $date['hours'] - 12; - } else { - if ($date['hours'] == 0) { - $hour = '12'; - } else { - $hour = $date['hours']; - } - } - $output .= (($hour < 10) ? '0'.$hour : $hour); - break; - - case 'H': // hours with leading zeros, 24h format - $output .= (($date['hours'] < 10) ? '0' . $date['hours'] : $date['hours']); - break; - - case 'i': // minutes with leading zeros - $output .= (($date['minutes'] < 10) ? '0' . $date['minutes'] : $date['minutes']); - break; - - case 's': // seconds with leading zeros - $output .= (($date['seconds'] < 10) ? '0' . $date['seconds'] : $date['seconds']); - break; - - - // timezone formats - case 'e': // timezone identifier - if ($gmt === true) { - $output .= gmdate('e', mktime($date['hours'], $date['minutes'], $date['seconds'], - $date['mon'], $date['mday'], 2000)); - } else { - $output .= date('e', mktime($date['hours'], $date['minutes'], $date['seconds'], - $date['mon'], $date['mday'], 2000)); - } - break; - - case 'I': // daylight saving time or not - if ($gmt === true) { - $output .= gmdate('I', mktime($date['hours'], $date['minutes'], $date['seconds'], - $date['mon'], $date['mday'], 2000)); - } else { - $output .= date('I', mktime($date['hours'], $date['minutes'], $date['seconds'], - $date['mon'], $date['mday'], 2000)); - } - break; - - case 'O': // difference to GMT in hours - $gmtstr = ($gmt === true) ? 0 : $this->getGmtOffset(); - $output .= sprintf('%s%04d', ($gmtstr <= 0) ? '+' : '-', abs($gmtstr) / 36); - break; - - case 'P': // difference to GMT with colon - $gmtstr = ($gmt === true) ? 0 : $this->getGmtOffset(); - $gmtstr = sprintf('%s%04d', ($gmtstr <= 0) ? '+' : '-', abs($gmtstr) / 36); - $output = $output . substr($gmtstr, 0, 3) . ':' . substr($gmtstr, 3); - break; - - case 'T': // timezone settings - if ($gmt === true) { - $output .= gmdate('T', mktime($date['hours'], $date['minutes'], $date['seconds'], - $date['mon'], $date['mday'], 2000)); - } else { - $output .= date('T', mktime($date['hours'], $date['minutes'], $date['seconds'], - $date['mon'], $date['mday'], 2000)); - } - break; - - case 'Z': // timezone offset in seconds - $output .= ($gmt === true) ? 0 : -$this->getGmtOffset(); - break; - - - // complete time formats - case 'c': // ISO 8601 date format - $difference = $this->getGmtOffset(); - $difference = sprintf('%s%04d', ($difference <= 0) ? '+' : '-', abs($difference) / 36); - $difference = substr($difference, 0, 3) . ':' . substr($difference, 3); - $output .= $date['year'] . '-' - . (($date['mon'] < 10) ? '0' . $date['mon'] : $date['mon']) . '-' - . (($date['mday'] < 10) ? '0' . $date['mday'] : $date['mday']) . 'T' - . (($date['hours'] < 10) ? '0' . $date['hours'] : $date['hours']) . ':' - . (($date['minutes'] < 10) ? '0' . $date['minutes'] : $date['minutes']) . ':' - . (($date['seconds'] < 10) ? '0' . $date['seconds'] : $date['seconds']) - . $difference; - break; - - case 'r': // RFC 2822 date format - $difference = $this->getGmtOffset(); - $difference = sprintf('%s%04d', ($difference <= 0) ? '+' : '-', abs($difference) / 36); - $output .= gmdate('D', 86400 * (3 + self::dayOfWeek($date['year'], $date['mon'], $date['mday']))) . ', ' - . (($date['mday'] < 10) ? '0' . $date['mday'] : $date['mday']) . ' ' - . date('M', mktime(0, 0, 0, $date['mon'], 2, 1971)) . ' ' - . $date['year'] . ' ' - . (($date['hours'] < 10) ? '0' . $date['hours'] : $date['hours']) . ':' - . (($date['minutes'] < 10) ? '0' . $date['minutes'] : $date['minutes']) . ':' - . (($date['seconds'] < 10) ? '0' . $date['seconds'] : $date['seconds']) . ' ' - . $difference; - break; - - case 'U': // Unix timestamp - $output .= $origstamp; - break; - - - // special formats - case "\\": // next letter to print with no format - $i++; - if ($i < $length) { - $output .= $format[$i]; - } - break; - - default: // letter is no format so add it direct - $output .= $format[$i]; - break; - } - } - - return (string) $output; - } - - /** - * Returns the day of week for a Gregorian calendar date. - * 0 = sunday, 6 = saturday - * - * @param integer $year - * @param integer $month - * @param integer $day - * @return integer dayOfWeek - */ - protected static function dayOfWeek($year, $month, $day) - { - if ((1901 < $year) and ($year < 2038)) { - return (int) date('w', mktime(0, 0, 0, $month, $day, $year)); - } - - // gregorian correction - $correction = 0; - if (($year < 1582) or (($year == 1582) and (($month < 10) or (($month == 10) && ($day < 15))))) { - $correction = 3; - } - - if ($month > 2) { - $month -= 2; - } else { - $month += 10; - $year--; - } - - $day = floor((13 * $month - 1) / 5) + $day + ($year % 100) + floor(($year % 100) / 4); - $day += floor(($year / 100) / 4) - 2 * floor($year / 100) + 77 + $correction; - - return (int) ($day - 7 * floor($day / 7)); - } - - /** - * Internal getDateParts function for handling 64bit timestamps, similar to: - * http://www.php.net/getdate - * - * Returns an array of date parts for $timestamp, relative to 1970/01/01 00:00:00 GMT/UTC. - * - * $fast specifies ALL date parts should be returned (slower) - * Default is false, and excludes $dayofweek, weekday, month and timestamp from parts returned. - * - * @param mixed $timestamp - * @param boolean $fast OPTIONAL defaults to fast (false), resulting in fewer date parts - * @return array - */ - protected function getDateParts($timestamp = null, $fast = null) - { - - // actual timestamp - if (!is_numeric($timestamp)) { - return getdate(); - } - - // 32bit timestamp - if (abs($timestamp) <= 0x7FFFFFFF) { - return @getdate((int) $timestamp); - } - - if (isset(self::$_cache)) { - $id = strtr('Zend_DateObject_getDateParts_' . $timestamp.'_'.(int)$fast, '-','_'); - $rs = self::$_cache->getItem($id, $success); - if ($success) { - return $rs; - } - } - - $otimestamp = $timestamp; - $numday = 0; - $month = 0; - // gregorian correction - if ($timestamp < -12219321600) { - $timestamp -= 864000; - } - - // timestamp lower 0 - if ($timestamp < 0) { - $sec = 0; - $act = 1970; - - // iterate through 10 years table, increasing speed - foreach(self::$_yearTable as $year => $seconds) { - if ($timestamp >= $seconds) { - $i = $act; - break; - } - $sec = $seconds; - $act = $year; - } - - $timestamp -= $sec; - if (!isset($i)) { - $i = $act; - } - - // iterate the max last 10 years - do { - --$i; - $day = $timestamp; - - $timestamp += 31536000; - $leapyear = self::isYearLeapYear($i); - if ($leapyear === true) { - $timestamp += 86400; - } - - if ($timestamp >= 0) { - $year = $i; - break; - } - } while ($timestamp < 0); - - $secondsPerYear = 86400 * ($leapyear ? 366 : 365) + $day; - - $timestamp = $day; - // iterate through months - for ($i = 12; --$i >= 0;) { - $day = $timestamp; - - $timestamp += self::$_monthTable[$i] * 86400; - if (($leapyear === true) and ($i == 1)) { - $timestamp += 86400; - } - - if ($timestamp >= 0) { - $month = $i; - $numday = self::$_monthTable[$i]; - if (($leapyear === true) and ($i == 1)) { - ++$numday; - } - break; - } - } - - $timestamp = $day; - $numberdays = $numday + ceil(($timestamp + 1) / 86400); - - $timestamp += ($numday - $numberdays + 1) * 86400; - $hours = floor($timestamp / 3600); - } else { - - // iterate through years - for ($i = 1970;;$i++) { - $day = $timestamp; - - $timestamp -= 31536000; - $leapyear = self::isYearLeapYear($i); - if ($leapyear === true) { - $timestamp -= 86400; - } - - if ($timestamp < 0) { - $year = $i; - break; - } - } - - $secondsPerYear = $day; - - $timestamp = $day; - // iterate through months - for ($i = 0; $i <= 11; $i++) { - $day = $timestamp; - $timestamp -= self::$_monthTable[$i] * 86400; - - if (($leapyear === true) and ($i == 1)) { - $timestamp -= 86400; - } - - if ($timestamp < 0) { - $month = $i; - $numday = self::$_monthTable[$i]; - if (($leapyear === true) and ($i == 1)) { - ++$numday; - } - break; - } - } - - $timestamp = $day; - $numberdays = ceil(($timestamp + 1) / 86400); - $timestamp = $timestamp - ($numberdays - 1) * 86400; - $hours = floor($timestamp / 3600); - } - - $timestamp -= $hours * 3600; - - $month += 1; - $minutes = floor($timestamp / 60); - $seconds = $timestamp - $minutes * 60; - - if ($fast === true) { - $array = array( - 'seconds' => $seconds, - 'minutes' => $minutes, - 'hours' => $hours, - 'mday' => $numberdays, - 'mon' => $month, - 'year' => $year, - 'yday' => floor($secondsPerYear / 86400), - ); - } else { - - $dayofweek = self::dayOfWeek($year, $month, $numberdays); - $array = array( - 'seconds' => $seconds, - 'minutes' => $minutes, - 'hours' => $hours, - 'mday' => $numberdays, - 'wday' => $dayofweek, - 'mon' => $month, - 'year' => $year, - 'yday' => floor($secondsPerYear / 86400), - 'weekday' => gmdate('l', 86400 * (3 + $dayofweek)), - 'month' => gmdate('F', mktime(0, 0, 0, $month, 1, 1971)), - 0 => $otimestamp - ); - } - - if (isset(self::$_cache)) { - self::$_cache->setItem($id, $array); - } - - return $array; - } - - /** - * Internal getWeekNumber function for handling 64bit timestamps - * - * Returns the ISO 8601 week number of a given date - * - * @param integer $year - * @param integer $month - * @param integer $day - * @return integer - */ - protected function weekNumber($year, $month, $day) - { - if ((1901 < $year) and ($year < 2038)) { - return (int) date('W', mktime(0, 0, 0, $month, $day, $year)); - } - - $dayofweek = self::dayOfWeek($year, $month, $day); - $firstday = self::dayOfWeek($year, 1, 1); - if (($month == 1) and (($firstday < 1) or ($firstday > 4)) and ($day < 4)) { - $firstday = self::dayOfWeek($year - 1, 1, 1); - $month = 12; - $day = 31; - - } else if (($month == 12) and ((self::dayOfWeek($year + 1, 1, 1) < 5) and - (self::dayOfWeek($year + 1, 1, 1) > 0))) { - return 1; - } - - return intval (((self::dayOfWeek($year, 1, 1) < 5) and (self::dayOfWeek($year, 1, 1) > 0)) + - 4 * ($month - 1) + (2 * ($month - 1) + ($day - 1) + $firstday - $dayofweek + 6) * 36 / 256); - } - - /** - * Internal _range function - * Sets the value $a to be in the range of [0, $b] - * - * @param float $a - value to correct - * @param float $b - maximum range to set - */ - private function _range($a, $b) - { - while ($a < 0) { - $a += $b; - } - while ($a >= $b) { - $a -= $b; - } - return $a; - } - - /** - * Calculates the sunrise or sunset based on a location - * - * @param array $location Location for calculation MUST include 'latitude', 'longitude', 'horizon' - * @param bool $horizon true: sunrise; false: sunset - * @return mixed - false: midnight sun, integer: - */ - protected function calcSun($location, $horizon, $rise = false) - { - // timestamp within 32bit - if (abs($this->_unixTimestamp) <= 0x7FFFFFFF) { - if ($rise === false) { - return date_sunset($this->_unixTimestamp, SUNFUNCS_RET_TIMESTAMP, $location['latitude'], - $location['longitude'], 90 + $horizon, $this->getGmtOffset() / 3600); - } - return date_sunrise($this->_unixTimestamp, SUNFUNCS_RET_TIMESTAMP, $location['latitude'], - $location['longitude'], 90 + $horizon, $this->getGmtOffset() / 3600); - } - - // self calculation - timestamp bigger than 32bit - // fix circle values - $quarterCircle = 0.5 * M_PI; - $halfCircle = M_PI; - $threeQuarterCircle = 1.5 * M_PI; - $fullCircle = 2 * M_PI; - - // radiant conversion for coordinates - $radLatitude = $location['latitude'] * $halfCircle / 180; - $radLongitude = $location['longitude'] * $halfCircle / 180; - - // get solar coordinates - $tmpRise = $rise ? $quarterCircle : $threeQuarterCircle; - $radDay = $this->date('z',$this->_unixTimestamp) + ($tmpRise - $radLongitude) / $fullCircle; - - // solar anomoly and longitude - $solAnomoly = $radDay * 0.017202 - 0.0574039; - $solLongitude = $solAnomoly + 0.0334405 * sin($solAnomoly); - $solLongitude += 4.93289 + 3.49066E-4 * sin(2 * $solAnomoly); - - // get quadrant - $solLongitude = $this->_range($solLongitude, $fullCircle); - - if (($solLongitude / $quarterCircle) - intval($solLongitude / $quarterCircle) == 0) { - $solLongitude += 4.84814E-6; - } - - // solar ascension - $solAscension = sin($solLongitude) / cos($solLongitude); - $solAscension = atan2(0.91746 * $solAscension, 1); - - // adjust quadrant - if ($solLongitude > $threeQuarterCircle) { - $solAscension += $fullCircle; - } else if ($solLongitude > $quarterCircle) { - $solAscension += $halfCircle; - } - - // solar declination - $solDeclination = 0.39782 * sin($solLongitude); - $solDeclination /= sqrt(-$solDeclination * $solDeclination + 1); - $solDeclination = atan2($solDeclination, 1); - - $solHorizon = $horizon - sin($solDeclination) * sin($radLatitude); - $solHorizon /= cos($solDeclination) * cos($radLatitude); - - // midnight sun, always night - if (abs($solHorizon) > 1) { - return false; - } - - $solHorizon /= sqrt(-$solHorizon * $solHorizon + 1); - $solHorizon = $quarterCircle - atan2($solHorizon, 1); - - if ($rise) { - $solHorizon = $fullCircle - $solHorizon; - } - - // time calculation - $localTime = $solHorizon + $solAscension - 0.0172028 * $radDay - 1.73364; - $universalTime = $localTime - $radLongitude; - - // determinate quadrant - $universalTime = $this->_range($universalTime, $fullCircle); - - // radiant to hours - $universalTime *= 24 / $fullCircle; - - // convert to time - $hour = intval($universalTime); - $universalTime = ($universalTime - $hour) * 60; - $min = intval($universalTime); - $universalTime = ($universalTime - $min) * 60; - $sec = intval($universalTime); - - return $this->mktime($hour, $min, $sec, $this->date('m', $this->_unixTimestamp), - $this->date('j', $this->_unixTimestamp), $this->date('Y', $this->_unixTimestamp), - -1, true); - } - - /** - * Sets a new timezone for calculation of $this object's gmt offset. - * For a list of supported timezones look here: http://php.net/timezones - * If no timezone can be detected or the given timezone is wrong UTC will be set. - * - * @param string $zone OPTIONAL timezone for date calculation; defaults to date_default_timezone_get() - * @return \Zend\Date\DateObject Provides fluent interface - * @throws \Zend\Date\Exception - */ - public function setTimezone($zone = null) - { - $oldzone = @date_default_timezone_get(); - if ($zone === null) { - $zone = $oldzone; - } - - // throw an error on false input, but only if the new date extension is available - if (!@timezone_open($zone)) { - throw new Exception\InvalidArgumentException("timezone ($zone) is not a known timezone"); - } - // this can generate an error if the date extension is not available and a false timezone is given - $result = @date_default_timezone_set($zone); - if ($result === true) { - $this->_offset = mktime(0, 0, 0, 1, 2, 1970) - gmmktime(0, 0, 0, 1, 2, 1970); - $this->_timezone = $zone; - } - date_default_timezone_set($oldzone); - - if (($zone == 'UTC') or ($zone == 'GMT')) { - $this->_dst = false; - } else { - $this->_dst = true; - } - - return $this; - } - - /** - * Return the timezone of $this object. - * The timezone is initially set when the object is instantiated. - * - * @return string actual set timezone string - */ - public function getTimezone() - { - return $this->_timezone; - } - - /** - * Return the offset to GMT of $this object's timezone. - * The offset to GMT is initially set when the object is instantiated using the currently, - * in effect, default timezone for PHP functions. - * - * @return integer seconds difference between GMT timezone and timezone when object was instantiated - */ - public function getGmtOffset() - { - $date = $this->getDateParts($this->getUnixTimestamp(), true); - $zone = @date_default_timezone_get(); - $result = @date_default_timezone_set($this->_timezone); - if ($result === true) { - $offset = $this->mktime($date['hours'], $date['minutes'], $date['seconds'], - $date['mon'], $date['mday'], $date['year'], false) - - $this->mktime($date['hours'], $date['minutes'], $date['seconds'], - $date['mon'], $date['mday'], $date['year'], true); - } - date_default_timezone_set($zone); - - return $offset; - } -} diff --git a/library/Zend/Date/Exception/ExceptionInterface.php b/library/Zend/Date/Exception/ExceptionInterface.php deleted file mode 100644 index 7c90165e72b..00000000000 --- a/library/Zend/Date/Exception/ExceptionInterface.php +++ /dev/null @@ -1,31 +0,0 @@ -get('Configuration'); + return new Adapter($config['db']); + } +} diff --git a/library/Zend/Db/Adapter/Driver/Feature/AbstractFeature.php b/library/Zend/Db/Adapter/Driver/Feature/AbstractFeature.php index 76d7fc389f1..cd142216ab1 100644 --- a/library/Zend/Db/Adapter/Driver/Feature/AbstractFeature.php +++ b/library/Zend/Db/Adapter/Driver/Feature/AbstractFeature.php @@ -5,7 +5,7 @@ * @link http://github.com/zendframework/zf2 for the canonical source repository * @copyright Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License - * @package Zend_Package + * @package Zend_Db */ namespace Zend\Db\Adapter\Driver\Feature; diff --git a/library/Zend/Db/Adapter/Driver/Feature/DriverFeatureInterface.php b/library/Zend/Db/Adapter/Driver/Feature/DriverFeatureInterface.php index b38ccb57bf7..0c9be962577 100644 --- a/library/Zend/Db/Adapter/Driver/Feature/DriverFeatureInterface.php +++ b/library/Zend/Db/Adapter/Driver/Feature/DriverFeatureInterface.php @@ -5,7 +5,7 @@ * @link http://github.com/zendframework/zf2 for the canonical source repository * @copyright Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License - * @package Zend_Package + * @package Zend_Db */ namespace Zend\Db\Adapter\Driver\Feature; @@ -20,4 +20,4 @@ interface DriverFeatureInterface public function setupDefaultFeatures(); public function addFeature($name, $feature); public function getFeature($name); -} \ No newline at end of file +} diff --git a/library/Zend/Db/Adapter/Driver/Mysqli/Connection.php b/library/Zend/Db/Adapter/Driver/Mysqli/Connection.php index cd06747af44..3459fef64e5 100644 --- a/library/Zend/Db/Adapter/Driver/Mysqli/Connection.php +++ b/library/Zend/Db/Adapter/Driver/Mysqli/Connection.php @@ -10,8 +10,8 @@ namespace Zend\Db\Adapter\Driver\Mysqli; -use Zend\Db\Adapter\Driver\ConnectionInterface, - Zend\Db\Adapter\Exception; +use Zend\Db\Adapter\Driver\ConnectionInterface; +use Zend\Db\Adapter\Exception; /** * @category Zend diff --git a/library/Zend/Db/Adapter/Driver/Mysqli/Mysqli.php b/library/Zend/Db/Adapter/Driver/Mysqli/Mysqli.php index d00ef5161fe..c3d099d297b 100644 --- a/library/Zend/Db/Adapter/Driver/Mysqli/Mysqli.php +++ b/library/Zend/Db/Adapter/Driver/Mysqli/Mysqli.php @@ -10,8 +10,8 @@ namespace Zend\Db\Adapter\Driver\Mysqli; -use Zend\Db\Adapter\Driver\DriverInterface, - Zend\Db\Adapter\Exception; +use Zend\Db\Adapter\Driver\DriverInterface; +use Zend\Db\Adapter\Exception; /** * @category Zend diff --git a/library/Zend/Db/Adapter/Driver/Mysqli/Result.php b/library/Zend/Db/Adapter/Driver/Mysqli/Result.php index 8ddb45269d6..3f834d33697 100644 --- a/library/Zend/Db/Adapter/Driver/Mysqli/Result.php +++ b/library/Zend/Db/Adapter/Driver/Mysqli/Result.php @@ -10,8 +10,8 @@ namespace Zend\Db\Adapter\Driver\Mysqli; -use Zend\Db\Adapter\Driver\ResultInterface, - Zend\Db\Adapter\Exception; +use Zend\Db\Adapter\Driver\ResultInterface; +use Zend\Db\Adapter\Exception; /** * @category Zend diff --git a/library/Zend/Db/Adapter/Driver/Pdo/Connection.php b/library/Zend/Db/Adapter/Driver/Pdo/Connection.php index 62f5302e028..e366e349500 100644 --- a/library/Zend/Db/Adapter/Driver/Pdo/Connection.php +++ b/library/Zend/Db/Adapter/Driver/Pdo/Connection.php @@ -10,9 +10,9 @@ namespace Zend\Db\Adapter\Driver\Pdo; -use Zend\Db\Adapter\Driver\ConnectionInterface, - Zend\Db\Adapter\Driver\DriverInterface, - Zend\Db\Adapter\Exception; +use Zend\Db\Adapter\Driver\ConnectionInterface; +use Zend\Db\Adapter\Driver\DriverInterface; +use Zend\Db\Adapter\Exception; /** * @category Zend @@ -358,13 +358,7 @@ public function prepare($sql) public function getLastGeneratedValue($name = null) { if ($name === null && $this->driverName == 'pgsql') { - // @todo create a feature that opts-into this behavior, using sql to find serial name - try { - $stmt = $this->resource->query('SELECT LASTVAL() as "lastvalue"'); - return $stmt->fetchColumn(0); - } catch (\PDOException $e) { - return false; - } + return null; } try { diff --git a/library/Zend/Db/Adapter/Driver/Pdo/Feature/SqliteRowCounter.php b/library/Zend/Db/Adapter/Driver/Pdo/Feature/SqliteRowCounter.php index 266fc01357a..fa4d13f1922 100644 --- a/library/Zend/Db/Adapter/Driver/Pdo/Feature/SqliteRowCounter.php +++ b/library/Zend/Db/Adapter/Driver/Pdo/Feature/SqliteRowCounter.php @@ -5,13 +5,13 @@ * @link http://github.com/zendframework/zf2 for the canonical source repository * @copyright Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License - * @package Zend_Package + * @package Zend_Db */ namespace Zend\Db\Adapter\Driver\Pdo\Feature; -use Zend\Db\Adapter\Driver\Feature\AbstractFeature, - Zend\Db\Adapter\Driver\Pdo; +use Zend\Db\Adapter\Driver\Feature\AbstractFeature; +use Zend\Db\Adapter\Driver\Pdo; /** * SqliteRowCounter diff --git a/library/Zend/Db/Adapter/Driver/Pdo/Pdo.php b/library/Zend/Db/Adapter/Driver/Pdo/Pdo.php index e57e01da50a..aa6217fced0 100644 --- a/library/Zend/Db/Adapter/Driver/Pdo/Pdo.php +++ b/library/Zend/Db/Adapter/Driver/Pdo/Pdo.php @@ -10,10 +10,10 @@ namespace Zend\Db\Adapter\Driver\Pdo; -use Zend\Db\Adapter\Driver\DriverInterface, - Zend\Db\Adapter\Driver\Feature\DriverFeatureInterface, - Zend\Db\Adapter\Driver\Feature\AbstractFeature, - Zend\Db\Adapter\Exception; +use Zend\Db\Adapter\Driver\DriverInterface; +use Zend\Db\Adapter\Driver\Feature\AbstractFeature; +use Zend\Db\Adapter\Driver\Feature\DriverFeatureInterface; +use Zend\Db\Adapter\Exception; /** * @category Zend diff --git a/library/Zend/Db/Adapter/Driver/Pdo/Result.php b/library/Zend/Db/Adapter/Driver/Pdo/Result.php index 46574f0024b..af8963bb887 100644 --- a/library/Zend/Db/Adapter/Driver/Pdo/Result.php +++ b/library/Zend/Db/Adapter/Driver/Pdo/Result.php @@ -10,10 +10,10 @@ namespace Zend\Db\Adapter\Driver\Pdo; -use Zend\Db\Adapter\Driver\ResultInterface; use Iterator; use PDO as PDOResource; use PDOStatement; +use Zend\Db\Adapter\Driver\ResultInterface; use Zend\Db\Adapter\Exception; /** diff --git a/library/Zend/Db/Adapter/Driver/Pdo/Statement.php b/library/Zend/Db/Adapter/Driver/Pdo/Statement.php index 0210671e3c7..17955530022 100644 --- a/library/Zend/Db/Adapter/Driver/Pdo/Statement.php +++ b/library/Zend/Db/Adapter/Driver/Pdo/Statement.php @@ -10,9 +10,9 @@ namespace Zend\Db\Adapter\Driver\Pdo; -use Zend\Db\Adapter\Driver\StatementInterface, - Zend\Db\Adapter\ParameterContainer, - Zend\Db\Adapter\Exception; +use Zend\Db\Adapter\Driver\StatementInterface; +use Zend\Db\Adapter\Exception; +use Zend\Db\Adapter\ParameterContainer; /** * @category Zend diff --git a/library/Zend/Db/Adapter/Driver/Pgsql/Connection.php b/library/Zend/Db/Adapter/Driver/Pgsql/Connection.php index 0b923897eab..2ef5afd5980 100644 --- a/library/Zend/Db/Adapter/Driver/Pgsql/Connection.php +++ b/library/Zend/Db/Adapter/Driver/Pgsql/Connection.php @@ -91,17 +91,17 @@ public function setResource($resource) /** * @return null */ - public function getDefaultCatalog() + public function getCurrentSchema() { - return null; - } + if (!$this->isConnected()) { + $this->connect(); + } - /** - * @return null - */ - public function getDefaultSchema() - { - // TODO: Implement getDefaultSchema() method. + $result = pg_query($this->resource, 'SELECT CURRENT_SCHEMA AS "currentschema"'); + if ($result == false) { + return null; + } + return pg_fetch_result($result, 0, 'currentschema'); } /** @@ -227,19 +227,11 @@ public function execute($sql) */ public function getLastGeneratedValue($name = null) { - // @todo create a feature that opts-into this behavior, using sql to find serial name - $result = @pg_query($this->resource, 'SELECT LASTVAL() as "lastvalue"'); - if ($result == false) { + if ($name == null) { return null; } - return pg_fetch_result($result, 0, 'lastvalue'); + $result = pg_query($this->resource, 'SELECT CURRVAL(\'' . str_replace('\'', '\\\'', $name) . '\') as "currval"'); + return pg_fetch_result($result, 0, 'currval'); } - /** - * @return null - */ - public function getCurrentSchema() - { - return null; - } } diff --git a/library/Zend/Db/Adapter/Driver/Pgsql/Feature/SequenceHelper.php b/library/Zend/Db/Adapter/Driver/Pgsql/Feature/SequenceHelper.php index 98fa91d1a98..97678518af1 100644 --- a/library/Zend/Db/Adapter/Driver/Pgsql/Feature/SequenceHelper.php +++ b/library/Zend/Db/Adapter/Driver/Pgsql/Feature/SequenceHelper.php @@ -1,8 +1,9 @@ setColumnName($column); - } - - /** - * Get column name - * - * @return string - */ - public function getColumnName() - { - return $this->columnName; - } - - /** - * Set column name - * - * @param string $columnName - * @return ConstraintKeyObject - */ - public function setColumnName($columnName) - { - $this->columnName = $columnName; - return $this; - } - - /** - * Get ordinal position - * - * @return type - */ - public function getOrdinalPosition() - { - return $this->ordinalPosition; - } - - /** - * Set ordinal position - * - * @param type $ordinalPosition - * @return ConstraintKeyObject - */ - public function setOrdinalPosition($ordinalPosition) - { - $this->ordinalPosition = $ordinalPosition; - return $this; - } - - /** - * Get position in unique constraint - * - * @return type - */ - public function getPositionInUniqueConstraint() - { - return $this->positionInUniqueConstraint; - } - - /** - * Set position in unique constraint - * - * @param type $positionInUniqueConstraint - * @return ConstraintKeyObject - */ - public function setPositionInUniqueConstraint($positionInUniqueConstraint) - { - $this->positionInUniqueConstraint = $positionInUniqueConstraint; - return $this; - } - - /** - * Get referencred table schema - * - * @return string - */ - public function getReferencedTableSchema() - { - return $this->referencedTableSchema; - } - - /** - * Set referenced table schema - * - * @param type $referencedTableSchema - * @return ConstraintKeyObject - */ - public function setReferencedTableSchema($referencedTableSchema) - { - $this->referencedTableSchema = $referencedTableSchema; - return $this; - } - - /** - * Get referenced table name - * - * @return string - */ - public function getReferencedTableName() - { - return $this->referencedTableName; - } - - /** - * Set Referenced table name - * - * @param string $referencedTableName - * @return ConstraintKeyObject - */ - public function setReferencedTableName($referencedTableName) - { - $this->referencedTableName = $referencedTableName; - return $this; - } - - /** - * Get referenced column name - * - * @return string - */ - public function getReferencedColumnName() - { - return $this->referencedColumnName; - } - - /** - * Set referenced column name - * - * @param string $referencedColumnName - * @return ConstraintKeyObject - */ - public function setReferencedColumnName($referencedColumnName) - { - $this->referencedColumnName = $referencedColumnName; - return $this; - } - - /** - * set foreign key update rule - * - * @param type $foreignKeyUpdateRule - */ - public function setForeignKeyUpdateRule($foreignKeyUpdateRule) - { - $this->foreignKeyUpdateRule = $foreignKeyUpdateRule; - } - - /** - * Get foreign key update rule - * - * @return type - */ - public function getForeignKeyUpdateRule() - { - return $this->foreignKeyUpdateRule; - } - - /** - * Set foreign key delete rule - * - * @param type $foreignKeyDeleteRule - */ - public function setForeignKeyDeleteRule($foreignKeyDeleteRule) - { - $this->foreignKeyDeleteRule = $foreignKeyDeleteRule; - } - - /** - * get foreign key delete rule - * - * @return type - */ - public function getForeignKeyDeleteRule() - { - return $this->foreignKeyUpdateRule; - } - -} diff --git a/library/Zend/Db/Metadata/Object/ConstraintObject.php b/library/Zend/Db/Metadata/Object/ConstraintObject.php index 463c609f83f..3bb78e4a10a 100644 --- a/library/Zend/Db/Metadata/Object/ConstraintObject.php +++ b/library/Zend/Db/Metadata/Object/ConstraintObject.php @@ -17,64 +17,86 @@ */ class ConstraintObject { - /* - protected $catalogName = null; - protected $schemaName = null; - */ - /** * * @var string */ protected $name = null; + /** * * @var string */ protected $tableName = null; + /** * * @var string */ protected $schemaName = null; -// protected $tableCatalogName = null; -// protected $tableSchemaName = null; - /** + * One of "PRIMARY KEY", "UNIQUE", "FOREIGN KEY", or "CHECK" * * @var string */ protected $type = null; + /** * - * @var array + * + * @var string[] */ - protected $keys = null; + protected $columns = array(); - /* - public function getCatalogName() - { - return $this->catalogName; - } + /** + * + * + * @var string + */ + protected $referencedTableSchema; - public function setCatalogName($catalogName) - { - $this->catalogName = $catalogName; - return $this; - } + /** + * + * + * @var string + */ + protected $referencedTableName; - public function getSchemaName() - { - return $this->schemaName; - } + /** + * + * + * @var string[] + */ + protected $referencedColumns; - public function setSchemaName($schemaName) - { - $this->schemaName = $schemaName; - return $this; - } - */ + /** + * + * + * @var string + */ + protected $matchOption; + + /** + * + * + * @var string + */ + protected $updateRule; + + /** + * + * + * @var string + */ + protected $deleteRule; + + /** + * + * + * @var string + */ + protected $checkClause; /** * Constructor @@ -83,13 +105,11 @@ public function setSchemaName($schemaName) * @param string $table * @param string $schemaName */ - public function __construct($name, $table, $schemaName = null) + public function __construct($name, $tableName, $schemaName = null) { $this->setName($name); - $this->setTableName($table); - if ($schemaName) { - $this->setSchemaName($schemaName); - } + $this->setTableName($tableName); + $this->setSchemaName($schemaName); } /** @@ -159,9 +179,9 @@ public function setTableName($tableName) * * @param type $constraintType */ - public function setType($constraintType) + public function setType($type) { - $this->type = $constraintType; + $this->type = $type; } /** @@ -174,24 +194,185 @@ public function getType() return $this->type; } + public function hasColumns() + { + return (!empty($this->columns)); + } + /** - * Set keys - * - * @param array $keys + * Get Columns. + * + * @return string[] */ - public function setKeys(array $keys) + public function getColumns() { - $this->keys = $keys; + return $this->columns; } /** - * Get keys - * - * @return string + * Set Columns. + * + * @param string[] $columns + * @return ConstraintObject + */ + public function setColumns(array $columns) + { + $this->columns = $columns; + return $this; + } + + /** + * Get Referenced Table Schema. + * + * @return string + */ + public function getReferencedTableSchema() + { + return $this->referencedTableSchema; + } + + /** + * Set Referenced Table Schema. + * + * @param string $referencedTableSchema + * @return ConstraintObject + */ + public function setReferencedTableSchema($referencedTableSchema) + { + $this->referencedTableSchema = $referencedTableSchema; + return $this; + } + + /** + * Get Referenced Table Name. + * + * @return string + */ + public function getReferencedTableName() + { + return $this->referencedTableName; + } + + /** + * Set Referenced Table Name. + * + * @param string $referencedTableName + * @return ConstraintObject + */ + public function setReferencedTableName($referencedTableName) + { + $this->referencedTableName = $referencedTableName; + return $this; + } + + /** + * Get Referenced Columns. + * + * @return string[] + */ + public function getReferencedColumns() + { + return $this->referencedColumns; + } + + /** + * Set Referenced Columns. + * + * @param string[] $referencedColumns + * @return ConstraintObject + */ + public function setReferencedColumns(array $referencedColumns) + { + $this->referencedColumns = $referencedColumns; + return $this; + } + + /** + * Get Match Option. + * + * @return string + */ + public function getMatchOption() + { + return $this->matchOption; + } + + /** + * Set Match Option. + * + * @param string $matchOption + * @return ConstraintObject + */ + public function setMatchOption($matchOption) + { + $this->matchOption = $matchOption; + return $this; + } + + /** + * Get Update Rule. + * + * @return string */ - public function getKeys() + public function getUpdateRule() { - return $this->keys; + return $this->updateRule; + } + + /** + * Set Update Rule. + * + * @param string $updateRule + * @return ConstraintObject + */ + public function setUpdateRule($updateRule) + { + $this->updateRule = $updateRule; + return $this; + } + + /** + * Get Delete Rule. + * + * @return string + */ + public function getDeleteRule() + { + return $this->deleteRule; + } + + /** + * Set Delete Rule. + * + * @param string $deleteRule + * @return ConstraintObject + */ + public function setDeleteRule($deleteRule) + { + $this->deleteRule = $deleteRule; + return $this; + } + + /** + * Get Check Clause. + * + * @return string + */ + public function getCheckClause() + { + return $this->checkClause; + } + + /** + * Set Check Clause. + * + * @param string $checkClause + * @return ConstraintObject + */ + public function setCheckClause($checkClause) + { + $this->checkClause = $checkClause; + return $this; } /** @@ -201,7 +382,7 @@ public function getKeys() */ public function isPrimaryKey() { - return (strtoupper($this->type) == 'PRIMARY KEY'); + return ('PRIMARY KEY' == $this->type); } /** @@ -209,9 +390,9 @@ public function isPrimaryKey() * * @return boolean */ - public function isUniqueKey() + public function isUnique() { - return (strtoupper($this->type) == 'UNIQUE'); + return ('UNIQUE' == $this->type); } /** @@ -221,7 +402,17 @@ public function isUniqueKey() */ public function isForeignKey() { - return (strtoupper($this->type) == 'FOREIGN KEY'); + return ('FOREIGN KEY' == $this->type); + } + + /** + * Is foreign key + * + * @return boolean + */ + public function isCheck() + { + return ('CHECK' == $this->type); } } diff --git a/library/Zend/Db/Metadata/Object/ReferentialConstraintObject.php b/library/Zend/Db/Metadata/Object/ReferentialConstraintObject.php deleted file mode 100644 index 2a1b61cd81d..00000000000 --- a/library/Zend/Db/Metadata/Object/ReferentialConstraintObject.php +++ /dev/null @@ -1,189 +0,0 @@ -uniqueConstraintCatalogName; - } - - /** - * Set unique constraint catalog name - * - * @param string $uniqueConstraintCatalogName - * @return ReferentialConstraint - */ - public function setUniqueConstraintCatalogName($uniqueConstraintCatalogName) - { - $this->uniqueConstraintCatalogName = $uniqueConstraintCatalogName; - return $this; - } - - /** - * Get unique constraint schema name - * - * @return string - */ - public function getUniqueConstraintSchemaName() - { - return $this->uniqueConstraintSchemaName; - } - - /** - * Set unique constraint schema name - * - * @param string $uniqueConstraintSchemaName - * @return ReferentialConstraint - */ - public function setUniqueConstraintSchemaName($uniqueConstraintSchemaName) - { - $this->uniqueConstraintSchemaName = $uniqueConstraintSchemaName; - return $this; - } - - /** - * Get unique constraint name - * - * @return string - */ - public function getUniqueConstraintName() - { - return $this->uniqueConstraintName; - } - - /** - * Set unique constraint name - * - * @param string $uniqueConstraintName - * @return ReferentialConstraint - */ - public function setUniqueConstraintName($uniqueConstraintName) - { - $this->uniqueConstraintName = $uniqueConstraintName; - return $this; - } - - /** - * Get match option - * - * @return type - */ - public function getMatchOption() - { - return $this->matchOption; - } - - /** - * Set match option - * - * @param type $matchOption - * @return ReferentialConstraint - */ - public function setMatchOption($matchOption) - { - $this->matchOption = $matchOption; - return $this; - } - - /** - * Get update rule - * - * @return type - */ - public function getUpdateRule() - { - return $this->updateRule; - } - - /** - * Set update rule - * - * @param type $updateRule - * @return ReferentialConstraint - */ - public function setUpdateRule($updateRule) - { - $this->updateRule = $updateRule; - return $this; - } - - /** - * Get delete rule - * - * @return type - */ - public function getDeleteRule() - { - return $this->deleteRule; - } - - /** - * Set delete rule - * - * @param type $deleteRule - * @return ReferentialConstraint - */ - public function setDeleteRule($deleteRule) - { - $this->deleteRule = $deleteRule; - return $this; - } - -} diff --git a/library/Zend/Db/Metadata/Source/AbstractSource.php b/library/Zend/Db/Metadata/Source/AbstractSource.php index 534904c43ac..29252ce7a10 100644 --- a/library/Zend/Db/Metadata/Source/AbstractSource.php +++ b/library/Zend/Db/Metadata/Source/AbstractSource.php @@ -10,8 +10,8 @@ namespace Zend\Db\Metadata\Source; -use Zend\Db\Metadata\MetadataInterface; use Zend\Db\Adapter\Adapter; +use Zend\Db\Metadata\MetadataInterface; use Zend\Db\Metadata\Object; /** @@ -317,10 +317,8 @@ public function getConstraints($table, $schema = null) $this->loadConstraintData($table, $schema); $constraints = array(); - foreach ($this->data['constraint_names'][$schema] as $constraintName => $constraintInfo) { - if ($constraintInfo['table_name'] == $table) { - $constraints[] = $this->getConstraint($constraintInfo['constraint_name'], $table, $schema); - } + foreach (array_keys($this->data['constraints'][$schema][$table]) as $constraintName) { + $constraints[] = $this->getConstraint($constraintName, $table, $schema); } return $constraints; @@ -332,7 +330,6 @@ public function getConstraints($table, $schema = null) * @param string $constraintName * @param string $table * @param string $schema - * @param string $database * @return Object\ConstraintObject */ public function getConstraint($constraintName, $table, $schema = null) @@ -343,21 +340,32 @@ public function getConstraint($constraintName, $table, $schema = null) $this->loadConstraintData($table, $schema); - $found = false; - foreach ($this->data['constraint_names'][$schema] as $constraintInfo) { - if ($constraintInfo['constraint_name'] == $constraintName && $constraintInfo['table_name'] == $table) { - $found = $constraintInfo; - break; - } - } - - if (!$found) { + if (!isset($this->data['constraints'][$schema][$table][$constraintName])) { throw new \Exception('Cannot find a constraint by that name in this table'); } + $info = $this->data['constraints'][$schema][$table][$constraintName]; $constraint = new Object\ConstraintObject($constraintName, $table, $schema); - $constraint->setType($found['constraint_type']); - $constraint->setKeys($this->getConstraintKeys($constraintName, $table, $schema)); + + foreach (array( + 'constraint_type' => 'setType', + 'match_option' => 'setMatchOption', + 'update_rule' => 'setUpdateRule', + 'delete_rule' => 'setDeleteRule', + 'columns' => 'setColumns', + 'referenced_table_schema' => 'setReferencedTableSchema', + 'referenced_table_name' => 'setReferencedTableName', + 'referenced_columns' => 'setReferencedColumns', + 'match_option' => 'setMatchOption', + 'update_rule' => 'setUpdateRule', + 'delete_rule' => 'setDeleteRule', + 'check_clause' => 'setCheckClause', + ) as $key => $setMethod) { + if (isset($info[$key])) { + $constraint->{$setMethod}($info[$key]); + } + } + return $constraint; } @@ -521,11 +529,11 @@ protected function loadColumnData($table, $schema) protected function loadConstraintData($table, $schema) { - if (isset($this->data['constraint_names'][$schema])) { + if (isset($this->data['constraints'][$schema])) { return; } - $this->prepareDataHierarchy('constraint_names', $schema); + $this->prepareDataHierarchy('constraints', $schema); } protected function loadTriggerData($schema) diff --git a/library/Zend/Db/Metadata/Source/MysqlMetadata.php b/library/Zend/Db/Metadata/Source/MysqlMetadata.php index 1fbb3875f8a..7ed5fde1536 100644 --- a/library/Zend/Db/Metadata/Source/MysqlMetadata.php +++ b/library/Zend/Db/Metadata/Source/MysqlMetadata.php @@ -10,8 +10,8 @@ namespace Zend\Db\Metadata\Source; -use Zend\Db\Metadata\MetadataInterface; use Zend\Db\Adapter\Adapter; +use Zend\Db\Metadata\MetadataInterface; use Zend\Db\Metadata\Object; /** @@ -164,9 +164,111 @@ protected function loadColumnData($table, $schema) protected function loadConstraintData($table, $schema) { - $this->loadConstraintDataNames($schema); - $this->loadConstraintDataKeys($schema); - $this->loadConstraintReferences($schema); + if (isset($this->data['constraints'][$schema][$table])) { + return; + } + + $this->prepareDataHierarchy('constraints', $schema, $table); + + $isColumns = array( + array('T','TABLE_NAME'), + array('TC','CONSTRAINT_NAME'), + array('TC','CONSTRAINT_TYPE'), + array('KCU','COLUMN_NAME'), + array('RC','MATCH_OPTION'), + array('RC','UPDATE_RULE'), + array('RC','DELETE_RULE'), + array('KCU','REFERENCED_TABLE_SCHEMA'), + array('KCU','REFERENCED_TABLE_NAME'), + array('KCU','REFERENCED_COLUMN_NAME'), + ); + + $p = $this->adapter->getPlatform(); + + array_walk($isColumns, function (&$c) use ($p) { + $c = $p->quoteIdentifierChain($c); + }); + + $sql = 'SELECT ' . implode(', ', $isColumns) + . ' FROM ' . $p->quoteIdentifierChain(array('INFORMATION_SCHEMA','TABLES')) . ' T' + + . ' INNER JOIN ' . $p->quoteIdentifierChain(array('INFORMATION_SCHEMA','TABLE_CONSTRAINTS')) . ' TC' + . ' ON ' . $p->quoteIdentifierChain(array('T','TABLE_SCHEMA')) + . ' = ' . $p->quoteIdentifierChain(array('TC','TABLE_SCHEMA')) + . ' AND ' . $p->quoteIdentifierChain(array('T','TABLE_NAME')) + . ' = ' . $p->quoteIdentifierChain(array('TC','TABLE_NAME')) + + . ' LEFT JOIN ' . $p->quoteIdentifierChain(array('INFORMATION_SCHEMA','KEY_COLUMN_USAGE')) . ' KCU' + . ' ON ' . $p->quoteIdentifierChain(array('TC','TABLE_SCHEMA')) + . ' = ' . $p->quoteIdentifierChain(array('KCU','TABLE_SCHEMA')) + . ' AND ' . $p->quoteIdentifierChain(array('TC','TABLE_NAME')) + . ' = ' . $p->quoteIdentifierChain(array('KCU','TABLE_NAME')) + . ' AND ' . $p->quoteIdentifierChain(array('TC','CONSTRAINT_NAME')) + . ' = ' . $p->quoteIdentifierChain(array('KCU','CONSTRAINT_NAME')) + + . ' LEFT JOIN ' . $p->quoteIdentifierChain(array('INFORMATION_SCHEMA','REFERENTIAL_CONSTRAINTS')) . ' RC' + . ' ON ' . $p->quoteIdentifierChain(array('TC','CONSTRAINT_SCHEMA')) + . ' = ' . $p->quoteIdentifierChain(array('RC','CONSTRAINT_SCHEMA')) + . ' AND ' . $p->quoteIdentifierChain(array('TC','CONSTRAINT_NAME')) + . ' = ' . $p->quoteIdentifierChain(array('RC','CONSTRAINT_NAME')) + + . ' WHERE ' . $p->quoteIdentifierChain(array('T','TABLE_NAME')) + . ' = ' . $p->quoteValue($table) + . ' AND ' . $p->quoteIdentifierChain(array('T','TABLE_TYPE')) + . ' IN (' . $p->quoteValueList(array('BASE TABLE', 'VIEW')) . ')'; + + if ($schema != self::DEFAULT_SCHEMA) { + $sql .= ' AND ' . $p->quoteIdentifierChain(array('T','TABLE_SCHEMA')) + . ' = ' . $p->quoteValue($schema); + } else { + $sql .= ' AND ' . $p->quoteIdentifierChain(array('T','TABLE_SCHEMA')) + . ' != ' . $p->quoteValue('INFORMATION_SCHEMA'); + } + + $sql .= ' ORDER BY CASE ' . $p->quoteIdentifierChain(array('TC','CONSTRAINT_TYPE')) + . " WHEN 'PRIMARY KEY' THEN 1" + . " WHEN 'UNIQUE' THEN 2" + . " WHEN 'FOREIGN KEY' THEN 3" + . " ELSE 4 END" + + . ', ' . $p->quoteIdentifierChain(array('TC','CONSTRAINT_NAME')) + . ', ' . $p->quoteIdentifierChain(array('KCU','ORDINAL_POSITION')); + + $results = $this->adapter->query($sql, Adapter::QUERY_MODE_EXECUTE); + + $realName = null; + $constraints = array(); + foreach ($results->toArray() as $row) { + if ($row['CONSTRAINT_NAME'] !== $realName) { + $realName = $row['CONSTRAINT_NAME']; + $isFK = ('FOREIGN KEY' == $row['CONSTRAINT_TYPE']); + if ($isFK) { + $name = $realName; + } else { + $name = '_zf_' . $row['TABLE_NAME'] . '_' . $realName; + } + $constraints[$name] = array( + 'constraint_name' => $name, + 'constraint_type' => $row['CONSTRAINT_TYPE'], + 'table_name' => $row['TABLE_NAME'], + 'columns' => array(), + ); + if ($isFK) { + $constraints[$name]['referenced_table_schema'] = $row['REFERENCED_TABLE_SCHEMA']; + $constraints[$name]['referenced_table_name'] = $row['REFERENCED_TABLE_NAME']; + $constraints[$name]['referenced_columns'] = array(); + $constraints[$name]['match_option'] = $row['MATCH_OPTION']; + $constraints[$name]['update_rule'] = $row['UPDATE_RULE']; + $constraints[$name]['delete_rule'] = $row['DELETE_RULE']; + } + } + $constraints[$name]['columns'][] = $row['COLUMN_NAME']; + if ($isFK) { + $constraints[$name]['referenced_columns'][] = $row['REFERENCED_COLUMN_NAME']; + } + } + + $this->data['constraints'][$schema][$table] = $constraints; } protected function loadConstraintDataNames($schema) diff --git a/library/Zend/Db/Metadata/Source/PostgresqlMetadata.php b/library/Zend/Db/Metadata/Source/PostgresqlMetadata.php index 18b6afd16d9..6c92b0c2ccb 100644 --- a/library/Zend/Db/Metadata/Source/PostgresqlMetadata.php +++ b/library/Zend/Db/Metadata/Source/PostgresqlMetadata.php @@ -30,16 +30,17 @@ protected function loadSchemaData() $p = $this->adapter->getPlatform(); - $sql = 'SELECT ' . $p->quoteIdentifier('SCHEMA_NAME') - . ' FROM ' . $p->quoteIdentifierChain(array('INFORMATION_SCHEMA', 'SCHEMATA')) - . ' WHERE ' . $p->quoteIdentifier('SCHEMA_NAME') - . ' != ' . $p->quoteValue('INFORMATION_SCHEMA'); + $sql = 'SELECT ' . $p->quoteIdentifier('schema_name') + . ' FROM ' . $p->quoteIdentifierChain(array('information_schema', 'schemata')) + . ' WHERE ' . $p->quoteIdentifier('schema_name') + . ' != ' . $p->quoteValue('information_schema') + . ' AND ' . $p->quoteIdentifier('schema_name') . " NOT LIKE 'pg_%'"; $results = $this->adapter->query($sql, Adapter::QUERY_MODE_EXECUTE); $schemas = array(); foreach ($results->toArray() as $row) { - $schemas[] = $row['SCHEMA_NAME']; + $schemas[] = $row['schema_name']; } $this->data['schemas'] = $schemas; @@ -101,6 +102,12 @@ protected function loadTableNameData($schema) protected function loadColumnData($table, $schema) { + if (isset($this->data['columns'][$schema][$table])) { + return; + } + + $this->prepareDataHierarchy('columns', $schema, $table); + $platform = $this->adapter->getPlatform(); $isColumns = array( @@ -122,7 +129,9 @@ protected function loadColumnData($table, $schema) . ' FROM ' . $platform->quoteIdentifier('information_schema') . $platform->getIdentifierSeparator() . $platform->quoteIdentifier('columns') . ' WHERE ' . $platform->quoteIdentifier('table_schema') - . ' != ' . $platform->quoteValue('information'); + . ' != ' . $platform->quoteValue('information') + . ' AND ' . $platform->quoteIdentifier('table_name') + . ' = ' . $platform->quoteValue($table); if ($schema != '__DEFAULT_SCHEMA__') { $sql .= ' AND ' . $platform->quoteIdentifier('table_schema') @@ -146,122 +155,134 @@ protected function loadColumnData($table, $schema) ); } - $this->prepareDataHierarchy('columns', $schema, $table); - $this->data['columns'][$schema][$table] = $columns;; + $this->data['columns'][$schema][$table] = $columns; } protected function loadConstraintData($table, $schema) { - $platform = $this->adapter->getPlatform(); - - // LOAD CONSTRAINT NAMES - - $isColumns = array( - 'constraint_name', - 'table_schema', - 'table_name', - 'constraint_type' - ); - - array_walk($isColumns, function (&$c) use ($platform) { $c = $platform->quoteIdentifier($c); }); - - $sql = 'SELECT ' . implode(', ', $isColumns) - . ' FROM ' . $platform->quoteIdentifier('information_schema') - . $platform->getIdentifierSeparator() . $platform->quoteIdentifier('table_constraints') - . ' WHERE ' . $platform->quoteIdentifier('table_schema') - . ' != ' . $platform->quoteValue('information_schema'); - - if ($schema !== '__DEFAULT_SCHEMA__') { - $sql .= ' AND ' . $platform->quoteIdentifier('table_schema') - . ' = ' . $platform->quoteValue($schema); - } - - $results = $this->adapter->query($sql, Adapter::QUERY_MODE_EXECUTE); - - $constraintData = array(); - foreach ($results->toArray() as $row) { - $constraintData[] = array_change_key_case($row, CASE_LOWER); + if (isset($this->data['constraints'][$schema][$table])) { + return; } - $this->prepareDataHierarchy('constraint_names', $schema); - $this->data['constraint_names'][$schema] = $constraintData; - - // LOAD CONSTRAINT KEYS + $this->prepareDataHierarchy('constraints', $schema, $table); $isColumns = array( - 'constraint_name', - 'table_schema', - 'table_name', - 'column_name', - 'ordinal_position' + array('t','table_name'), + array('tc','constraint_name'), + array('tc','constraint_type'), + array('kcu','column_name'), + array('cc','check_clause'), + array('rc','match_option'), + array('rc','update_rule'), + array('rc','delete_rule'), + array('referenced_table_schema' => 'kcu2','table_schema'), + array('referenced_table_name' => 'kcu2','table_name'), + array('referenced_column_name' => 'kcu2','column_name'), ); - array_walk($isColumns, function (&$c) use ($platform) { $c = $platform->quoteIdentifier($c); }); - - $sql = 'SELECT ' . implode(', ', $isColumns) - . ' FROM ' . $platform->quoteIdentifier('information_schema') - . $platform->getIdentifierSeparator() . $platform->quoteIdentifier('key_column_usage') - . ' WHERE ' . $platform->quoteIdentifier('table_schema') - . ' != ' . $platform->quoteValue('information_schema'); + $p = $this->adapter->getPlatform(); - if ($schema != null || $this->defaultSchema != null) { - if ($schema == null) { - $schema = $this->defaultSchema; + array_walk($isColumns, function (&$c) use ($p) { + $alias = key($c); + $c = $p->quoteIdentifierChain($c); + if (is_string($alias)) { + $c .= ' ' . $p->quoteIdentifier($alias); } - $sql .= ' AND ' . $platform->quoteIdentifier('table_schema') - . ' = ' . $platform->quoteValue($schema); - } + }); - $results = $this->adapter->query($sql, Adapter::QUERY_MODE_EXECUTE); + $sql = 'SELECT ' . implode(', ', $isColumns) + . ' FROM ' . $p->quoteIdentifierChain(array('information_schema','tables')) . ' t' + + . ' INNER JOIN ' . $p->quoteIdentifierChain(array('information_schema','table_constraints')) . ' tc' + . ' ON ' . $p->quoteIdentifierChain(array('t','table_schema')) + . ' = ' . $p->quoteIdentifierChain(array('tc','table_schema')) + . ' AND ' . $p->quoteIdentifierChain(array('t','table_name')) + . ' = ' . $p->quoteIdentifierChain(array('tc','table_name')) + + . ' LEFT JOIN ' . $p->quoteIdentifierChain(array('information_schema','key_column_usage')) . ' kcu' + . ' ON ' . $p->quoteIdentifierChain(array('tc','table_schema')) + . ' = ' . $p->quoteIdentifierChain(array('kcu','table_schema')) + . ' AND ' . $p->quoteIdentifierChain(array('tc','table_name')) + . ' = ' . $p->quoteIdentifierChain(array('kcu','table_name')) + . ' AND ' . $p->quoteIdentifierChain(array('tc','constraint_name')) + . ' = ' . $p->quoteIdentifierChain(array('kcu','constraint_name')) + + . ' LEFT JOIN ' . $p->quoteIdentifierChain(array('information_schema','check_constraints')) . ' cc' + . ' ON ' . $p->quoteIdentifierChain(array('tc','constraint_schema')) + . ' = ' . $p->quoteIdentifierChain(array('cc','constraint_schema')) + . ' AND ' . $p->quoteIdentifierChain(array('tc','constraint_name')) + . ' = ' . $p->quoteIdentifierChain(array('cc','constraint_name')) + + . ' LEFT JOIN ' . $p->quoteIdentifierChain(array('information_schema','referential_constraints')) . ' rc' + . ' ON ' . $p->quoteIdentifierChain(array('tc','constraint_schema')) + . ' = ' . $p->quoteIdentifierChain(array('rc','constraint_schema')) + . ' AND ' . $p->quoteIdentifierChain(array('tc','constraint_name')) + . ' = ' . $p->quoteIdentifierChain(array('rc','constraint_name')) + + . ' LEFT JOIN ' . $p->quoteIdentifierChain(array('information_schema','key_column_usage')) . ' kcu2' + . ' ON ' . $p->quoteIdentifierChain(array('rc','unique_constraint_schema')) + . ' = ' . $p->quoteIdentifierChain(array('kcu2','constraint_schema')) + . ' AND ' . $p->quoteIdentifierChain(array('rc','unique_constraint_name')) + . ' = ' . $p->quoteIdentifierChain(array('kcu2','constraint_name')) + . ' AND ' . $p->quoteIdentifierChain(array('kcu','position_in_unique_constraint')) + . ' = ' . $p->quoteIdentifierChain(array('kcu2','ordinal_position')) + + . ' WHERE ' . $p->quoteIdentifierChain(array('t','table_name')) + . ' = ' . $p->quoteValue($table) + . ' AND ' . $p->quoteIdentifierChain(array('t','table_type')) + . ' IN (' . $p->quoteValueList(array('BASE TABLE', 'VIEW')) . ')'; - $constraintKeyData = array(); - foreach ($results->toArray() as $row) { - $constraintKeyData[] = array_change_key_case($row, CASE_LOWER); + if ($schema != self::DEFAULT_SCHEMA) { + $sql .= ' AND ' . $p->quoteIdentifierChain(array('t','table_schema')) + . ' = ' . $p->quoteValue($schema); + } else { + $sql .= ' AND ' . $p->quoteIdentifierChain(array('t','table_schema')) + . ' != ' . $p->quoteValue('information_schema'); } - $this->prepareDataHierarchy('constraint_keys', $schema); - $this->data['constraint_keys'][$schema] = $constraintKeyData; - - // LOAD CONSTRAINT REFERENCES - - $quoteIdentifierForWalk = function (&$c) use ($platform) { $c = $platform->quoteIdentifierInFragment($c); }; - $quoteSelectList = function (array $identifierList) use ($platform, $quoteIdentifierForWalk) { - array_walk($identifierList, $quoteIdentifierForWalk); - return implode(', ', $identifierList); - }; - - // target: CONSTRAINT_SCHEMA, CONSTRAINT_NAME, UPDATE_RULE, DELETE_RULE, REFERENCE_CONSTRAINT_NAME - - $sql = 'SELECT ' . $quoteSelectList(array( - 'rc.constraint_name', 'rc.update_rule', 'rc.delete_rule', - 'tc1.table_name', 'ck.table_name AS referenced_table_name', 'ck.column_name AS referenced_column_name' - )) - . ' FROM ' . $platform->quoteIdentifierInFragment('information_schema.referential_constraints rc') - . ' INNER JOIN ' . $platform->quoteIdentifierInFragment('information_schema.table_constraints tc1') - . ' ON ' . $platform->quoteIdentifierInFragment('rc.constraint_name') - . ' = ' . $platform->quoteIdentifierInFragment('tc1.constraint_name') - . ' INNER JOIN ' . $platform->quoteIdentifierInFragment('information_schema.table_constraints tc2') - . ' ON ' . $platform->quoteIdentifierInFragment('rc.unique_constraint_name') - . ' = ' . $platform->quoteIdentifierInFragment('tc2.constraint_name') - . ' INNER JOIN ' . $platform->quoteIdentifierInFragment('information_schema.key_column_usage ck') - . ' ON ' . $platform->quoteIdentifierInFragment('tc2.constraint_name') - . ' = ' . $platform->quoteIdentifierInFragment('ck.constraint_name'); - - if ($schema != '__DEFAULT_SCHEMA__') { - $sql .= ' AND ' . $platform->quoteIdentifierInFragment('rc.constraint_schema') - . ' = ' . $platform->quoteValue($schema); - } + $sql .= ' ORDER BY CASE ' . $p->quoteIdentifierChain(array('tc','constraint_type')) + . " WHEN 'PRIMARY KEY' THEN 1" + . " WHEN 'UNIQUE' THEN 2" + . " WHEN 'FOREIGN KEY' THEN 3" + . " WHEN 'CHECK' THEN 4" + . " ELSE 5 END" + . ', ' . $p->quoteIdentifierChain(array('tc','constraint_name')) + . ', ' . $p->quoteIdentifierChain(array('kcu','ordinal_position')); $results = $this->adapter->query($sql, Adapter::QUERY_MODE_EXECUTE); - $constraintRefData = array(); + $name = null; + $constraints = array(); foreach ($results->toArray() as $row) { - $constraintRefData[] = array_change_key_case($row, CASE_LOWER); + if ($row['constraint_name'] !== $name) { + $name = $row['constraint_name']; + $constraints[$name] = array( + 'constraint_name' => $name, + 'constraint_type' => $row['constraint_type'], + 'table_name' => $row['table_name'], + ); + if ('CHECK' == $row['constraint_type']) { + $constraints[$name]['check_clause'] = $row['check_clause']; + continue; + } + $constraints[$name]['columns'] = array(); + $isFK = ('FOREIGN KEY' == $row['constraint_type']); + if ($isFK) { + $constraints[$name]['referenced_table_schema'] = $row['referenced_table_schema']; + $constraints[$name]['referenced_table_name'] = $row['referenced_table_name']; + $constraints[$name]['referenced_columns'] = array(); + $constraints[$name]['match_option'] = $row['match_option']; + $constraints[$name]['update_rule'] = $row['update_rule']; + $constraints[$name]['delete_rule'] = $row['delete_rule']; + } + } + $constraints[$name]['columns'][] = $row['column_name']; + if ($isFK) { + $constraints[$name]['referenced_columns'][] = $row['referenced_column_name']; + } } - $this->prepareDataHierarchy('constraint_references', $schema); - $this->data['constraint_references'][$schema] = $constraintRefData; - + $this->data['constraints'][$schema][$table] = $constraints; } protected function loadTriggerData($schema) @@ -284,16 +305,22 @@ protected function loadTriggerData($schema) 'action_condition', 'action_statement', 'action_orientation', - 'action_timing', - 'action_reference_old_table', - 'action_reference_new_table', - 'action_reference_old_row', - 'action_reference_new_row', + array('action_timing' => 'condition_timing'), + array('action_reference_old_table' => 'condition_reference_old_table'), + array('action_reference_new_table' => 'condition_reference_new_table'), 'created', ); array_walk($isColumns, function (&$c) use ($p) { - $c = $p->quoteIdentifier($c); + if (is_array($c)) { + $alias = key($c); + $c = $p->quoteIdentifierChain($c); + if (is_string($alias)) { + $c .= ' ' . $p->quoteIdentifier($alias); + } + } else { + $c = $p->quoteIdentifier($c); + } }); $sql = 'SELECT ' . implode(', ', $isColumns) @@ -313,6 +340,8 @@ protected function loadTriggerData($schema) $data = array(); foreach ($results->toArray() as $row) { $row = array_change_key_case($row, CASE_LOWER); + $row['action_reference_old_row'] = 'OLD'; + $row['action_reference_new_row'] = 'NEW'; if (null !== $row['created']) { $row['created'] = new \DateTime($row['created']); } diff --git a/library/Zend/Db/Metadata/Source/SqlServerMetadata.php b/library/Zend/Db/Metadata/Source/SqlServerMetadata.php index 736997a1422..34f62a018d9 100644 --- a/library/Zend/Db/Metadata/Source/SqlServerMetadata.php +++ b/library/Zend/Db/Metadata/Source/SqlServerMetadata.php @@ -10,9 +10,9 @@ namespace Zend\Db\Metadata\Source; -use Zend\Db\Metadata\MetadataInterface, - Zend\Db\Adapter\Adapter, - Zend\Db\Metadata\Object; +use Zend\Db\Adapter\Adapter; +use Zend\Db\Metadata\MetadataInterface; +use Zend\Db\Metadata\Object; /** * @category Zend @@ -165,116 +165,130 @@ protected function loadColumnData($table, $schema) protected function loadConstraintData($table, $schema) { - $platform = $this->adapter->getPlatform(); - - // LOAD CONSTRAINT NAMES - - $isColumns = array( - 'CONSTRAINT_NAME', - 'TABLE_SCHEMA', - 'TABLE_NAME', - 'CONSTRAINT_TYPE' - ); - - array_walk($isColumns, function (&$c) use ($platform) { $c = $platform->quoteIdentifier($c); }); - - $sql = 'SELECT ' . implode(', ', $isColumns) - . ' FROM ' . $platform->quoteIdentifier('INFORMATION_SCHEMA') - . $platform->getIdentifierSeparator() . $platform->quoteIdentifier('TABLE_CONSTRAINTS') - . ' WHERE ' . $platform->quoteIdentifier('TABLE_SCHEMA') - . ' != ' . $platform->quoteValue('INFORMATION_SCHEMA'); - - if ($schema !== '__DEFAULT_SCHEMA__') { - $sql .= ' AND ' . $platform->quoteIdentifier('TABLE_SCHEMA') - . ' = ' . $platform->quoteValue($schema); - } - - $results = $this->adapter->query($sql, Adapter::QUERY_MODE_EXECUTE); - - $constraintData = array(); - foreach ($results->toArray() as $row) { - $constraintData[] = array_change_key_case($row, CASE_LOWER); + if (isset($this->data['constraints'][$schema][$table])) { + return; } - $this->prepareDataHierarchy('constraint_names', $schema); - $this->data['constraint_names'][$schema] = $constraintData; - - // LOAD CONSTRAINT KEYS + $this->prepareDataHierarchy('constraints', $schema, $table); $isColumns = array( - 'CONSTRAINT_NAME', - 'TABLE_SCHEMA', - 'TABLE_NAME', - 'COLUMN_NAME', - 'ORDINAL_POSITION' + array('T','TABLE_NAME'), + array('TC','CONSTRAINT_NAME'), + array('TC','CONSTRAINT_TYPE'), + array('KCU','COLUMN_NAME'), + array('CC','CHECK_CLAUSE'), + array('RC','MATCH_OPTION'), + array('RC','UPDATE_RULE'), + array('RC','DELETE_RULE'), + array('REFERENCED_TABLE_SCHEMA' => 'KCU2','TABLE_SCHEMA'), + array('REFERENCED_TABLE_NAME' => 'KCU2','TABLE_NAME'), + array('REFERENCED_COLUMN_NAME' => 'KCU2','COLUMN_NAME'), ); - array_walk($isColumns, function (&$c) use ($platform) { $c = $platform->quoteIdentifier($c); }); + $p = $this->adapter->getPlatform(); - $sql = 'SELECT ' . implode(', ', $isColumns) - . ' FROM ' . $platform->quoteIdentifier('INFORMATION_SCHEMA') - . $platform->getIdentifierSeparator() . $platform->quoteIdentifier('KEY_COLUMN_USAGE') - . ' WHERE ' . $platform->quoteIdentifier('TABLE_SCHEMA') - . ' != ' . $platform->quoteValue('INFORMATION_SCHEMA'); - - if ($schema != null || $this->defaultSchema != null) { - if ($schema == null) { - $schema = $this->defaultSchema; + array_walk($isColumns, function (&$c) use ($p) { + $alias = key($c); + $c = $p->quoteIdentifierChain($c); + if (is_string($alias)) { + $c .= ' ' . $p->quoteIdentifier($alias); } - $sql .= ' AND ' . $platform->quoteIdentifier('TABLE_SCHEMA') - . ' = ' . $platform->quoteValue($schema); - } + }); - $results = $this->adapter->query($sql, Adapter::QUERY_MODE_EXECUTE); + $sql = 'SELECT ' . implode(', ', $isColumns) + . ' FROM ' . $p->quoteIdentifierChain(array('INFORMATION_SCHEMA','TABLES')) . ' T' + + . ' INNER JOIN ' . $p->quoteIdentifierChain(array('INFORMATION_SCHEMA','TABLE_CONSTRAINTS')) . ' TC' + . ' ON ' . $p->quoteIdentifierChain(array('T','TABLE_SCHEMA')) + . ' = ' . $p->quoteIdentifierChain(array('TC','TABLE_SCHEMA')) + . ' AND ' . $p->quoteIdentifierChain(array('T','TABLE_NAME')) + . ' = ' . $p->quoteIdentifierChain(array('TC','TABLE_NAME')) + + . ' LEFT JOIN ' . $p->quoteIdentifierChain(array('INFORMATION_SCHEMA','KEY_COLUMN_USAGE')) . ' KCU' + . ' ON ' . $p->quoteIdentifierChain(array('TC','TABLE_SCHEMA')) + . ' = ' . $p->quoteIdentifierChain(array('KCU','TABLE_SCHEMA')) + . ' AND ' . $p->quoteIdentifierChain(array('TC','TABLE_NAME')) + . ' = ' . $p->quoteIdentifierChain(array('KCU','TABLE_NAME')) + . ' AND ' . $p->quoteIdentifierChain(array('TC','CONSTRAINT_NAME')) + . ' = ' . $p->quoteIdentifierChain(array('KCU','CONSTRAINT_NAME')) + + . ' LEFT JOIN ' . $p->quoteIdentifierChain(array('INFORMATION_SCHEMA','CHECK_CONSTRAINTS')) . ' CC' + . ' ON ' . $p->quoteIdentifierChain(array('TC','CONSTRAINT_SCHEMA')) + . ' = ' . $p->quoteIdentifierChain(array('CC','CONSTRAINT_SCHEMA')) + . ' AND ' . $p->quoteIdentifierChain(array('TC','CONSTRAINT_NAME')) + . ' = ' . $p->quoteIdentifierChain(array('CC','CONSTRAINT_NAME')) + + . ' LEFT JOIN ' . $p->quoteIdentifierChain(array('INFORMATION_SCHEMA','REFERENTIAL_CONSTRAINTS')) . ' RC' + . ' ON ' . $p->quoteIdentifierChain(array('TC','CONSTRAINT_SCHEMA')) + . ' = ' . $p->quoteIdentifierChain(array('RC','CONSTRAINT_SCHEMA')) + . ' AND ' . $p->quoteIdentifierChain(array('TC','CONSTRAINT_NAME')) + . ' = ' . $p->quoteIdentifierChain(array('RC','CONSTRAINT_NAME')) + + . ' LEFT JOIN ' . $p->quoteIdentifierChain(array('INFORMATION_SCHEMA','KEY_COLUMN_USAGE')) . ' KCU2' + . ' ON ' . $p->quoteIdentifierChain(array('RC','UNIQUE_CONSTRAINT_SCHEMA')) + . ' = ' . $p->quoteIdentifierChain(array('KCU2','CONSTRAINT_SCHEMA')) + . ' AND ' . $p->quoteIdentifierChain(array('RC','UNIQUE_CONSTRAINT_NAME')) + . ' = ' . $p->quoteIdentifierChain(array('KCU2','CONSTRAINT_NAME')) + . ' AND ' . $p->quoteIdentifierChain(array('KCU','ORDINAL_POSITION')) + . ' = ' . $p->quoteIdentifierChain(array('KCU2','ORDINAL_POSITION')) + + . ' WHERE ' . $p->quoteIdentifierChain(array('T','TABLE_NAME')) + . ' = ' . $p->quoteValue($table) + . ' AND ' . $p->quoteIdentifierChain(array('T','TABLE_TYPE')) + . ' IN (' . $p->quoteValueList(array('BASE TABLE', 'VIEW')) . ')'; - $constraintKeyData = array(); - foreach ($results->toArray() as $row) { - $constraintKeyData[] = array_change_key_case($row, CASE_LOWER); + if ($schema != self::DEFAULT_SCHEMA) { + $sql .= ' AND ' . $p->quoteIdentifierChain(array('T','TABLE_SCHEMA')) + . ' = ' . $p->quoteValue($schema); + } else { + $sql .= ' AND ' . $p->quoteIdentifierChain(array('T','TABLE_SCHEMA')) + . ' != ' . $p->quoteValue('INFORMATION_SCHEMA'); } - $this->prepareDataHierarchy('constraint_keys', $schema); - $this->data['constraint_keys'][$schema] = $constraintKeyData; - - // LOAD CONSTRAINT REFERENCES - - $quoteIdentifierForWalk = function (&$c) use ($platform) { $c = $platform->quoteIdentifierInFragment($c); }; - $quoteSelectList = function (array $identifierList) use ($platform, $quoteIdentifierForWalk) { - array_walk($identifierList, $quoteIdentifierForWalk); - return implode(', ', $identifierList); - }; - - // target: CONSTRAINT_SCHEMA, CONSTRAINT_NAME, UPDATE_RULE, DELETE_RULE, REFERENCE_CONSTRAINT_NAME - - $sql = 'SELECT ' . $quoteSelectList(array( - 'RC.CONSTRAINT_NAME', 'RC.UPDATE_RULE', 'RC.DELETE_RULE', - 'TC1.TABLE_NAME', 'CK.TABLE_NAME AS REFERENCED_TABLE_NAME', 'CK.COLUMN_NAME AS REFERENCED_COLUMN_NAME' - )) - . ' FROM ' . $platform->quoteIdentifierInFragment('INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS RC') - . ' INNER JOIN ' . $platform->quoteIdentifierInFragment('INFORMATION_SCHEMA.TABLE_CONSTRAINTS TC1') - . ' ON ' . $platform->quoteIdentifierInFragment('RC.CONSTRAINT_NAME') - . ' = ' . $platform->quoteIdentifierInFragment('TC1.CONSTRAINT_NAME') - . ' INNER JOIN ' . $platform->quoteIdentifierInFragment('INFORMATION_SCHEMA.TABLE_CONSTRAINTS TC2') - . ' ON ' . $platform->quoteIdentifierInFragment('RC.UNIQUE_CONSTRAINT_NAME') - . ' = ' . $platform->quoteIdentifierInFragment('TC2.CONSTRAINT_NAME') - . ' INNER JOIN ' . $platform->quoteIdentifierInFragment('INFORMATION_SCHEMA.KEY_COLUMN_USAGE CK') - . ' ON ' . $platform->quoteIdentifierInFragment('TC2.CONSTRAINT_NAME') - . ' = ' . $platform->quoteIdentifierInFragment('CK.CONSTRAINT_NAME'); - - if ($schema != '__DEFAULT_SCHEMA__') { - $sql .= ' AND ' . $platform->quoteIdentifierInFragment('RC.CONSTRAINT_SCHEMA') - . ' = ' . $platform->quoteValue($schema); - } + $sql .= ' ORDER BY CASE ' . $p->quoteIdentifierChain(array('TC','CONSTRAINT_TYPE')) + . " WHEN 'PRIMARY KEY' THEN 1" + . " WHEN 'UNIQUE' THEN 2" + . " WHEN 'FOREIGN KEY' THEN 3" + . " WHEN 'CHECK' THEN 4" + . " ELSE 5 END" + . ', ' . $p->quoteIdentifierChain(array('TC','CONSTRAINT_NAME')) + . ', ' . $p->quoteIdentifierChain(array('KCU','ORDINAL_POSITION')); $results = $this->adapter->query($sql, Adapter::QUERY_MODE_EXECUTE); - $constraintRefData = array(); + $name = null; + $constraints = array(); + $isFK = false; foreach ($results->toArray() as $row) { - $constraintRefData[] = array_change_key_case($row, CASE_LOWER); + if ($row['CONSTRAINT_NAME'] !== $name) { + $name = $row['CONSTRAINT_NAME']; + $constraints[$name] = array( + 'constraint_name' => $name, + 'constraint_type' => $row['CONSTRAINT_TYPE'], + 'table_name' => $row['TABLE_NAME'], + ); + if ('CHECK' == $row['CONSTRAINT_TYPE']) { + $constraints[$name]['check_clause'] = $row['CHECK_CLAUSE']; + continue; + } + $constraints[$name]['columns'] = array(); + $isFK = ('FOREIGN KEY' == $row['CONSTRAINT_TYPE']); + if ($isFK) { + $constraints[$name]['referenced_table_schema'] = $row['REFERENCED_TABLE_SCHEMA']; + $constraints[$name]['referenced_table_name'] = $row['REFERENCED_TABLE_NAME']; + $constraints[$name]['referenced_columns'] = array(); + $constraints[$name]['match_option'] = $row['MATCH_OPTION']; + $constraints[$name]['update_rule'] = $row['UPDATE_RULE']; + $constraints[$name]['delete_rule'] = $row['DELETE_RULE']; + } + } + $constraints[$name]['columns'][] = $row['COLUMN_NAME']; + if ($isFK) { + $constraints[$name]['referenced_columns'][] = $row['REFERENCED_COLUMN_NAME']; + } } - $this->prepareDataHierarchy('constraint_references', $schema); - $this->data['constraint_references'][$schema] = $constraintRefData; - + $this->data['constraints'][$schema][$table] = $constraints; } protected function loadTriggerData($schema) diff --git a/library/Zend/Db/Metadata/Source/SqliteMetadata.php b/library/Zend/Db/Metadata/Source/SqliteMetadata.php index a717a2cca46..edf74dd2d11 100644 --- a/library/Zend/Db/Metadata/Source/SqliteMetadata.php +++ b/library/Zend/Db/Metadata/Source/SqliteMetadata.php @@ -10,8 +10,8 @@ namespace Zend\Db\Metadata\Source; -use Zend\Db\Metadata\MetadataInterface; use Zend\Db\Adapter\Adapter; +use Zend\Db\Metadata\MetadataInterface; use Zend\Db\Metadata\Object; use Zend\Db\ResultSet\ResultSetInterface; @@ -116,8 +116,12 @@ protected function loadColumnData($table, $schema) protected function loadConstraintData($table, $schema) { - parent::loadConstraintData($table, $schema); - return; + if (isset($this->data['constraints'][$schema][$table])) { + return; + } + + $this->prepareDataHierarchy('constraints', $schema, $table); + $this->loadColumnData($table, $schema); $primaryKey = array(); @@ -137,9 +141,10 @@ protected function loadConstraintData($table, $schema) continue; } $constraint = array( - 'constraint_name' => $index['name'], - 'constraint_type' => 'UNIQUE', - 'columns' => array(), + 'constraint_name' => $index['name'], + 'constraint_type' => 'UNIQUE', + 'table_name' => $table, + 'columns' => array(), ); $info = $this->fetchPragma('index_info', $index['name'], $schema); @@ -151,45 +156,45 @@ protected function loadConstraintData($table, $schema) $constraint['constraint_type'] = 'PRIMARY KEY'; $primaryKey = null; } - $constraints[] = $constraint; + $constraints[$constraint['constraint_name']] = $constraint; } if (null !== $primaryKey) { - $constraints[] = array( - 'constraint_name' => '_zf_pk_' . $table, + $constraintName = '_zf_' . $table . '_PRIMARY'; + $constraints[$constraintName] = array( + 'constraint_name' => $constraintName, 'constraint_type' => 'PRIMARY KEY', + 'table_name' => $table, 'columns' => $primaryKey, ); } $foreignKeys = $this->fetchPragma('foreign_key_list', $table, $schema); - $id = $constraint = null; + $id = $name = null; foreach ($foreignKeys as $fk) { if ($id !== $fk['id']) { - if (null !== $constraint) { - $constraints[] = $constraint; - } $id = $fk['id']; - $constraint = array( - 'constraint_name' => '_zf_fk_' . $table . '_' . $id, + $name = '_zf_' . $table . '_FOREIGN_KEY_' . ($id + 1); + $constraints[$name] = array( + 'constraint_name' => $name, 'constraint_type' => 'FOREIGN KEY', + 'table_name' => $table, 'columns' => array(), - 'referenced_table' => $fk['table'], - 'referenced_columns' => array(), + 'referenced_table_schema' => $schema, + 'referenced_table_name' => $fk['table'], + 'referenced_columns' => array(), // TODO: Verify match, on_update, and on_delete values conform to SQL Standard 'match_option' => strtoupper($fk['match']), 'update_rule' => strtoupper($fk['on_update']), 'delete_rule' => strtoupper($fk['on_delete']), ); } - $constraint['columns'][] = $fk['from']; - $constraint['referenced_columns'][] = $fk['to']; - } - if (null !== $constraint) { - $constraints[] = $constraint; + $constraints[$name]['columns'][] = $fk['from']; + $constraints[$name]['referenced_columns'][] = $fk['to']; } + $this->data['constraints'][$schema][$table] = $constraints; } protected function loadTriggerData($schema) diff --git a/library/Zend/Db/ResultSet/AbstractResultSet.php b/library/Zend/Db/ResultSet/AbstractResultSet.php index 6db053407db..c72773ae1d9 100644 --- a/library/Zend/Db/ResultSet/AbstractResultSet.php +++ b/library/Zend/Db/ResultSet/AbstractResultSet.php @@ -10,12 +10,12 @@ namespace Zend\Db\ResultSet; -use Iterator; -use Zend\Db\Adapter\Driver\ResultInterface; use ArrayIterator; -use IteratorAggregate; -use Countable; use ArrayObject; +use Countable; +use Iterator; +use IteratorAggregate; +use Zend\Db\Adapter\Driver\ResultInterface; /** * @category Zend diff --git a/library/Zend/Db/ResultSet/HydratingResultSet.php b/library/Zend/Db/ResultSet/HydratingResultSet.php index a55c218eabe..da6022cae8a 100644 --- a/library/Zend/Db/ResultSet/HydratingResultSet.php +++ b/library/Zend/Db/ResultSet/HydratingResultSet.php @@ -10,9 +10,9 @@ namespace Zend\Db\ResultSet; -use Zend\Stdlib\Hydrator\HydratorInterface; -use Zend\Stdlib\Hydrator\ArraySerializable; use ArrayObject; +use Zend\Stdlib\Hydrator\ArraySerializable; +use Zend\Stdlib\Hydrator\HydratorInterface; /** * @category Zend diff --git a/library/Zend/Db/ResultSet/ResultSetInterface.php b/library/Zend/Db/ResultSet/ResultSetInterface.php index ff5d605406e..b8e9523675a 100644 --- a/library/Zend/Db/ResultSet/ResultSetInterface.php +++ b/library/Zend/Db/ResultSet/ResultSetInterface.php @@ -1,4 +1,12 @@ table = $table; @@ -209,6 +209,9 @@ public function columns(array $columns, $prefixColumnsWithTable = true) */ public function join($name, $on, $columns = self::SQL_STAR, $type = self::JOIN_INNER) { + if (is_array($name) && (!is_string(key($name)) || count($name) !== 1)) { + throw new Exception\InvalidArgumentException('join() expects $name as an array is a single element associative array'); + } if (!is_array($columns)) { $columns = array($columns); } @@ -236,7 +239,7 @@ public function where($predicate, $combination = Predicate\PredicateSet::OP_AND) $predicate($this->where); } else { if (is_string($predicate)) { - $predicate = new Predicate\Expression(str_replace('%', '%%',$predicate)); + $predicate = new Predicate\Expression($predicate); $this->where->addPredicate($predicate, $combination); } elseif (is_array($predicate)) { foreach ($predicate as $pkey => $pvalue) { @@ -423,38 +426,40 @@ protected function processSelect(PlatformInterface $platform, Adapter $adapter = return null; } + $table = $this->table; + $schema = $alias = null; + + if (is_array($table)) { + $alias = key($this->table); + $table = current($this->table); + } + // create quoted table name to use in columns processing - if ($this->table instanceof TableIdentifier) { - list($table, $schema, $alias) = $this->table->getTableAndSchema(); - $table = $platform->quoteIdentifier($table); - if ($schema) { - $table = $platform->quoteIdentifier($schema) . $platform->getIdentifierSeparator() . $table; - } - - if ($alias) { - $alias = $platform->quoteIdentifier($alias); - $table = $table . ' AS ' . $alias; - } - } else { - $table = $platform->quoteIdentifier($this->table); + if ($table instanceof TableIdentifier) { + list($table, $schema) = $table->getTableAndSchema(); } - $quotedTable = ''; - if ($this->prefixColumnsWithTable) { - if (isset($alias)) { - $quotedTable = $alias . $platform->getIdentifierSeparator(); - } else { - $quotedTable = $table . $platform->getIdentifierSeparator(); - } + $table = $platform->quoteIdentifier($table); + if ($schema) { + $table = $platform->quoteIdentifier($schema) . $platform->getIdentifierSeparator() . $table; + } + + if ($alias) { + $fromTable = $platform->quoteIdentifier($alias); + $table .= ' AS ' . $fromTable; + } else { + $fromTable = ($this->prefixColumnsWithTable) ? $table : ''; } + $fromTable .= $platform->getIdentifierSeparator(); + // process table columns $columns = array(); foreach ($this->columns as $columnIndexOrAs => $column) { $columnName = ''; if ($column === self::SQL_STAR) { - $columns[] = array($quotedTable . self::SQL_STAR); + $columns[] = array($fromTable . self::SQL_STAR); continue; } @@ -470,7 +475,7 @@ protected function processSelect(PlatformInterface $platform, Adapter $adapter = } $columnName .= $columnParts['sql']; } else { - $columnName .= $quotedTable . $platform->quoteIdentifier($column); + $columnName .= $fromTable . $platform->quoteIdentifier($column); } // process As portion @@ -488,12 +493,7 @@ protected function processSelect(PlatformInterface $platform, Adapter $adapter = foreach ($this->joins as $join) { foreach ($join['columns'] as $jKey => $jColumn) { $jColumns = array(); - if (is_array($join['name'])) { - $keys = array_keys($join['name']); - $name = array_pop($keys); - } else { - $name = $join['name']; - } + $name = (is_array($join['name'])) ? key($join['name']) : $name = $join['name']; $jColumns[] = $platform->quoteIdentifier($name) . $separator . $platform->quoteIdentifierInFragment($jColumn); if (is_string($jKey)) { $jColumns[] = $platform->quoteIdentifier($jKey); @@ -516,20 +516,11 @@ protected function processJoin(PlatformInterface $platform, Adapter $adapter = n // process joins $joinSpecArgArray = array(); foreach ($this->joins as $j => $join) { - - if (is_array($join['name'])) { - $keys = array_keys($join['name']); - $alias = array_pop($keys); - $name = $join['name'][$alias]; - - $nameArg = $platform->quoteIdentifier($name) . ' AS ' . $platform->quoteIdentifier($alias); - } else { - $nameArg = $platform->quoteIdentifier($join['name']); - } - $joinSpecArgArray[$j] = array(); $joinSpecArgArray[$j][] = strtoupper($join['type']); // type - $joinSpecArgArray[$j][] = $nameArg; // table + $joinSpecArgArray[$j][] = (is_array($join['name'])) + ? $platform->quoteIdentifier(current($join['name'])) . ' AS ' . $platform->quoteIdentifier(key($join['name'])) + : $platform->quoteIdentifier($join['name']); // table $joinSpecArgArray[$j][] = $platform->quoteIdentifierInFragment($join['on'], array('=', 'AND', 'OR', '(', ')', 'BETWEEN')); // on } diff --git a/library/Zend/Db/Sql/Sql.php b/library/Zend/Db/Sql/Sql.php index 3a28cf99e2f..3c7a0d2d5fd 100644 --- a/library/Zend/Db/Sql/Sql.php +++ b/library/Zend/Db/Sql/Sql.php @@ -10,9 +10,9 @@ namespace Zend\Db\Sql; -use Zend\Db\Adapter\Adapter, - Zend\Db\Adapter\Driver\StatementInterface, - Zend\Db\Adapter\Platform\PlatformInterface; +use Zend\Db\Adapter\Adapter; +use Zend\Db\Adapter\Driver\StatementInterface; +use Zend\Db\Adapter\Platform\PlatformInterface; /** * @category Zend diff --git a/library/Zend/Db/Sql/TableIdentifier.php b/library/Zend/Db/Sql/TableIdentifier.php index 5d7b3609a32..f1f75c23861 100644 --- a/library/Zend/Db/Sql/TableIdentifier.php +++ b/library/Zend/Db/Sql/TableIdentifier.php @@ -26,23 +26,12 @@ class TableIdentifier */ protected $schema; - /** - * @var string - */ - protected $alias; - /** * @param string $table * @param string $schema */ public function __construct($table, $schema = null) { - if (is_array($table)) { - $keys = array_keys($table); - $this->alias = array_pop($keys) ?: null; - - $table = $table[$this->alias]; - } $this->table = $table; $this->schema = $schema; } @@ -87,33 +76,9 @@ public function getSchema() return $this->schema; } - /** - * @return bool - */ - public function hasAlias() - { - return ($this->alias != null); - } - - /** - * @return null|string - */ - public function getAlias() - { - return $this->alias; - } - - /** - * @param string $alias - */ - public function setAlias($alias) - { - $this->alias = $alias; - } - public function getTableAndSchema() { - return array($this->table, $this->schema, $this->alias); + return array($this->table, $this->schema); } } diff --git a/library/Zend/Db/Sql/Update.php b/library/Zend/Db/Sql/Update.php index df6fbd09152..5507b3bfa5b 100644 --- a/library/Zend/Db/Sql/Update.php +++ b/library/Zend/Db/Sql/Update.php @@ -10,11 +10,11 @@ namespace Zend\Db\Sql; -use Zend\Db\Adapter\Adapter, - Zend\Db\Adapter\Driver\StatementInterface, - Zend\Db\Adapter\Platform\PlatformInterface, - Zend\Db\Adapter\Platform\Sql92, - Zend\Db\Adapter\ParameterContainer; +use Zend\Db\Adapter\Adapter; +use Zend\Db\Adapter\Driver\StatementInterface; +use Zend\Db\Adapter\ParameterContainer; +use Zend\Db\Adapter\Platform\PlatformInterface; +use Zend\Db\Adapter\Platform\Sql92; /** * @category Zend diff --git a/library/Zend/Db/Sql/Where.php b/library/Zend/Db/Sql/Where.php index 693c3e82f22..d0d2673cd9f 100644 --- a/library/Zend/Db/Sql/Where.php +++ b/library/Zend/Db/Sql/Where.php @@ -10,10 +10,10 @@ namespace Zend\Db\Sql; -use Zend\Db\Adapter\Adapter, - Zend\Db\Adapter\Driver\StatementInterface, - Zend\Db\Adapter\Platform\PlatformInterface, - Zend\Db\Adapter\Platform\Sql92; +use Zend\Db\Adapter\Adapter; +use Zend\Db\Adapter\Driver\StatementInterface; +use Zend\Db\Adapter\Platform\PlatformInterface; +use Zend\Db\Adapter\Platform\Sql92; /** * @category Zend diff --git a/library/Zend/Db/TableGateway/AbstractTableGateway.php b/library/Zend/Db/TableGateway/AbstractTableGateway.php index 0c34f33cb92..75d05a43d7c 100644 --- a/library/Zend/Db/TableGateway/AbstractTableGateway.php +++ b/library/Zend/Db/TableGateway/AbstractTableGateway.php @@ -10,15 +10,15 @@ namespace Zend\Db\TableGateway; -use Zend\Db\Adapter\Adapter, - Zend\Db\Sql\TableIdentifier, - Zend\Db\ResultSet\ResultSetInterface, - Zend\Db\ResultSet\ResultSet, - Zend\Db\Sql\Sql, - Zend\Db\Sql\Select, - Zend\Db\Sql\Insert, - Zend\Db\Sql\Update, - Zend\Db\Sql\Delete; +use Zend\Db\Adapter\Adapter; +use Zend\Db\ResultSet\ResultSet; +use Zend\Db\ResultSet\ResultSetInterface; +use Zend\Db\Sql\Delete; +use Zend\Db\Sql\Insert; +use Zend\Db\Sql\Select; +use Zend\Db\Sql\Sql; +use Zend\Db\Sql\TableIdentifier; +use Zend\Db\Sql\Update; /** * @category Zend diff --git a/library/Zend/Db/TableGateway/Feature/AbstractFeature.php b/library/Zend/Db/TableGateway/Feature/AbstractFeature.php index 6f2caf65e67..500f1de52e3 100644 --- a/library/Zend/Db/TableGateway/Feature/AbstractFeature.php +++ b/library/Zend/Db/TableGateway/Feature/AbstractFeature.php @@ -1,9 +1,17 @@ tableGateway->adapter = $this->masterAdapter; } -} \ No newline at end of file +} diff --git a/library/Zend/Db/TableGateway/Feature/MetadataFeature.php b/library/Zend/Db/TableGateway/Feature/MetadataFeature.php index d928d61a99c..f050e7a0d21 100644 --- a/library/Zend/Db/TableGateway/Feature/MetadataFeature.php +++ b/library/Zend/Db/TableGateway/Feature/MetadataFeature.php @@ -10,9 +10,9 @@ namespace Zend\Db\TableGateway\Feature; -use Zend\Db\Metadata\MetadataInterface, - Zend\Db\Metadata\Metadata, - Zend\Db\TableGateway\Exception; +use Zend\Db\Metadata\Metadata; +use Zend\Db\Metadata\MetadataInterface; +use Zend\Db\TableGateway\Exception; /** * @category Zend diff --git a/library/Zend/Db/TableGateway/Feature/RowGatewayFeature.php b/library/Zend/Db/TableGateway/Feature/RowGatewayFeature.php index b03ddafdaed..e900aaa77ec 100644 --- a/library/Zend/Db/TableGateway/Feature/RowGatewayFeature.php +++ b/library/Zend/Db/TableGateway/Feature/RowGatewayFeature.php @@ -1,10 +1,18 @@ =5.3.3" + } +} \ No newline at end of file diff --git a/library/Zend/Debug.php b/library/Zend/Debug.php index d34abd594c0..1c230accabe 100644 --- a/library/Zend/Debug.php +++ b/library/Zend/Debug.php @@ -1,21 +1,11 @@ directoryScanner == null) { $this->directoryScanner = new DirectoryScanner(); } - + $this->directoryScanner->addFileScanner($fileScanner); } @@ -103,8 +111,8 @@ public function addCodeScannerFile(FileScanner $fileScanner) */ public function compile() { - /* - * @var $classScanner \Zend\Code\Scanner\DerivedClassScanner + /* + * @var $classScanner \Zend\Code\Scanner\DerivedClassScanner */ foreach ($this->directoryScanner->getClassNames() as $class) { $this->processClass($class); @@ -246,9 +254,6 @@ protected function processClass($class) } } } - - - //var_dump($this->classes); } protected function processParams(&$def, Reflection\ClassReflection $rClass, Reflection\MethodReflection $rMethod) diff --git a/library/Zend/Di/Definition/DefinitionInterface.php b/library/Zend/Di/Definition/DefinitionInterface.php index 45ea83a5c74..9b5370cd8fe 100644 --- a/library/Zend/Di/Definition/DefinitionInterface.php +++ b/library/Zend/Di/Definition/DefinitionInterface.php @@ -1,4 +1,12 @@ introspectionStrategy = $introspectionStrategy; } - + /** * @return IntrospectionStrategy */ @@ -82,7 +90,7 @@ public function forceLoadClass($class) /** * Retrieves registered classes names - * + * * @return array */ public function getClasses() @@ -101,7 +109,7 @@ public function hasClass($class) if ($this->explicitLookups === true) { return (array_key_exists($class, $this->classes)); } - + return class_exists($class) || interface_exists($class); } @@ -324,9 +332,6 @@ protected function processClass($class) } } } - - - //var_dump($this->classes); } protected function processParams(&$def, Reflection\ClassReflection $rClass, Reflection\MethodReflection $rMethod) diff --git a/library/Zend/Di/DefinitionList.php b/library/Zend/Di/DefinitionList.php index 22f21abf765..a5a5b3892e5 100644 --- a/library/Zend/Di/DefinitionList.php +++ b/library/Zend/Di/DefinitionList.php @@ -1,4 +1,12 @@ definitions(); - $class = get_class($instance); + $class = $this->getClass($instance); $injectionMethods = array( $class => ($definitions->hasClass($class)) ? $definitions->getMethods($class) : array() ); @@ -300,7 +308,8 @@ protected function handleInjectDependencies($instance, $injectionMethods, $param $methodParams = $definitions->getMethodParameters($type, $typeInjectionMethod); if ($methodParams) { foreach ($methodParams as $methodParam) { - if (get_class($objectToInject) == $methodParam[1] || $this->isSubclassOf(get_class($objectToInject), $methodParam[1])) { + $objectToInjectClass = $this->getClass($objectToInject); + if ($objectToInjectClass == $methodParam[1] || $this->isSubclassOf($objectToInjectClass, $methodParam[1])) { if ($this->resolveAndCallInjectionMethodForInstance($instance, $typeInjectionMethod, array($methodParam[0] => $objectToInject), $instanceAlias, true, $type)) { $calledMethods[$typeInjectionMethod] = true; } @@ -315,7 +324,7 @@ protected function handleInjectDependencies($instance, $injectionMethods, $param } if ($methodsToCall) { foreach ($methodsToCall as $methodInfo) { - $this->resolveAndCallInjectionMethodForInstance($instance, $methodInfo['method'], $methodInfo['args'], $instanceAlias, true, get_class($instance)); + $this->resolveAndCallInjectionMethodForInstance($instance, $methodInfo['method'], $methodInfo['args'], $instanceAlias, true, $instanceClass); } } } @@ -375,7 +384,7 @@ protected function createInstanceViaCallback($callback, $params, $alias) } if (is_array($callback)) { - $class = (is_object($callback[0])) ? get_class($callback[0]) : $callback[0]; + $class = (is_object($callback[0])) ? $this->getClass($callback[0]) : $callback[0]; $method = $callback[1]; } elseif (is_string($callback) && strpos($callback, '::') !== false) { list($class, $method) = explode('::', $callback, 2); @@ -402,7 +411,7 @@ protected function createInstanceViaCallback($callback, $params, $alias) */ protected function resolveAndCallInjectionMethodForInstance($instance, $method, $params, $alias, $methodIsRequired, $methodClass = null) { - $methodClass = ($methodClass) ?: get_class($instance); + $methodClass = ($methodClass) ?: $this->getClass($instance); $callParameters = $this->resolveMethodParameters($methodClass, $method, $params, $alias, $methodIsRequired); if ($callParameters == false) { return false; @@ -657,6 +666,21 @@ protected function resolveMethodParameters($class, $method, array $callTimeUserP return $resolvedParams; // return ordered list of parameters } + /** + * Utility method used to retrieve the class of a particular instance. This is here to allow extending classes to + * override how class names are resolved + * + * @internal this method is used by the ServiceLocator\DependencyInjectorProxy class to interact with instances + * and is a hack to be used internally until a major refactor does not split the `resolveMethodParameters`. Do not + * rely on its functionality. + * @param Object $instance + * @return string + */ + protected function getClass($instance) + { + return get_class($instance); + } + /** * @see https://bugs.php.net/bug.php?id=53727 * diff --git a/library/Zend/Di/Display/Console.php b/library/Zend/Di/Display/Console.php index de48d393332..8426b551b6b 100644 --- a/library/Zend/Di/Display/Console.php +++ b/library/Zend/Di/Display/Console.php @@ -1,4 +1,13 @@ instanceManager = $di->instanceManager(); } - /** - * Methods with functionality overrides - */ - /** * Override, as we want it to use the functionality defined in the proxy * @@ -35,19 +42,27 @@ public function __construct(Di $di) */ public function get($name, array $params = array()) { - $im = $this->instanceManager(); + return parent::get($name, $params); + } + /** + * {@inheritDoc} + */ + public function newInstance($name, array $params = array(), $isShared = true) + { + $instance = parent::newInstance($name, $params, $isShared); - if ($params) { - $fastHash = $im->hasSharedInstanceWithParameters($name, $params, true); - if ($fastHash) { - return $im->getSharedInstanceWithParameters(null, array(), $fastHash); - } - } else { - if ($im->hasSharedInstance($name, $params)) { - return $im->getSharedInstance($name, $params); + if ($instance instanceof GeneratorInstance) { + /* @var $instance GeneratorInstance */ + $instance->setShared($isShared); + + // When a callback is used, we don't know instance the class name. + // That's why we assume $name as the instance alias + if (null === $instance->getName()) { + $instance->setAlias($name); } } - return $this->newInstance($name, $params); + + return $instance; } /** @@ -63,32 +78,40 @@ public function get($name, array $params = array()) public function createInstanceViaConstructor($class, $params, $alias = null) { $callParameters = array(); + if ($this->di->definitions->hasMethod($class, '__construct') && (count($this->di->definitions->getMethodParameters($class, '__construct')) > 0) ) { - $callParameters = $this->resolveMethodParameters( - $class, '__construct', $params, true, $alias, true - ); + $callParameters = $this->resolveMethodParameters($class, '__construct', $params, $alias, true, true); + $callParameters = $callParameters ?: array(); } - return new GeneratorInstance($class, '__construct', $callParameters); + + return new GeneratorInstance($class, $alias, '__construct', $callParameters); } /** * Override instance creation via callback * - * @param callback $callback - * @param null|array $params + * @param callback $callback + * @param null|array $params + * @param null|string $alias * @return GeneratorInstance * @throws Exception\InvalidCallbackException */ - public function createInstanceViaCallback($callback, $params, $alias = null) + public function createInstanceViaCallback($callback, $params, $alias) { + if (is_string($callback)) { + $callback = explode('::', $callback); + } + if (!is_callable($callback)) { throw new Exception\InvalidCallbackException('An invalid constructor callback was provided'); } if (!is_array($callback) || is_object($callback[0])) { - throw new Exception\InvalidCallbackException('For purposes of service locator generation, constructor callbacks must refer to static methods only'); + throw new Exception\InvalidCallbackException( + 'For purposes of service locator generation, constructor callbacks must refer to static methods only' + ); } $class = $callback[0]; @@ -96,89 +119,59 @@ public function createInstanceViaCallback($callback, $params, $alias = null) $callParameters = array(); if ($this->di->definitions->hasMethod($class, $method)) { - $callParameters = $this->resolveMethodParameters($class, $method, $params, true, $alias, true); + $callParameters = $this->resolveMethodParameters($class, $method, $params, $alias, true, true); } - return new GeneratorInstance(null, $callback, $callParameters); + $callParameters = $callParameters ?: array(); + + return new GeneratorInstance(null, $alias, $callback, $callParameters); } /** - * Retrieve metadata for injectible methods - * - * @param string $class - * @param string $method - * @param array $params - * @param string $alias - * @return array + * {@inheritDoc} */ public function handleInjectionMethodForObject($class, $method, $params, $alias, $isRequired) { - $callParameters = $this->resolveMethodParameters($class, $method, $params, false, $alias, $isRequired); return array( 'method' => $method, - 'params' => $callParameters, + 'params' => $this->resolveMethodParameters($class, $method, $params, $alias, $isRequired), ); } /** - * Override new instance creation - * - * @param string $name - * @param array $params - * @param bool $isShared - * @return GeneratorInstance - * @throws Exception\ClassNotFoundException - * @throws Exception\RuntimeException + * {@inheritDoc} */ - public function newInstance($name, array $params = array(), $isShared = true) + protected function resolveAndCallInjectionMethodForInstance($instance, $method, $params, $alias, $methodIsRequired, $methodClass = null) { - $definition = $this->definitions(); - $instanceManager = $this->instanceManager(); - - if ($instanceManager->hasAlias($name)) { - $class = $instanceManager->getClassFromAlias($name); - $alias = $name; - } else { - $class = $name; - $alias = null; + if (!$instance instanceof GeneratorInstance) { + return parent::resolveAndCallInjectionMethodForInstance($instance, $method, $params, $alias, $methodIsRequired, $methodClass); } - if (!$definition->hasClass($class)) { - $aliasMsg = ($alias) ? '(specified by alias ' . $alias . ') ' : ''; - throw new Exception\ClassNotFoundException( - 'Class ' . $aliasMsg . $class . ' could not be located in provided definitions.' - ); - } + /* @var $instance GeneratorInstance */ + $methodClass = $instance->getClass(); + $callParameters = $this->resolveMethodParameters($methodClass, $method, $params, $alias, $methodIsRequired); - $instantiator = $definition->getInstantiator($class); - $injectionMethods = $definition->getMethods($class); - - if ($instantiator === '__construct') { - $object = $this->createInstanceViaConstructor($class, $params, $alias); - if (in_array('__construct', $injectionMethods)) { - unset($injectionMethods[array_search('__construct', $injectionMethods)]); - } - } elseif (is_callable($instantiator)) { - $object = $this->createInstanceViaCallback($instantiator, $params, $alias); - $object->setName($class); - } else { - throw new Exception\RuntimeException('Invalid instantiator'); + if ($callParameters === false) { + $instance->addMethod(array( + 'method' => $method, + 'params' => $callParameters, + )); + return true; } - if ($injectionMethods) { - foreach ($injectionMethods as $injectionMethod) { - $methodMetadata[] = $this->handleInjectionMethodForObject($class, $injectionMethod, $params, $alias); - } - } + return false; + } - if ($isShared) { - if ($params) { - $instanceManager->addSharedInstanceWithParameters($object, $name, $params); - } else { - $instanceManager->addSharedInstance($object, $name); - } + /** + * {@inheritDoc} + */ + protected function getClass($instance) + { + if ($instance instanceof GeneratorInstance) { + /* @var $instance GeneratorInstance */ + return $instance->getClass(); } - return $object; + return parent::getClass($instance); } } diff --git a/library/Zend/Di/ServiceLocator/Generator.php b/library/Zend/Di/ServiceLocator/Generator.php index dfa602aacf1..2daf035070d 100644 --- a/library/Zend/Di/ServiceLocator/Generator.php +++ b/library/Zend/Di/ServiceLocator/Generator.php @@ -1,8 +1,19 @@ definitions(); - foreach ($definitions->getClasses() as $name) { + $fetched = array_unique(array_merge($definitions->getClasses(), $im->getAliases())); + + foreach ($fetched as $name) { $getter = $this->normalizeAlias($name); $meta = $injector->get($name); $params = $meta->getParams(); - + // Build parameter list for instantiation foreach ($params as $key => $param) { if (null === $param || is_scalar($param) || is_array($param)) { @@ -88,6 +101,7 @@ public function getCodeGenerator($filename = null) } $params[$key] = $string; } elseif ($param instanceof GeneratorInstance) { + /* @var $param GeneratorInstance */ $params[$key] = sprintf('$this->%s()', $this->normalizeAlias($param->getName())); } else { $message = sprintf('Unable to use object arguments when building containers. Encountered with "%s", parameter of type "%s"', $name, get_class($param)); @@ -106,7 +120,6 @@ public function getCodeGenerator($filename = null) } // Create instantiation code - $creation = ''; $constructor = $meta->getConstructor(); if ('__construct' != $constructor) { // Constructor callback @@ -188,9 +201,9 @@ public function getCodeGenerator($filename = null) // End getter body $getterBody .= "return \$object;\n"; - $getterDef = new CodeGen\MethodGenerator(); - $getterDef->setName($getter) - ->setBody($getterBody); + $getterDef = new MethodGenerator(); + $getterDef->setName($getter); + $getterDef->setBody($getterBody); $getters[] = $getterDef; // Get cases for case statements @@ -215,14 +228,14 @@ public function getCodeGenerator($filename = null) $switch .= "}\n\n"; // Build get() method - $nameParam = new CodeGen\ParameterGenerator(); + $nameParam = new ParameterGenerator(); $nameParam->setName('name'); - $paramsParam = new CodeGen\ParameterGenerator(); + $paramsParam = new ParameterGenerator(); $paramsParam->setName('params') ->setType('array') ->setDefaultValue(array()); - $get = new CodeGen\MethodGenerator(); + $get = new MethodGenerator(); $get->setName('get'); $get->setParameters(array( $nameParam, @@ -239,7 +252,7 @@ public function getCodeGenerator($filename = null) } // Create class code generation object - $container = new CodeGen\ClassGenerator(); + $container = new ClassGenerator(); $container->setName($this->containerClass) ->setExtendedClass('ServiceLocator') ->addMethodFromGenerator($get) @@ -247,7 +260,7 @@ public function getCodeGenerator($filename = null) ->addMethods($aliasMethods); // Create PHP file code generation object - $classFile = new CodeGen\FileGenerator(); + $classFile = new FileGenerator(); $classFile->setUse('Zend\Di\ServiceLocator') ->setClass($container); @@ -265,11 +278,11 @@ public function getCodeGenerator($filename = null) /** * Reduces aliases * - * Takes alias list and reduces it to a 2-dimensional array of - * class names pointing to an array of aliases that resolve to + * Takes alias list and reduces it to a 2-dimensional array of + * class names pointing to an array of aliases that resolve to * it. - * - * @param array $aliasList + * + * @param array $aliasList * @return array */ protected function reduceAliases(array $aliasList) @@ -292,24 +305,24 @@ protected function reduceAliases(array $aliasList) /** * Create a PhpMethod code generation object named after a given alias - * - * @param string $alias - * @param class $class Class to which alias refers - * @return CodeGen\MethodGenerator + * + * @param string $alias + * @param string $class Class to which alias refers + * @return MethodGenerator */ protected function getCodeGenMethodFromAlias($alias, $class) { $alias = $this->normalizeAlias($alias); - $method = new CodeGen\MethodGenerator(); - $method->setName($alias) - ->setBody(sprintf('return $this->get(\'%s\');', $class)); + $method = new MethodGenerator(); + $method->setName($alias); + $method->setBody(sprintf('return $this->get(\'%s\');', $class)); return $method; } /** * Normalize an alias to a getter method name - * - * @param string $alias + * + * @param string $alias * @return string */ protected function normalizeAlias($alias) diff --git a/library/Zend/Di/ServiceLocator/GeneratorInstance.php b/library/Zend/Di/ServiceLocator/GeneratorInstance.php index c4f889bcb7c..997b8085987 100644 --- a/library/Zend/Di/ServiceLocator/GeneratorInstance.php +++ b/library/Zend/Di/ServiceLocator/GeneratorInstance.php @@ -1,13 +1,29 @@ name = $name; + $this->class = $class; + $this->alias = $alias; $this->constructor = $constructor; $this->params = $params; } /** - * Get name + * Retrieves the best available name for this instance (instance alias first then class name) * - * @return string + * @return string|null */ public function getName() { - return $this->name; + return $this->alias ? $this->alias : $this->class; + } + + /** + * Class of the instance. Null if class is unclear (such as when the instance is produced by a callback) + * + * @return string|null + */ + public function getClass() + { + return $this->class; + } + + /** + * Alias for the instance (if any) + * + * @return string|null + */ + public function getAlias() + { + return $this->alias; } /** * Set class name * - * In the case of an instance created via a callback, we need to set the + * In the case of an instance created via a callback, we need to set the * class name after creating the generator instance. - * - * @param string $name + * + * @param string $class * @return GeneratorInstance */ - public function setName($name) + public function setClass($class) { - $this->name = $name; + $this->class = $class; return $this; } /** - * Get constructor + * Set instance alias * - * @return mixed + * @param string $alias + * @return GeneratorInstance + */ + public function setAlias($alias) + { + $this->alias = $alias; + return $this; + } + + /** + * Get instantiator + * + * @return mixed constructor method name or callable responsible for generating instance */ public function getConstructor() { @@ -74,7 +127,8 @@ public function getConstructor() } /** - * Get params + * Parameters passed to the instantiator as an ordered list of parameters. Each parameter that refers to another + * instance fetched recursively is a GeneratorInstance itself * * @return array */ @@ -96,7 +150,21 @@ public function setMethods(array $methods) } /** - * Get methods + * Add a method called on the instance + * + * @param $method + * @return GeneratorInstance + */ + public function addMethod($method) + { + $this->methods[] = $method; + return $this; + } + + /** + * Retrieves a list of methods that are called on the instance in their call order. Each returned element has form + * array('method' => 'methodName', 'params' => array( ... ordered list of call parameters ... ), where every call + * parameter that is a recursively fetched instance is a GeneratorInstance itself * * @return array */ @@ -104,4 +172,22 @@ public function getMethods() { return $this->methods; } + + /** + * @param bool $shared + */ + public function setShared($shared) + { + $this->shared = (bool) $shared; + } + + /** + * Retrieves whether the instance is shared or not + * + * @return bool + */ + public function isShared() + { + return $this->shared; + } } diff --git a/library/Zend/Di/ServiceLocatorInterface.php b/library/Zend/Di/ServiceLocatorInterface.php index ca773bd0683..fbf6d0c83de 100644 --- a/library/Zend/Di/ServiceLocatorInterface.php +++ b/library/Zend/Di/ServiceLocatorInterface.php @@ -1,4 +1,13 @@ =5.3.3", + "zendframework/zend-code": "self.version" + } +} \ No newline at end of file diff --git a/library/Zend/DocBook/ClassMethod.php b/library/Zend/DocBook/ClassMethod.php index c63d3505593..d4a6afd1ac5 100644 --- a/library/Zend/DocBook/ClassMethod.php +++ b/library/Zend/DocBook/ClassMethod.php @@ -11,11 +11,10 @@ namespace Zend\DocBook; use Zend\Code\NameInformation; -use Zend\Code\Reflection\MethodReflection; use Zend\Code\Reflection\DocBlockReflection; +use Zend\Code\Reflection\MethodReflection; use Zend\Filter\Word\CamelCaseToDash as CamelCaseToDashFilter; - /** * @category Zend * @package Zend_DocBook diff --git a/library/Zend/DocBook/ClassParser.php b/library/Zend/DocBook/ClassParser.php index 018ab5cce8f..ca2687bdb3e 100644 --- a/library/Zend/DocBook/ClassParser.php +++ b/library/Zend/DocBook/ClassParser.php @@ -11,8 +11,8 @@ namespace Zend\DocBook; use ReflectionMethod; -use Zend\Filter\Word\CamelCaseToDash as CamelCaseToDashFilter; use Zend\Code\Reflection\ClassReflection; +use Zend\Filter\Word\CamelCaseToDash as CamelCaseToDashFilter; /** * @category Zend diff --git a/library/Zend/DocBook/composer.json b/library/Zend/DocBook/composer.json new file mode 100644 index 00000000000..d940fc10f53 --- /dev/null +++ b/library/Zend/DocBook/composer.json @@ -0,0 +1,20 @@ +{ + "name": "zendframework/zend-docbook", + "description": " ", + "license": "BSD-3-Clause", + "keywords": [ + "zf2", + "docbook" + ], + "autoload": { + "psr-0": { + "Zend\\DocBook": "" + } + }, + "target-dir": "Zend/DocBook", + "require": { + "php": ">=5.3.3", + "zendframework/zend\\code": "self.version", + "zendframework/zend\\filter": "self.version" + } +} \ No newline at end of file diff --git a/library/Zend/Dojo/BuildLayer.php b/library/Zend/Dojo/BuildLayer.php index 10303d59d03..226cbc49ebe 100644 --- a/library/Zend/Dojo/BuildLayer.php +++ b/library/Zend/Dojo/BuildLayer.php @@ -1,36 +1,24 @@ =5.3.3" + } +} \ No newline at end of file diff --git a/library/Zend/Dom/Css2Xpath.php b/library/Zend/Dom/Css2Xpath.php index ea032a686b9..861ef1fa71d 100644 --- a/library/Zend/Dom/Css2Xpath.php +++ b/library/Zend/Dom/Css2Xpath.php @@ -1,21 +1,11 @@ _encoding = (null === $encoding) ? null : (string) $encoding; + $this->encoding = (null === $encoding) ? null : (string) $encoding; return $this; } @@ -101,7 +95,7 @@ public function setEncoding($encoding) */ public function getEncoding() { - return $this->_encoding; + return $this->encoding; } /** @@ -109,7 +103,7 @@ public function getEncoding() * * @param string $document * @param null|string $encoding Document encoding - * @return \Zend\Dom\Query + * @return Query */ public function setDocument($document, $encoding = null) { @@ -118,6 +112,10 @@ public function setDocument($document, $encoding = null) } // breaking XML declaration to make syntax highlighting work if ('<' . '?xml' == substr(trim($document), 0, 5)) { + if (preg_match('/]*xmlns="([^"]+)"[^>]*>/i', $document, $matches)) { + $this->xpathNamespaces[] = $matches[1]; + return $this->setDocumentXhtml($document, $encoding); + } return $this->setDocumentXml($document, $encoding); } if (strstr($document, 'DTD XHTML')) { @@ -131,12 +129,12 @@ public function setDocument($document, $encoding = null) * * @param string $document * @param null|string $encoding Document encoding - * @return \Zend\Dom\Query + * @return Query */ public function setDocumentHtml($document, $encoding = null) { - $this->_document = (string) $document; - $this->_docType = self::DOC_HTML; + $this->document = (string) $document; + $this->docType = self::DOC_HTML; if (null !== $encoding) { $this->setEncoding($encoding); } @@ -148,12 +146,12 @@ public function setDocumentHtml($document, $encoding = null) * * @param string $document * @param null|string $encoding Document encoding - * @return \Zend\Dom\Query + * @return Query */ public function setDocumentXhtml($document, $encoding = null) { - $this->_document = (string) $document; - $this->_docType = self::DOC_XHTML; + $this->document = (string) $document; + $this->docType = self::DOC_XHTML; if (null !== $encoding) { $this->setEncoding($encoding); } @@ -165,12 +163,12 @@ public function setDocumentXhtml($document, $encoding = null) * * @param string $document * @param null|string $encoding Document encoding - * @return \Zend\Dom\Query + * @return Query */ public function setDocumentXml($document, $encoding = null) { - $this->_document = (string) $document; - $this->_docType = self::DOC_XML; + $this->document = (string) $document; + $this->docType = self::DOC_XML; if (null !== $encoding) { $this->setEncoding($encoding); } @@ -184,7 +182,7 @@ public function setDocumentXml($document, $encoding = null) */ public function getDocument() { - return $this->_document; + return $this->document; } /** @@ -194,7 +192,7 @@ public function getDocument() */ public function getDocumentType() { - return $this->_docType; + return $this->docType; } /** @@ -204,7 +202,7 @@ public function getDocumentType() */ public function getDocumentErrors() { - return $this->_documentErrors; + return $this->documentErrors; } /** @@ -254,7 +252,7 @@ public function queryXpath($xpathQuery, $query = null) } $errors = libxml_get_errors(); if (!empty($errors)) { - $this->_documentErrors = $errors; + $this->documentErrors = $errors; libxml_clear_errors(); } libxml_use_internal_errors(false); @@ -263,19 +261,30 @@ public function queryXpath($xpathQuery, $query = null) throw new Exception\RuntimeException(sprintf('Error parsing document (type == %s)', $type)); } - $nodeList = $this->_getNodeList($domDoc, $xpathQuery); + $nodeList = $this->getNodeList($domDoc, $xpathQuery); return new NodeList($query, $xpathQuery, $domDoc, $nodeList); } /** * Register XPath namespaces * - * @param array $xpathNamespaces - * @return void + * @param array $xpathNamespaces + * @return void */ public function registerXpathNamespaces($xpathNamespaces) { - $this->_xpathNamespaces = $xpathNamespaces; + $this->xpathNamespaces = $xpathNamespaces; + } + + /** + * Register PHP Functions to use in internal DOMXPath + * + * @param mixed $restrict + * @return void + */ + public function registerXpathPhpFunctions($xpathPhpFunctions = true) + { + $this->xpathPhpFunctions = $xpathPhpFunctions; } /** @@ -285,12 +294,18 @@ public function registerXpathNamespaces($xpathNamespaces) * @param string|array $xpathQuery * @return array */ - protected function _getNodeList($document, $xpathQuery) + protected function getNodeList($document, $xpathQuery) { $xpath = new DOMXPath($document); - foreach ($this->_xpathNamespaces as $prefix => $namespaceUri) { + foreach ($this->xpathNamespaces as $prefix => $namespaceUri) { $xpath->registerNamespace($prefix, $namespaceUri); } + if ($this->xpathPhpFunctions) { + $xpath->registerNamespace("php", "http://php.net/xpath"); + ($this->xpathPhpFunctions === true) ? + $xpath->registerPHPFunctions() + : $xpath->registerPHPFunctions($this->xpathPhpFunctions); + } $xpathQuery = (string) $xpathQuery; return $xpath->query($xpathQuery); } diff --git a/library/Zend/Dom/composer.json b/library/Zend/Dom/composer.json new file mode 100644 index 00000000000..b422ea665bc --- /dev/null +++ b/library/Zend/Dom/composer.json @@ -0,0 +1,18 @@ +{ + "name": "zendframework/zend-dom", + "description": "provides tools for working with DOM documents and structures", + "license": "BSD-3-Clause", + "keywords": [ + "zf2", + "dom" + ], + "autoload": { + "psr-0": { + "Zend\\Dom": "" + } + }, + "target-dir": "Zend/Dom", + "require": { + "php": ">=5.3.3" + } +} \ No newline at end of file diff --git a/library/Zend/Escaper/Escaper.php b/library/Zend/Escaper/Escaper.php index a98d971bab6..d35af4e1fd9 100644 --- a/library/Zend/Escaper/Escaper.php +++ b/library/Zend/Escaper/Escaper.php @@ -1,21 +1,11 @@ encoding = $encoding; + $this->encoding = strtolower($encoding); } if (version_compare(PHP_VERSION, '5.4') >= 0) { $this->htmlSpecialCharsFlags = ENT_QUOTES | ENT_SUBSTITUTE; @@ -639,4 +627,4 @@ protected function convertEncoding($string, $to, $from) 9829 => 'hearts', /* black heart suit */ 9830 => 'diams', /* black diamond suit */ ); -} \ No newline at end of file +} diff --git a/library/Zend/Escaper/Exception/ExceptionInterface.php b/library/Zend/Escaper/Exception/ExceptionInterface.php index f1a3bb97641..65a818e0880 100644 --- a/library/Zend/Escaper/Exception/ExceptionInterface.php +++ b/library/Zend/Escaper/Exception/ExceptionInterface.php @@ -1,21 +1,11 @@ =5.3.3" + } +} \ No newline at end of file diff --git a/library/Zend/EventManager/Event.php b/library/Zend/EventManager/Event.php index 73a2785cfd0..85b405f4894 100644 --- a/library/Zend/EventManager/Event.php +++ b/library/Zend/EventManager/Event.php @@ -1,21 +1,11 @@ - * SharedEventManager::getInstance()->connect( + * $sharedEventManager = new SharedEventManager(); + * $sharedEventManager->attach( * array('My\Resource\AbstractResource', 'My\Resource\EntityResource'), * 'getAll', * function ($e) use ($cache) { diff --git a/library/Zend/EventManager/SharedEventManagerAwareInterface.php b/library/Zend/EventManager/SharedEventManagerAwareInterface.php index dbe2853af31..c69adc39aed 100644 --- a/library/Zend/EventManager/SharedEventManagerAwareInterface.php +++ b/library/Zend/EventManager/SharedEventManagerAwareInterface.php @@ -1,22 +1,11 @@ =5.3.3", + "zendframework/zend-stdlib": "self.version" + } +} \ No newline at end of file diff --git a/library/Zend/Feed/Exception/BadMethodCallException.php b/library/Zend/Feed/Exception/BadMethodCallException.php index 5f1e9a1b6a3..0cc4b76d0cb 100644 --- a/library/Zend/Feed/Exception/BadMethodCallException.php +++ b/library/Zend/Feed/Exception/BadMethodCallException.php @@ -1,8 +1,16 @@ _domDocument = $entry->ownerDocument; if ($type !== null) { $this->_data['type'] = $type; + } else if ($this->_domDocument !== null) { + $this->_data['type'] = Reader\Reader::detectType($this->_domDocument); } else { - $this->_data['type'] = Reader\Reader::detectType($feed); + $this->_data['type'] = Reader\Reader::TYPE_ANY; } $this->_loadExtensions(); } diff --git a/library/Zend/Feed/Reader/Entry/Atom.php b/library/Zend/Feed/Reader/Entry/Atom.php index 9e09d0d9a82..417204d648a 100644 --- a/library/Zend/Feed/Reader/Entry/Atom.php +++ b/library/Zend/Feed/Reader/Entry/Atom.php @@ -1,34 +1,22 @@ isValid()) { + if (!Uri\UriFactory::factory($link)->isAbsolute()) { if ($this->getBaseUrl() !== null) { $link = $this->getBaseUrl() . $link; if (!Uri\UriFactory::factory($link)->isValid()) { diff --git a/library/Zend/Feed/Reader/Extension/Atom/Feed.php b/library/Zend/Feed/Reader/Extension/Atom/Feed.php index 377d06f9e9c..36aaa6a7945 100644 --- a/library/Zend/Feed/Reader/Extension/Atom/Feed.php +++ b/library/Zend/Feed/Reader/Extension/Atom/Feed.php @@ -1,21 +1,11 @@ isValid()) { + if (!Uri\UriFactory::factory($link)->isAbsolute()) { if ($this->getBaseUrl() !== null) { $link = $this->getBaseUrl() . $link; if (!Uri\UriFactory::factory($link)->isValid()) { diff --git a/library/Zend/Feed/Reader/Extension/Content/Entry.php b/library/Zend/Feed/Reader/Extension/Content/Entry.php index 80e587377aa..b1bf605b03a 100644 --- a/library/Zend/Feed/Reader/Extension/Content/Entry.php +++ b/library/Zend/Feed/Reader/Extension/Content/Entry.php @@ -1,21 +1,11 @@ getBody(); $cache->setItem($cacheId, $responseXml); - if ($response->headers()->get('ETag')) { - $cache->setItem($cacheId . '_etag', $response->headers()->get('ETag')->getFieldValue()); + if ($response->getHeaders()->get('ETag')) { + $cache->setItem($cacheId . '_etag', $response->getHeaders()->get('ETag')->getFieldValue()); } - if ($response->headers()->get('Last-Modified')) { - $cache->setItem($cacheId . '_lastmodified', $response->headers()->get('Last-Modified')->getFieldValue()); + if ($response->getHeaders()->get('Last-Modified')) { + $cache->setItem($cacheId . '_lastmodified', $response->getHeaders()->get('Last-Modified')->getFieldValue()); } } return self::importString($responseXml); diff --git a/library/Zend/Feed/Writer/AbstractFeed.php b/library/Zend/Feed/Writer/AbstractFeed.php index fab9b7bd919..a2477a005ef 100644 --- a/library/Zend/Feed/Writer/AbstractFeed.php +++ b/library/Zend/Feed/Writer/AbstractFeed.php @@ -1,21 +1,11 @@ =5.3.3" + }, + "suggest": { + "zendframework/zend-uri": "Zend\\Uri component", + "zendframework/zend-validator": "Zend\\Validator component" + } +} \ No newline at end of file diff --git a/library/Zend/File/ClassFileLocator.php b/library/Zend/File/ClassFileLocator.php index 3c761b3f14a..008d0b0bb36 100644 --- a/library/Zend/File/ClassFileLocator.php +++ b/library/Zend/File/ClassFileLocator.php @@ -1,39 +1,27 @@ setInfoClass('Zend\File\PhpClassFile'); } /** * Filter for files containing PHP classes, interfaces, or abstracts - * + * * @return bool */ public function accept() { $file = $this->getInnerIterator()->current(); - - // If we somehow have something other than an SplFileInfo object, just + // If we somehow have something other than an SplFileInfo object, just // return false - if (!$file instanceof \SplFileInfo) { + if (!$file instanceof SplFileInfo) { return false; } @@ -95,13 +83,11 @@ public function accept() $t_trait = defined('T_TRAIT') ? T_TRAIT : -1; // For preserve PHP 5.3 compatibility for ($i = 0; $i < $count; $i++) { $token = $tokens[$i]; - if (!is_array($token)) { // single character token found; skip $i++; continue; } - switch ($token[0]) { case T_NAMESPACE: // Namespace found; grab it for later @@ -110,6 +96,11 @@ public function accept() $token = $tokens[$i]; if (is_string($token)) { if (';' === $token) { + $saveNamespace = false; + break; + } + if ('{' === $token) { + $saveNamespace = true; break; } continue; @@ -122,9 +113,9 @@ public function accept() break; } } - - // Set the namespace of this file in the object - $file->namespace = $namespace; + if ($saveNamespace) { + $savedNamespace = $namespace; + } break; case $t_trait: case T_CLASS: @@ -141,8 +132,18 @@ public function accept() if (T_STRING == $type) { // If a classname was found, set it in the object, and // return boolean true (found) - $file->classname = $content; - return true; + if (!isset($namespace) || null === $namespace) { + if (isset($saveNamespace) && $saveNamespace) { + $namespace = $savedNamespace; + } else { + $namespace = null; + } + + } + $class = (null === $namespace) ? $content : $namespace . '\\' . $content; + $file->addClass($class); + $namespace = null; + break; } } break; @@ -150,7 +151,10 @@ public function accept() break; } } - + $classes = $file->getClasses(); + if (!empty($classes)) { + return true; + } // No class-type tokens found; return false return false; } diff --git a/library/Zend/File/Exception/BadMethodCallException.php b/library/Zend/File/Exception/BadMethodCallException.php index cfd7ef828ed..d9c373428f5 100644 --- a/library/Zend/File/Exception/BadMethodCallException.php +++ b/library/Zend/File/Exception/BadMethodCallException.php @@ -1,21 +1,11 @@ classes; + } + + /** + * Add class + * + * @param string $class + * @return PhpClassFile + */ + public function addClass($class) + { + $this->classes[] = $class; + return $this; + } +} diff --git a/library/Zend/File/Transfer/Adapter/AbstractAdapter.php b/library/Zend/File/Transfer/Adapter/AbstractAdapter.php index 0f771d186fc..c5ebdcb94d1 100644 --- a/library/Zend/File/Transfer/Adapter/AbstractAdapter.php +++ b/library/Zend/File/Transfer/Adapter/AbstractAdapter.php @@ -1,33 +1,22 @@ translator = null; - } elseif ($translator instanceof AdapterTranslator\AbstractAdapter) { - $this->translator = $translator; - } elseif ($translator instanceof Translator\Translator) { - $this->translator = $translator->getAdapter(); - } else { - throw new Exception\InvalidArgumentException('Invalid translator specified'); - } - + $this->translator = $translator; return $this; } /** * Retrieve localization translator object * - * @return AdapterTranslator\AbstractAdapter|null + * @return Translator|null */ public function getTranslator() { diff --git a/library/Zend/File/Transfer/Adapter/Http.php b/library/Zend/File/Transfer/Adapter/Http.php index 6e8ae7ed0cb..1f6048b5b52 100644 --- a/library/Zend/File/Transfer/Adapter/Http.php +++ b/library/Zend/File/Transfer/Adapter/Http.php @@ -1,37 +1,25 @@ =5.3.3" + }, + "suggest": { + "zendframework/zend-filter": "Zend\\Filter component", + "zendframework/zend-loader": "Zend\\Loader component", + "zendframework/zend-i18n": "Zend\\I18n component", + "zendframework/zend-validator": "Zend\\Validator component" + } +} \ No newline at end of file diff --git a/library/Zend/Filter/AbstractFilter.php b/library/Zend/Filter/AbstractFilter.php index 8aa925f389a..2bfc209ae9d 100644 --- a/library/Zend/Filter/AbstractFilter.php +++ b/library/Zend/Filter/AbstractFilter.php @@ -1,33 +1,94 @@ $value) { + $setter = 'set' . str_replace(' ', '', ucwords(str_replace('_', ' ', $key))); + if (method_exists($this, $setter)) { + $this->{$setter}($value); + } elseif (array_key_exists($key, $this->options)) { + $this->options[$key] = $value; + } else { + throw new Exception\InvalidArgumentException(sprintf( + 'The option "%s" does not have a matching %s setter method or options[%s] array key', + $key, $setter, $key + )); + } + } + return $this; + } + + /** + * Retrieve options representing object state + * + * @return array + */ + public function getOptions() + { + return $this->options; + } + /** * Invoke filter as a command * @@ -41,4 +102,14 @@ public function __invoke($value) { return $this->filter($value); } + + /** + * + * @param mixed $options + * @return bool + */ + protected static function isOptions($options) + { + return (is_array($options) || $options instanceof Traversable); + } } diff --git a/library/Zend/Filter/AbstractUnicode.php b/library/Zend/Filter/AbstractUnicode.php new file mode 100644 index 00000000000..c535c7bb6bb --- /dev/null +++ b/library/Zend/Filter/AbstractUnicode.php @@ -0,0 +1,64 @@ +options['encoding'] = $encoding; + return $this; + } + + /** + * Returns the set encoding + * + * @return string + */ + public function getEncoding() + { + if ($this->options['encoding'] === null && function_exists('mb_internal_encoding')) { + $this->options['encoding'] = mb_internal_encoding(); + } + + return $this->options['encoding']; + } +} diff --git a/library/Zend/Filter/Alnum.php b/library/Zend/Filter/Alnum.php deleted file mode 100644 index 3f70b2f7d9a..00000000000 --- a/library/Zend/Filter/Alnum.php +++ /dev/null @@ -1,167 +0,0 @@ -setAllowWhiteSpace($options['allowWhiteSpace']); - } - - if (!array_key_exists('locale', $options)) { - $options['locale'] = null; - } - - $this->setLocale($options['locale']); - } - - /** - * Returns the allowWhiteSpace option - * - * @return boolean - */ - public function getAllowWhiteSpace() - { - return $this->allowWhiteSpace; - } - - /** - * Sets the allowWhiteSpace option - * - * @param boolean $allowWhiteSpace - * @return Alnum Provides a fluent interface - */ - public function setAllowWhiteSpace($allowWhiteSpace) - { - $this->allowWhiteSpace = (boolean) $allowWhiteSpace; - return $this; - } - - /** - * Returns the locale option - * - * @return string - */ - public function getLocale() - { - return $this->locale; - } - - /** - * Sets the locale option - * - * @param boolean $locale - * @return Alnum Provides a fluent interface - */ - public function setLocale($locale = null) - { - $this->locale = ZendLocale::findLocale($locale); - return $this; - } - - /** - * Defined by Zend\Filter\FilterInterface - * - * Returns the string $value, removing all but alphabetic and digit characters - * - * @param string $value - * @return string - */ - public function filter($value) - { - $whiteSpace = $this->allowWhiteSpace ? '\s' : ''; - - if (!self::$unicodeEnabled) { - // POSIX named classes are not supported, use alternative a-zA-Z0-9 match - $pattern = '/[^a-zA-Z0-9' . $whiteSpace . ']/'; - } elseif (((string) $this->locale == 'ja') - || ((string) $this->locale == 'ko') - || ((string) $this->locale == 'zh') - ) { - // Use english alphabeth - $pattern = '/[^a-zA-Z0-9' . $whiteSpace . ']/u'; - } else { - // Use native language alphabeth - $pattern = '/[^\p{L}\p{N}' . $whiteSpace . ']/u'; - } - - return preg_replace($pattern, '', (string) $value); - } -} diff --git a/library/Zend/Filter/Alpha.php b/library/Zend/Filter/Alpha.php deleted file mode 100644 index 34d98bf7e62..00000000000 --- a/library/Zend/Filter/Alpha.php +++ /dev/null @@ -1,216 +0,0 @@ -setUnicodeEnabled($options['unicodeEnabled']); - } - - if (array_key_exists('allowWhiteSpace', $options)) { - $this->setAllowWhiteSpace($options['allowWhiteSpace']); - } - - if (!array_key_exists('locale', $options)) { - $options['locale'] = null; - } - - $this->setLocale($options['locale']); - } - - /** - * Returns the allowWhiteSpace option - * - * @return boolean - */ - public function getAllowWhiteSpace() - { - return $this->allowWhiteSpace; - } - - /** - * Sets the allowWhiteSpace option - * - * @param boolean $allowWhiteSpace - * @return Alpha Provides a fluent interface - */ - public function setAllowWhiteSpace($allowWhiteSpace) - { - $this->allowWhiteSpace = (boolean) $allowWhiteSpace; - return $this; - } - - /** - * Toggle unicode matching capabilities - * - * @param bool $flag - * @return Alpha - */ - public function setUnicodeEnabled($flag) - { - $flag = (bool) $flag; - if (!$flag) { - static::$unicodeEnabled = $flag; - return; - } - - if (!static::isUnicodeCapable()) { - throw new Exception\RuntimeException(sprintf( - '%s cannot be unicode enabled; installed PCRE is not capable', - __CLASS__ - )); - } - - static::$unicodeEnabled = $flag; - return $this; - } - - /** - * Is this instance unicode enabled? - * - * @return bool - */ - public function isUnicodeEnabled() - { - if (null === static::$unicodeEnabled) { - static::$unicodeEnabled = static::isUnicodeCapable(); - } - return static::$unicodeEnabled; - } - - /** - * Returns the locale option - * - * @return string - */ - public function getLocale() - { - return $this->locale; - } - - /** - * Sets the locale option - * - * @param boolean $locale - * @return Alpha Provides a fluent interface - */ - public function setLocale($locale = null) - { - $this->locale = ZendLocale::findLocale($locale); - return $this; - } - - /** - * Defined by Zend\Filter\FilterInterface - * - * Returns the string $value, removing all but alphabetic characters - * - * @param string $value - * @return string - */ - public function filter($value) - { - $whiteSpace = $this->allowWhiteSpace ? '\s' : ''; - - $locale = (string) $this->locale; - if (!$this->isUnicodeEnabled()) { - // POSIX named classes are not supported, use alternative a-zA-Z match - $pattern = '/[^a-zA-Z' . $whiteSpace . ']/'; - } elseif (($locale == 'ja') - || ($locale == 'ko') - || ($locale == 'zh') - ) { - // Use english alphabet - $pattern = '/[^a-zA-Z' . $whiteSpace . ']/u'; - } else { - // Use native language alphabet - $pattern = '/[^\p{L}' . $whiteSpace . ']/u'; - } - - return preg_replace($pattern, '', (string) $value); - } - - /** - * Are we unicode capable? - * - * @return bool - */ - protected static function isUnicodeCapable() - { - return (@preg_match('/\pL/u', 'a') ? true : false); - } -} diff --git a/library/Zend/Filter/BaseName.php b/library/Zend/Filter/BaseName.php index 0b1b0ae5815..84578d7bf95 100644 --- a/library/Zend/Filter/BaseName.php +++ b/library/Zend/Filter/BaseName.php @@ -1,21 +1,11 @@ 'boolean', - self::INTEGER => 'integer', - self::FLOAT => 'float', - self::STRING => 'string', - self::ZERO => 'zero', - self::EMPTY_ARRAY => 'array', - self::NULL => 'null', - self::PHP => 'php', - self::FALSE_STRING => 'false', - self::YES => 'yes', - self::ALL => 'all', - ); - - /** - * Internal type to detect - * - * @var integer - */ - protected $_type = self::PHP; + const TYPE_BOOLEAN = 1; + const TYPE_INTEGER = 2; + const TYPE_FLOAT = 4; + const TYPE_STRING = 8; + const TYPE_ZERO_STRING = 16; + const TYPE_EMPTY_ARRAY = 32; + const TYPE_NULL = 64; + const TYPE_PHP = 127; + const TYPE_FALSE_STRING = 128; + const TYPE_LOCALIZED = 256; + const TYPE_ALL = 511; /** - * Internal locale - * * @var array */ - protected $_locale = array('auto'); + protected $constants = array( + self::TYPE_BOOLEAN => 'boolean', + self::TYPE_INTEGER => 'integer', + self::TYPE_FLOAT => 'float', + self::TYPE_STRING => 'string', + self::TYPE_ZERO_STRING => 'zero', + self::TYPE_EMPTY_ARRAY => 'array', + self::TYPE_NULL => 'null', + self::TYPE_PHP => 'php', + self::TYPE_FALSE_STRING => 'false', + self::TYPE_LOCALIZED => 'localized', + self::TYPE_ALL => 'all', + ); /** - * Internal mode - * - * @var boolean + * @var array */ - protected $_casting = true; + protected $options = array( + 'type' => self::TYPE_PHP, + 'casting' => true, + 'translations' => array(), + ); /** * Constructor * - * @param string|array|Traversable $options OPTIONAL + * @param array|Traversable|int|null $typeOrOptions + * @param bool $casting + * @param array $translations */ - public function __construct($options = null) + public function __construct($typeOrOptions = null, $casting = true, $translations = array()) { - if ($options instanceof Traversable) { - $options = ArrayUtils::iteratorToArray($options); - } - if (!is_array($options)) { - $options = func_get_args(); - $temp = array(); - if (!empty($options)) { - $temp['type'] = array_shift($options); - } - - if (!empty($options)) { - $temp['casting'] = array_shift($options); + if ($typeOrOptions !== null) { + if ($typeOrOptions instanceof Traversable) { + $typeOrOptions = ArrayUtils::iteratorToArray($typeOrOptions); } - if (!empty($options)) { - $temp['locale'] = array_shift($options); + if (is_array($typeOrOptions)) { + if (isset($typeOrOptions['type']) + || isset($typeOrOptions['casting']) + || isset($typeOrOptions['translations'])) + { + $this->setOptions($typeOrOptions); + } else { + $this->setType($typeOrOptions); + $this->setCasting($casting); + $this->setTranslations($translations); + } + } else { + $this->setType($typeOrOptions); + $this->setCasting($casting); + $this->setTranslations($translations); } - - $options = $temp; - } - - if (array_key_exists('type', $options)) { - $this->setType($options['type']); - } - - if (array_key_exists('casting', $options)) { - $this->setCasting($options['casting']); - } - - if (array_key_exists('locale', $options)) { - $this->setLocale($options['locale']); } } /** - * Returns the set null types - * - * @return int - */ - public function getType() - { - return $this->_type; - } - - /** - * Set the null types + * Set boolean types * * @param integer|array $type * @throws Exception\InvalidArgumentException @@ -141,61 +101,52 @@ public function setType($type = null) { if (is_array($type)) { $detected = 0; - foreach($type as $value) { + foreach ($type as $value) { if (is_int($value)) { $detected += $value; - } elseif (in_array($value, $this->_constants)) { - $detected += array_search($value, $this->_constants); + } elseif (in_array($value, $this->constants)) { + $detected += array_search($value, $this->constants); } } $type = $detected; - } elseif (is_string($type) && in_array($type, $this->_constants)) { - $type = array_search($type, $this->_constants); + } elseif (is_string($type) && in_array($type, $this->constants)) { + $type = array_search($type, $this->constants); } - if (!is_int($type) || ($type < 0) || ($type > self::ALL)) { - throw new Exception\InvalidArgumentException('Unknown type'); + if (!is_int($type) || ($type < 0) || ($type > self::TYPE_ALL)) { + throw new Exception\InvalidArgumentException(sprintf( + 'Unknown type value "%s" (%s)', + $type, + gettype($type) + )); } - $this->_type = $type; + $this->options['type'] = $type; return $this; } /** - * Returns the set locale + * Returns defined boolean types * - * @return array + * @return int */ - public function getLocale() + public function getType() { - return $this->_locale; + return $this->options['type']; } /** - * Set the locales which are accepted + * Set the working mode * - * @param string|array|\Zend\Locale\Locale $locale - * @throws Exception\ExceptionInterface + * @param boolean $flag When true this filter works like cast + * When false it recognises only true and false + * and all other values are returned as is * @return Boolean */ - public function setLocale($locale = null) + public function setCasting($flag = true) { - if (is_string($locale)) { - $locale = array($locale); - } elseif ($locale instanceof Locale) { - $locale = array($locale->toString()); - } elseif (!is_array($locale)) { - throw new Exception\InvalidArgumentException('Locale has to be string, array or an instance of Zend_Locale'); - } - - foreach ($locale as $single) { - if (!Locale::isLocale($single)) { - throw new Exception\InvalidArgumentException("Unknown locale '$single'"); - } - } - - $this->_locale = $locale; + $this->options['casting'] = (boolean) $flag; return $this; } @@ -206,23 +157,38 @@ public function setLocale($locale = null) */ public function getCasting() { - return $this->_casting; + return $this->options['casting']; } /** - * Set the working mode - * - * @param boolean $locale When true this filter works like cast - * When false it recognises only true and false - * and all other values are returned as is + * @param array|Traversable $translations * @return Boolean */ - public function setCasting($casting = true) + public function setTranslations($translations) { - $this->_casting = (boolean) $casting; + if (!is_array($translations) && !$translations instanceof Traversable) { + throw new Exception\InvalidArgumentException(sprintf( + '"%s" expects an array or Traversable; received "%s"', + __METHOD__, + (is_object($translations) ? get_class($translations) : gettype($translations)) + )); + } + + foreach ($translations as $message => $flag) { + $this->options['translations'][$message] = (bool) $flag; + } + return $this; } + /** + * @return array + */ + public function getTranslations() + { + return $this->options['translations']; + } + /** * Defined by Zend\Filter\FilterInterface * @@ -236,98 +202,91 @@ public function filter($value) $type = $this->getType(); $casting = $this->getCasting(); - // STRING YES (Localized) - if ($type >= self::YES) { - $type -= self::YES; + // LOCALIZED + if ($type >= self::TYPE_LOCALIZED) { + $type -= self::TYPE_LOCALIZED; if (is_string($value)) { - $locales = $this->getLocale(); - foreach ($locales as $locale) { - if ($this->_getLocalizedQuestion($value, false, $locale) === false) { - return false; - } - - if (!$casting && ($this->_getLocalizedQuestion($value, true, $locale) === true)) { - return true; - } + if (isset($this->options['translations'][$value])) { + return (bool) $this->options['translations'][$value]; } } } - // STRING FALSE ('false') - if ($type >= self::FALSE_STRING) { - $type -= self::FALSE_STRING; + // FALSE_STRING ('false') + if ($type >= self::TYPE_FALSE_STRING) { + $type -= self::TYPE_FALSE_STRING; if (is_string($value) && (strtolower($value) == 'false')) { return false; } - if ((!$casting) && is_string($value) && (strtolower($value) == 'true')) { + if (!$casting && is_string($value) && (strtolower($value) == 'true')) { return true; } } // NULL (null) - if ($type >= self::NULL) { - $type -= self::NULL; + if ($type >= self::TYPE_NULL) { + $type -= self::TYPE_NULL; if ($value === null) { return false; } } // EMPTY_ARRAY (array()) - if ($type >= self::EMPTY_ARRAY) { - $type -= self::EMPTY_ARRAY; + if ($type >= self::TYPE_EMPTY_ARRAY) { + $type -= self::TYPE_EMPTY_ARRAY; if (is_array($value) && ($value == array())) { return false; } } - // ZERO ('0') - if ($type >= self::ZERO) { - $type -= self::ZERO; + // ZERO_STRING ('0') + if ($type >= self::TYPE_ZERO_STRING) { + $type -= self::TYPE_ZERO_STRING; if (is_string($value) && ($value == '0')) { return false; } - if ((!$casting) && (is_string($value)) && ($value == '1')) { + if (!$casting && (is_string($value)) && ($value == '1')) { return true; } } // STRING ('') - if ($type >= self::STRING) { - $type -= self::STRING; + if ($type >= self::TYPE_STRING) { + $type -= self::TYPE_STRING; if (is_string($value) && ($value == '')) { return false; } } // FLOAT (0.0) - if ($type >= self::FLOAT) { - $type -= self::FLOAT; + if ($type >= self::TYPE_FLOAT) { + $type -= self::TYPE_FLOAT; if (is_float($value) && ($value == 0.0)) { return false; } - if ((!$casting) && is_float($value) && ($value == 1.0)) { + if (!$casting && is_float($value) && ($value == 1.0)) { return true; } } // INTEGER (0) - if ($type >= self::INTEGER) { - $type -= self::INTEGER; + if ($type >= self::TYPE_INTEGER) { + $type -= self::TYPE_INTEGER; if (is_int($value) && ($value == 0)) { return false; } - if ((!$casting) && is_int($value) && ($value == 1)) { + if (!$casting && is_int($value) && ($value == 1)) { return true; } } // BOOLEAN (false) - if ($type >= self::BOOLEAN) { - $type -= self::BOOLEAN; + if ($type >= self::TYPE_BOOLEAN) { + $type -= self::TYPE_BOOLEAN; if (is_bool($value)) { return $value; } @@ -339,32 +298,4 @@ public function filter($value) return $value; } - - /** - * Determine the value of a localized string, and compare it to a given value - * - * @param string $value - * @param boolean $yes - * @param array $locale - * @return boolean - */ - protected function _getLocalizedQuestion($value, $yes, $locale) - { - if ($yes == true) { - $question = 'yes'; - $return = true; - } else { - $question = 'no'; - $return = false; - } - $str = Locale::getTranslation($question, 'question', $locale); - $str = explode(':', $str); - if (!empty($str)) { - foreach($str as $no) { - if (($no == $value) || (strtolower($no) == strtolower($value))) { - return $return; - } - } - } - } } diff --git a/library/Zend/Filter/Callback.php b/library/Zend/Filter/Callback.php index e4f5c3d8792..9a8e3d174f7 100644 --- a/library/Zend/Filter/Callback.php +++ b/library/Zend/Filter/Callback.php @@ -1,127 +1,92 @@ null, + 'callback_params' => array() + ); /** - * Default options to set for the filter - * - * @var mixed + * @param array|Traversable $options */ - protected $_options = null; + public function __construct($callbackOrOptions, $callbackParams = array()) + { + if (is_callable($callbackOrOptions)) { + $this->setCallback($callbackOrOptions); + $this->setCallbackParams($callbackParams); + } else { + $this->setOptions($callbackOrOptions); + } + } /** - * Constructor + * Sets a new callback for this filter * - * @param string|array $callback Callback in a call_user_func format - * @param mixed $options (Optional) Default options for this filter + * @param callable $callback + * @return Callback */ - public function __construct($options = array()) + public function setCallback($callback) { - if ($options instanceof Traversable) { - $options = ArrayUtils::iteratorToArray($options); - } elseif (!is_array($options) || !array_key_exists('callback', $options)) { - $options = func_get_args(); - $temp['callback'] = array_shift($options); - if (!empty($options)) { - $temp['options'] = array_shift($options); - } - - $options = $temp; - } - - if (!array_key_exists('callback', $options)) { - throw new Exception\InvalidArgumentException('Missing callback to use'); + if (!is_callable($callback)) { + throw new Exception\InvalidArgumentException( + 'Invalid parameter for callback: must be callable' + ); } - $this->setCallback($options['callback']); - if (array_key_exists('options', $options)) { - $this->setOptions($options['options']); - } + $this->options['callback'] = $callback; + return $this; } /** * Returns the set callback * - * @return string|array Set callback + * @return callable */ public function getCallback() { - return $this->_callback; + return $this->options['callback']; } /** - * Sets a new callback for this filter + * Sets parameters for the callback * - * @param \callable $callback + * @param mixed $params * @return Callback */ - public function setCallback($callback, $options = null) + public function setCallbackParams($params) { - if (!is_callable($callback)) { - throw new Exception\InvalidArgumentException('Callback can not be accessed'); - } - - $this->_callback = $callback; - $this->setOptions($options); + $this->options['callback_params'] = (array) $params; return $this; } /** - * Returns the set default options + * Get parameters for the callback * * @return mixed */ - public function getOptions() - { - return $this->_options; - } - - /** - * Sets new default options to the callback filter - * - * @param mixed $options Default options to set - * @return Callback - */ - public function setOptions($options) + public function getCallbackParams() { - $this->_options = $options; - return $this; + return $this->options['callback_params']; } /** @@ -132,18 +97,9 @@ public function setOptions($options) */ public function filter($value) { - $options = array(); - - if ($this->_options !== null) { - if (!is_array($this->_options)) { - $options = array($this->_options); - } else { - $options = $this->_options; - } - } - - array_unshift($options, $value); + $params = (array) $this->options['callback_params']; + array_unshift($params, $value); - return call_user_func_array($this->_callback, $options); + return call_user_func_array($this->options['callback'], $params); } } diff --git a/library/Zend/Filter/Compress.php b/library/Zend/Filter/Compress.php index 578c78dd935..af7d35fc86d 100644 --- a/library/Zend/Filter/Compress.php +++ b/library/Zend/Filter/Compress.php @@ -1,21 +1,11 @@ $value) { if ($key == 'options') { $key = 'adapterOptions'; @@ -167,6 +163,18 @@ public function setAdapterOptions(array $options) return $this; } + /** + * Get individual or all options from underlying adapter + * + * @param null|string $option + * @return mixed + */ + public function getOptions($option = null) + { + $adapter = $this->getAdapter(); + return $adapter->getOptions($option); + } + /** * Calls adapter methods * diff --git a/library/Zend/Filter/Compress/AbstractCompressionAlgorithm.php b/library/Zend/Filter/Compress/AbstractCompressionAlgorithm.php index 1b0d7c8a77c..5bd983695e4 100644 --- a/library/Zend/Filter/Compress/AbstractCompressionAlgorithm.php +++ b/library/Zend/Filter/Compress/AbstractCompressionAlgorithm.php @@ -1,21 +1,11 @@ setEncoding($options); - } - } - /** * Defined by Zend\Filter\Filter * @@ -52,7 +29,7 @@ public function __construct($options = null) * @throws Exception\InvalidArgumentException * @throws Exception\RuntimeException */ - public function __invoke($value) + public function filter($value) { if (!file_exists($value)) { throw new Exception\InvalidArgumentException("File '$value' not found"); @@ -67,7 +44,7 @@ public function __invoke($value) throw new Exception\RuntimeException("Problem while reading file '$value'"); } - $content = parent::__invoke($content); + $content = parent::filter($content); $result = file_put_contents($value, $content); if (!$result) { diff --git a/library/Zend/Filter/File/Rename.php b/library/Zend/Filter/File/Rename.php index 073e1bff207..8faf82b8b38 100644 --- a/library/Zend/Filter/File/Rename.php +++ b/library/Zend/Filter/File/Rename.php @@ -1,35 +1,23 @@ Shall existing files be overwritten ? * * @param string|array|Traversable $options Target file or directory to be renamed - * @param string $target Source filename or directory (deprecated) - * @param bool $overwrite Should existing files be overwritten (deprecated) * @throws Exception\InvalidArgumentException */ public function __construct($options) @@ -62,18 +48,6 @@ public function __construct($options) throw new Exception\InvalidArgumentException('Invalid options argument provided to filter'); } - if (1 < func_num_args()) { - $argv = func_get_args(); - array_shift($argv); - $source = array_shift($argv); - $overwrite = false; - if (!empty($argv)) { - $overwrite = array_shift($argv); - } - $options['source'] = $source; - $options['overwrite'] = $overwrite; - } - $this->setFile($options); } diff --git a/library/Zend/Filter/File/UpperCase.php b/library/Zend/Filter/File/UpperCase.php index b37938a3a8f..05a42de2c29 100644 --- a/library/Zend/Filter/File/UpperCase.php +++ b/library/Zend/Filter/File/UpperCase.php @@ -1,47 +1,24 @@ setEncoding($options); - } - } - /** * Defined by Zend\Filter\FilterInterface * @@ -52,7 +29,7 @@ public function __construct($options = null) * @throws Exception\RuntimeException * @throws Exception\InvalidArgumentException */ - public function __invoke($value) + public function filter($value) { if (!file_exists($value)) { throw new Exception\InvalidArgumentException("File '$value' not found"); @@ -67,7 +44,7 @@ public function __invoke($value) throw new Exception\RuntimeException("Problem while reading file '$value'"); } - $content = parent::__invoke($content); + $content = parent::filter($content); $result = file_put_contents($value, $content); if (!$result) { diff --git a/library/Zend/Filter/FilterChain.php b/library/Zend/Filter/FilterChain.php index 058b0076e99..f8fb82d5ae3 100644 --- a/library/Zend/Filter/FilterChain.php +++ b/library/Zend/Filter/FilterChain.php @@ -1,21 +1,11 @@ attach($filter, $priority); } + /** + * Merge the filter chain with the one given in parameter + * + * @param FilterChain $filterChain + * @return FilterChain + */ + public function merge(FilterChain $filterChain) + { + foreach ($filterChain->filters as $filter) { + $this->attach($filter); + } + + return $this; + } + /** * Get all the filters * diff --git a/library/Zend/Filter/FilterInterface.php b/library/Zend/Filter/FilterInterface.php index 939f29fb7fc..b246861a6a4 100644 --- a/library/Zend/Filter/FilterInterface.php +++ b/library/Zend/Filter/FilterInterface.php @@ -1,21 +1,11 @@ 'Zend\Filter\Alnum', - 'alpha' => 'Zend\Filter\Alpha', + 'alnum' => 'Zend\I18n\Filter\Alnum', + 'alpha' => 'Zend\I18n\Filter\Alpha', 'basename' => 'Zend\Filter\BaseName', 'boolean' => 'Zend\Filter\Boolean', 'callback' => 'Zend\Filter\Callback', @@ -72,6 +60,7 @@ class FilterPluginManager extends AbstractPluginManager 'localizedtonormalized' => 'Zend\Filter\LocalizedToNormalized', 'normalizedtolocalized' => 'Zend\Filter\NormalizedToLocalized', 'null' => 'Zend\Filter\Null', + 'numberformat' => 'Zend\I18n\Filter\NumberFormat', 'pregreplace' => 'Zend\Filter\PregReplace', 'realpath' => 'Zend\Filter\RealPath', 'stringtolower' => 'Zend\Filter\StringToLower', diff --git a/library/Zend/Filter/HtmlEntities.php b/library/Zend/Filter/HtmlEntities.php index 8ca8a31584c..eed16feae03 100644 --- a/library/Zend/Filter/HtmlEntities.php +++ b/library/Zend/Filter/HtmlEntities.php @@ -1,21 +1,11 @@ null, - 'date_format' => null, - 'precision' => null - ); - - /** - * Class constructor - * - * @param array|Traversable $options (Optional) Locale to set - */ - public function __construct($options = null) - { - if ($options instanceof Traversable) { - $options = ArrayUtils::iteratorToArray($options); - } - - if (null !== $options) { - $this->setOptions($options); - } - } - - /** - * Returns the set options - * - * @return array - */ - public function getOptions() - { - return $this->_options; - } - - /** - * Sets options to use - * - * @param array $options (Optional) Options to use - * @return LocalizedToNormalized - */ - public function setOptions(array $options = null) - { - $this->_options = $options + $this->_options; - return $this; - } - - /** - * Defined by Zend\Filter\FilterInterface - * - * Normalizes the given input - * - * @param string $value Value to normalized - * @return string|array The normalized value - */ - public function filter($value) - { - if (Format::isNumber($value, $this->_options)) { - return Format::getNumber($value, $this->_options); - } else if (($this->_options['date_format'] === null) && (strpos($value, ':') !== false)) { - // Special case, no date format specified, detect time input - return Format::getTime($value, $this->_options); - } else if (Format::checkDateFormat($value, $this->_options)) { - // Detect date or time input - return Format::getDate($value, $this->_options); - } - - return $value; - } -} diff --git a/library/Zend/Filter/NormalizedToLocalized.php b/library/Zend/Filter/NormalizedToLocalized.php deleted file mode 100644 index 2f6cedc1b34..00000000000 --- a/library/Zend/Filter/NormalizedToLocalized.php +++ /dev/null @@ -1,106 +0,0 @@ - null, - 'date_format' => null, - 'precision' => null - ); - - /** - * Class constructor - * - * @param array|Traversable $options (Optional) Locale to set - */ - public function __construct($options = null) - { - if ($options instanceof Traversable) { - $options = ArrayUtils::iteratorToArray($options); - } - - if (null !== $options) { - $this->setOptions($options); - } - } - - /** - * Returns the set options - * - * @return array - */ - public function getOptions() - { - return $this->_options; - } - - /** - * Sets options to use - * - * @param array $options (Optional) Options to use - * @return NormalizedToLocalized - */ - public function setOptions(array $options = null) - { - $this->_options = $options + $this->_options; - return $this; - } - - /** - * Defined by Zend\Filter\FilterInterface - * - * Normalizes the given input - * - * @param string $value Value to normalized - * @return string|array The normalized value - */ - public function filter($value) - { - if (is_array($value)) { - $date = new Date($value, $this->_options['locale']); - return $date->toString($this->_options['date_format']); - } else if ($this->_options['precision'] === 0) { - return Format::toInteger($value, $this->_options); - } else if ($this->_options['precision'] === null) { - return Format::toFloat($value, $this->_options); - } - - return Format::toNumber($value, $this->_options); - } -} diff --git a/library/Zend/Filter/Null.php b/library/Zend/Filter/Null.php index 3826a86e0f8..b9e6e6a07d8 100644 --- a/library/Zend/Filter/Null.php +++ b/library/Zend/Filter/Null.php @@ -1,21 +1,11 @@ 'boolean', - self::INTEGER => 'integer', - self::EMPTY_ARRAY => 'array', - self::STRING => 'string', - self::ZERO => 'zero', - self::FLOAT => 'float', - self::ALL => 'all', + const TYPE_BOOLEAN = 1; + const TYPE_INTEGER = 2; + const TYPE_EMPTY_ARRAY = 4; + const TYPE_STRING = 8; + const TYPE_ZERO_STRING = 16; + const TYPE_FLOAT = 32; + const TYPE_ALL = 63; + + /** + * @var array + */ + protected $constants = array( + self::TYPE_BOOLEAN => 'boolean', + self::TYPE_INTEGER => 'integer', + self::TYPE_EMPTY_ARRAY => 'array', + self::TYPE_STRING => 'string', + self::TYPE_ZERO_STRING => 'zero', + self::TYPE_FLOAT => 'float', + self::TYPE_ALL => 'all', ); /** - * Internal type to detect - * - * @var integer + * @var array */ - protected $_type = self::ALL; + protected $options = array( + 'type' => self::TYPE_ALL, + ); /** * Constructor * * @param string|array|Traversable $options OPTIONAL */ - public function __construct($options = null) + public function __construct($typeOrOptions = null) { - if ($options instanceof Traversable) { - $options = ArrayUtils::iteratorToArray($options); - } - if (!is_array($options)) { - $options = func_get_args(); - $temp = array(); - if (!empty($options)) { - $temp = array_shift($options); + if ($typeOrOptions !== null) { + if ($typeOrOptions instanceof Traversable) { + $typeOrOptions = iterator_to_array($typeOrOptions); } - $options = $temp; - } elseif (is_array($options) && array_key_exists('type', $options)) { - $options = $options['type']; - } - if (!empty($options)) { - $this->setType($options); + if (is_array($typeOrOptions)) { + if (isset($typeOrOptions['type'])) { + $this->setOptions($typeOrOptions); + } else { + $this->setType($typeOrOptions); + } + } else { + $this->setType($typeOrOptions); + } } } /** - * Returns the set null types - * - * @return array - */ - public function getType() - { - return $this->_type; - } - - /** - * Set the null types + * Set boolean types * * @param integer|array $type * @throws Exception\InvalidArgumentException - * @return Null + * @return Boolean */ public function setType($type = null) { if (is_array($type)) { $detected = 0; - foreach($type as $value) { + foreach ($type as $value) { if (is_int($value)) { $detected += $value; - } else if (in_array($value, $this->_constants)) { - $detected += array_search($value, $this->_constants); + } elseif (in_array($value, $this->constants)) { + $detected += array_search($value, $this->constants); } } $type = $detected; - } else if (is_string($type)) { - if (in_array($type, $this->_constants)) { - $type = array_search($type, $this->_constants); - } + } elseif (is_string($type) && in_array($type, $this->constants)) { + $type = array_search($type, $this->constants); } - if (!is_int($type) || ($type < 0) || ($type > self::ALL)) { - throw new Exception\InvalidArgumentException('Unknown type'); + if (!is_int($type) || ($type < 0) || ($type > self::TYPE_ALL)) { + throw new Exception\InvalidArgumentException(sprintf( + 'Unknown type value "%s" (%s)', + $type, + gettype($type) + )); } - $this->_type = $type; + $this->options['type'] = $type; return $this; } + /** + * Returns defined boolean types + * + * @return int + */ + public function getType() + { + return $this->options['type']; + } + /** * Defined by Zend\Filter\FilterInterface * @@ -140,48 +131,48 @@ public function filter($value) $type = $this->getType(); // FLOAT (0.0) - if ($type >= self::FLOAT) { - $type -= self::FLOAT; + if ($type >= self::TYPE_FLOAT) { + $type -= self::TYPE_FLOAT; if (is_float($value) && ($value == 0.0)) { return null; } } // STRING ZERO ('0') - if ($type >= self::ZERO) { - $type -= self::ZERO; + if ($type >= self::TYPE_ZERO_STRING) { + $type -= self::TYPE_ZERO_STRING; if (is_string($value) && ($value == '0')) { return null; } } // STRING ('') - if ($type >= self::STRING) { - $type -= self::STRING; + if ($type >= self::TYPE_STRING) { + $type -= self::TYPE_STRING; if (is_string($value) && ($value == '')) { return null; } } // EMPTY_ARRAY (array()) - if ($type >= self::EMPTY_ARRAY) { - $type -= self::EMPTY_ARRAY; + if ($type >= self::TYPE_EMPTY_ARRAY) { + $type -= self::TYPE_EMPTY_ARRAY; if (is_array($value) && ($value == array())) { return null; } } // INTEGER (0) - if ($type >= self::INTEGER) { - $type -= self::INTEGER; + if ($type >= self::TYPE_INTEGER) { + $type -= self::TYPE_INTEGER; if (is_int($value) && ($value == 0)) { return null; } } // BOOLEAN (false) - if ($type >= self::BOOLEAN) { - $type -= self::BOOLEAN; + if ($type >= self::TYPE_BOOLEAN) { + $type -= self::TYPE_BOOLEAN; if (is_bool($value) && ($value == false)) { return null; } diff --git a/library/Zend/Filter/PregReplace.php b/library/Zend/Filter/PregReplace.php index 7372606e36a..c0d58a49d62 100644 --- a/library/Zend/Filter/PregReplace.php +++ b/library/Zend/Filter/PregReplace.php @@ -1,21 +1,11 @@ null, + 'replacement' => '', + ); /** * Constructor * Supported options are - * 'match' => matching pattern - * 'replace' => replace with this + * 'pattern' => matching pattern + * 'replacement' => replace with this * - * @param string|array $options + * @param array|Traversable|string|null $options * @return void */ - public function __construct($options = array()) + public function __construct($options = null) { if ($options instanceof Traversable) { - $options = ArrayUtils::iteratorToArray($options); - } elseif (!is_array($options)) { - $options = func_get_args(); - $temp = array(); - if (!empty($options)) { - $temp['match'] = array_shift($options); - } - - if (!empty($options)) { - $temp['replace'] = array_shift($options); - } - - $options = $temp; - } - - if (array_key_exists('match', $options)) { - $this->setMatchPattern($options['match']); + $options = iterator_to_array($options); } - if (array_key_exists('replace', $options)) { - $this->setReplacement($options['replace']); + if (!is_array($options) + || (!isset($options['pattern']) && !isset($options['replacement']))) + { + $args = func_get_args(); + if (isset($args[0])) { + $this->setPattern($args[0]); + } + if (isset($args[1])) { + $this->setReplacement($args[1]); + } + } else { + $this->setOptions($options); } } /** - * Set the match pattern for the regex being called within filter() + * Set the regex pattern to search for + * @see preg_replace() * - * @param mixed $match - same as the first argument of preg_replace + * @param string|array $pattern - same as the first argument of preg_replace * @return PregReplace + * @throws Exception\InvalidArgumentException */ - public function setMatchPattern($match) + public function setPattern($pattern) { - $this->_matchPattern = $match; + if (!is_array($pattern) && !is_string($pattern)) { + throw new Exception\InvalidArgumentException(sprintf( + '%s expects pattern to be array or string; received "%s"', + __METHOD__, + (is_object($pattern) ? get_class($pattern) : gettype($pattern)) + )); + } + $this->options['pattern'] = $pattern; return $this; } /** * Get currently set match pattern * - * @return string + * @return string|array */ - public function getMatchPattern() + public function getPattern() { - return $this->_matchPattern; + return $this->options['pattern']; } /** - * Set the Replacement pattern/string for the preg_replace called in filter + * Set the replacement array/string + * @see preg_replace() * - * @param mixed $replacement - same as the second argument of preg_replace + * @param array|string $replacement - same as the second argument of preg_replace * @return PregReplace + * @throws Exception\InvalidArgumentException */ public function setReplacement($replacement) { - $this->_replacement = $replacement; + if (!is_array($replacement) && !is_string($replacement)) { + throw new Exception\InvalidArgumentException(sprintf( + '%s expects replacement to be array or string; received "%s"', + __METHOD__, + (is_object($replacement) ? get_class($replacement) : gettype($replacement)) + )); + } + $this->options['replacement'] = $replacement; return $this; } /** * Get currently set replacement value * - * @return string + * @return string|array */ public function getReplacement() { - return $this->_replacement; + return $this->options['replacement']; } /** * Perform regexp replacement as filter * - * @param string $value - * @return string + * @param mixed $value + * @return mixed + * @throws Exception\RuntimeException */ public function filter($value) { - if ($this->_matchPattern == null) { - throw new Exception\RuntimeException(get_called_class() . ' does not have a valid MatchPattern set.'); + if ($this->options['pattern'] === null) { + throw new Exception\RuntimeException(sprintf( + 'Filter %s does not have a valid pattern set', + get_called_class() + )); } - return preg_replace($this->_matchPattern, $this->_replacement, $value); + return preg_replace($this->options['pattern'], $this->options['replacement'], $value); } } diff --git a/library/Zend/Filter/RealPath.php b/library/Zend/Filter/RealPath.php index 306ec718bce..6139787c0be 100644 --- a/library/Zend/Filter/RealPath.php +++ b/library/Zend/Filter/RealPath.php @@ -1,83 +1,66 @@ true + ); /** * Class constructor * * @param boolean|\Traversable $options Options to set */ - public function __construct($options = true) + public function __construct($existsOrOptions = true) { - $this->setExists($options); + if ($existsOrOptions !== null) { + if (!static::isOptions($existsOrOptions)){ + $this->setExists($existsOrOptions); + } else { + $this->setOptions($existsOrOptions); + } + } } /** - * Returns true if the filtered path must exist + * Sets if the path has to exist + * TRUE when the path must exist + * FALSE when not existing paths can be given * - * @return boolean + * @param boolean $flag Path must exist + * @return RealPath */ - public function getExists() + public function setExists($flag = true) { - return $this->_exists; + $this->options['exists'] = (boolean) $flag; + return $this; } /** - * Sets if the path has to exist - * TRUE when the path must exist - * FALSE when not existing paths can be given + * Returns true if the filtered path must exist * - * @param boolean|array|Traversable $options Path must exist - * @return RealPath + * @return boolean */ - public function setExists($options) + public function getExists() { - if ($options instanceof Traversable) { - $options = ArrayUtils::iteratorToArray($options); - } - - if (is_array($options)) { - if (isset($options['exists'])) { - $options = (boolean) $options['exists']; - } - } - - $this->_exists = (boolean) $options; - return $this; + return $this->options['exists']; } /** @@ -91,7 +74,7 @@ public function setExists($options) public function filter($value) { $path = (string) $value; - if ($this->_exists) { + if ($this->options['exists']) { return realpath($path); } @@ -101,10 +84,10 @@ public function filter($value) } $drive = ''; - if (substr(PHP_OS, 0, 3) == 'WIN') { + if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') { $path = preg_replace('/[\\\\\/]/', DIRECTORY_SEPARATOR, $path); if (preg_match('/([a-zA-Z]\:)(.*)/', $path, $matches)) { - list($fullMatch, $drive, $path) = $matches; + list(, $drive, $path) = $matches; } else { $cwd = getcwd(); $drive = substr($cwd, 0, 2); diff --git a/library/Zend/Filter/StaticFilter.php b/library/Zend/Filter/StaticFilter.php index decd71b3845..57e058970ad 100644 --- a/library/Zend/Filter/StaticFilter.php +++ b/library/Zend/Filter/StaticFilter.php @@ -1,21 +1,11 @@ null, + ); /** * Constructor * * @param string|array|Traversable $options OPTIONAL */ - public function __construct($options = null) - { - if ($options instanceof Traversable) { - $options = ArrayUtils::iteratorToArray($options); - } - if (!is_array($options)) { - $options = func_get_args(); - $temp = array(); - if (!empty($options)) { - $temp['encoding'] = array_shift($options); - } - $options = $temp; - } - - if (!array_key_exists('encoding', $options) && function_exists('mb_internal_encoding')) { - $options['encoding'] = mb_internal_encoding(); - } - - if (array_key_exists('encoding', $options)) { - $this->setEncoding($options['encoding']); - } - } - - /** - * Returns the set encoding - * - * @return string - */ - public function getEncoding() - { - return $this->_encoding; - } - - /** - * Set the input encoding for the given string - * - * @param string $encoding - * @return StringToLower Provides a fluent interface - * @throws Exception\ExceptionInterface - */ - public function setEncoding($encoding = null) + public function __construct($encodingOrOptions = null) { - if ($encoding !== null) { - if (!function_exists('mb_strtolower')) { - throw new Exception\ExtensionNotLoadedException('mbstring is required for this feature'); - } - - $encoding = (string) $encoding; - if (!in_array(strtolower($encoding), array_map('strtolower', mb_list_encodings()))) { - throw new Exception\InvalidArgumentException("The given encoding '$encoding' is not supported by mbstring"); + if ($encodingOrOptions !== null) { + if (!static::isOptions($encodingOrOptions)){ + $this->setEncoding($encodingOrOptions); + } else { + $this->setOptions($encodingOrOptions); } } - - $this->_encoding = $encoding; - return $this; } /** @@ -110,8 +51,8 @@ public function setEncoding($encoding = null) */ public function filter($value) { - if ($this->_encoding !== null) { - return mb_strtolower((string) $value, $this->_encoding); + if ($this->options['encoding'] !== null) { + return mb_strtolower((string) $value, $this->options['encoding']); } return strtolower((string) $value); diff --git a/library/Zend/Filter/StringToUpper.php b/library/Zend/Filter/StringToUpper.php index d2ca0a63fc7..d11c94d108a 100644 --- a/library/Zend/Filter/StringToUpper.php +++ b/library/Zend/Filter/StringToUpper.php @@ -1,117 +1,58 @@ null, + ); /** * Constructor * * @param string|array|Traversable $options OPTIONAL */ - public function __construct($options = null) - { - if ($options instanceof Traversable) { - $options = ArrayUtils::iteratorToArray($options); - } - if (!is_array($options)) { - $options = func_get_args(); - $temp = array(); - if (!empty($options)) { - $temp['encoding'] = array_shift($options); - } - $options = $temp; - } - - if (!array_key_exists('encoding', $options) && function_exists('mb_internal_encoding')) { - $options['encoding'] = mb_internal_encoding(); - } - - if (array_key_exists('encoding', $options)) { - $this->setEncoding($options['encoding']); - } - } - - /** - * Returns the set encoding - * - * @return string - */ - public function getEncoding() - { - return $this->_encoding; - } - - /** - * Set the input encoding for the given string - * - * @param string $encoding - * @return StringToUpper Provides a fluent interface - * @throws Exception\ExceptionInterface - */ - public function setEncoding($encoding = null) + public function __construct($encodingOrOptions = null) { - if ($encoding !== null) { - if (!function_exists('mb_strtoupper')) { - throw new Exception\ExtensionNotLoadedException('mbstring is required for this feature'); - } - - $encoding = (string) $encoding; - if (!in_array(strtolower($encoding), array_map('strtolower', mb_list_encodings()))) { - throw new Exception\InvalidArgumentException("The given encoding '$encoding' is not supported by mbstring"); + if ($encodingOrOptions !== null) { + if (!static::isOptions($encodingOrOptions)){ + $this->setEncoding($encodingOrOptions); + } else { + $this->setOptions($encodingOrOptions); } } - - $this->_encoding = $encoding; - return $this; } /** * Defined by Zend\Filter\FilterInterface * - * Returns the string $value, converting characters to uppercase as necessary + * Returns the string $value, converting characters to lowercase as necessary * * @param string $value * @return string */ public function filter($value) { - if ($this->_encoding) { - return mb_strtoupper((string) $value, $this->_encoding); + if ($this->options['encoding'] !== null) { + return mb_strtoupper((string) $value, $this->options['encoding']); } return strtoupper((string) $value); diff --git a/library/Zend/Filter/StringTrim.php b/library/Zend/Filter/StringTrim.php index 832bfdfdff8..812053bf09d 100644 --- a/library/Zend/Filter/StringTrim.php +++ b/library/Zend/Filter/StringTrim.php @@ -1,21 +1,11 @@ null, + ); /** * Sets filter options * * @param string|array|Traversable $options */ - public function __construct($options = null) + public function __construct($charlistOrOptions = null) { - if ($options instanceof Traversable) { - $options = ArrayUtils::iteratorToArray($options); - } - if (!is_array($options)) { - $options = func_get_args(); - $temp['charlist'] = array_shift($options); - $options = $temp; - } - - if (array_key_exists('charlist', $options)) { - $this->setCharList($options['charlist']); + if ($charlistOrOptions !== null) { + if (!is_array($charlistOrOptions) + && !$charlistOrOptions instanceof Traversable) + { + $this->setCharList($charlistOrOptions); + } else { + $this->setOptions($charlistOrOptions); + } } } /** - * Returns the charList option + * Sets the charList option * - * @return string|null + * @param string $charList + * @return StringTrim Provides a fluent interface */ - public function getCharList() + public function setCharList($charList) { - return $this->_charList; + if (empty($charList)) { + $charList = null; + } + $this->options['charlist'] = $charList; + return $this; } /** - * Sets the charList option + * Returns the charList option * - * @param string|null $charList - * @return StringTrim Provides a fluent interface + * @return string|null */ - public function setCharList($charList) + public function getCharList() { - $this->_charList = $charList; - return $this; + return $this->options['charlist']; } /** @@ -99,11 +84,11 @@ public function filter($value) return $value; } - if (null === $this->_charList) { - return $this->_unicodeTrim((string) $value); + if (null === $this->options['charlist']) { + return $this->unicodeTrim((string) $value); } - return $this->_unicodeTrim((string) $value, $this->_charList); + return $this->unicodeTrim((string) $value, $this->options['charlist']); } /** @@ -114,15 +99,16 @@ public function filter($value) * @param string $charlist * @return string */ - protected function _unicodeTrim($value, $charlist = '\\\\s') + protected function unicodeTrim($value, $charlist = '\\\\s') { $chars = preg_replace( - array( '/[\^\-\]\\\]/S', '/\\\{4}/S', '/\//'), - array( '\\\\\\0', '\\', '\/' ), + array('/[\^\-\]\\\]/S', '/\\\{4}/S', '/\//'), + array('\\\\\\0', '\\', '\/'), $charlist ); - $pattern = '^[' . $chars . ']*|[' . $chars . ']*$'; - return preg_replace("/$pattern/sSD", '', $value); + $pattern = '/^[' . $chars . ']*|[' . $chars . ']*$/sSD'; + + return preg_replace($pattern, '', $value); } } diff --git a/library/Zend/Filter/StripNewlines.php b/library/Zend/Filter/StripNewlines.php index 4a343e82739..1a62872d203 100644 --- a/library/Zend/Filter/StripNewlines.php +++ b/library/Zend/Filter/StripNewlines.php @@ -1,21 +1,11 @@ _separator . '\1', $this->_separator . '\1')); } else { - parent::setMatchPattern(array('#(?<=(?:[A-Z]))([A-Z]+)([A-Z][A-z])#', '#(?<=(?:[a-z0-9]))([A-Z])#')); + parent::setPattern(array('#(?<=(?:[A-Z]))([A-Z]+)([A-Z][A-z])#', '#(?<=(?:[a-z0-9]))([A-Z])#')); parent::setReplacement(array('\1' . $this->_separator . '\2', $this->_separator . '\1')); } diff --git a/library/Zend/Filter/Word/CamelCaseToUnderscore.php b/library/Zend/Filter/Word/CamelCaseToUnderscore.php index 81608a41196..5dbfbf0e6c7 100644 --- a/library/Zend/Filter/Word/CamelCaseToUnderscore.php +++ b/library/Zend/Filter/Word/CamelCaseToUnderscore.php @@ -1,21 +1,11 @@ setMatchPattern('#-#'); + $this->setPattern('#-#'); $this->setReplacement($this->_separator); return parent::filter($value); } diff --git a/library/Zend/Filter/Word/DashToUnderscore.php b/library/Zend/Filter/Word/DashToUnderscore.php index ee4ffccaa7d..f41f604dd7e 100644 --- a/library/Zend/Filter/Word/DashToUnderscore.php +++ b/library/Zend/Filter/Word/DashToUnderscore.php @@ -1,21 +1,11 @@ _separator, '#'); - if (self::isUnicodeSupportEnabled()) { - parent::setMatchPattern(array('#('.$pregQuotedSeparator.')(\p{L}{1})#eu','#(^\p{Ll}{1})#eu')); + if (self::hasPcreUnicodeSupport()) { + parent::setPattern(array('#('.$pregQuotedSeparator.')(\p{L}{1})#eu','#(^\p{Ll}{1})#eu')); if (!extension_loaded('mbstring')) { parent::setReplacement(array("strtoupper('\\2')","strtoupper('\\1')")); } else { parent::setReplacement(array("mb_strtoupper('\\2', 'UTF-8')","mb_strtoupper('\\1', 'UTF-8')")); } } else { - parent::setMatchPattern(array('#('.$pregQuotedSeparator.')([A-Za-z]{1})#e','#(^[A-Za-z]{1})#e')); + parent::setPattern(array('#('.$pregQuotedSeparator.')([A-Za-z]{1})#e','#(^[A-Za-z]{1})#e')); parent::setReplacement(array("strtoupper('\\2')","strtoupper('\\1')")); } diff --git a/library/Zend/Filter/Word/SeparatorToDash.php b/library/Zend/Filter/Word/SeparatorToDash.php index a59cf3554db..65772d4e23d 100644 --- a/library/Zend/Filter/Word/SeparatorToDash.php +++ b/library/Zend/Filter/Word/SeparatorToDash.php @@ -1,21 +1,11 @@ setMatchPattern('#' . preg_quote($this->_searchSeparator, '#') . '#'); + $this->setPattern('#' . preg_quote($this->_searchSeparator, '#') . '#'); $this->setReplacement($this->_replacementSeparator); return parent::filter($value); } diff --git a/library/Zend/Filter/Word/UnderscoreToCamelCase.php b/library/Zend/Filter/Word/UnderscoreToCamelCase.php index 9bda91d057a..2beac9d0db4 100644 --- a/library/Zend/Filter/Word/UnderscoreToCamelCase.php +++ b/library/Zend/Filter/Word/UnderscoreToCamelCase.php @@ -1,21 +1,11 @@ =5.3.3" + }, + "suggest": { + "zendframework/zend-i18n": "Zend\\I18n component", + "zendframework/zend-validator": "Zend\\Validator component" + } +} \ No newline at end of file diff --git a/library/Zend/Form/Annotation/AbstractAnnotationsListener.php b/library/Zend/Form/Annotation/AbstractAnnotationsListener.php index 3ea82a407ab..61890e9925a 100644 --- a/library/Zend/Form/Annotation/AbstractAnnotationsListener.php +++ b/library/Zend/Form/Annotation/AbstractAnnotationsListener.php @@ -1,22 +1,11 @@ listeners[] = $events->attach('configureElement', array($this, 'handleErrorMessageAnnotation')); $this->listeners[] = $events->attach('configureElement', array($this, 'handleFilterAnnotation')); $this->listeners[] = $events->attach('configureElement', array($this, 'handleFlagsAnnotation')); + $this->listeners[] = $events->attach('configureElement', array($this, 'handleHydratorAnnotation')); $this->listeners[] = $events->attach('configureElement', array($this, 'handleInputAnnotation')); + $this->listeners[] = $events->attach('configureElement', array($this, 'handleObjectAnnotation')); + $this->listeners[] = $events->attach('configureElement', array($this, 'handleOptionsAnnotation')); $this->listeners[] = $events->attach('configureElement', array($this, 'handleRequiredAnnotation')); $this->listeners[] = $events->attach('configureElement', array($this, 'handleTypeAnnotation')); $this->listeners[] = $events->attach('configureElement', array($this, 'handleValidatorAnnotation')); @@ -227,6 +219,25 @@ public function handleFlagsAnnotation($e) $elementSpec['flags'] = $annotation->getFlags(); } + /** + * Handle the Hydrator annotation + * + * Sets the hydrator class to use in the fieldset specification. + * + * @param \Zend\EventManager\EventInterface $e + * @return void + */ + public function handleHydratorAnnotation($e) + { + $annotation = $e->getParam('annotation'); + if (!$annotation instanceof Hydrator) { + return; + } + + $elementSpec = $e->getParam('element'); + $elementSpec['hydrator'] = $annotation->getHydrator(); + } + /** * Handle the Input annotation * @@ -248,6 +259,44 @@ public function handleInputAnnotation($e) $filterSpec[$name] = $annotation->getInput(); } + /** + * Handle the Object annotation + * + * Sets the object to bind to the form or fieldset + * + * @param \Zend\EventManager\EventInterface $e + * @return void + */ + public function handleObjectAnnotation($e) + { + $annotation = $e->getParam('annotation'); + if (!$annotation instanceof Object) { + return; + } + + $elementSpec = $e->getParam('elementSpec'); + $elementSpec['object'] = $annotation->getObject(); + } + + /** + * Handle the Options annotation + * + * Sets the element options in the specification. + * + * @param \Zend\EventManager\EventInterface $e + * @return void + */ + public function handleOptionsAnnotation($e) + { + $annotation = $e->getParam('annotation'); + if (!$annotation instanceof Options) { + return; + } + + $elementSpec = $e->getParam('elementSpec'); + $elementSpec['spec']['options'] = $annotation->getOptions(); + } + /** * Handle the Required annotation * diff --git a/library/Zend/Form/Annotation/ErrorMessage.php b/library/Zend/Form/Annotation/ErrorMessage.php index 1b6ce3f1e94..3b889eed9b0 100644 --- a/library/Zend/Form/Annotation/ErrorMessage.php +++ b/library/Zend/Form/Annotation/ErrorMessage.php @@ -1,22 +1,11 @@ listeners[] = $events->attach('configureForm', array($this, 'handleFlagsAnnotation')); $this->listeners[] = $events->attach('configureForm', array($this, 'handleHydratorAnnotation')); $this->listeners[] = $events->attach('configureForm', array($this, 'handleInputFilterAnnotation')); + $this->listeners[] = $events->attach('configureForm', array($this, 'handleObjectAnnotation')); + $this->listeners[] = $events->attach('configureForm', array($this, 'handleOptionsAnnotation')); $this->listeners[] = $events->attach('configureForm', array($this, 'handleTypeAnnotation')); + $this->listeners[] = $events->attach('configureForm', array($this, 'handleValidationGroupAnnotation')); $this->listeners[] = $events->attach('discoverName', array($this, 'handleNameAnnotation')); $this->listeners[] = $events->attach('discoverName', array($this, 'discoverFallbackName')); @@ -141,6 +133,44 @@ public function handleInputFilterAnnotation($e) $formSpec['input_filter'] = $annotation->getInputFilter(); } + /** + * Handle the Object annotation + * + * Sets the object to bind to the form or fieldset + * + * @param \Zend\EventManager\EventInterface $e + * @return void + */ + public function handleObjectAnnotation($e) + { + $annotation = $e->getParam('annotation'); + if (!$annotation instanceof Object) { + return; + } + + $formSpec = $e->getParam('formSpec'); + $formSpec['object'] = $annotation->getObject(); + } + + /** + * Handle the Options annotation + * + * Sets the options key of the form specification. + * + * @param \Zend\EventManager\EventInterface $e + * @return void + */ + public function handleOptionsAnnotation($e) + { + $annotation = $e->getParam('annotation'); + if (!$annotation instanceof Options) { + return; + } + + $formSpec = $e->getParam('formSpec'); + $formSpec['options'] = $annotation->getOptions(); + } + /** * Handle the Type annotation * @@ -159,4 +189,23 @@ public function handleTypeAnnotation($e) $formSpec = $e->getParam('formSpec'); $formSpec['type'] = $annotation->getType(); } + + /** + * Handle the ValidationGroup annotation + * + * Sets the validation group to use in the form specification. + * + * @param \Zend\EventManager\EventInterface $e + * @return void + */ + public function handleValidationGroupAnnotation($e) + { + $annotation = $e->getParam('annotation'); + if (!$annotation instanceof ValidationGroup) { + return; + } + + $formSpec = $e->getParam('formSpec'); + $formSpec['validation_group'] = $annotation->getValidationGroup(); + } } diff --git a/library/Zend/Form/Annotation/Hydrator.php b/library/Zend/Form/Annotation/Hydrator.php index 7e3ceb109be..b309e7c2ada 100644 --- a/library/Zend/Form/Annotation/Hydrator.php +++ b/library/Zend/Form/Annotation/Hydrator.php @@ -1,22 +1,11 @@ value; + } +} diff --git a/library/Zend/Form/Annotation/Options.php b/library/Zend/Form/Annotation/Options.php new file mode 100644 index 00000000000..faf6ae2d772 --- /dev/null +++ b/library/Zend/Form/Annotation/Options.php @@ -0,0 +1,36 @@ +value; + } +} diff --git a/library/Zend/Form/Annotation/Required.php b/library/Zend/Form/Annotation/Required.php index ee9ffb3539e..2fc9127fcdd 100644 --- a/library/Zend/Form/Annotation/Required.php +++ b/library/Zend/Form/Annotation/Required.php @@ -1,22 +1,11 @@ value; + } +} diff --git a/library/Zend/Form/Annotation/Validator.php b/library/Zend/Form/Annotation/Validator.php index 7fddf817e14..3d08cb604f3 100644 --- a/library/Zend/Form/Annotation/Validator.php +++ b/library/Zend/Form/Annotation/Validator.php @@ -1,22 +1,11 @@ 'POST', - ); - - /** - * How to bind values to the attached object - * - * @var int - */ - protected $bindAs = FormInterface::VALUES_NORMALIZED; - - /** - * Whether or not to bind values to the bound object on successful validation - * - * @var int - */ - protected $bindOnValidate = self::BIND_ON_VALIDATE; - - /** - * Base fieldset to use for hydrating (if none specified, directly hydrate elements) - * - * @var FieldsetInterface - */ - protected $baseFieldset; - - /** - * Data being validated - * - * @var null|array|Traversable - */ - protected $data; - - /** - * @var null|InputFilterInterface - */ - protected $filter; - - /** - * Whether or not validation has occurred - * - * @var bool - */ - protected $hasValidated = false; - - /** - * Result of last validation operation - * - * @var bool - */ - protected $isValid = false; - - /** - * Validation group, if any - * - * @var null|array - */ - protected $validationGroup; - - /** - * Set data to validate and/or populate elements - * - * Typically, also passes data on to the composed input filter. - * - * @param array|\ArrayAccess $data - * @return BaseForm - */ - public function setData($data) - { - if ($data instanceof Traversable) { - $data = ArrayUtils::iteratorToArray($data); - } - if (!is_array($data)) { - throw new Exception\InvalidArgumentException(sprintf( - '%s expects an array or Traversable argument; received "%s"', - __METHOD__, - (is_object($data) ? get_class($data) : gettype($data)) - )); - } - - $this->hasValidated = false; - $this->data = $data; - $this->populateValues($data); - - return $this; - } - - /** - * Bind an object to the form - * - * Ensures the object is populated with validated values. - * - * @param object $object - * @param int $flags - * @return mixed|void - * @throws Exception\InvalidArgumentException - */ - public function bind($object, $flags = FormInterface::VALUES_NORMALIZED) - { - if (!is_object($object)) { - throw new Exception\InvalidArgumentException(sprintf( - '%s expects an object argument; received "%s"', - __METHOD__, - $object - )); - } - - if (!in_array($flags, array(FormInterface::VALUES_NORMALIZED, FormInterface::VALUES_RAW))) { - throw new Exception\InvalidArgumentException(sprintf( - '%s expects the $flags argument to be one of "%s" or "%s"; received "%s"', - __METHOD__, - 'Zend\Form\FormInterface::VALUES_NORMALIZED', - 'Zend\Form\FormInterface::VALUES_RAW', - $flags - )); - } - - if ($this->baseFieldset !== null) { - $this->baseFieldset->setObject($object); - } - - $this->bindAs = $flags; - $this->object = $object; - $this->extract(); - } - - /** - * Bind values to the bound object - * - * @param array $values - * @return mixed - */ - public function bindValues(array $values = array()) - { - if (!is_object($this->object)) { - return; - } - if (!$this->isValid) { - return; - } - - $filter = $this->getInputFilter(); - - switch ($this->bindAs) { - case FormInterface::VALUES_RAW: - $data = $filter->getRawValues(); - break; - case FormInterface::VALUES_NORMALIZED: - default: - $data = $filter->getValues(); - break; - } - - $this->object = parent::bindValues($data); - } - - /** - * Set flag indicating whether or not to bind values on successful validation - * - * @param int $bindOnValidateFlag - * @return void|BaseForm - * @throws Exception\InvalidArgumentException - */ - public function setBindOnValidate($bindOnValidateFlag) - { - if (!in_array($bindOnValidateFlag, array(self::BIND_ON_VALIDATE, self::BIND_MANUAL))) { - throw new Exception\InvalidArgumentException(sprintf( - '%s expects the flag to be one of %s::%s or %s::%s', - __METHOD__, - get_called_class(), - 'BIND_ON_VALIDATE', - get_called_class(), - 'BIND_MANUAL' - )); - } - $this->bindOnValidate = $bindOnValidateFlag; - return $this; - } - - /** - * Will we bind values to the bound object on successful validation? - * - * @return bool - */ - public function bindOnValidate() - { - return (self::BIND_ON_VALIDATE === $this->bindOnValidate); - } - - /** - * Set the base fieldset to use when hydrating - * - * @param FieldsetInterface $baseFieldset - * @return BaseForm - * @throws Exception\InvalidArgumentException - */ - public function setBaseFieldset(FieldsetInterface $baseFieldset) - { - $this->baseFieldset = $baseFieldset; - return $this; - } - - /** - * Get the base fieldset to use when hydrating - * - * @return FieldsetInterface - */ - public function getBaseFieldset() - { - return $this->baseFieldset; - } - - /** - * Validate the form - * - * Typically, will proxy to the composed input filter. - * - * @return bool - * @throws Exception\DomainException - */ - public function isValid() - { - $this->isValid = false; - - if (!is_array($this->data) && !is_object($this->object)) { - throw new Exception\DomainException(sprintf( - '%s is unable to validate as there is no data currently set', - __METHOD__ - )); - } - - if (!is_array($this->data)) { - $hydrator = $this->getHydrator(); - if (!$hydrator instanceof Hydrator\HydratorInterface) { - throw new Exception\DomainException(sprintf( - '%s is unable to validate as there is no data currently set', - __METHOD__ - )); - } - $data = $hydrator->extract($this->object); - if (!is_array($data)) { - throw new Exception\DomainException(sprintf( - '%s is unable to validate as there is no data currently set', - __METHOD__ - )); - } - $this->data = $data; - } - - $filter = $this->getInputFilter(); - if (!$filter instanceof InputFilterInterface) { - throw new Exception\DomainException(sprintf( - '%s is unable to validate as there is no input filter present', - __METHOD__ - )); - } - - $filter->setData($this->data); - $filter->setValidationGroup(InputFilterInterface::VALIDATE_ALL); - - if ($this->validationGroup !== null) { - $filter->setValidationGroup($this->validationGroup); - } - - $this->isValid = $result = $filter->isValid(); - if ($result && $this->bindOnValidate()) { - $this->bindValues(); - } - - if (!$result) { - $this->setMessages($filter->getMessages()); - } - - $this->hasValidated = true; - return $result; - } - - /** - * Retrieve the validated data - * - * By default, retrieves normalized values; pass one of the - * FormInterface::VALUES_* constants to shape the behavior. - * - * @param int $flag - * @return array|object - */ - public function getData($flag = FormInterface::VALUES_NORMALIZED) - { - if (!$this->hasValidated) { - throw new Exception\DomainException(sprintf( - '%s cannot return data as validation has not yet occurred', - __METHOD__ - )); - } - - if (($flag !== FormInterface::VALUES_AS_ARRAY) && is_object($this->object)) { - return $this->object; - } - - $filter = $this->getInputFilter(); - - if ($flag === FormInterface::VALUES_RAW) { - return $filter->getRawValues(); - } - - return $filter->getValues(); - } - - /** - * Set the validation group (set of values to validate) - * - * Typically, proxies to the composed input filter - * - * @return BaseForm - */ - public function setValidationGroup() - { - $argc = func_num_args(); - if (0 === $argc) { - throw new Exception\InvalidArgumentException(sprintf( - '%s expects at least one argument; none provided', - __METHOD__ - )); - } - - $argv = func_get_args(); - $this->hasValidated = false; - - if (1 < $argc) { - $this->validationGroup = $argv; - return $this; - } - - $arg = array_shift($argv); - if ($arg === FormInterface::VALIDATE_ALL) { - $this->validationGroup = null; - return $this; - } - - if (!is_array($arg)) { - $arg = (array) $arg; - } - $this->validationGroup = $arg; - return $this; - } - - /** - * Set the input filter used by this form - * - * @param InputFilterInterface $inputFilter - * @return BaseForm - */ - public function setInputFilter(InputFilterInterface $inputFilter) - { - $this->hasValidated = false; - $this->filter = $inputFilter; - return $this; - } - - /** - * Retrieve input filter used by this form - * - * @return null|InputFilterInterface - */ - public function getInputFilter() - { - if ($this->object instanceof InputFilterAwareInterface) { - $this->filter = $this->object->getInputFilter(); - } - return $this->filter; - } - - /** - * Extract values from the bound object and populate - * the form elements - * - * @return void - */ - protected function extract() - { - if (!is_object($this->object)) { - return; - } - $hydrator = $this->getHydrator(); - if (!$hydrator instanceof Hydrator\HydratorInterface) { - return; - } - - $values = $hydrator->extract($this->object); - if (!is_array($values)) { - // Do nothing if the hydrator returned a non-array - return; - } - - if ($this->baseFieldset) { - $this->baseFieldset->populateValues($values); - } else { - $this->populateValues($values); - } - } -} diff --git a/library/Zend/Form/Element.php b/library/Zend/Form/Element.php index 965ee19359a..6fb1729badb 100644 --- a/library/Zend/Form/Element.php +++ b/library/Zend/Form/Element.php @@ -1,32 +1,21 @@ setName($name); } + + if (!empty($options)) { + $this->setOptions($options); + } } /** @@ -64,7 +67,7 @@ public function setName($name) $this->setAttribute('name', $name); return $this; } - + /** * Get value for name * @@ -75,6 +78,36 @@ public function getName() return $this->getAttribute('name'); } + /** + * Set options for an element. Accepted options are: + * - label: label to associate with the element + * - label_attributes: attributes to use when the label is rendered + * + * @param array|\Traversable $options + * @return Element|ElementInterface + * @throws Exception\InvalidArgumentException + */ + public function setOptions($options) + { + if ($options instanceof Traversable) { + $options = ArrayUtils::iteratorToArray($options); + } elseif (!is_array($options)) { + throw new Exception\InvalidArgumentException( + 'The options parameter must be an array or a Traversable' + ); + } + + if (isset($options['label'])) { + $this->setLabel($options['label']); + } + + if (isset($options['label_attributes'])) { + $this->setLabelAttributes($options['label_attributes']); + } + + return $this; + } + /** * Set a single element attribute * @@ -149,12 +182,60 @@ public function getAttributes() /** * Clear all attributes - * - * @return void + * + * @return Element|ElementInterface */ public function clearAttributes() { $this->attributes = array(); + return $this; + } + + /** + * Set the label used for this element + * + * @param $label + * @return Element|ElementInterface + */ + public function setLabel($label) + { + if (is_string($label)) { + $this->label = $label; + } + + return $this; + } + + /** + * Retrieve the label used for this element + * + * @return string + */ + public function getLabel() + { + return $this->label; + } + + /** + * Set the attributes to use with the label + * + * @param array $labelAttributes + * @return Element|ElementInterface + */ + public function setLabelAttributes(array $labelAttributes) + { + $this->labelAttributes = $labelAttributes; + return $this; + } + + /** + * Get the attributes to use with the label + * + * @return array + */ + public function getLabelAttributes() + { + return $this->labelAttributes; } /** @@ -182,7 +263,7 @@ public function setMessages($messages) * Get validation error messages, if any. * * Returns a list of validation failure messages, if any. - * + * * @return array|Traversable */ public function getMessages() diff --git a/library/Zend/Form/Element/Button.php b/library/Zend/Form/Element/Button.php new file mode 100644 index 00000000000..d9d4e679741 --- /dev/null +++ b/library/Zend/Form/Element/Button.php @@ -0,0 +1,43 @@ + 'button', + ); +} diff --git a/library/Zend/Form/Element/Captcha.php b/library/Zend/Form/Element/Captcha.php index 6973856ac69..f8951dd2728 100644 --- a/library/Zend/Form/Element/Captcha.php +++ b/library/Zend/Form/Element/Captcha.php @@ -1,22 +1,11 @@ setCaptcha($value); - return $this; + parent::setOptions($options); + + if (isset($options['captcha'])) { + $this->setCaptcha($options['captcha']); } - return parent::setAttribute($key, $value); + + return $this; } /** @@ -69,7 +63,8 @@ public function setCaptcha($captcha) (is_object($captcha) ? get_class($captcha) : gettype($captcha)) )); } - $this->attributes['captcha'] = $captcha; + $this->captcha = $captcha; + return $this; } @@ -80,7 +75,7 @@ public function setCaptcha($captcha) */ public function getCaptcha() { - return $this->getAttribute('captcha'); + return $this->captcha; } /** diff --git a/library/Zend/Form/Element/Checkbox.php b/library/Zend/Form/Element/Checkbox.php new file mode 100644 index 00000000000..36f8642a3e7 --- /dev/null +++ b/library/Zend/Form/Element/Checkbox.php @@ -0,0 +1,198 @@ + 'checkbox' + ); + + /** + * @var ValidatorInterface + */ + protected $validator; + + /** + * @var bool + */ + protected $useHiddenElement = true; + + /** + * @var string + */ + protected $uncheckedValue = '0'; + + /** + * @var string + */ + protected $checkedValue = '1'; + + /** + * Accepted options for MultiCheckbox: + * - use_hidden_element: do we render hidden element? + * - unchecked_value: value for checkbox when unchecked + * - checked_value: value for checkbox when checked + * + * @param array|\Traversable $options + * @return Checkbox + */ + public function setOptions($options) + { + parent::setOptions($options); + + if (isset($options['use_hidden_element'])) { + $this->setUseHiddenElement($options['use_hidden_element']); + } + + if (isset($options['unchecked_value'])) { + $this->setUncheckedValue($options['unchecked_value']); + } + + if (isset($options['checked_value'])) { + $this->setCheckedValue($options['checked_value']); + } + + return $this; + } + + /** + * Do we render hidden element? + * + * @param bool $useHiddenElement + * @return Checkbox + */ + public function setUseHiddenElement($useHiddenElement) + { + $this->useHiddenElement = (bool)$useHiddenElement; + return $this; + } + + /** + * Do we render hidden element? + * + * @return bool + */ + public function useHiddenElement() + { + return $this->useHiddenElement; + } + + /** + * Set the value to use when checkbox is unchecked + * + * @param $uncheckedValue + * @return Checkbox + */ + public function setUncheckedValue($uncheckedValue) + { + $this->uncheckedValue = $uncheckedValue; + return $this; + } + + /** + * Get the value to use when checkbox is unchecked + * + * @return string + */ + public function getUncheckedValue() + { + return $this->uncheckedValue; + } + + /** + * Set the value to use when checkbox is checked + * + * @param $checkedValue + * @return Checkbox + */ + public function setCheckedValue($checkedValue) + { + $this->checkedValue = $checkedValue; + return $this; + } + + /** + * Get the value to use when checkbox is checked + * + * @return string + */ + public function getCheckedValue() + { + return $this->checkedValue; + } + + /** + * Get validator + * + * @return ValidatorInterface + */ + protected function getValidator() + { + if (null === $this->validator) { + $this->validator = new InArrayValidator(array( + 'haystack' => array($this->checkedValue, $this->uncheckedValue), + 'strict' => false + )); + } + return $this->validator; + } + + /** + * Provide default input rules for this element + * + * Attaches the captcha as a validator. + * + * @return array + */ + public function getInputSpecification() + { + $spec = array( + 'name' => $this->getName(), + 'required' => true, + 'validators' => array( + $this->getValidator() + ) + ); + + return $spec; + } +} diff --git a/library/Zend/Form/Element/Collection.php b/library/Zend/Form/Element/Collection.php index 441c72f5ca4..68212d03072 100644 --- a/library/Zend/Form/Element/Collection.php +++ b/library/Zend/Form/Element/Collection.php @@ -1,22 +1,11 @@ setCount(1); - $this->setAllowAdd(true); - $this->setTemplatePlaceholder(self::DEFAULT_TEMPLATE_PLACEHOLDER); + protected $targetElement; + + /** + * Initial count of target element + * + * @var int + */ + protected $count = 1; + + /** + * Are new elements allowed to be added dynamically ? + * + * @var bool + */ + protected $allowAdd = true; + + /** + * Is the template generated ? + * + * @var bool + */ + protected $shouldCreateTemplate = false; + + /** + * Placeholder used in template content for making your life easier with JavaScript + * + * @var string + */ + protected $templatePlaceholder = self::DEFAULT_TEMPLATE_PLACEHOLDER; + + /** + * Element used as a template + * + * @var ElementInterface|FieldsetInterface + */ + protected $templateElement; - parent::__construct(); - } /** - * Set a single element attribute + * Accepted options for Collection: + * - target_element: an array or element used in the collection + * - count: number of times the element is added initially + * - allow_add: if set to true, elements can be added to the form dynamically (using JavaScript) + * - should_create_template: if set to true, a template is generated (inside a ) + * - template_placeholder: placeholder used in the data template * - * @param string $key - * @param mixed $value - * @return Element|ElementInterface + * @param array|\Traversable $options + * @return Collection */ - public function setAttribute($key, $value) + public function setOptions($options) { - switch(strtolower($key)) { - case 'count': - $this->setCount($value); - return $this; - case 'targetelement': - $this->setTargetElement($value); - return $this; - case 'allowadd': - $this->setAllowAdd($value); - return $this; - case 'shouldcreatetemplate': - $this->setShouldCreateTemplate($value); - return $this; - case 'templateplaceholder': - $this->setTemplatePlaceholder($value); - return $this; + parent::setOptions($options); + + if (isset($options['target_element'])) { + $this->setTargetElement($options['target_element']); + } + + if (isset($options['count'])) { + $this->setCount($options['count']); + } + + if (isset($options['allow_add'])) { + $this->setAllowAdd($options['allow_add']); + } + + if (isset($options['should_create_template'])) { + $this->setShouldCreateTemplate($options['should_create_template']); + } + + if (isset($options['template_placeholder'])) { + $this->setTemplatePlaceholder($options['template_placeholder']); } - return parent::setAttribute($key, $value); + return $this; } /** @@ -93,34 +120,36 @@ public function setAttribute($key, $value) */ public function populateValues($data) { - $count = $this->getCount(); + if (!is_array($data) && !$data instanceof Traversable) { + throw new Exception\InvalidArgumentException(sprintf( + '%s expects an array or Traversable set of data; received "%s"', + __METHOD__, + (is_object($data) ? get_class($data) : gettype($data)) + )); + } - if ($this->getTargetElement() instanceof FieldsetInterface) { - foreach ($data as $key => $value) { - if ($count > 0) { - $this->fieldsets[$key]->populateValues($value); - unset($data[$key]); + // Can't do anything with empty data + if (empty($data)) { - } + return; + } - $count--; + if ($this->targetElement instanceof FieldsetInterface) { + foreach ($this->byName as $name => $fieldset) { + $fieldset->populateValues($data[$name]); + unset($data[$name]); } } else { - foreach ($data as $key => $value) { - if ($count > 0) { - $this->elements[$key]->setAttribute('value', $value); - unset($data[$key]); - - } - - $count--; + foreach ($this->byName as $name => $element) { + $element->setAttribute('value', $data[$name]); + unset($data[$name]); } } // If there are still data, this means that elements or fieldsets were dynamically added. If allowed by the user, add them - if (!empty($data) && $this->getAllowAdd()) { + if (!empty($data) && $this->allowAdd) { foreach ($data as $key => $value) { - $elementOrFieldset = clone $this->getTargetElement(); + $elementOrFieldset = $this->createNewTargetElementInstance(); $elementOrFieldset->setName($key); if ($elementOrFieldset instanceof FieldsetInterface) { @@ -134,6 +163,28 @@ public function populateValues($data) } } + /** + * Bind values to the object + * + * @param array $values + * @return array|mixed|void + */ + public function bindValues(array $values = array()) + { + $collection = array(); + foreach ($values as $name => $value) { + $element = $this->get($name); + + if ($element instanceof FieldsetInterface) { + $collection[] = $element->bindValues($value); + } else { + $collection[] = $value; + } + } + + return $collection; + } + /** * Set the initial count of target element * @@ -142,7 +193,7 @@ public function populateValues($data) */ public function setCount($count) { - $this->attributes['count'] = $count > 0 ? $count : 0; + $this->count = $count > 0 ? $count : 0; return $this; } @@ -153,7 +204,7 @@ public function setCount($count) */ public function getCount() { - return $this->getAttribute('count'); + return $this->count; } /** @@ -181,7 +232,7 @@ public function setTargetElement($elementOrFieldset) )); } - $this->attributes['targetElement'] = $elementOrFieldset; + $this->targetElement = $elementOrFieldset; return $this; } @@ -193,7 +244,7 @@ public function setTargetElement($elementOrFieldset) */ public function getTargetElement() { - return $this->getAttribute('targetElement'); + return $this->targetElement; } /** @@ -204,7 +255,7 @@ public function getTargetElement() */ public function setAllowAdd($allowAdd) { - $this->attributes['allowAdd'] = (bool)$allowAdd; + $this->allowAdd = (bool)$allowAdd; return $this; } @@ -215,7 +266,7 @@ public function setAllowAdd($allowAdd) */ public function getAllowAdd() { - return $this->getAttribute('allowAdd'); + return $this->allowAdd; } /** @@ -226,12 +277,7 @@ public function getAllowAdd() */ public function setShouldCreateTemplate($shouldCreateTemplate) { - $this->attributes['shouldCreateTemplate'] = (bool)$shouldCreateTemplate; - - // If it doesn't exist yet, create it - if ($shouldCreateTemplate && !$this->has($this->getTemplatePlaceholder())) { - $this->addTemplateElement(); - } + $this->shouldCreateTemplate = (bool)$shouldCreateTemplate; return $this; } @@ -243,7 +289,7 @@ public function setShouldCreateTemplate($shouldCreateTemplate) */ public function shouldCreateTemplate() { - return $this->getAttribute('shouldCreateTemplate'); + return $this->shouldCreateTemplate; } /** @@ -255,7 +301,7 @@ public function shouldCreateTemplate() public function setTemplatePlaceholder($templatePlaceholder) { if (is_string($templatePlaceholder)) { - $this->attributes['templatePlaceholder'] = $templatePlaceholder; + $this->templatePlaceholder = $templatePlaceholder; } return $this; @@ -268,7 +314,64 @@ public function setTemplatePlaceholder($templatePlaceholder) */ public function getTemplatePlaceholder() { - return $this->attributes['templatePlaceholder']; + return $this->templatePlaceholder; + } + + /** + * Get a template element used for rendering purposes only + * + * @return null|ElementInterface|FieldsetInterface + */ + public function getTemplateElement() + { + if ($this->templateElement === null) { + $this->templateElement = $this->createTemplateElement(); + } + + return $this->templateElement; + } + + /** + * Prepare the collection by adding a dummy template element if the user want one + * + * @param Form $form + * @return mixed|void + */ + public function prepareElement(Form $form) + { + // Create a template that will also be prepared + if ($this->shouldCreateTemplate) { + $templateElement = $this->getTemplateElement(); + $this->add($templateElement); + } + + parent::prepareElement($form); + + // The template element has been prepared, but we don't want it to be rendered nor validated, so remove it from the list + if ($this->shouldCreateTemplate) { + $this->remove($this->templatePlaceholder); + } + } + + /** + * @return array + */ + public function extract() + { + // In this specific situation, object holds the data, that is too say an array + if (!is_array($this->object)) { + return array(); + } + + $values = array(); + foreach ($this->object as $key => $value) { + if ($value instanceof $this->targetElement->object) { + $this->targetElement->object = $value; + $values[$key] = $this->targetElement->extract(); + } + } + + return $values; } /** @@ -278,54 +381,44 @@ public function getTemplatePlaceholder() */ protected function prepareCollection() { - if ($this->getTargetElement() !== null) { - for ($i = 0 ; $i != $this->getCount() ; ++$i) { - $elementOrFieldset = clone $this->getTargetElement(); + if ($this->targetElement !== null) { + for ($i = 0 ; $i != $this->count ; ++$i) { + $elementOrFieldset = $this->createNewTargetElementInstance(); $elementOrFieldset->setName($i); $this->add($elementOrFieldset); } - - // If a template is wanted, we add a "dummy" element - if ($this->shouldCreateTemplate()) { - $this->addTemplateElement(); - } } } /** - * Add a "dummy" template element to be used with JavaScript + * Create a new instance of the target element * - * @return Collection + * @return ElementInterface */ - protected function addTemplateElement() + protected function createNewTargetElementInstance() { - if ($this->getTargetElement() !== null) { - $elementOrFieldset = clone $this->getTargetElement(); - $elementOrFieldset->setName($this->getTemplatePlaceholder()); - $this->add($elementOrFieldset); - } - - return $this; + return clone $this->targetElement; } /** - * Should return an array specification compatible with - * {@link Zend\InputFilter\Factory::createInputFilter()}. + * Create a dummy template element * - * @return array + * @return null|ElementInterface|FieldsetInterface */ - public function getInputFilterSpecification() + protected function createTemplateElement() { - // Ignore any template - if ($this->shouldCreateTemplate()) { - return array( - $this->getTemplatePlaceholder() => array( - 'required' => false - ) - ); + if (!$this->shouldCreateTemplate) { + return null; } - return array(); + if ($this->templateElement) { + return $this->templateElement; + } + + $elementOrFieldset = $this->createNewTargetElementInstance(); + $elementOrFieldset->setName($this->templatePlaceholder); + + return $elementOrFieldset; } -} \ No newline at end of file +} diff --git a/library/Zend/Form/Element/Color.php b/library/Zend/Form/Element/Color.php index f5da7825a2c..924943d0949 100644 --- a/library/Zend/Form/Element/Color.php +++ b/library/Zend/Form/Element/Color.php @@ -1,22 +1,11 @@ attributes['step'] : 1; // Days $baseValue = (isset($this->attributes['min'])) - ? $this->attributes['min'] : '1970-01-01T00:00:00Z'; + ? $this->attributes['min'] : '1970-01-01'; return new DateStepValidator(array( - 'format' => \DateTime::ISO8601, - 'baseValue' => $baseValue, - 'step' => new \DateInterval("P{$stepValue}D"), + 'format' => 'Y-m-d', + 'baseValue' => $baseValue, + 'step' => new \DateInterval("P{$stepValue}D"), )); } } diff --git a/library/Zend/Form/Element/DateTime.php b/library/Zend/Form/Element/DateTime.php index e27f3062026..f828cc68df6 100644 --- a/library/Zend/Form/Element/DateTime.php +++ b/library/Zend/Form/Element/DateTime.php @@ -1,22 +1,11 @@ attributes['min'] : '1970-01-01T00:00:00Z'; return new DateStepValidator(array( - 'format' => PhpDateTime::ISO8601, - 'baseValue' => $baseValue, - 'step' => new DateInterval("PT{$stepValue}M"), + 'format' => PhpDateTime::ISO8601, + 'baseValue' => $baseValue, + 'step' => new DateInterval("PT{$stepValue}M"), )); } diff --git a/library/Zend/Form/Element/DateTimeLocal.php b/library/Zend/Form/Element/DateTimeLocal.php index 01719a676e6..7c50e2b6a60 100644 --- a/library/Zend/Form/Element/DateTimeLocal.php +++ b/library/Zend/Form/Element/DateTimeLocal.php @@ -1,22 +1,11 @@ attributes['min'] : '1970-01-01T00:00:00'; return new DateStepValidator(array( - 'format' => \DateTime::ISO8601, - 'baseValue' => $baseValue, - 'step' => new \DateInterval("PT{$stepValue}M"), + 'format' => \DateTime::ISO8601, + 'baseValue' => $baseValue, + 'step' => new \DateInterval("PT{$stepValue}M"), )); } } diff --git a/library/Zend/Form/Element/Email.php b/library/Zend/Form/Element/Email.php index 7fa75945904..30aecbfd389 100644 --- a/library/Zend/Form/Element/Email.php +++ b/library/Zend/Form/Element/Email.php @@ -1,38 +1,25 @@ validator) { + $emailValidator = $this->getEmailValidator(); if (!empty($this->attributes['multiple'])) { $this->validator = new ExplodeValidator(array( - 'validator' => new EmailValidator(), + 'validator' => $emailValidator, )); } else { - $this->validator = new EmailValidator(); + $this->validator = $emailValidator; } } return $this->validator; } + /** + * Sets the primary validator to use for this element + * + * @param ValidatorInterface $validator + * @return Email + */ + public function setValidator(ValidatorInterface $validator) + { + $this->validator = $validator; + return $this; + } + + /** + * Get the email validator to use for multiple or single + * email addresses. + * + * Note from the HTML5 Specs regarding the regex: + * + * "This requirement is a *willful* violation of RFC 5322, which + * defines a syntax for e-mail addresses that is simultaneously + * too strict (before the "@" character), too vague + * (after the "@" character), and too lax (allowing comments, + * whitespace characters, and quoted strings in manners + * unfamiliar to most users) to be of practical use here." + * + * The default Regex validator is in use to match that of the + * browser validation, but you are free to set a different + * (more strict) email validator such as Zend\Validator\Email + * if you wish. + * + * @return ValidatorInterface + */ + public function getEmailValidator() + { + if (null === $this->emailValidator) { + $this->emailValidator = new RegexValidator( + '/^[a-zA-Z0-9.!#$%&\'*+\/=?^_`{|}~-]+@[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*$/' + ); + } + return $this->emailValidator; + } + + /** + * Sets the email validator to use for multiple or single + * email addresses. + * + * @param ValidatorInterface $validator + * @return Email + */ + public function setEmailValidator(ValidatorInterface $validator) + { + $this->emailValidator = $validator; + return $this; + } + + /** * Provide default input rules for this element * diff --git a/library/Zend/Form/Element/File.php b/library/Zend/Form/Element/File.php new file mode 100644 index 00000000000..9d36787188c --- /dev/null +++ b/library/Zend/Form/Element/File.php @@ -0,0 +1,43 @@ + 'file', + ); +} diff --git a/library/Zend/Form/Element/Hidden.php b/library/Zend/Form/Element/Hidden.php new file mode 100644 index 00000000000..f09525b73ad --- /dev/null +++ b/library/Zend/Form/Element/Hidden.php @@ -0,0 +1,43 @@ + 'hidden', + ); +} diff --git a/library/Zend/Form/Element/Image.php b/library/Zend/Form/Element/Image.php new file mode 100644 index 00000000000..45d9b47dc86 --- /dev/null +++ b/library/Zend/Form/Element/Image.php @@ -0,0 +1,43 @@ + 'image', + ); +} diff --git a/library/Zend/Form/Element/Month.php b/library/Zend/Form/Element/Month.php index 36b34021d75..354c2f34627 100644 --- a/library/Zend/Form/Element/Month.php +++ b/library/Zend/Form/Element/Month.php @@ -1,38 +1,25 @@ attributes['step'] : 1; // Months $baseValue = (isset($this->attributes['min'])) - ? $this->attributes['min'] : '1970-01-01T00:00:00Z'; + ? $this->attributes['min'] : '1970-01'; return new DateStepValidator(array( - 'format' => "Y-m", - 'baseValue' => $baseValue, - 'step' => new \DateInterval("P{$stepValue}M"), + 'format' => "Y-m", + 'baseValue' => $baseValue, + 'step' => new \DateInterval("P{$stepValue}M"), )); } } diff --git a/library/Zend/Form/Element/MultiCheckbox.php b/library/Zend/Form/Element/MultiCheckbox.php new file mode 100644 index 00000000000..140c7926f9c --- /dev/null +++ b/library/Zend/Form/Element/MultiCheckbox.php @@ -0,0 +1,24 @@ +attributes['step']) && $this->attributes['step'] !== 'any') { + if (!isset($this->attributes['step']) + || 'any' !== $this->attributes['step'] + ) { $validators[] = new StepValidator(array( - 'baseValue' => (isset($this->attributes['min'])) ? $this->attributes['min'] : 0, - 'step' => $this->attributes['step'] + 'baseValue' => (isset($this->attributes['min'])) ?: 0, + 'step' => (isset($this->attributes['step'])) ?: 1, )); } diff --git a/library/Zend/Form/Element/Password.php b/library/Zend/Form/Element/Password.php new file mode 100644 index 00000000000..8d5310d34da --- /dev/null +++ b/library/Zend/Form/Element/Password.php @@ -0,0 +1,43 @@ + 'password', + ); +} diff --git a/library/Zend/Form/Element/Radio.php b/library/Zend/Form/Element/Radio.php new file mode 100644 index 00000000000..32a66bf188f --- /dev/null +++ b/library/Zend/Form/Element/Radio.php @@ -0,0 +1,28 @@ + 'radio' + ); +} diff --git a/library/Zend/Form/Element/Range.php b/library/Zend/Form/Element/Range.php index 3701b722fce..2b15b1077d9 100644 --- a/library/Zend/Form/Element/Range.php +++ b/library/Zend/Form/Element/Range.php @@ -1,34 +1,26 @@ 'range', ); + + /** + * Get validator + * + * @return ValidatorInterface[] + */ + protected function getValidators() + { + if ($this->validators) { + return $this->validators; + } + + $validators = array(); + $validators[] = new NumberValidator(); + + $inclusive = true; + if (!empty($this->attributes['inclusive'])) { + $inclusive = $this->attributes['inclusive']; + } + + $validators[] = new GreaterThanValidator(array( + 'min' => (isset($this->attributes['min'])) ?: 0, + 'inclusive' => $inclusive + )); + + $validators[] = new LessThanValidator(array( + 'max' => (isset($this->attributes['max'])) ?: 100, + 'inclusive' => $inclusive + )); + + + if (!isset($this->attributes['step']) + || 'any' !== $this->attributes['step'] + ) { + $validators[] = new StepValidator(array( + 'baseValue' => (isset($this->attributes['min'])) ?: 0, + 'step' => (isset($this->attributes['step'])) ?: 1, + )); + } + + $this->validators = $validators; + return $this->validators; + } } diff --git a/library/Zend/Form/Element/Select.php b/library/Zend/Form/Element/Select.php new file mode 100644 index 00000000000..07ac41b64bc --- /dev/null +++ b/library/Zend/Form/Element/Select.php @@ -0,0 +1,44 @@ + 'select', + ); +} diff --git a/library/Zend/Form/Element/Submit.php b/library/Zend/Form/Element/Submit.php new file mode 100644 index 00000000000..8eb61676a99 --- /dev/null +++ b/library/Zend/Form/Element/Submit.php @@ -0,0 +1,43 @@ + 'submit', + ); +} diff --git a/library/Zend/Form/Element/Text.php b/library/Zend/Form/Element/Text.php new file mode 100644 index 00000000000..4ae42385017 --- /dev/null +++ b/library/Zend/Form/Element/Text.php @@ -0,0 +1,43 @@ + 'text', + ); +} diff --git a/library/Zend/Form/Element/Textarea.php b/library/Zend/Form/Element/Textarea.php new file mode 100644 index 00000000000..108728ac64b --- /dev/null +++ b/library/Zend/Form/Element/Textarea.php @@ -0,0 +1,43 @@ + 'textarea', + ); +} diff --git a/library/Zend/Form/Element/Time.php b/library/Zend/Form/Element/Time.php index 90319528d8c..1b6c3140fee 100644 --- a/library/Zend/Form/Element/Time.php +++ b/library/Zend/Form/Element/Time.php @@ -1,22 +1,11 @@ attributes['step'])) - ? $this->attributes['step'] : 1; // Minutes + ? $this->attributes['step'] : 60; // Seconds $baseValue = (isset($this->attributes['min'])) ? $this->attributes['min'] : '00:00:00'; return new DateStepValidator(array( - 'format' => 'H:i:s', - 'baseValue' => $baseValue, - 'step' => new \DateInterval("PT{$stepValue}M"), + 'format' => 'H:i:s', + 'baseValue' => $baseValue, + 'step' => new \DateInterval("PT{$stepValue}S"), )); } } diff --git a/library/Zend/Form/Element/Url.php b/library/Zend/Form/Element/Url.php index efa9ac8e77f..9912620e380 100644 --- a/library/Zend/Form/Element/Url.php +++ b/library/Zend/Form/Element/Url.php @@ -1,22 +1,11 @@ attributes['min'] : '1970-W01'; return new DateStepValidator(array( - 'format' => 'Y-\WW', - 'baseValue' => $baseValue, - 'step' => new \DateInterval("P{$stepValue}W"), + 'format' => 'Y-\WW', + 'baseValue' => $baseValue, + 'step' => new \DateInterval("P{$stepValue}W"), )); } } diff --git a/library/Zend/Form/ElementInterface.php b/library/Zend/Form/ElementInterface.php index ecb948d9462..12101c92f7f 100644 --- a/library/Zend/Form/ElementInterface.php +++ b/library/Zend/Form/ElementInterface.php @@ -1,21 +1,11 @@ setName($name); } + if (is_array($options) || $options instanceof Traversable || $options instanceof ArrayAccess) { + $element->setOptions($options); + } + if (is_array($attributes) || $attributes instanceof Traversable || $attributes instanceof ArrayAccess) { $element->setAttributes($attributes); } @@ -166,6 +161,7 @@ public function createElement($spec) * Specification can contain any of the following: * - type: the Fieldset class to use; defaults to \Zend\Form\Fieldset * - name: what name to provide the fieldset, if any + * - options: an array, Traversable, or ArrayAccess object of element options * - attributes: an array, Traversable, or ArrayAccess object of element * attributes to assign * - elements: an array or Traversable object where each entry is an array @@ -194,6 +190,14 @@ public function createFieldset($spec) )); } + if (isset($spec['object'])) { + $this->prepareAndInjectObject($spec['object'], $fieldset, __METHOD__); + } + + if (isset($spec['hydrator'])) { + $this->prepareAndInjectHydrator($spec['hydrator'], $fieldset, __METHOD__); + } + if (isset($spec['elements'])) { $this->prepareAndInjectElements($spec['elements'], $fieldset, __METHOD__); } @@ -240,8 +244,8 @@ public function createForm($spec) $this->prepareAndInjectInputFilter($spec['input_filter'], $form, __METHOD__); } - if (isset($spec['hydrator'])) { - $this->prepareAndInjectHydrator($spec['hydrator'], $form, __METHOD__); + if (isset($spec['validation_group'])) { + $this->prepareAndInjectValidationGroup($spec['validation_group'], $form, __METHOD__); } return $form; @@ -321,6 +325,81 @@ public function prepareAndInjectFieldsets($fieldsets, FieldsetInterface $masterF } } + /** + * Prepare and inject an object + * + * Takes a string indicating a class name, instantiates the class + * by that name, and injects the class instance as the bound object. + * + * @param string $objectName + * @param FieldsetInterface $fieldset + * @param string $method + * @throws Exception\DomainException + * @return void + */ + protected function prepareAndInjectObject($objectName, FieldsetInterface $fieldset, $method) + { + if (!is_string($objectName)) { + throw new Exception\DomainException(sprintf( + '%s expects string class name; received "%s"', + $method, + (is_object($objectName) ? get_class($objectName) : gettype($objectName)) + )); + } + + if (!class_exists($objectName)) { + throw new Exception\DomainException(sprintf( + '%s expects string class name to be a valid class name; received "%s"', + $method, + $objectName + )); + } + + $fieldset->setObject(new $objectName); + } + + /** + * Prepare and inject a named hydrator + * + * Takes a string indicating a hydrator class name, instantiates the class + * by that name, and injects the hydrator instance into the form. + * + * @param string $hydratorName + * @param FieldsetInterface $fieldset + * @param string $method + * @return void + * @throws Exception\DomainException if $hydratorName is not a string, does not resolve to a known class, or the class does not implement Hydrator\HydratorInterface + */ + protected function prepareAndInjectHydrator($hydratorName, FieldsetInterface $fieldset, $method) + { + if (!is_string($hydratorName)) { + throw new Exception\DomainException(sprintf( + '%s expects string hydrator class name; received "%s"', + $method, + (is_object($hydratorName) ? get_class($hydratorName) : gettype($hydratorName)) + )); + } + + if (!class_exists($hydratorName)) { + throw new Exception\DomainException(sprintf( + '%s expects string hydrator name to be a valid class name; received "%s"', + $method, + $hydratorName + )); + } + + $hydrator = new $hydratorName; + if (!$hydrator instanceof Hydrator\HydratorInterface) { + throw new Exception\DomainException(sprintf( + '%s expects a valid implementation of Zend\Form\Hydrator\HydratorInterface; received "%s"', + $method, + $hydratorName + )); + } + + $fieldset->setHydrator($hydrator); + } + /** * Prepare an input filter instance and inject in the provided form * @@ -365,45 +444,28 @@ protected function prepareAndInjectInputFilter($spec, FormInterface $form, $meth } /** - * Prepare and inject a named hydrator + * Prepare a validaiton group and inject in the provided form * - * Takes a string indicating a hydrator class name, instantiates the class - * by that name, and injects the hydrator instance into the form. + * Takes an array of elements names * - * @param string $hydratorName + * @param string|array|Traversable $spec * @param FormInterface $form * @param string $method * @return void - * @throws Exception\DomainException if $hydratorName is not a string, does not resolve to a known class, or the class does not implement Hydrator\HydratorInterface + * @throws Exception\DomainException if validation group given is not an array */ - protected function prepareAndInjectHydrator($hydratorName, FormInterface $form, $method) + protected function prepareAndInjectValidationGroup($spec, FormInterface $form, $method) { - if (!is_string($hydratorName)) { - throw new Exception\DomainException(sprintf( - '%s expects string hydrator class name; received "%s"', - $method, - (is_object($hydratorName) ? get_class($hydratorName) : gettype($hydratorName)) - )); - } - - if (!class_exists($hydratorName)) { - throw new Exception\DomainException(sprintf( - '%s expects string hydrator name to be a valid class name; received "%s"', - $method, - $hydratorName - )); - } - - $hydrator = new $hydratorName; - if (!$hydrator instanceof Hydrator\HydratorInterface) { - throw new Exception\DomainException(sprintf( - '%s expects a valid implementation of Zend\Form\Hydrator\HydratorInterface; received "%s"', - $method, - $hydratorName - )); + if (!is_array($spec)) { + if (!class_exists($spec)) { + throw new Exception\DomainException(sprintf( + '%s expects an array for validation group; received "%s"', + $method, + $spec + )); + } } - $form->setHydrator($hydrator); - return; + $form->setValidationGroup($spec); } } diff --git a/library/Zend/Form/Fieldset.php b/library/Zend/Form/Fieldset.php index 4136225058e..86e21ae71cd 100644 --- a/library/Zend/Form/Fieldset.php +++ b/library/Zend/Form/Fieldset.php @@ -1,35 +1,24 @@ setUseAsBaseFieldset($options['use_as_base_fieldset']); + } + + return $this; + } + /** * Compose a form factory to use when calling add() with a non-element/fieldset * @@ -130,8 +138,8 @@ public function getFormFactory() * the element or fieldset, order in which to prioritize it, etc. * * @todo Should we detect if the element/fieldset name conflicts? - * @param array|ElementInterface $elementOrFieldset - * @param array $flags + * @param array|Traversable|ElementInterface $elementOrFieldset + * @param array $flags * @return Fieldset|FieldsetInterface * @throws Exception\InvalidArgumentException */ @@ -154,7 +162,7 @@ public function add($elementOrFieldset, array $flags = array()) } $name = $elementOrFieldset->getName(); - if ((null === $name || '' === $name) + if ((null === $name || '' === $name) && (!array_key_exists('name', $flags) || $flags['name'] === '') ) { throw new Exception\InvalidArgumentException(sprintf( @@ -178,7 +186,7 @@ public function add($elementOrFieldset, array $flags = array()) $this->byName[$name] = $elementOrFieldset; if ($elementOrFieldset instanceof FieldsetInterface) { - if ($elementOrFieldset instanceof Element\Collection) { + if ($elementOrFieldset instanceof Collection) { $elementOrFieldset->prepareCollection(); } @@ -270,7 +278,7 @@ public function getFieldsets() * Set a hash of element names/messages to use when validation fails * * @param array|Traversable $messages - * @return FieldsetInterface + * @return Element|ElementInterface|FieldsetInterface * @throws Exception\InvalidArgumentException */ public function setMessages($messages) @@ -335,7 +343,7 @@ public function getMessages($elementName = null) * Ensures state is ready for use. Here, we append the name of the fieldsets to every elements in order to avoid * name clashes if the same fieldset is used multiple times * - * @param Form $form + * @param Form $form * @return mixed|void */ public function prepareElement(Form $form) @@ -345,7 +353,7 @@ public function prepareElement(Form $form) foreach($this->byName as $elementOrFieldset) { $elementOrFieldset->setName($name . '[' . $elementOrFieldset->getName() . ']'); - // Recursively prepare fieldsets + // Recursively prepare elements if ($elementOrFieldset instanceof ElementPrepareAwareInterface) { $elementOrFieldset->prepareElement($form); } @@ -375,6 +383,7 @@ public function populateValues($data) } $element = $this->get($name); + if ($element instanceof FieldsetInterface && is_array($value)) { $element->populateValues($value); continue; @@ -404,36 +413,23 @@ public function getIterator() return $this->iterator; } - /** - * Make a deep clone of the object - * - * @return void - */ - public function __clone() - { - $this->iterator = new PriorityQueue(); - - foreach ($this->byName as $key => $value) { - $value = clone $value; - $this->byName[$key] = $value; - $this->iterator->insert($value); - - if ($value instanceof FieldsetInterface) { - $this->fieldsets[$key] = $value; - } elseif ($value instanceof ElementInterface) { - $this->elements[$key] = $value; - } - } - } - /** * Set the object used by the hydrator * - * @param $object - * @return FieldsetInterface + * @param object $object + * @return Fieldset|FieldsetInterface + * @throws Exception\InvalidArgumentException */ public function setObject($object) { + if (!is_object($object)) { + throw new Exception\InvalidArgumentException(sprintf( + '%s expects an object argument; received "%s"', + __METHOD__, + $object + )); + } + $this->object = $object; return $this; } @@ -451,7 +447,7 @@ public function getObject() /** * Set the hydrator to use when binding an object to the element * - * @param HydratorInterface $hydrator + * @param HydratorInterface $hydrator * @return FieldsetInterface */ public function setHydrator(HydratorInterface $hydrator) @@ -469,7 +465,7 @@ public function setHydrator(HydratorInterface $hydrator) */ public function getHydrator() { - if (!$this->hydrator instanceof Hydrator\HydratorInterface) { + if (!$this->hydrator instanceof HydratorInterface) { $this->setHydrator(new Hydrator\ArraySerializable()); } return $this->hydrator; @@ -486,13 +482,16 @@ public function bindValues(array $values = array()) $hydrator = $this->getHydrator(); $hydratableData = array(); - foreach ($values as $key => $value) { - $element = $this->byName[$key]; - if ($element instanceof FieldsetInterface && is_object($element->object)) { + foreach ($values as $name => $value) { + $element = $this->byName[$name]; + + if ($element instanceof Collection) { + $value = $element->bindValues($value); + } elseif ($element instanceof FieldsetInterface && is_object($element->object)) { $value = $element->bindValues($value); } - $hydratableData[$key] = $value; + $hydratableData[$name] = $value; } $this->object = $hydrator->hydrate($hydratableData, $this->object); @@ -502,7 +501,7 @@ public function bindValues(array $values = array()) /** * Set if this fieldset is used as a base fieldset * - * @param bool $useAsBaseFieldset + * @param bool $useAsBaseFieldset * @return Fieldset */ public function setUseAsBaseFieldset($useAsBaseFieldset) @@ -520,4 +519,73 @@ public function useAsBaseFieldset() { return $this->useAsBaseFieldset; } + + /** + * Extract values from the bound object + * + * @return array + */ + protected function extract() + { + if (!is_object($this->object)) { + return array(); + } + $hydrator = $this->getHydrator(); + if (!$hydrator instanceof Hydrator\HydratorInterface) { + return array(); + } + + $values = $hydrator->extract($this->object); + + if (!is_array($values)) { + // Do nothing if the hydrator returned a non-array + return array(); + } + + // Recursively extract and populate values for nested fieldsets + foreach ($this->fieldsets as $fieldset) { + $name = $fieldset->getName(); + + if (isset($values[$name])) { + $object = $values[$name]; + + // Is the object bound to the fieldset of the same type ? Note that we are using a little hack + // here, as in case of collection, we bind array to object instance, and let the collection extract + // the data + if ($fieldset instanceof Collection || (is_object($object) && $object instanceof $fieldset->object)) { + $fieldset->object = $object; + $values[$name] = $fieldset->extract(); + } + } + } + + return $values; + } + + /** + * Make a deep clone of a fieldset + * + * @return void + */ + public function __clone() + { + $this->iterator = new PriorityQueue(); + + foreach ($this->byName as $key => $value) { + $value = clone $value; + $this->byName[$key] = $value; + $this->iterator->insert($value); + + if ($value instanceof FieldsetInterface) { + $this->fieldsets[$key] = $value; + } elseif ($value instanceof ElementInterface) { + $this->elements[$key] = $value; + } + } + + // Also make a deep copy of the object in case it's used within a collection + if (is_object($this->object)) { + $this->object = clone $this->object; + } + } } diff --git a/library/Zend/Form/FieldsetInterface.php b/library/Zend/Form/FieldsetInterface.php index c4b0469b639..ec5c8e8ad20 100644 --- a/library/Zend/Form/FieldsetInterface.php +++ b/library/Zend/Form/FieldsetInterface.php @@ -1,21 +1,11 @@ 'POST', + ); + + /** + * How to bind values to the attached object + * + * @var int + */ + protected $bindAs = FormInterface::VALUES_NORMALIZED; + + /** + * Whether or not to bind values to the bound object on successful validation + * + * @var int + */ + protected $bindOnValidate = FormInterface::BIND_ON_VALIDATE; + + /** + * Base fieldset to use for hydrating (if none specified, directly hydrate elements) + * + * @var FieldsetInterface + */ + protected $baseFieldset; + + /** + * Data being validated + * + * @var null|array|Traversable + */ + protected $data; + + /** + * @var null|InputFilterInterface + */ + protected $filter; + /** * Whether or not to automatically scan for input filter defaults on * attached fieldsets and elements @@ -43,26 +79,32 @@ class Form extends BaseForm implements FormFactoryAwareInterface protected $useInputFilterDefaults = true; /** - * Set flag indicating whether or not to scan elements and fieldsets for defaults + * Whether or not validation has occurred * - * @param bool $useInputFilterDefaults - * @return Form + * @var bool */ - public function setUseInputFilterDefaults($useInputFilterDefaults) - { - $this->useInputFilterDefaults = (bool) $useInputFilterDefaults; - return $this; - } + protected $hasValidated = false; /** - * Should we use input filter defaults from elements and fieldsets? + * Result of last validation operation * - * @return bool + * @var bool */ - public function useInputFilterDefaults() - { - return $this->useInputFilterDefaults; - } + protected $isValid = false; + + /** + * Is the form prepared ? + * + * @var bool + */ + protected $isPrepared = false; + + /** + * Validation group, if any + * + * @var null|array + */ + protected $validationGroup; /** * Add an element or fieldset @@ -74,11 +116,20 @@ public function useInputFilterDefaults() * the element or fieldset, order in which to prioritize it, etc. * * @param array|Traversable|ElementInterface $elementOrFieldset - * @param array $flags - * @return Form + * @param array $flags + * @return \Zend\Form\Fieldset|\Zend\Form\FieldsetInterface|\Zend\Form\FormInterface */ public function add($elementOrFieldset, array $flags = array()) { + // TODO: find a better solution than duplicating the factory code, the problem being that if $elementOrFieldset is an array, + // it is passed by value, and we don't get back the concrete ElementInterface + if (is_array($elementOrFieldset) + || ($elementOrFieldset instanceof Traversable && !$elementOrFieldset instanceof ElementInterface) + ) { + $factory = $this->getFormFactory(); + $elementOrFieldset = $factory->create($elementOrFieldset); + } + parent::add($elementOrFieldset, $flags); if ($elementOrFieldset instanceof Fieldset && $elementOrFieldset->useAsBaseFieldset()) { @@ -99,32 +150,381 @@ public function add($elementOrFieldset, array $flags = array()) */ public function prepare() { - $this->getInputFilter(); + if (!$this->isPrepared) { + $this->getInputFilter(); - foreach ($this->getIterator() as $elementOrFieldset) { - if ($elementOrFieldset instanceof ElementPrepareAwareInterface) { - $elementOrFieldset->prepareElement($this); + foreach ($this->getIterator() as $elementOrFieldset) { + if ($elementOrFieldset instanceof ElementPrepareAwareInterface) { + $elementOrFieldset->prepareElement($this); + } } + + $this->isPrepared = true; } } /** - * Retrieve input filter used by this form. + * Set data to validate and/or populate elements * - * Attaches defaults from attached elements, if no corresponding input - * exists for the given element in the input filter. + * Typically, also passes data on to the composed input filter. * - * @return InputFilterInterface + * @param array|\ArrayAccess|\Traversable $data + * @return Form|FormInterface + * @throws Exception\InvalidArgumentException + */ + public function setData($data) + { + if ($data instanceof Traversable) { + $data = ArrayUtils::iteratorToArray($data); + } + if (!is_array($data)) { + throw new Exception\InvalidArgumentException(sprintf( + '%s expects an array or Traversable argument; received "%s"', + __METHOD__, + (is_object($data) ? get_class($data) : gettype($data)) + )); + } + + $this->hasValidated = false; + $this->data = $data; + $this->populateValues($data); + + return $this; + } + + /** + * Bind an object to the form + * + * Ensures the object is populated with validated values. + * + * @param object $object + * @param int $flags + * @return mixed|void + * @throws Exception\InvalidArgumentException + */ + public function bind($object, $flags = FormInterface::VALUES_NORMALIZED) + { + if (!in_array($flags, array(FormInterface::VALUES_NORMALIZED, FormInterface::VALUES_RAW))) { + throw new Exception\InvalidArgumentException(sprintf( + '%s expects the $flags argument to be one of "%s" or "%s"; received "%s"', + __METHOD__, + 'Zend\Form\FormInterface::VALUES_NORMALIZED', + 'Zend\Form\FormInterface::VALUES_RAW', + $flags + )); + } + + if ($this->baseFieldset !== null) { + $this->baseFieldset->setObject($object); + } + + $this->bindAs = $flags; + $this->setObject($object); + $this->extract(); + } + + /** + * Bind values to the bound object + * + * @param array $values + * @return mixed + */ + public function bindValues(array $values = array()) + { + if (!is_object($this->object)) { + return; + } + if (!$this->isValid) { + return; + } + + $filter = $this->getInputFilter(); + + switch ($this->bindAs) { + case FormInterface::VALUES_RAW: + $data = $filter->getRawValues(); + break; + case FormInterface::VALUES_NORMALIZED: + default: + $data = $filter->getValues(); + break; + } + + $this->object = parent::bindValues($data); + } + + /** + * Set flag indicating whether or not to bind values on successful validation + * + * @param int $bindOnValidateFlag + * @return void|Form + * @throws Exception\InvalidArgumentException + */ + public function setBindOnValidate($bindOnValidateFlag) + { + if (!in_array($bindOnValidateFlag, array(self::BIND_ON_VALIDATE, self::BIND_MANUAL))) { + throw new Exception\InvalidArgumentException(sprintf( + '%s expects the flag to be one of %s::%s or %s::%s', + __METHOD__, + get_called_class(), + 'BIND_ON_VALIDATE', + get_called_class(), + 'BIND_MANUAL' + )); + } + $this->bindOnValidate = $bindOnValidateFlag; + return $this; + } + + /** + * Will we bind values to the bound object on successful validation? + * + * @return bool + */ + public function bindOnValidate() + { + return (self::BIND_ON_VALIDATE === $this->bindOnValidate); + } + + /** + * Set the base fieldset to use when hydrating + * + * @param FieldsetInterface $baseFieldset + * @return Form + * @throws Exception\InvalidArgumentException + */ + public function setBaseFieldset(FieldsetInterface $baseFieldset) + { + $this->baseFieldset = $baseFieldset; + return $this; + } + + /** + * Get the base fieldset to use when hydrating + * + * @return FieldsetInterface + */ + public function getBaseFieldset() + { + return $this->baseFieldset; + } + + /** + * Validate the form + * + * Typically, will proxy to the composed input filter. + * + * @return bool + * @throws Exception\DomainException + */ + public function isValid() + { + $this->isValid = false; + + if (!is_array($this->data) && !is_object($this->object)) { + throw new Exception\DomainException(sprintf( + '%s is unable to validate as there is no data currently set', + __METHOD__ + )); + } + + if (!is_array($this->data)) { + $data = $this->extract(); + if (!is_array($data)) { + throw new Exception\DomainException(sprintf( + '%s is unable to validate as there is no data currently set', + __METHOD__ + )); + } + $this->data = $data; + } + + $filter = $this->getInputFilter(); + if (!$filter instanceof InputFilterInterface) { + throw new Exception\DomainException(sprintf( + '%s is unable to validate as there is no input filter present', + __METHOD__ + )); + } + + $filter->setData($this->data); + $filter->setValidationGroup(InputFilterInterface::VALIDATE_ALL); + + if ($this->validationGroup !== null) { + $this->prepareValidationGroup($this, $this->data, $this->validationGroup); + $filter->setValidationGroup($this->validationGroup); + } + + $this->isValid = $result = $filter->isValid(); + if ($result && $this->bindOnValidate()) { + $this->bindValues(); + } + + if (!$result) { + $this->setMessages($filter->getMessages()); + } + + $this->hasValidated = true; + return $result; + } + + /** + * Retrieve the validated data + * + * By default, retrieves normalized values; pass one of the + * FormInterface::VALUES_* constants to shape the behavior. + * + * @param int $flag + * @return array|object + * @throws Exception\DomainException + */ + public function getData($flag = FormInterface::VALUES_NORMALIZED) + { + if (!$this->hasValidated) { + throw new Exception\DomainException(sprintf( + '%s cannot return data as validation has not yet occurred', + __METHOD__ + )); + } + + if (($flag !== FormInterface::VALUES_AS_ARRAY) && is_object($this->object)) { + return $this->object; + } + + $filter = $this->getInputFilter(); + + if ($flag === FormInterface::VALUES_RAW) { + return $filter->getRawValues(); + } + + return $filter->getValues(); + } + + /** + * Set the validation group (set of values to validate) + * + * Typically, proxies to the composed input filter + * + * @throws Exception\InvalidArgumentException + * @return Form|FormInterface + */ + public function setValidationGroup() + { + $argc = func_num_args(); + if (0 === $argc) { + throw new Exception\InvalidArgumentException(sprintf( + '%s expects at least one argument; none provided', + __METHOD__ + )); + } + + $argv = func_get_args(); + $this->hasValidated = false; + + if (1 < $argc) { + $this->validationGroup = $argv; + return $this; + } + + $arg = array_shift($argv); + if ($arg === FormInterface::VALIDATE_ALL) { + $this->validationGroup = null; + return $this; + } + + if (!is_array($arg)) { + $arg = (array) $arg; + } + + $this->validationGroup = $arg; + return $this; + } + + /** + * Prepare the validation group in case Collection elements were used (this function also handle the case where elements + * could have been dynamically added or removed from a collection using JavaScript) + * + * @param FieldsetInterface $formOrFieldset + * @param array $data + * @param array $validationGroup + */ + protected function prepareValidationGroup(FieldsetInterface $formOrFieldset, array $data, array &$validationGroup) + { + foreach ($validationGroup as $key => &$value) { + if (!$formOrFieldset->has($key)) { + continue; + } + + $fieldset = $formOrFieldset->byName[$key]; + + if ($fieldset instanceof Collection) { + $values = array(); + $count = count($data[$key]); + + for ($i = 0 ; $i != $count ; ++$i) { + $values[] = $value; + } + + $value = $values; + } else { + $this->prepareValidationGroup($fieldset, $data[$key], $validationGroup[$key]); + } + } + } + + /** + * Set the input filter used by this form + * + * @param InputFilterInterface $inputFilter + * @return FormInterface + */ + public function setInputFilter(InputFilterInterface $inputFilter) + { + $this->hasValidated = false; + $this->filter = $inputFilter; + return $this; + } + + /** + * Retrieve input filter used by this form + * + * @return null|InputFilterInterface */ public function getInputFilter() { - $filter = parent::getInputFilter(); - if ($filter instanceof InputFilterInterface && $this->useInputFilterDefaults()) { - $this->attachInputFilterDefaults($filter, $this); + if ($this->object instanceof InputFilterAwareInterface) { + $this->filter = $this->object->getInputFilter(); } + + if ($this->filter instanceof InputFilterInterface && $this->useInputFilterDefaults()) { + $this->attachInputFilterDefaults($this->filter, $this); + } + return $this->filter; } + /** + * Set flag indicating whether or not to scan elements and fieldsets for defaults + * + * @param bool $useInputFilterDefaults + * @return Form + */ + public function setUseInputFilterDefaults($useInputFilterDefaults) + { + $this->useInputFilterDefaults = (bool) $useInputFilterDefaults; + return $this; + } + + /** + * Should we use input filter defaults from elements and fieldsets? + * + * @return bool + */ + public function useInputFilterDefaults() + { + return $this->useInputFilterDefaults; + } + /** * Attach defaults provided by the elements to the input filter * @@ -137,16 +537,12 @@ public function attachInputFilterDefaults(InputFilterInterface $inputFilter, Fie $formFactory = $this->getFormFactory(); $inputFactory = $formFactory->getInputFilterFactory(); foreach ($fieldset->getElements() as $element) { - if (!$element instanceof InputProviderInterface ) { + if (!$element instanceof InputProviderInterface) { // only interested in the element if it provides input information continue; } $name = $element->getName(); - if ($inputFilter->has($name)) { - // if we already have an input by this name, use it - continue; - } // Create an input based on the specification returned from the element $spec = $element->getInputSpecification(); @@ -182,7 +578,7 @@ public function attachInputFilterDefaults(InputFilterInterface $inputFilter, Fie continue; } - // Create an inputfilter based on the specification returned from the fieldset + // Create an input filter based on the specification returned from the fieldset $spec = $fieldset->getInputFilterSpecification(); $filter = $inputFactory->createInputFilter($spec); $inputFilter->add($filter, $name); @@ -191,4 +587,23 @@ public function attachInputFilterDefaults(InputFilterInterface $inputFilter, Fie $this->attachInputFilterDefaults($filter, $fieldset); } } + + /** + * Recursively extract values for elements and sub-fieldsets, and populate form values + * + * @return array + */ + protected function extract() + { + if (null !== $this->baseFieldset) { + $name = $this->baseFieldset->getName(); + $values[$name] = $this->baseFieldset->extract(); + $this->baseFieldset->populateValues($values[$name]); + } else { + $values = parent::extract(); + $this->populateValues($values); + } + + return $values; + } } diff --git a/library/Zend/Form/FormFactoryAwareInterface.php b/library/Zend/Form/FormFactoryAwareInterface.php index a14f30198de..cadab76ed49 100644 --- a/library/Zend/Form/FormFactoryAwareInterface.php +++ b/library/Zend/Form/FormFactoryAwareInterface.php @@ -1,21 +1,11 @@ getDoctypeHelper()->setDoctype($doctype); return $this; } - + /** * Get value for doctype * @@ -181,10 +174,10 @@ public function getDoctype() */ public function setEncoding($encoding) { - $this->getEscapeHelper()->setEncoding($encoding); + $this->getEscapeHtmlHelper()->setEncoding($encoding); return $this; } - + /** * Get character encoding * @@ -192,23 +185,23 @@ public function setEncoding($encoding) */ public function getEncoding() { - return $this->getEscapeHelper()->getEncoding(); + return $this->getEscapeHtmlHelper()->getEncoding(); } /** * Create a string of all attribute/value pairs * * Escapes all attribute values - * - * @param array $attributes + * + * @param array $attributes * @return string */ public function createAttributesString(array $attributes) { $attributes = $this->prepareAttributes($attributes); - $escape = $this->getEscapeHelper(); - $strings = array(); + $escape = $this->getEscapeHtmlHelper(); + $strings = array(); foreach ($attributes as $key => $value) { $key = strtolower($key); if (!$value && isset($this->booleanAttributes[$key])) { @@ -217,7 +210,8 @@ public function createAttributesString(array $attributes) continue; } } - $strings[] = sprintf('%s="%s"', $key, $escape($value)); + //@TODO Escape event attributes like AbstractHtmlElement view helper does in _htmlAttribs ?? + $strings[] = sprintf('%s="%s"', $escape($key), $escape($value)); } return implode(' ', $strings); } @@ -227,8 +221,8 @@ public function createAttributesString(array $attributes) * * If no ID attribute present, attempts to use the name attribute. * If no name attribute is present, either, returns null. - * - * @param ElementInterface $element + * + * @param ElementInterface $element * @return null|string */ public function getId(ElementInterface $element) @@ -245,7 +239,7 @@ public function getId(ElementInterface $element) * Get the closing bracket for an inline tag * * Closes as either "/>" for XHTML doctypes or ">" otherwise. - * + * * @return string */ public function getInlineClosingBracket() @@ -259,7 +253,7 @@ public function getInlineClosingBracket() /** * Retrieve the doctype helper - * + * * @return Doctype */ protected function getDoctypeHelper() @@ -280,36 +274,58 @@ protected function getDoctypeHelper() } /** - * Retrieve the escape helper - * - * @return Escape + * Retrieve the escapeHtml helper + * + * @return EscapeHtml */ - protected function getEscapeHelper() + protected function getEscapeHtmlHelper() { - if ($this->escapeHelper) { - return $this->escapeHelper; + if ($this->escapeHtmlHelper) { + return $this->escapeHtmlHelper; } if (method_exists($this->view, 'plugin')) { - $this->escapeHelper = $this->view->plugin('escape'); + $this->escapeHtmlHelper = $this->view->plugin('escapehtml'); } - if (!$this->escapeHelper instanceof Escape) { - $this->escapeHelper = new Escape(); + if (!$this->escapeHtmlHelper instanceof EscapeHtml) { + $this->escapeHtmlHelper = new EscapeHtml(); } - return $this->escapeHelper; + return $this->escapeHtmlHelper; + } + + /** + * Retrieve the escapeHtmlAttr helper + * + * @return EscapeHtmlAttr + */ + protected function getEscapeHtmlAttrHelper() + { + if ($this->escapeHtmlAttrHelper) { + return $this->escapeHtmlAttrHelper; + } + + if (method_exists($this->view, 'plugin')) { + $this->escapeHtmlAttrHelper = $this->view->plugin('escapehtmlattr'); + } + + if (!$this->escapeHtmlAttrHelper instanceof EscapeHtmlAttr) { + $this->escapeHtmlAttrHelper = new EscapeHtmlAttr(); + } + + return $this->escapeHtmlAttrHelper; } /** * Prepare attributes for rendering * - * Ensures appropriate attributes are present (e.g., if "name" is present, + * Ensures appropriate attributes are present (e.g., if "name" is present, * but no "id", sets the latter to the former). * * Removes any invalid attributes - * - * @param array $attributes + * + * @param array $attributes * @return array */ protected function prepareAttributes(array $attributes) @@ -345,15 +361,19 @@ protected function prepareAttributes(array $attributes) * Prepare a boolean attribute value * * Prepares the expected representation for the boolean attribute specified. - * - * @param string $attribute - * @param mixed $value + * + * @param string $attribute + * @param mixed $value * @return string */ protected function prepareBooleanAttributeValue($attribute, $value) { + if (!is_bool($value) && in_array($value, $this->booleanAttributes[$attribute])) { + return $value; + } + $value = (bool) $value; - return ($value + return ($value ? $this->booleanAttributes[$attribute]['on'] : $this->booleanAttributes[$attribute]['off'] ); diff --git a/library/Zend/Form/View/Helper/Captcha/AbstractWord.php b/library/Zend/Form/View/Helper/Captcha/AbstractWord.php index 30ad8dabbdf..9f36be9f0dc 100644 --- a/library/Zend/Form/View/Helper/Captcha/AbstractWord.php +++ b/library/Zend/Form/View/Helper/Captcha/AbstractWord.php @@ -1,22 +1,11 @@ captchaPosition = $captchaPosition; return $this; } - + /** * Get position of captcha * @@ -86,7 +84,7 @@ public function setSeparator($separator) $this->separator = (string) $separator; return $this; } - + /** * Get separator for captcha and inputs * @@ -105,14 +103,14 @@ public function getSeparator() * - Text input for entering captcha value (name[input]) * * More specific renderers will consume this and render it. - * - * @param ElementInterface $element + * + * @param ElementInterface $element * @return string */ protected function renderCaptchaInputs(ElementInterface $element) { $name = $element->getName(); - if (empty($name)) { + if ($name === null || $name === '') { throw new Exception\DomainException(sprintf( '%s requires that the element has an assigned name; none discovered', __METHOD__ @@ -120,19 +118,15 @@ protected function renderCaptchaInputs(ElementInterface $element) } $attributes = $element->getAttributes(); + $captcha = $element->getCaptcha(); - if (!isset($attributes['captcha']) - || !$attributes['captcha'] instanceof CaptchaAdapter - ) { + if ($captcha === null || !$captcha instanceof CaptchaAdapter) { throw new Exception\DomainException(sprintf( '%s requires that the element has a "captcha" attribute implementing Zend\Captcha\AdapterInterface; none found', __METHOD__ )); } - $captcha = $attributes['captcha']; - unset($attributes['captcha']); - $hidden = $this->renderCaptchaHidden($captcha, $attributes); $input = $this->renderCaptchaInput($captcha, $attributes); $separator = $this->getSeparator(); @@ -144,8 +138,8 @@ protected function renderCaptchaInputs(ElementInterface $element) * Invoke helper as functor * * Proxies to {@link render()}. - * - * @param ElementInterface $element + * + * @param ElementInterface $element * @return string */ public function __invoke(ElementInterface $element = null) @@ -159,9 +153,9 @@ public function __invoke(ElementInterface $element = null) /** * Render the hidden input with the captcha identifier - * - * @param CaptchaAdapter $captcha - * @param array $attributes + * + * @param CaptchaAdapter $captcha + * @param array $attributes * @return string */ protected function renderCaptchaHidden(CaptchaAdapter $captcha, array $attributes) @@ -177,8 +171,8 @@ protected function renderCaptchaHidden(CaptchaAdapter $captcha, array $attribute } $closingBracket = $this->getInlineClosingBracket(); $hidden = sprintf( - 'createAttributesString($attributes), + 'createAttributesString($attributes), $closingBracket ); return $hidden; @@ -186,9 +180,9 @@ protected function renderCaptchaHidden(CaptchaAdapter $captcha, array $attribute /** * Render the input for capturing the captcha value from the client - * - * @param CaptchaAdapter $captcha - * @param array $attributes + * + * @param CaptchaAdapter $captcha + * @param array $attributes * @return string */ protected function renderCaptchaInput(CaptchaAdapter $captcha, array $attributes) @@ -200,8 +194,8 @@ protected function renderCaptchaInput(CaptchaAdapter $captcha, array $attributes } $closingBracket = $this->getInlineClosingBracket(); $input = sprintf( - 'createAttributesString($attributes), + 'createAttributesString($attributes), $closingBracket ); return $input; diff --git a/library/Zend/Form/View/Helper/Captcha/Dumb.php b/library/Zend/Form/View/Helper/Captcha/Dumb.php index 4998659ee4f..e1aa52a6e7d 100644 --- a/library/Zend/Form/View/Helper/Captcha/Dumb.php +++ b/library/Zend/Form/View/Helper/Captcha/Dumb.php @@ -1,22 +1,11 @@ getAttributes(); + $captcha = $element->getCaptcha(); - if (!isset($attributes['captcha']) - || !$attributes['captcha'] instanceof CaptchaAdapter - ) { + if ($captcha === null || !$captcha instanceof CaptchaAdapter) { throw new Exception\DomainException(sprintf( '%s requires that the element has a "captcha" attribute of type Zend\Captcha\Dumb; none found', __METHOD__ )); } - $captcha = $attributes['captcha']; + $captcha->generate(); $label = sprintf( diff --git a/library/Zend/Form/View/Helper/Captcha/Figlet.php b/library/Zend/Form/View/Helper/Captcha/Figlet.php index de9bf92b781..e9d7ecb22d0 100644 --- a/library/Zend/Form/View/Helper/Captcha/Figlet.php +++ b/library/Zend/Form/View/Helper/Captcha/Figlet.php @@ -1,22 +1,11 @@ getAttributes(); + $captcha = $element->getCaptcha(); - if (!isset($attributes['captcha']) - || !$attributes['captcha'] instanceof CaptchaAdapter - ) { + if ($captcha === null || !$captcha instanceof CaptchaAdapter) { throw new Exception\DomainException(sprintf( '%s requires that the element has a "captcha" attribute of type Zend\Captcha\Figlet; none found', __METHOD__ )); } - $captcha = $attributes['captcha']; + $captcha->generate(); $figlet = sprintf( diff --git a/library/Zend/Form/View/Helper/Captcha/Image.php b/library/Zend/Form/View/Helper/Captcha/Image.php index ddab9559925..2913baa0227 100644 --- a/library/Zend/Form/View/Helper/Captcha/Image.php +++ b/library/Zend/Form/View/Helper/Captcha/Image.php @@ -1,22 +1,11 @@ getAttributes(); + $captcha = $element->getCaptcha(); - if (!isset($attributes['captcha']) - || !$attributes['captcha'] instanceof CaptchaAdapter - ) { + if ($captcha === null || !$captcha instanceof CaptchaAdapter) { throw new Exception\DomainException(sprintf( '%s requires that the element has a "captcha" attribute of type Zend\Captcha\Image; none found', __METHOD__ )); } - $captcha = $attributes['captcha']; + $captcha->generate(); $imgAttributes = array( diff --git a/library/Zend/Form/View/Helper/Captcha/ReCaptcha.php b/library/Zend/Form/View/Helper/Captcha/ReCaptcha.php index 0387250e233..d96b5e4d843 100644 --- a/library/Zend/Form/View/Helper/Captcha/ReCaptcha.php +++ b/library/Zend/Form/View/Helper/Captcha/ReCaptcha.php @@ -1,22 +1,11 @@ getAttributes(); - if (!isset($attributes['captcha']) - || !$attributes['captcha'] instanceof CaptchaAdapter - ) { + $captcha = $element->getCaptcha(); + + if ($captcha === null || !$captcha instanceof CaptchaAdapter) { throw new Exception\DomainException(sprintf( '%s requires that the element has a "captcha" attribute implementing Zend\Captcha\AdapterInterface; none found', __METHOD__ )); } - $captcha = $attributes['captcha']; - unset($attributes['captcha']); - $name = $element->getName(); $id = isset($attributes['id']) ? $attributes['id'] : $name; $challengeName = empty($name) ? 'recaptcha_challenge_field' : $name . '[recaptcha_challenge_field]'; @@ -75,8 +59,8 @@ public function render(ElementInterface $element) * Invoke helper as functor * * Proxies to {@link render()}. - * - * @param ElementInterface $element + * + * @param ElementInterface $element * @return string */ public function __invoke(ElementInterface $element = null) @@ -90,11 +74,11 @@ public function __invoke(ElementInterface $element = null) /** * Render hidden input elements for the challenge and response - * - * @param string $challengeName - * @param string $challengeId - * @param string $responseName - * @param string $responseId + * + * @param string $challengeName + * @param string $challengeId + * @param string $responseName + * @param string $responseId * @return string */ protected function renderHiddenInput($challengeName, $challengeId, $responseName, $responseId) @@ -119,9 +103,9 @@ protected function renderHiddenInput($challengeName, $challengeId, $responseName /** * Create the JS events used to bind the challenge and response values to the submitted form. - * - * @param string $challengeId - * @param string $responseId + * + * @param string $challengeId + * @param string $responseId * @return string */ protected function renderJsEvents($challengeId, $responseId) diff --git a/library/Zend/Form/View/Helper/Form.php b/library/Zend/Form/View/Helper/Form.php index 47cc1ba5465..fd3f70d3eee 100644 --- a/library/Zend/Form/View/Helper/Form.php +++ b/library/Zend/Form/View/Helper/Form.php @@ -1,22 +1,11 @@ closeTag(); + $escape = $this->getEscapeHtmlHelper(); + + return $openTag . $escape($buttonContent) . $this->closeTag(); } /** diff --git a/library/Zend/Form/View/Helper/FormCaptcha.php b/library/Zend/Form/View/Helper/FormCaptcha.php index d70161e92c4..1f73e543240 100644 --- a/library/Zend/Form/View/Helper/FormCaptcha.php +++ b/library/Zend/Form/View/Helper/FormCaptcha.php @@ -1,22 +1,11 @@ getAttributes(); - if (!isset($attributes['captcha']) - || !$attributes['captcha'] instanceof CaptchaAdapter - ) { + $captcha = $element->getCaptcha(); + + if ($captcha === null || !$captcha instanceof CaptchaAdapter) { throw new Exception\DomainException(sprintf( '%s requires that the element has a "captcha" attribute implementing Zend\Captcha\AdapterInterface; none found', __METHOD__ )); } - $captcha = $attributes['captcha']; $helper = $captcha->getHelperName(); $renderer = $this->getView(); @@ -73,8 +58,8 @@ public function render(ElementInterface $element) * Invoke helper as functor * * Proxies to {@link render()}. - * - * @param ElementInterface $element + * + * @param ElementInterface $element * @return string|FormCaptcha */ public function __invoke(ElementInterface $element) diff --git a/library/Zend/Form/View/Helper/FormCheckbox.php b/library/Zend/Form/View/Helper/FormCheckbox.php index 46b1bf96063..40bbc559c1d 100644 --- a/library/Zend/Form/View/Helper/FormCheckbox.php +++ b/library/Zend/Form/View/Helper/FormCheckbox.php @@ -1,22 +1,11 @@ '1', - 'uncheckedValue' => '0', - ); - - /** - * Returns the option for prefixing the element with a hidden element - * for the unset value. - * - * @return boolean - */ - public function getUseHiddenElement() - { - return $this->useHiddenElement; - } - - /** - * Sets the option for prefixing the element with a hidden element - * for the unset value. - * - * @param boolean $useHiddenElement - * @return FormCheckbox - */ - public function setUseHiddenElement($useHiddenElement) - { - $this->useHiddenElement = (bool) $useHiddenElement; - return $this; - } - /** * Render a form element from the provided $element * * @param ElementInterface $element + * @throws \Zend\Form\Exception\DomainException * @return string */ public function render(ElementInterface $element) @@ -87,36 +38,16 @@ public function render(ElementInterface $element) )); } - $attributes = $element->getAttributes(); - if (empty($attributes['options'])) { - $attributes['options'] = array(); - } - $options = $attributes['options']; - unset($attributes['options']); - - // default checked/unchecked values - foreach ($this->defaultStateValues as $key => $value) { - if (empty($options[$key])) { - $options[$key] = $value; - } - } - - if (!is_array($options) && !$options instanceof Traversable) { - throw new Exception\DomainException(sprintf( - '%s requires that the element has an array or Traversable "options" attribute.', - __METHOD__ - )); - } - + $attributes = $element->getAttributes(); $attributes['name'] = $name; $attributes['checked'] = ''; $attributes['type'] = $this->getInputType(); $closingBracket = $this->getInlineClosingBracket(); - if (isset($attributes['value']) && $attributes['value'] == $options['checkedValue']) { + if (isset($attributes['value']) && $attributes['value'] == $element->getCheckedValue()) { $attributes['checked'] = 'checked'; } - $attributes['value'] = $options['checkedValue']; + $attributes['value'] = $element->getCheckedValue(); $rendered = sprintf( 'useHiddenElement; + $useHiddenElement = $element->useHiddenElement(); if ($useHiddenElement) { $hiddenAttributes = array( 'name' => $attributes['name'], - 'value' => $options['uncheckedValue'], + 'value' => $element->getUncheckedValue() ); $rendered = sprintf( diff --git a/library/Zend/Form/View/Helper/FormCollection.php b/library/Zend/Form/View/Helper/FormCollection.php index 2244b5ee7b9..7d7970fe3de 100644 --- a/library/Zend/Form/View/Helper/FormCollection.php +++ b/library/Zend/Form/View/Helper/FormCollection.php @@ -1,36 +1,24 @@ getAttributes(); - $escapeHelper = $this->getEscapeHelper(); + $escapeHtmlHelper = $this->getEscapeHtmlHelper(); $rowHelper = $this->getRowHelper(); - if (isset($attributes['shouldCreateTemplate']) && $attributes['shouldCreateTemplate'] === true) { - $templatePlaceholder = $attributes['templatePlaceholder']; - $elementOrFieldset = $element->get($templatePlaceholder); + if ($element instanceof CollectionElement && $element->shouldCreateTemplate()) { + $elementOrFieldset = $element->getTemplateElement(); if ($elementOrFieldset instanceof FieldsetInterface) { $templateMarkup .= $this->render($elementOrFieldset); } elseif ($elementOrFieldset instanceof ElementInterface) { $templateMarkup .= $rowHelper($elementOrFieldset); } - - // Remove it as we don't want to draw it multiple times - $element->remove($templatePlaceholder); } foreach($element->getIterator() as $elementOrFieldset) { @@ -91,16 +74,20 @@ public function render(ElementInterface $element) // If $templateMarkup is not empty, use it for simplify adding new element in JavaScript if (!empty($templateMarkup)) { + $escapeHtmlAttribHelper = $this->getEscapeHtmlAttrHelper(); + $markup .= sprintf( '', - $escapeHelper($templateMarkup) + $escapeHtmlAttribHelper($templateMarkup) ); } // Every collection is wrapped by a fieldset if needed if ($this->shouldWrap) { - if (isset($attributes['label'])) { - $label = $escapeHelper($attributes['label']); + $label = $element->getLabel(); + + if (!empty($label)) { + $label = $escapeHtmlHelper($label); $markup = sprintf( '
%s%s
', @@ -176,4 +163,4 @@ protected function getRowHelper() return $this->rowHelper; } -} \ No newline at end of file +} diff --git a/library/Zend/Form/View/Helper/FormColor.php b/library/Zend/Form/View/Helper/FormColor.php index 9ddf11f6da6..4df88959fed 100644 --- a/library/Zend/Form/View/Helper/FormColor.php +++ b/library/Zend/Form/View/Helper/FormColor.php @@ -1,22 +1,11 @@ plugin('form_input'); + $helper = $renderer->plugin('form_hidden'); return $helper($element); } @@ -68,38 +55,136 @@ public function render(ElementInterface $element) $type = $element->getAttribute('type'); $options = $element->getAttribute('options'); - $captcha = $element->getAttribute('captcha'); - if (!empty($captcha)) { - $helper = $renderer->plugin('form_captcha'); + if ('checkbox' == $type) { + $helper = $renderer->plugin('form_checkbox'); return $helper($element); } - if (is_array($options) && $type == 'radio') { - $helper = $renderer->plugin('form_radio'); + if ('color' == $type) { + $helper = $renderer->plugin('form_color'); return $helper($element); } - if ($type == 'checkbox') { - $helper = $renderer->plugin('form_checkbox'); + if ('date' == $type) { + $helper = $renderer->plugin('form_date'); + return $helper($element); + } + + if ('datetime' == $type) { + $helper = $renderer->plugin('form_date_time'); + return $helper($element); + } + + if ('datetime-local' == $type) { + $helper = $renderer->plugin('form_date_time_local'); + return $helper($element); + } + + if ('email' == $type) { + $helper = $renderer->plugin('form_email'); + return $helper($element); + } + + if ('file' == $type) { + $helper = $renderer->plugin('form_file'); + return $helper($element); + } + + if ('hidden' == $type) { + $helper = $renderer->plugin('form_hidden'); + return $helper($element); + } + + if ('image' == $type) { + $helper = $renderer->plugin('form_image'); return $helper($element); } - if (is_array($options) && $type == 'multi_checkbox') { + if ('month' == $type) { + $helper = $renderer->plugin('form_month'); + return $helper($element); + } + + if ('multi_checkbox' == $type && is_array($options)) { $helper = $renderer->plugin('form_multi_checkbox'); return $helper($element); } - if (is_array($options) && $type == 'select') { + if ('number' == $type) { + $helper = $renderer->plugin('form_number'); + return $helper($element); + } + + if ('password' == $type) { + $helper = $renderer->plugin('form_password'); + return $helper($element); + } + + if ('radio' == $type && is_array($options)) { + $helper = $renderer->plugin('form_radio'); + return $helper($element); + } + + if ('range' == $type) { + $helper = $renderer->plugin('form_range'); + return $helper($element); + } + + if ('reset' == $type) { + $helper = $renderer->plugin('form_reset'); + return $helper($element); + } + + if ('search' == $type) { + $helper = $renderer->plugin('form_search'); + return $helper($element); + } + + if ('select' == $type && is_array($options)) { $helper = $renderer->plugin('form_select'); return $helper($element); } - if ($type == 'textarea') { + if ('submit' == $type) { + $helper = $renderer->plugin('form_submit'); + return $helper($element); + } + + if ('tel' == $type) { + $helper = $renderer->plugin('form_tel'); + return $helper($element); + } + + if ('text' == $type) { + $helper = $renderer->plugin('form_text'); + return $helper($element); + } + + if ('textarea' == $type) { $helper = $renderer->plugin('form_textarea'); return $helper($element); } + if ('time' == $type) { + $helper = $renderer->plugin('form_time'); + return $helper($element); + } + + if ('time' == $type) { + $helper = $renderer->plugin('form_time'); + return $helper($element); + } + + if ('url' == $type) { + $helper = $renderer->plugin('form_url'); + return $helper($element); + } + + if ('week' == $type) { + $helper = $renderer->plugin('form_week'); + return $helper($element); + } $helper = $renderer->plugin('form_input'); return $helper($element); @@ -109,8 +194,8 @@ public function render(ElementInterface $element) * Invoke helper as function * * Proxies to {@link render()}. - * - * @param ElementInterface|null $element + * + * @param ElementInterface|null $element * @return string|FormElement */ public function __invoke(ElementInterface $element = null) diff --git a/library/Zend/Form/View/Helper/FormElementErrors.php b/library/Zend/Form/View/Helper/FormElementErrors.php index e3081cb6c3c..18818fe316f 100644 --- a/library/Zend/Form/View/Helper/FormElementErrors.php +++ b/library/Zend/Form/View/Helper/FormElementErrors.php @@ -1,22 +1,11 @@ getEscapeHelper(); + $escapeHtml = $this->getEscapeHtmlHelper(); $messagesToPrint = array(); - array_walk_recursive($messages, function($item) use (&$messagesToPrint, $escape) { - $messagesToPrint[] = $escape($item); + array_walk_recursive($messages, function($item) use (&$messagesToPrint, $escapeHtml) { + $messagesToPrint[] = $escapeHtml($item); }); + if (empty($messagesToPrint)) { + return ''; + } + // Generate markup $markup = sprintf($this->getMessageOpenFormat(), $attributes); $markup .= implode($this->getMessageSeparatorString(), $messagesToPrint); diff --git a/library/Zend/Form/View/Helper/FormEmail.php b/library/Zend/Form/View/Helper/FormEmail.php index f6050aa7cbe..ff88702a325 100644 --- a/library/Zend/Form/View/Helper/FormEmail.php +++ b/library/Zend/Form/View/Helper/FormEmail.php @@ -1,22 +1,11 @@ element from the provided $element - * - * @param ElementInterface $element + * + * @param ElementInterface $element * @return string */ public function render(ElementInterface $element) { - $name = $element->getName(); - if (strlen($name) === 0) { + $name = $element->getName(); + if ($name === null || $name === '') { throw new Exception\DomainException(sprintf( '%s requires that the element has an assigned name; none discovered', __METHOD__ @@ -124,8 +111,8 @@ public function render(ElementInterface $element) $attributes['type'] = $this->getType($element); return sprintf( - 'createAttributesString($attributes), + 'createAttributesString($attributes), $this->getInlineClosingBracket() ); } @@ -134,8 +121,8 @@ public function render(ElementInterface $element) * Invoke helper as functor * * Proxies to {@link render()}. - * - * @param ElementInterface|null $element + * + * @param ElementInterface|null $element * @return string|FormInput */ public function __invoke(ElementInterface $element = null) @@ -149,8 +136,8 @@ public function __invoke(ElementInterface $element = null) /** * Determine input type to use - * - * @param ElementInterface $element + * + * @param ElementInterface $element * @return string */ protected function getType(ElementInterface $element) diff --git a/library/Zend/Form/View/Helper/FormLabel.php b/library/Zend/Form/View/Helper/FormLabel.php index 6a0ac65977b..ff3e6282142 100644 --- a/library/Zend/Form/View/Helper/FormLabel.php +++ b/library/Zend/Form/View/Helper/FormLabel.php @@ -1,22 +1,11 @@ getLabelAttributes(); $attributes = array('for' => $id); + + if (!empty($labelAttributes)) { + $attributes = array_merge($labelAttributes, $attributes); + } + $attributes = $this->createAttributesString($attributes); return sprintf('