diff --git a/demos/Zend/Cloud/cloudexp/.zfproject.xml b/demos/Zend/Cloud/cloudexp/.zfproject.xml deleted file mode 100755 index 1a75acc276..0000000000 --- a/demos/Zend/Cloud/cloudexp/.zfproject.xml +++ /dev/null @@ -1,126 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/demos/Zend/Cloud/cloudexp/README.txt b/demos/Zend/Cloud/cloudexp/README.txt deleted file mode 100644 index 79dd4f453c..0000000000 --- a/demos/Zend/Cloud/cloudexp/README.txt +++ /dev/null @@ -1,25 +0,0 @@ -Cloud Explorer --------------- - -Cloud Explorer is written as a demonstration of the Simple Cloud API as -implemented in Zend Framework (Zend_Cloud component). It provides the -ability: - - * to browse collections within a document storage, and to add and - delete documents from collections - * to create queues, and to send and receive messages from queues - * to upload and retrieve files to and from a storage service - -To try it out: - - * You will either need Zend Framework on your include_path, or you will - need to symlink it into the library/ subdirectory. - * You will need to create a virtual host pointing at the public/ - subdirectory as the DocumentRoot. - * You will need to copy application/configs/application.ini.dist to - application/configs/application.ini, and edit it to point at the - appropriate services, and to provide the appropriate credentials for - those services. - -Once you have accomplished the above, simply fire up a browser and point -it to your virtual host. diff --git a/demos/Zend/Cloud/cloudexp/application/Bootstrap.php b/demos/Zend/Cloud/cloudexp/application/Bootstrap.php deleted file mode 100755 index fd7e8e4657..0000000000 --- a/demos/Zend/Cloud/cloudexp/application/Bootstrap.php +++ /dev/null @@ -1,42 +0,0 @@ -getOptions()); - } - - protected function _initResourceInjector() - { - Zend_Controller_Action_HelperBroker::addHelper( - new CloudExplorer_ResourceInjector() - ); - } -} diff --git a/demos/Zend/Cloud/cloudexp/application/configs/application.ini.dist b/demos/Zend/Cloud/cloudexp/application/configs/application.ini.dist deleted file mode 100755 index 5294e1250e..0000000000 --- a/demos/Zend/Cloud/cloudexp/application/configs/application.ini.dist +++ /dev/null @@ -1,32 +0,0 @@ -[production] -autoloadernamespaces[] = "CloudExplorer_" - -phpSettings.display_startup_errors = 0 -phpSettings.display_errors = 0 -includePaths.library = APPLICATION_PATH "/../library" -bootstrap.path = APPLICATION_PATH "/Bootstrap.php" -bootstrap.class = "Bootstrap" -appnamespace = "Application" -resources.frontController.controllerDirectory = APPLICATION_PATH "/controllers" -resources.frontController.params.displayExceptions = 0 - -storage.storage_adapter = "Zend_Cloud_StorageService_Adapter_S3" -storage.bucket_name = cloudexp -storage.aws_accesskey = TEST -storage.aws_secretkey = TEST - -queue.queue_adapter = "Zend_Cloud_QueueService_Adapter_WindowsAzure" -queue.storage_host = "queue.core.windows.net" -queue.storage_accountname = TEST -queue.storage_accountkey = TEST - -[staging : production] - -[testing : production] -phpSettings.display_startup_errors = 1 -phpSettings.display_errors = 1 - -[development : production] -phpSettings.display_startup_errors = 1 -phpSettings.display_errors = 1 -resources.frontController.params.displayExceptions = 1 diff --git a/demos/Zend/Cloud/cloudexp/application/controllers/DocumentController.php b/demos/Zend/Cloud/cloudexp/application/controllers/DocumentController.php deleted file mode 100644 index e2c7798c0c..0000000000 --- a/demos/Zend/Cloud/cloudexp/application/controllers/DocumentController.php +++ /dev/null @@ -1,120 +0,0 @@ -_doc = Zend_Cloud_DocumentService_Factory::getAdapter( - $this->config->document - ); - } - - public function indexAction() - { - $this->view->collections = $this->_doc->listCollections(); - } - - public function showAction() - { - $request = $this->getRequest(); - if (!$name = $this->view->collection = $this->_getParam('collection', false)) { - return; - } - $q = $this->_doc->select("*"); - $this->view->data = $this->_doc->query($name, $q, array( - Zend_Cloud_DocumentService_Adapter_SimpleDB::RETURN_DOCUMENTS => true - )); - } - - public function createAction() - { - $request = $this->getRequest(); - if (!$request->isPost()) { - return; - } - if (!$name = $this->_getParam('name', false)) { - return; - } - $this->_doc->createCollection($name); - return $this->_helper->redirector('index'); - } - - public function addDocumentAction() - { - $this->view->fieldcount = 5; - $this->view->collections = $this->_doc->listCollections(); - $request = $this->getRequest(); - if (!$request->isPost()) { - return; - } - if (!$name = $this->view->name = $this->_getParam('name', false)) { - return; - } - if (!$id = $this->_getParam('id', false)) { - return; - } - $fields = array(); - foreach ($this->_getParam('field', array()) as $field) { - if (!$field["name"]) { - continue; - } - $fields[$field["name"]] = $field["value"]; - } - if (empty($fields)) { - return; - } - $document = new Zend_Cloud_DocumentService_Document($id, $fields); - $this->_doc->insertDocument($name, $document); - return $this->_helper->redirector('show', null, null, array("collection" => $name)); - } - - public function deleteDocumentAction() - { - $request = $this->getRequest(); - if (!$request->isPost()) { - return; - } - if (!$name = $this->view->name = $this->_getParam('name', false)) { - return; - } - if (!$id = $this->_getParam('id', false)) { - return; - } - $this->_doc->deleteDocument($name, $id); - return $this->_helper->redirector('show', null, null, array("collection" => $name)); - } -} diff --git a/demos/Zend/Cloud/cloudexp/application/controllers/ErrorController.php b/demos/Zend/Cloud/cloudexp/application/controllers/ErrorController.php deleted file mode 100755 index a1e7107889..0000000000 --- a/demos/Zend/Cloud/cloudexp/application/controllers/ErrorController.php +++ /dev/null @@ -1,73 +0,0 @@ -_getParam('error_handler'); - - switch ($errors->type) { - case Zend_Controller_Plugin_ErrorHandler::EXCEPTION_NO_ROUTE: - case Zend_Controller_Plugin_ErrorHandler::EXCEPTION_NO_CONTROLLER: - case Zend_Controller_Plugin_ErrorHandler::EXCEPTION_NO_ACTION: - - // 404 error -- controller or action not found - $this->getResponse()->setHttpResponseCode(404); - $this->view->message = 'Page not found'; - break; - default: - // application error - $this->getResponse()->setHttpResponseCode(500); - $this->view->message = 'Application error'; - break; - } - - // Log exception, if logger available - if ($log = $this->getLog()) { - $log->crit($this->view->message, $errors->exception); - } - - // conditionally display exceptions - if ($this->getInvokeArg('displayExceptions') == true) { - $this->view->exception = $errors->exception; - } - - $this->view->request = $errors->request; - } - - public function getLog() - { - $bootstrap = $this->getInvokeArg('bootstrap'); - if (!$bootstrap->hasPluginResource('Log')) { - return false; - } - $log = $bootstrap->getResource('Log'); - return $log; - } -} diff --git a/demos/Zend/Cloud/cloudexp/application/controllers/IndexController.php b/demos/Zend/Cloud/cloudexp/application/controllers/IndexController.php deleted file mode 100755 index 0c6d0d4c8f..0000000000 --- a/demos/Zend/Cloud/cloudexp/application/controllers/IndexController.php +++ /dev/null @@ -1,35 +0,0 @@ -_queue = Zend_Cloud_QueueService_Factory::getAdapter($this->config->queue); - } - - public function indexAction() - { - $this->view->qs = $this->_queue->listQueues(); - } - - public function createAction() - { - $request = $this->getRequest(); - if (!$request->isPost()) { - return; - } - if (!$name = $this->_getParam('name', false)) { - return; - } - $this->_queue->createQueue($name); - return $this->_helper->redirector('index'); - } - - public function sendAction() - { - $this->view->qs = $this->_queue->listQueues(); - $request = $this->getRequest(); - $name = $this->view->name = $this->_getParam('name', false); - if (!$name) { - return; - } - if (!$request->isPost()) { - return; - } - if (!$message = $this->_getParam('message', false)) { - return; - } - $ret = $this->_queue->sendMessage($name, $message); - return $this->_helper->redirector('index'); - } - - public function receiveAction() - { - $this->view->qs = $this->_queue->listQueues(); - $request = $this->getRequest(); - $name = $this->view->name = $this->_getParam('name', false); - if (!$name) { - return; - } - $messages = $this->_queue->receiveMessages($name); - foreach ($messages as $msg) { - $texts[] = $msg->getBody(); - // remove messages from the queue - $this->_queue->deleteMessage($name, $msg); - } - $this->view->messages = $texts; - } -} diff --git a/demos/Zend/Cloud/cloudexp/application/controllers/StorageController.php b/demos/Zend/Cloud/cloudexp/application/controllers/StorageController.php deleted file mode 100755 index 6d04c85e29..0000000000 --- a/demos/Zend/Cloud/cloudexp/application/controllers/StorageController.php +++ /dev/null @@ -1,117 +0,0 @@ -_storage = Zend_Cloud_StorageService_Factory::getAdapter($this->config->storage); - } - - public function indexAction() - { - $this->view->items = $this->_storage->listItems("/"); - } - - public function getAction() - { - if (!$name = $this->_getParam('item', false)) { - return $this->_helper->redirector('index'); - } - - $item = $this->_storage->fetchItem($name, array( - Zend_Cloud_StorageService_Adapter_S3::FETCH_STREAM => true, - Zend_Cloud_StorageService_Adapter_WindowsAzure::RETURN_TYPE => Zend_Cloud_StorageService_Adapter_WindowsAzure::RETURN_STREAM - )); - - if (!$item) { - $this->getResponse()->setHttpResponseCode(404); - return; - } - - $meta = $this->_storage->fetchMetadata($name); - if (isset($meta["type"])) { - $this->getResponse()->setHeader('Content-Type', $meta["type"]); - } - - // don't render the view, send the item instead - $this->_helper->viewRenderer->setNoRender(true); - if ($item instanceof Zend_Http_Response_Stream) { - fpassthru($item->getStream()); - } elseif (is_resource($item)) { - fpassthru($item); - } else { - $this->getResponse()->setBody($item); - } - } - - public function uploadAction() - { - $request = $this->getRequest(); - if (!$request->isPost()) { - return; - } - $name = $this->_getParam('name', false); - - $upload = new Zend_File_Transfer(); - $upload->addValidator('Count', false, 1); - if (!$upload->isValid()) { - return; - } - $upload->receive(); - $file = $upload->getFileName(); - $fp = fopen($file, "r"); - if (!$fp) { - return; - } - $mime = $upload->getMimeType(); - if (!$name) { - // get short name - $name = $upload->getFileName(null, false); - } - - $this->_storage->storeItem($name, $fp, array( - Zend_Cloud_StorageService_Adapter_S3::METADATA => array("type" => $mime) - )); - try { - $this->_storage->storeMetadata($name, array("type" => $mime)); - } catch(Zend_Cloud_OperationNotAvailableException $e) { - // ignore it - } - - return $this->_helper->redirector('index'); - } -} diff --git a/demos/Zend/Cloud/cloudexp/application/views/scripts/document/add-document.phtml b/demos/Zend/Cloud/cloudexp/application/views/scripts/document/add-document.phtml deleted file mode 100755 index c8014be8b8..0000000000 --- a/demos/Zend/Cloud/cloudexp/application/views/scripts/document/add-document.phtml +++ /dev/null @@ -1,22 +0,0 @@ -
-Collection name: -
-ID:
-Fields:
-fieldcount; $i++): ?> -:
- - -
diff --git a/demos/Zend/Cloud/cloudexp/application/views/scripts/document/create.phtml b/demos/Zend/Cloud/cloudexp/application/views/scripts/document/create.phtml deleted file mode 100755 index ffe39c6944..0000000000 --- a/demos/Zend/Cloud/cloudexp/application/views/scripts/document/create.phtml +++ /dev/null @@ -1,4 +0,0 @@ -
-Queue name:
- -
\ No newline at end of file diff --git a/demos/Zend/Cloud/cloudexp/application/views/scripts/document/delete-document.phtml b/demos/Zend/Cloud/cloudexp/application/views/scripts/document/delete-document.phtml deleted file mode 100755 index 38744bd265..0000000000 --- a/demos/Zend/Cloud/cloudexp/application/views/scripts/document/delete-document.phtml +++ /dev/null @@ -1 +0,0 @@ -Invalid parameters specified. \ No newline at end of file diff --git a/demos/Zend/Cloud/cloudexp/application/views/scripts/document/index.phtml b/demos/Zend/Cloud/cloudexp/application/views/scripts/document/index.phtml deleted file mode 100644 index 01bd7d453b..0000000000 --- a/demos/Zend/Cloud/cloudexp/application/views/scripts/document/index.phtml +++ /dev/null @@ -1,7 +0,0 @@ -collections) == 0) { - echo "No collections."; - return; -} -foreach($this->collections as $coll): ?> - "show", "controller" => "document", "collection" => $coll)) ?>">
- diff --git a/demos/Zend/Cloud/cloudexp/application/views/scripts/document/show.phtml b/demos/Zend/Cloud/cloudexp/application/views/scripts/document/show.phtml deleted file mode 100755 index feb94ecdbe..0000000000 --- a/demos/Zend/Cloud/cloudexp/application/views/scripts/document/show.phtml +++ /dev/null @@ -1,27 +0,0 @@ -data) == 0): - echo "Collection is empty.
"; -else: - foreach ($this->data as $document): -?> -Document ID: getID() ?>
-Document data:
-getFields() as $key => $value) { - echo "$key: $value
\n"; - } -?> -
"delete-document", "controller" => "document"), "", true) ?>" style="display: inline"> - - - -

- - -
"add-document", "controller" => "document"), "", true) ?>" style="display: inline"> - - -
diff --git a/demos/Zend/Cloud/cloudexp/application/views/scripts/error/error.phtml b/demos/Zend/Cloud/cloudexp/application/views/scripts/error/error.phtml deleted file mode 100755 index 1997506cbd..0000000000 --- a/demos/Zend/Cloud/cloudexp/application/views/scripts/error/error.phtml +++ /dev/null @@ -1,28 +0,0 @@ - - - - - Zend Framework Default Application - - -

An error occurred

-

message ?>

- - exception)): ?> - -

Exception information:

-

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

- -

Stack trace:

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

Request Parameters:

-
request->getParams(), true) ?>
-  
- - - - diff --git a/demos/Zend/Cloud/cloudexp/application/views/scripts/index/index.phtml b/demos/Zend/Cloud/cloudexp/application/views/scripts/index/index.phtml deleted file mode 100755 index 3e483f22b4..0000000000 --- a/demos/Zend/Cloud/cloudexp/application/views/scripts/index/index.phtml +++ /dev/null @@ -1,17 +0,0 @@ -

Storage API

- - "index", "controller" => "storage")) ?>">List items
- "upload", "controller" => "storage")) ?>">Upload item
- -

Queue API

- - "index", "controller" => "queue")) ?>">List queues
- "create", "controller" => "queue")) ?>">Create queue
- "send", "controller" => "queue")) ?>">Send messages
- "receive", "controller" => "queue")) ?>">Receive messages
- -

Document API

- - "index", "controller" => "document")) ?>">List collections
- "create", "controller" => "document")) ?>">Create collection
- diff --git a/demos/Zend/Cloud/cloudexp/application/views/scripts/queue/create.phtml b/demos/Zend/Cloud/cloudexp/application/views/scripts/queue/create.phtml deleted file mode 100755 index ffe39c6944..0000000000 --- a/demos/Zend/Cloud/cloudexp/application/views/scripts/queue/create.phtml +++ /dev/null @@ -1,4 +0,0 @@ -
-Queue name:
- -
\ No newline at end of file diff --git a/demos/Zend/Cloud/cloudexp/application/views/scripts/queue/index.phtml b/demos/Zend/Cloud/cloudexp/application/views/scripts/queue/index.phtml deleted file mode 100755 index 1935cbcc50..0000000000 --- a/demos/Zend/Cloud/cloudexp/application/views/scripts/queue/index.phtml +++ /dev/null @@ -1,18 +0,0 @@ -qs) == 0) { - echo "No queues."; - return; -} -?> -qs as $queue): ?> -
"send", "controller" => "queue")) ?>" style="display: inline"> -Queue : - - -
-
"receive", "controller" => "queue")) ?>" style="display: inline"> - - -
-
- diff --git a/demos/Zend/Cloud/cloudexp/application/views/scripts/queue/receive.phtml b/demos/Zend/Cloud/cloudexp/application/views/scripts/queue/receive.phtml deleted file mode 100755 index c0f4d47f90..0000000000 --- a/demos/Zend/Cloud/cloudexp/application/views/scripts/queue/receive.phtml +++ /dev/null @@ -1,8 +0,0 @@ -messages) == 0) { - echo "No messages."; - return; -} -foreach ($this->messages as $message) { - echo "Message from $this->name: ".$message; -} diff --git a/demos/Zend/Cloud/cloudexp/application/views/scripts/queue/send.phtml b/demos/Zend/Cloud/cloudexp/application/views/scripts/queue/send.phtml deleted file mode 100755 index 48b4b40331..0000000000 --- a/demos/Zend/Cloud/cloudexp/application/views/scripts/queue/send.phtml +++ /dev/null @@ -1,17 +0,0 @@ -
-Queue name: -
-Message:
- -
diff --git a/demos/Zend/Cloud/cloudexp/application/views/scripts/storage/get.phtml b/demos/Zend/Cloud/cloudexp/application/views/scripts/storage/get.phtml deleted file mode 100755 index da047cc2ce..0000000000 --- a/demos/Zend/Cloud/cloudexp/application/views/scripts/storage/get.phtml +++ /dev/null @@ -1 +0,0 @@ -The item was not found, sorry. \ No newline at end of file diff --git a/demos/Zend/Cloud/cloudexp/application/views/scripts/storage/index.phtml b/demos/Zend/Cloud/cloudexp/application/views/scripts/storage/index.phtml deleted file mode 100755 index f33e47e3a2..0000000000 --- a/demos/Zend/Cloud/cloudexp/application/views/scripts/storage/index.phtml +++ /dev/null @@ -1,3 +0,0 @@ -items as $item): ?> - "get", "controller" => "storage", "item" => $item)) ?>">
- diff --git a/demos/Zend/Cloud/cloudexp/application/views/scripts/storage/upload.phtml b/demos/Zend/Cloud/cloudexp/application/views/scripts/storage/upload.phtml deleted file mode 100755 index 44ba706719..0000000000 --- a/demos/Zend/Cloud/cloudexp/application/views/scripts/storage/upload.phtml +++ /dev/null @@ -1,6 +0,0 @@ -
- -Object name:
-Choose a file to upload:
- -
\ No newline at end of file diff --git a/demos/Zend/Cloud/cloudexp/library/CloudExplorer/ResourceInjector.php b/demos/Zend/Cloud/cloudexp/library/CloudExplorer/ResourceInjector.php deleted file mode 100755 index 4605801271..0000000000 --- a/demos/Zend/Cloud/cloudexp/library/CloudExplorer/ResourceInjector.php +++ /dev/null @@ -1,53 +0,0 @@ -getBootstrap(); - $controller = $this->getActionController(); - - if (!isset($controller->dependencies) - || !is_array($controller->dependencies) - ) { - return; - } - - foreach ($controller->dependencies as $name) { - if ($bootstrap->hasResource($name)) { - $controller->$name = $bootstrap->getResource($name); - } - } - } - - public function getBootstrap() - { - return $this->getFrontController()->getParam('bootstrap'); - } -} diff --git a/demos/Zend/Cloud/cloudexp/public/.htaccess b/demos/Zend/Cloud/cloudexp/public/.htaccess deleted file mode 100755 index 7fb009bfe6..0000000000 --- a/demos/Zend/Cloud/cloudexp/public/.htaccess +++ /dev/null @@ -1,7 +0,0 @@ - -RewriteEngine On -RewriteCond %{REQUEST_FILENAME} -s [OR] -RewriteCond %{REQUEST_FILENAME} -l [OR] -RewriteCond %{REQUEST_FILENAME} -d -RewriteRule ^.*$ - [NC,L] -RewriteRule ^.*$ index.php [NC,L] diff --git a/demos/Zend/Cloud/cloudexp/public/index.php b/demos/Zend/Cloud/cloudexp/public/index.php deleted file mode 100755 index a4b28ed9fd..0000000000 --- a/demos/Zend/Cloud/cloudexp/public/index.php +++ /dev/null @@ -1,26 +0,0 @@ -bootstrap() - ->run(); \ No newline at end of file diff --git a/demos/Zend/Feeds/consume-feed.php b/demos/Zend/Feeds/consume-feed.php deleted file mode 100644 index a86c2dcf79..0000000000 --- a/demos/Zend/Feeds/consume-feed.php +++ /dev/null @@ -1,39 +0,0 @@ -items as $item) { - - echo "

" . $item->title() . "
"; - echo $item->link() . "

"; - -} diff --git a/demos/Zend/Gdata/3LeggedOAuth/Gdata_OAuth_Helper.php b/demos/Zend/Gdata/3LeggedOAuth/Gdata_OAuth_Helper.php deleted file mode 100755 index 12f7ab9d81..0000000000 --- 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 e77c52375a..0000000000 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 39de3a1ae1..0000000000 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 839806e098..0000000000 --- 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) { -?> - - - - - - - - - - -
- -
-
-
">Logout
-
-
-

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 6ad2bbeaba..0000000000 --- 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 23d03fa4b0..0000000000 --- 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 b463068887..0000000000 --- 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 399558e884..0000000000 --- a/demos/Zend/Gdata/Calendar.php +++ /dev/null @@ -1,841 +0,0 @@ -= 5.2.11 - * - * 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->reminders = 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 0b46284f32..0000000000 --- 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-2015 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.2.11 - * - * 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 6b4c92f995..0000000000 --- a/demos/Zend/Gdata/Gapps.php +++ /dev/null @@ -1,1992 +0,0 @@ -= 5.2.11 - * - * 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 b3e21d80aa..0000000000 --- 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 ce473273ef..0000000000 --- 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 63e147d058..0000000000 --- a/demos/Zend/Gdata/Photos.php +++ /dev/null @@ -1,904 +0,0 @@ -= 5.2.11 - * - * 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 3cea242f61..0000000000 --- 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.2.11 -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 fd193a4aef..0000000000 --- a/demos/Zend/Gdata/YouTubeVideoApp/index.php +++ /dev/null @@ -1,193 +0,0 @@ -= 5.2.11 - * 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) . - '
'; - } - ?> - - - -
-
-
-
-
- - - - -
-
-
-
-
-
- - - diff --git a/demos/Zend/Gdata/YouTubeVideoApp/notfound.jpg b/demos/Zend/Gdata/YouTubeVideoApp/notfound.jpg deleted file mode 100755 index 76ec81c45f..0000000000 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 afa62b90d1..0000000000 --- a/demos/Zend/Gdata/YouTubeVideoApp/operations.php +++ /dev/null @@ -1,1097 +0,0 @@ -= 5.2.11 - * 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('https://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 = 'https://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('https://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 = 'https://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 = 'https://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 = 'https://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 0dfb393ff8..0000000000 --- a/demos/Zend/Gdata/YouTubeVideoApp/session_details.php +++ /dev/null @@ -1,66 +0,0 @@ -= 5.2.11 - * 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 -
diff --git a/demos/Zend/Gdata/YouTubeVideoApp/video_app.css b/demos/Zend/Gdata/YouTubeVideoApp/video_app.css deleted file mode 100755 index 0e4a743e05..0000000000 --- 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 6ec22308f4..0000000000 --- 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-2015 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 6b9dc38ec4..0000000000 --- a/demos/Zend/Gdata/YouTubeVideoBrowser/index.php +++ /dev/null @@ -1,278 +0,0 @@ -= 5.2.11 - * - * 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 = 'https://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 ce70aec37e..0000000000 --- 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 1984ed996b..0000000000 --- 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 16a81f8b59..0000000000 --- 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-2015 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/Mobile/Push/ApnsFeedback.php b/demos/Zend/Mobile/Push/ApnsFeedback.php deleted file mode 100644 index e2b5489eb0..0000000000 --- a/demos/Zend/Mobile/Push/ApnsFeedback.php +++ /dev/null @@ -1,21 +0,0 @@ -setCertificate('/path/to/provisioning-certificate.pem'); - -try { - $apns->connect(Zend_Mobile_Push_Apns::SERVER_FEEDBACK_SANDBOX_URI); -} catch (Zend_Mobile_Push_Exception_ServerUnavailable $e) { - // you can either attempt to reconnect here or try again later - exit(1); -} catch (Zend_Mobile_Push_Exception $e) { - echo 'APNS Connection Error:' . $e->getMessage(); - exit(1); -} - -$tokens = $apns->feedback(); -while(list($token, $time) = each($tokens)) { - echo $time . "\t" . $token . PHP_EOL; -} -$apns->close(); diff --git a/demos/Zend/Mobile/Push/ApnsServer.php b/demos/Zend/Mobile/Push/ApnsServer.php deleted file mode 100644 index 9e7477166f..0000000000 --- a/demos/Zend/Mobile/Push/ApnsServer.php +++ /dev/null @@ -1,34 +0,0 @@ -setAlert('Zend Mobile Push Example'); -$message->setBadge(1); -$message->setSound('default'); -$message->setId(time()); -$message->setToken('ABCDEF0123456789'); - -$apns = new Zend_Mobile_Push_Apns(); -$apns->setCertificate('/path/to/provisioning-certificate.pem'); - -try { - $apns->connect(Zend_Mobile_Push_Apns::SERVER_SANDBOX_URI); -} catch (Zend_Mobile_Push_Exception_ServerUnavailable $e) { - // you can either attempt to reconnect here or try again later - exit(1); -} catch (Zend_Mobile_Push_Exception $e) { - echo 'APNS Connection Error:' . $e->getMessage(); - exit(1); -} - -try { - $apns->send($message); -} catch (Zend_Mobile_Push_Exception_InvalidToken $e) { - // you would likely want to remove the token from being sent to again - echo $e->getMessage(); -} catch (Zend_Mobile_Push_Exception $e) { - // all other exceptions only require action to be sent - echo $e->getMessage(); -} -$apns->close(); diff --git a/demos/Zend/Mobile/Push/GcmServer.php b/demos/Zend/Mobile/Push/GcmServer.php deleted file mode 100644 index 22794324b7..0000000000 --- a/demos/Zend/Mobile/Push/GcmServer.php +++ /dev/null @@ -1,33 +0,0 @@ -addToken('ABCDEF0123456789'); -$message->setData(array( - 'foo' => 'bar', - 'bar' => 'foo', -)); - -$gcm = new Zend_Mobile_Push_Gcm(); -$gcm->setApiKey('YOUR_API_KEY'); - -try { - $response = $gcm->send($message); -} catch (Zend_Mobile_Push_Exception $e) { - // exceptions require action or implementation of exponential backoff. - die($e->getMessage()); -} - -// handle all errors and registration_id's -foreach ($response->getResults() as $k => $v) { - if (isset($v['registration_id'])) { - printf("%s has a new registration id of: %s\r\n", $k, $v['registration_id']); - } - if (isset($v['error'])) { - printf("%s had an error of: %s\r\n", $k, $v['error']); - } - if (isset($v['message_id'])) { - printf("%s was successfully sent the message, message id is: %s", $k, $v['message_id']); - } -} diff --git a/demos/Zend/Mobile/Push/MpnsServer.php b/demos/Zend/Mobile/Push/MpnsServer.php deleted file mode 100644 index a076068fde..0000000000 --- a/demos/Zend/Mobile/Push/MpnsServer.php +++ /dev/null @@ -1,39 +0,0 @@ -setToken('http://sn1.notify.live.net/throttledthirdparty/01.00/THETOKEN'); -$message->setMessage(''); -$messages[] = $message; - -// toast message -$message = new Zend_Mobile_Push_Message_Mpns_Toast(); -$message->setToken('http://sn1.notify.live.net/throttledthirdparty/01.00/THETOKEN'); -$message->setTitle('Foo'); -$message->setMessage('Bar'); -$messages[] = $message; - -// tile message -$message = new Zend_Mobile_Push_Mpns_Tile(); -$message->setToken('http://sn1.notify.live.net/throttledthirdparty/01.00/THETOKEN'); -$message->setBackgroundImage('foo.bar'); -$message->setCount(1); -$message->setTitle('Bar Foo'); -$messages[] = $message; - -foreach ($messages as $m) { - try { - $mpns->send($m); - } catch (Zend_Mobile_Push_Exception_InvalidToken $e) { - echo 'Remove token: ' . $m->getToken() . PHP_EOL; - } catch (Zend_Mobile_Push_Exception $e) { - echo 'Error occurred, token: ' . $m->getToken() . ' - ' . $e->getMessage() . PHP_EOL; - } -} diff --git a/demos/Zend/OpenId/login-bg.gif b/demos/Zend/OpenId/login-bg.gif deleted file mode 100644 index cde836c893..0000000000 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 13a054dc7b..0000000000 --- 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 c7bd398d1a..0000000000 --- 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 d4aa37821a..0000000000 --- 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 c7c48d1946..0000000000 --- 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 ddb5f0b9e6..0000000000 --- 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 df7f628d26..0000000000 --- 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 06cc9adafc..0000000000 --- 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 de05220d65..0000000000 --- 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 1575c85d12..0000000000 --- a/demos/Zend/OpenId/mvc_auth/html/index.php +++ /dev/null @@ -1,36 +0,0 @@ -setControllerDirectory(dirname(dirname(__FILE__)) . '/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 a1f3eea239..0000000000 --- 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 3cd7cd412a..0000000000 --- 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 28288a1da1..0000000000 --- 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 36f9d295fa..0000000000 --- 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 0b6157af5e..0000000000 --- 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 15661e1589..0000000000 --- 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 0c7a3645f2..0000000000 --- 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 4c14422072..0000000000 --- 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 96cf7a5bf0..0000000000 --- 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 d5aa16bbd0..0000000000 --- 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(dirname(__FILE__) . '/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/ProgressBar/JsPush.php b/demos/Zend/ProgressBar/JsPush.php deleted file mode 100644 index ea0b52c5ba..0000000000 --- a/demos/Zend/ProgressBar/JsPush.php +++ /dev/null @@ -1,165 +0,0 @@ - 'Zend_ProgressBar_Update', - 'finishMethodName' => 'Zend_ProgressBar_Finish')); - $progressBar = new Zend_ProgressBar($adapter, 0, 100); - - for ($i = 1; $i <= 100; $i++) { - if ($i < 20) { - $text = 'Just beginning'; - } else if ($i < 50) { - $text = 'A bit done'; - } else if ($i < 80) { - $text = 'Getting closer'; - } else { - $text = 'Nearly done'; - } - - $progressBar->update($i, $text); - usleep(100000); - } - - $progressBar->finish(); - - die; -} -?> - - - Zend_ProgressBar Javascript Push Demo and Test - - - - -
-
-
-
-
-
-
-
-
-
- - diff --git a/demos/Zend/ProgressBar/Upload.php b/demos/Zend/ProgressBar/Upload.php deleted file mode 100644 index efba065b7f..0000000000 --- a/demos/Zend/ProgressBar/Upload.php +++ /dev/null @@ -1,218 +0,0 @@ -finish(); - } else { - $progressBar->update($bytesUploaded); - } -} -?> - - - Zend_ProgressBar Upload Demo - - - - -
- - - -
- - -
-
-
-
-
-
-
-
-
-
- - diff --git a/demos/Zend/ProgressBar/ZendForm.php b/demos/Zend/ProgressBar/ZendForm.php deleted file mode 100644 index 5ea49c56fd..0000000000 --- a/demos/Zend/ProgressBar/ZendForm.php +++ /dev/null @@ -1,225 +0,0 @@ - $adapter)); - die; -} -?> - - - Zend_ProgressBar Upload Demo - - - - - 'multipart/form-data', - 'action' => 'ZendForm.php', - 'target' => 'uploadTarget', - 'onsubmit' => 'observeProgress();', - 'elements' => array( - 'file' => array('file', array('label' => 'File')), - 'submit' => array('submit', array('label' => 'Upload!')) - ) - )); - - $form->setView(new Zend_View()); - - echo $form; - ?> - - -
-
-
-
-
-
-
-
-
-
- - - diff --git a/demos/Zend/ProgressBar/animation.gif b/demos/Zend/ProgressBar/animation.gif deleted file mode 100644 index 99ec147870..0000000000 Binary files a/demos/Zend/ProgressBar/animation.gif and /dev/null differ 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 e63277e174..0000000000 --- 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 ba59f94dc0..0000000000 --- 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 c642dbca55..0000000000 --- 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 8a75445e75..0000000000 --- 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 cac8abe956..0000000000 --- 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 70035c2bb3..0000000000 --- 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 c9ba9c132e..0000000000 --- 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 e5e672a1f0..0000000000 --- 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 8ad9c4f091..0000000000 --- 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 d7d73f80f2..0000000000 --- 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 f5d13cecb5..0000000000 --- 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 d4e082bd83..0000000000 --- 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 cf811503a2..0000000000 --- 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/Service/LiveDocx/Helper.php b/demos/Zend/Service/LiveDocx/Helper.php deleted file mode 100644 index 8db4613ef9..0000000000 --- a/demos/Zend/Service/LiveDocx/Helper.php +++ /dev/null @@ -1,177 +0,0 @@ - 0) { - foreach ($result as $record) { - $date->set($record['createTime']); - $createTimeFormatted = $date->get(Zend_Date::RFC_1123); - $date->set($record['modifyTime']); - $modifyTimeFormatted = $date->get(Zend_Date::RFC_1123); - $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); - $ret .= sprintf('Last Modified Time : %d (%s)%s', $record['modifyTime'], $modifyTimeFormatted, PHP_EOL); - $ret .= PHP_EOL; - } - } - - unset($date); - - return $ret; - } - - /** - * Decorator to format array - * - * @param array $result - * @return string - */ - public static function arrayDecorator($result) - { - $ret = ''; - $count = count($result); - if ($count > 0) { - for ($i = 0; $i < $count; $i ++) { - $ret .= $result[$i]; - if ($count === ($i + 1)) { - $ret .= '.'; - } elseif ($count === ($i + 2)) { - $ret .= ' & '; - } else { - $ret .= ', '; - } - } - } else { - $ret .= 'none'; - } - return $ret; - } - - /** - * Wrap the length of long lines - * - * @param string $str - * @return string - */ - public static function wrapLine($str) - { - return wordwrap($str, self::LINE_LENGTH); - } -} diff --git a/demos/Zend/Service/LiveDocx/MailMerge/bitmaps/generate-bitmaps.php b/demos/Zend/Service/LiveDocx/MailMerge/bitmaps/generate-bitmaps.php deleted file mode 100755 index c42bf087c6..0000000000 --- a/demos/Zend/Service/LiveDocx/MailMerge/bitmaps/generate-bitmaps.php +++ /dev/null @@ -1,34 +0,0 @@ -setUsername(DEMOS_ZEND_SERVICE_LIVEDOCX_USERNAME) - ->setPassword(DEMOS_ZEND_SERVICE_LIVEDOCX_PASSWORD); - -$mailMerge->setLocalTemplate('template.docx'); - -$mailMerge->assign('software', 'Magic Graphical Compression Suite v1.9') - ->assign('licensee', 'Daï Lemaitre') - ->assign('company', 'Megasoft Co-operation') - ->assign('date', Zend_Date::now()->toString(Zend_Date::DATE_LONG)) - ->assign('time', Zend_Date::now()->toString(Zend_Date::TIME_LONG)) - ->assign('city', 'Lyon') - ->assign('country', 'France'); - -$mailMerge->createDocument(); - -// Get all bitmaps -$bitmaps = $mailMerge->getAllBitmaps(100, 'png'); // zoomFactor, format - -// Get just bitmaps in specified range -//$bitmaps = $mailMerge->getBitmaps(2, 2, 100, 'png'); // fromPage, toPage, zoomFactor, format - -foreach ($bitmaps as $pageNumber => $bitmapData) { - $filename = sprintf('document-page-%d.png', $pageNumber); - file_put_contents($filename, $bitmapData); -} - -unset($mailMerge); diff --git a/demos/Zend/Service/LiveDocx/MailMerge/bitmaps/template-screenshot.png b/demos/Zend/Service/LiveDocx/MailMerge/bitmaps/template-screenshot.png deleted file mode 100755 index a993087a7b..0000000000 Binary files a/demos/Zend/Service/LiveDocx/MailMerge/bitmaps/template-screenshot.png and /dev/null differ diff --git a/demos/Zend/Service/LiveDocx/MailMerge/bitmaps/template.docx b/demos/Zend/Service/LiveDocx/MailMerge/bitmaps/template.docx deleted file mode 100755 index 5854b708bf..0000000000 Binary files a/demos/Zend/Service/LiveDocx/MailMerge/bitmaps/template.docx and /dev/null differ diff --git a/demos/Zend/Service/LiveDocx/MailMerge/conference-pass/dailemaitre.jpg b/demos/Zend/Service/LiveDocx/MailMerge/conference-pass/dailemaitre.jpg deleted file mode 100644 index 987b79b204..0000000000 Binary files a/demos/Zend/Service/LiveDocx/MailMerge/conference-pass/dailemaitre.jpg and /dev/null differ diff --git a/demos/Zend/Service/LiveDocx/MailMerge/conference-pass/generate-document.php b/demos/Zend/Service/LiveDocx/MailMerge/conference-pass/generate-document.php deleted file mode 100755 index dd3a0e6739..0000000000 --- a/demos/Zend/Service/LiveDocx/MailMerge/conference-pass/generate-document.php +++ /dev/null @@ -1,36 +0,0 @@ -setUsername(DEMOS_ZEND_SERVICE_LIVEDOCX_USERNAME) - ->setPassword(DEMOS_ZEND_SERVICE_LIVEDOCX_PASSWORD); - -/** - * Image Source: - * iStock_000003413016Medium_business-man-with-hands-up.jpg - */ -$photoFilename = 'dailemaitre.jpg'; - -if (!$mailMerge->imageExists($photoFilename)) { - $mailMerge->uploadImage($photoFilename); -} - -$mailMerge->setLocalTemplate('template.docx'); - -$mailMerge->assign('name', 'Daï Lemaitre') - ->assign('company', 'Megasoft Co-operation') - ->assign('date', Zend_Date::now()->toString(Zend_Date::DATE_LONG)) - ->assign('image:photo', $photoFilename); - -$mailMerge->createDocument(); - -$document = $mailMerge->retrieveDocument('pdf'); - -file_put_contents('document.pdf', $document); - -$mailMerge->deleteImage($photoFilename); - -unset($mailMerge); \ No newline at end of file diff --git a/demos/Zend/Service/LiveDocx/MailMerge/conference-pass/template.docx b/demos/Zend/Service/LiveDocx/MailMerge/conference-pass/template.docx deleted file mode 100755 index 4c2bc00cb1..0000000000 Binary files a/demos/Zend/Service/LiveDocx/MailMerge/conference-pass/template.docx and /dev/null differ diff --git a/demos/Zend/Service/LiveDocx/MailMerge/constructors/credentials.ini b/demos/Zend/Service/LiveDocx/MailMerge/constructors/credentials.ini deleted file mode 100755 index 584b119aac..0000000000 --- a/demos/Zend/Service/LiveDocx/MailMerge/constructors/credentials.ini +++ /dev/null @@ -1,2 +0,0 @@ -username = myUsername -password = myPassword \ No newline at end of file diff --git a/demos/Zend/Service/LiveDocx/MailMerge/constructors/hosted-licensed.php b/demos/Zend/Service/LiveDocx/MailMerge/constructors/hosted-licensed.php deleted file mode 100755 index 0190c8ed0b..0000000000 --- a/demos/Zend/Service/LiveDocx/MailMerge/constructors/hosted-licensed.php +++ /dev/null @@ -1,34 +0,0 @@ -setWsdl('https://api.example.com/1.2/mailmerge.asmx?WSDL') - ->setUsername(DEMOS_ZEND_SERVICE_LIVEDOCX_USERNAME) - ->setPassword(DEMOS_ZEND_SERVICE_LIVEDOCX_PASSWORD); - -$mailMerge->getTemplateFormats(); // then call methods as usual - -printf('Username : %s%sPassword : %s%s WSDL : %s%s%s', - $mailMerge->getUsername(), - PHP_EOL, - $mailMerge->getPassword(), - PHP_EOL, - $mailMerge->getWsdl(), - PHP_EOL, - PHP_EOL -); - -unset($mailMerge, $mySoapClient); \ No newline at end of file diff --git a/demos/Zend/Service/LiveDocx/MailMerge/constructors/public-zend_config.php b/demos/Zend/Service/LiveDocx/MailMerge/constructors/public-zend_config.php deleted file mode 100755 index 8c64e60113..0000000000 --- a/demos/Zend/Service/LiveDocx/MailMerge/constructors/public-zend_config.php +++ /dev/null @@ -1,32 +0,0 @@ -getTemplateFormats(); // then call methods as usual - -printf('Username : %s%sPassword : %s%s WSDL : %s%s%s', - $mailMerge->getUsername(), - PHP_EOL, - $mailMerge->getPassword(), - PHP_EOL, - $mailMerge->getWsdl(), - PHP_EOL, - PHP_EOL -); - -unset($mailMerge, $options); \ No newline at end of file diff --git a/demos/Zend/Service/LiveDocx/MailMerge/constructors/public.php b/demos/Zend/Service/LiveDocx/MailMerge/constructors/public.php deleted file mode 100755 index a5973cad84..0000000000 --- a/demos/Zend/Service/LiveDocx/MailMerge/constructors/public.php +++ /dev/null @@ -1,58 +0,0 @@ -setUsername(DEMOS_ZEND_SERVICE_LIVEDOCX_USERNAME) - ->setPassword(DEMOS_ZEND_SERVICE_LIVEDOCX_PASSWORD); - -$mailMerge->getTemplateFormats(); // then call methods as usual - -printf('Username : %s%sPassword : %s%s WSDL : %s%s%s', - $mailMerge->getUsername(), - PHP_EOL, - $mailMerge->getPassword(), - PHP_EOL, - $mailMerge->getWsdl(), - PHP_EOL, - PHP_EOL -); - -unset($mailMerge); - -// ----------------------------------------------------------------------------- - -// Alternatively, you can pass username and password in the constructor. - -$mailMerge = new Zend_Service_LiveDocx_MailMerge( - array ( - 'username' => DEMOS_ZEND_SERVICE_LIVEDOCX_USERNAME, - 'password' => DEMOS_ZEND_SERVICE_LIVEDOCX_PASSWORD, - ) -); - -$mailMerge->getTemplateFormats(); // then call methods as usual - -printf('Username : %s%sPassword : %s%s WSDL : %s%s%s', - $mailMerge->getUsername(), - PHP_EOL, - $mailMerge->getPassword(), - PHP_EOL, - $mailMerge->getWsdl(), - PHP_EOL, - PHP_EOL -); - -unset($mailMerge); \ No newline at end of file diff --git a/demos/Zend/Service/LiveDocx/MailMerge/convert/convert-document.php b/demos/Zend/Service/LiveDocx/MailMerge/convert/convert-document.php deleted file mode 100755 index 28d97bcb55..0000000000 --- a/demos/Zend/Service/LiveDocx/MailMerge/convert/convert-document.php +++ /dev/null @@ -1,36 +0,0 @@ -setUsername(DEMOS_ZEND_SERVICE_LIVEDOCX_USERNAME) - ->setPassword(DEMOS_ZEND_SERVICE_LIVEDOCX_PASSWORD); - -$mailMerge->setLocalTemplate('document.doc'); - -$mailMerge->assign('dummyFieldName', 'dummyFieldValue'); // necessary as of LiveDocx 1.2 - -$mailMerge->createDocument(); - -$document = $mailMerge->retrieveDocument('pdf'); - -file_put_contents('document.pdf', $document); - -unset($mailMerge); \ No newline at end of file diff --git a/demos/Zend/Service/LiveDocx/MailMerge/convert/document.doc b/demos/Zend/Service/LiveDocx/MailMerge/convert/document.doc deleted file mode 100755 index c8441c5c3f..0000000000 Binary files a/demos/Zend/Service/LiveDocx/MailMerge/convert/document.doc and /dev/null differ diff --git a/demos/Zend/Service/LiveDocx/MailMerge/images/delete-all.php b/demos/Zend/Service/LiveDocx/MailMerge/images/delete-all.php deleted file mode 100755 index efcf229342..0000000000 --- a/demos/Zend/Service/LiveDocx/MailMerge/images/delete-all.php +++ /dev/null @@ -1,29 +0,0 @@ -setUsername(DEMOS_ZEND_SERVICE_LIVEDOCX_USERNAME) - ->setPassword(DEMOS_ZEND_SERVICE_LIVEDOCX_PASSWORD); - -$counter = 1; -foreach ($mailMerge->listImages() as $result) { - printf('%d) %s', $counter, $result['filename']); - $mailMerge->deleteImage($result['filename']); - print(' - DELETED.' . PHP_EOL); - $counter++; -} - -print(PHP_EOL); - -unset($mailMerge); \ No newline at end of file diff --git a/demos/Zend/Service/LiveDocx/MailMerge/images/download.php b/demos/Zend/Service/LiveDocx/MailMerge/images/download.php deleted file mode 100755 index ba6e48e8cd..0000000000 --- a/demos/Zend/Service/LiveDocx/MailMerge/images/download.php +++ /dev/null @@ -1,30 +0,0 @@ -setUsername(DEMOS_ZEND_SERVICE_LIVEDOCX_USERNAME) - ->setPassword(DEMOS_ZEND_SERVICE_LIVEDOCX_PASSWORD); - -$counter = 1; -foreach ($mailMerge->listImages() as $result) { - printf('%d) %s', $counter, $result['filename']); - $image = $mailMerge->downloadImage($result['filename']); - file_put_contents('downloaded-' . $result['filename'], $image); - print(" - DOWNLOADED.\n"); - $counter++; -} - -print(PHP_EOL); - -unset($mailMerge); \ No newline at end of file diff --git a/demos/Zend/Service/LiveDocx/MailMerge/images/image-1.png b/demos/Zend/Service/LiveDocx/MailMerge/images/image-1.png deleted file mode 100755 index 50f44d2dbd..0000000000 Binary files a/demos/Zend/Service/LiveDocx/MailMerge/images/image-1.png and /dev/null differ diff --git a/demos/Zend/Service/LiveDocx/MailMerge/images/image-2.png b/demos/Zend/Service/LiveDocx/MailMerge/images/image-2.png deleted file mode 100755 index 51df1173d8..0000000000 Binary files a/demos/Zend/Service/LiveDocx/MailMerge/images/image-2.png and /dev/null differ diff --git a/demos/Zend/Service/LiveDocx/MailMerge/images/image-exists.php b/demos/Zend/Service/LiveDocx/MailMerge/images/image-exists.php deleted file mode 100755 index 93411e843a..0000000000 --- a/demos/Zend/Service/LiveDocx/MailMerge/images/image-exists.php +++ /dev/null @@ -1,29 +0,0 @@ -setUsername(DEMOS_ZEND_SERVICE_LIVEDOCX_USERNAME) - ->setPassword(DEMOS_ZEND_SERVICE_LIVEDOCX_PASSWORD); - -print('Checking whether an image is available... '); -if (true === $mailMerge->imageExists('image-1.png')) { - print('EXISTS. '); -} else { - print('DOES NOT EXIST. '); -} -print('DONE' . PHP_EOL); - -print(PHP_EOL); - -unset($mailMerge); \ No newline at end of file diff --git a/demos/Zend/Service/LiveDocx/MailMerge/images/list.php b/demos/Zend/Service/LiveDocx/MailMerge/images/list.php deleted file mode 100755 index 4f35b28e0c..0000000000 --- a/demos/Zend/Service/LiveDocx/MailMerge/images/list.php +++ /dev/null @@ -1,23 +0,0 @@ -setUsername(DEMOS_ZEND_SERVICE_LIVEDOCX_USERNAME) - ->setPassword(DEMOS_ZEND_SERVICE_LIVEDOCX_PASSWORD); - -print(Demos_Zend_Service_LiveDocx_Helper::listDecorator($mailMerge->listImages())); - -unset($mailMerge); \ No newline at end of file diff --git a/demos/Zend/Service/LiveDocx/MailMerge/images/upload.php b/demos/Zend/Service/LiveDocx/MailMerge/images/upload.php deleted file mode 100755 index 4908f76217..0000000000 --- a/demos/Zend/Service/LiveDocx/MailMerge/images/upload.php +++ /dev/null @@ -1,29 +0,0 @@ -setUsername(DEMOS_ZEND_SERVICE_LIVEDOCX_USERNAME) - ->setPassword(DEMOS_ZEND_SERVICE_LIVEDOCX_PASSWORD); - -print('Uploading image... '); -$mailMerge->uploadImage('image-1.png'); -print('DONE.' . PHP_EOL); - -print('Uploading image... '); -$mailMerge->uploadImage('image-2.png'); -print('DONE.' . PHP_EOL); - -print(PHP_EOL); - -unset($mailMerge); \ No newline at end of file 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 deleted file mode 100755 index 5f33ba2152..0000000000 --- a/demos/Zend/Service/LiveDocx/MailMerge/license-agreement/generate-document-concat.php +++ /dev/null @@ -1,250 +0,0 @@ -log(sprintf('Making temporary directory %s.', $tempDirectory), Zend_Log::INFO); - -mkdir($tempDirectory); - -// ----------------------------------------------------------------------------- - -// Generate temporary documents - -$tempFilenames = array(); - -$mailMerge = new Zend_Service_LiveDocx_MailMerge(); - -$mailMerge->setUsername(DEMOS_ZEND_SERVICE_LIVEDOCX_USERNAME) - ->setPassword(DEMOS_ZEND_SERVICE_LIVEDOCX_PASSWORD); - -$mailMerge->setLocalTemplate('template.docx'); - -for ($iteration = 1; $iteration <= $iterations; $iteration ++) { - - $tempFilename = sprintf('%s/%010s.pdf', $tempDirectory, $iteration); - $tempFilenames[] = $tempFilename; - - $mailMerge->assign('software', randomString()) - ->assign('licensee', randomString()) - ->assign('company', randomString()) - ->assign('date', Zend_Date::now()->toString(Zend_Date::DATE_LONG)) - ->assign('time', Zend_Date::now()->toString(Zend_Date::TIME_LONG)) - ->assign('city', randomString()) - ->assign('country', randomString()); - - $mailMerge->createDocument(); - - file_put_contents($tempFilename, $mailMerge->retrieveDocument('pdf')); - - $logger->log(sprintf('Generating temporary document %s.', $tempFilename), Zend_Log::INFO); -} - -unset($mailMerge); - -// ----------------------------------------------------------------------------- - -// Concatenate temporary documents and write output document - -$outputFilename = './document-concat.pdf'; - -$logger->log('Concatenating temporary documents...', Zend_Log::INFO); - -if (true === concatenatePdfFilenames($tempFilenames, $outputFilename, $processor)) { - $logger->log(sprintf('...DONE. Saved output document as %s.', $outputFilename), Zend_Log::INFO); -} else { - $logger->log(sprintf('...ERROR.'), Zend_Log::ERR); -} - -// ----------------------------------------------------------------------------- - -// Delete temporary directory - -$logger->log(sprintf('Deleting temporary directory %s.', $tempDirectory), Zend_Log::INFO); - -if (is_dir($tempDirectory)) { - recursiveRemoveDirectory($tempDirectory); -} - -// ============================================================================= - -// Helper functions - -/** - * Create a random string - * - * @return string - */ -function randomString() -{ - $ret = ''; - - $pool = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'; - - $poolLen = strlen($pool); - $stringLen = rand(5, 25); - - for ($i = 0; $i < $stringLen; $i ++) { - $pos = (rand() % $poolLen); - $ret .= $pool{$pos}; - } - - return $ret; -} - -/** - * Recursively remove directory - * - * @param string $dir - * @return void - */ -function recursiveRemoveDirectory($dir) -{ - $files = glob($dir . '*', GLOB_MARK); - - foreach ($files as $file) { - if ('/' === substr($file, - 1)) { - recursiveRemoveDirectory($file); - } else { - unlink($file); - } - } - - if (is_dir($dir)) { - rmdir($dir); - } -} - -/** - * Concatenate the files in passed array $inputFilenames into one file - * $outputFilename, using concatenation processor (external 3rd party command - * line tool) specified in $processor - * - * @param array $inputFilenames - * @param array $outputFilename - * @param string $processor - * @return boolean - */ -function concatenatePdfFilenames($inputFilenames, $outputFilename, $processor = EXEC_PDFTK) -{ - $ret = false; - - $logger = Zend_Registry::get('logger'); - - if (! (is_file(EXEC_PDFTK) || is_file(EXEC_GHOSTSCRIPT))) { - $logger->log('Either pdftk or ghostscript are required for this sample application.', Zend_Log::CRIT); - exit(); - } - - if (is_file($outputFilename)) { - unlink($outputFilename); - } - - switch ($processor) { - - case PROCESSOR_PDFTK : - $format = '%s %s cat output %s'; - $command = sprintf($format, EXEC_PDFTK, implode($inputFilenames, ' '), $outputFilename); - break; - - case PROCESSOR_GHOSTSCRIPT : - $format = '%s -q -dNOPAUSE -dBATCH -sDEVICE=pdfwrite -dAutoFilterColorImages=false '; - $format .= '-dAutoFilterGrayImages=false -dAutoFilterMonoImages=false '; - $format .= '-dColorImageFilter=/FlateEncode -dCompatibilityLevel=1.3 -dEmbedAllFonts=true '; - $format .= '-dGrayImageFilter=/FlateEncode -dMaxSubsetPct=100 -dMonoImageFilter=/CCITTFaxEncode '; - $format .= '-dSubsetFonts=true -sOUTPUTFILE=%s %s'; - $command = sprintf($format, EXEC_GHOSTSCRIPT, $outputFilename, implode($inputFilenames, ' ')); - break; - - default: - $logger->log('Invalid concatenation processor - use PROCESSOR_PDFTK or PROCESSOR_GHOSTSCRIPT only.', Zend_Log::CRIT); - exit(); - break; - } - - $command = escapeshellcmd($command); - - exec($command); - - if (is_file($outputFilename) && filesize($outputFilename) > 0) { - $ret = true; - } - - return $ret; -} diff --git a/demos/Zend/Service/LiveDocx/MailMerge/license-agreement/generate-document.php b/demos/Zend/Service/LiveDocx/MailMerge/license-agreement/generate-document.php deleted file mode 100755 index 4895379769..0000000000 --- a/demos/Zend/Service/LiveDocx/MailMerge/license-agreement/generate-document.php +++ /dev/null @@ -1,82 +0,0 @@ -setUsername(DEMOS_ZEND_SERVICE_LIVEDOCX_USERNAME) - ->setPassword(DEMOS_ZEND_SERVICE_LIVEDOCX_PASSWORD); - -$mailMerge->setLocalTemplate('template.docx'); - -$mailMerge->assign('software', 'Magic Graphical Compression Suite v1.9') - ->assign('licensee', 'Henry Döner-Meyer') - ->assign('company', 'Co-Operation') - ->assign('date', Zend_Date::now()->toString(Zend_Date::DATE_LONG)) - ->assign('time', Zend_Date::now()->toString(Zend_Date::TIME_LONG)) - ->assign('city', 'Berlin') - ->assign('country', 'Germany'); - -/** - * ALTERNATIVE: Concatenating PDF files locally - basic - * - * You can also assign multiple sets of data. In this case, each set of data - * will populate the template and the resulting document (one per set of data) - * will be appended to the previous document. Thus, in this example, we create - * two documents that are concatenated into one PDF file. - * - * NOTE: In the case that you wish to generate several thousand documents that - * are concatenated into one PDF, please take a look at the sample - * application 'generate-document-pdftk.php' in this directory. - */ -/* -$fieldValues = array ( - // set 1 - array ( - 'software' => 'Magic Graphical Compression Suite v2.5', - 'licensee' => 'Henry Döner-Meyer', - 'company' => 'Megasoft Co-Operation', - 'date' => Zend_Date::now()->toString(Zend_Date::DATE_LONG), - 'time' => Zend_Date::now()->toString(Zend_Date::TIME_LONG), - 'city' => 'Berlin', - 'country' => 'Germany' - ), - // set 2 - array ( - 'software' => 'Magic CAD Suite v1.9', - 'licensee' => 'Brüno Döner-Meyer', - 'company' => 'Future Co-Operation', - 'date' => Zend_Date::now()->toString(Zend_Date::DATE_LONG), - 'time' => Zend_Date::now()->toString(Zend_Date::TIME_LONG), - 'city' => 'Berlin', - 'country' => 'Germany' - ) -); - -$mailMerge->assign($fieldValues); -*/ - -$mailMerge->createDocument(); - -$document = $mailMerge->retrieveDocument('pdf'); - -file_put_contents('document.pdf', $document); - -/* - * ALTERNATIVE: Retrieve document in all supported formats - * - * You can also retrieve the document in all supported formats. In this case, - * the generated document is written to the file system multiple times (one file - * per format). This is only for exemplary purposes. In a real-world - * application, you would probably decide on one or the other format. - */ -/* -foreach ($mailMerge->getDocumentFormats() as $format) { - $document = $mailMerge->retrieveDocument($format); - file_put_contents('document.' . $format, $document); -} - -*/ - -unset($mailMerge); diff --git a/demos/Zend/Service/LiveDocx/MailMerge/license-agreement/template-screenshot.png b/demos/Zend/Service/LiveDocx/MailMerge/license-agreement/template-screenshot.png deleted file mode 100755 index a993087a7b..0000000000 Binary files a/demos/Zend/Service/LiveDocx/MailMerge/license-agreement/template-screenshot.png and /dev/null differ diff --git a/demos/Zend/Service/LiveDocx/MailMerge/license-agreement/template.docx b/demos/Zend/Service/LiveDocx/MailMerge/license-agreement/template.docx deleted file mode 100755 index 5854b708bf..0000000000 Binary files a/demos/Zend/Service/LiveDocx/MailMerge/license-agreement/template.docx and /dev/null differ diff --git a/demos/Zend/Service/LiveDocx/MailMerge/metafiles/generate-metafiles.php b/demos/Zend/Service/LiveDocx/MailMerge/metafiles/generate-metafiles.php deleted file mode 100755 index c04f51cbcd..0000000000 --- a/demos/Zend/Service/LiveDocx/MailMerge/metafiles/generate-metafiles.php +++ /dev/null @@ -1,34 +0,0 @@ -setUsername(DEMOS_ZEND_SERVICE_LIVEDOCX_USERNAME) - ->setPassword(DEMOS_ZEND_SERVICE_LIVEDOCX_PASSWORD); - -$mailMerge->setLocalTemplate('template.docx'); - -$mailMerge->setFieldValue('software', 'Magic Graphical Compression Suite v1.9') - ->setFieldValue('licensee', 'Henry Döner-Meyer') - ->setFieldValue('company', 'Megasoft Co-operation') - ->setFieldValue('date', Zend_Date::now()->toString(Zend_Date::DATE_LONG)) - ->setFieldValue('time', Zend_Date::now()->toString(Zend_Date::TIME_LONG)) - ->setFieldValue('city', 'Bremen') - ->setFieldValue('country', 'Germany'); - -$mailMerge->createDocument(); - -// Get all metafiles -$metaFiles = $mailMerge->getAllMetafiles(); - -// Get just metafiles in specified range -//$metaFiles = $mailMerge->getMetafiles(1, 2); // fromPage, toPage - -foreach ($metaFiles as $pageNumber => $metaFileData) { - $filename = sprintf('document-page-%d.wmf', $pageNumber); - file_put_contents($filename, $metaFileData); -} - -unset($mailMerge); \ No newline at end of file diff --git a/demos/Zend/Service/LiveDocx/MailMerge/metafiles/template-screenshot.png b/demos/Zend/Service/LiveDocx/MailMerge/metafiles/template-screenshot.png deleted file mode 100755 index a993087a7b..0000000000 Binary files a/demos/Zend/Service/LiveDocx/MailMerge/metafiles/template-screenshot.png and /dev/null differ diff --git a/demos/Zend/Service/LiveDocx/MailMerge/metafiles/template.docx b/demos/Zend/Service/LiveDocx/MailMerge/metafiles/template.docx deleted file mode 100755 index 5854b708bf..0000000000 Binary files a/demos/Zend/Service/LiveDocx/MailMerge/metafiles/template.docx and /dev/null differ diff --git a/demos/Zend/Service/LiveDocx/MailMerge/pdf-security/generate-document.php b/demos/Zend/Service/LiveDocx/MailMerge/pdf-security/generate-document.php deleted file mode 100755 index 8855e95566..0000000000 --- a/demos/Zend/Service/LiveDocx/MailMerge/pdf-security/generate-document.php +++ /dev/null @@ -1,42 +0,0 @@ -setWsdl('https://api.example.com/1.2/mailmerge.asmx?WSDL'); - -$mailMerge->setUsername(DEMOS_ZEND_SERVICE_LIVEDOCX_USERNAME) - ->setPassword(DEMOS_ZEND_SERVICE_LIVEDOCX_PASSWORD); - -$mailMerge->setLocalTemplate('template.docx'); - -$mailMerge->assign('software', 'Magic Graphical Compression Suite v1.9') - ->assign('licensee', 'Henry Döner-Meyer') - ->assign('company', 'Co-Operation') - ->assign('date', Zend_Date::now()->toString(Zend_Date::DATE_LONG)) - ->assign('time', Zend_Date::now()->toString(Zend_Date::TIME_LONG)) - ->assign('city', 'Berlin') - ->assign('country', 'Germany'); - -// Available on premium service only -$mailMerge->setDocumentPassword('aaaaaaaaaa'); - -// Available on premium service only -$mailMerge->setDocumentAccessPermissions( - array( - 'AllowHighLevelPrinting' , // getDocumentAccessOptions() returns - 'AllowExtractContents' // array of permitted values - ), - 'myDocumentAccessPassword' -); - -$mailMerge->createDocument(); - -$document = $mailMerge->retrieveDocument('pdf'); - -file_put_contents('document.pdf', $document); - -unset($mailMerge); diff --git a/demos/Zend/Service/LiveDocx/MailMerge/pdf-security/template.docx b/demos/Zend/Service/LiveDocx/MailMerge/pdf-security/template.docx deleted file mode 100755 index 5854b708bf..0000000000 Binary files a/demos/Zend/Service/LiveDocx/MailMerge/pdf-security/template.docx and /dev/null differ 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 deleted file mode 100755 index f197a28429..0000000000 --- a/demos/Zend/Service/LiveDocx/MailMerge/supported-fonts/show-supported-fonts-cached.php +++ /dev/null @@ -1,58 +0,0 @@ - 2592000, // 30 days - 'automatic_serialization' => true -); - -$cacheBackendOptions = array( - 'cache_dir' => dirname(__FILE__) . '/cache' -); - -$cache = Zend_Cache::factory('Core', 'File', $cacheFrontendOptions, $cacheBackendOptions); - -if (! $fonts = $cache->load($cacheId)) { - - // Cache miss. Connect to backend service (expensive). - - $mailMerge = new Zend_Service_LiveDocx_MailMerge(); - - $mailMerge->setUsername(DEMOS_ZEND_SERVICE_LIVEDOCX_USERNAME) - ->setPassword(DEMOS_ZEND_SERVICE_LIVEDOCX_PASSWORD); - - $fonts = $mailMerge->getFontNames(); - - $cache->save($fonts, $cacheId); - - unset($mailMerge); - -} else { - - // Cache hit. Continue. - -} - -unset($cache); - -print(Demos_Zend_Service_LiveDocx_Helper::wrapLine( - PHP_EOL . 'Supported Fonts' . - PHP_EOL . - PHP_EOL . 'The following fonts are installed on the backend server and may be used in templates. Fonts used in templates, which are NOT listed below, will be substituted. If you would like to use a font, which is not installed on the backend server, please contact your LiveDocx provider.' . - PHP_EOL . - PHP_EOL . '(Note this method call is cached for maximum performance. The supported formats change very infrequently, hence, they are good candidates to be cached.)' . - PHP_EOL . - PHP_EOL . Demos_Zend_Service_LiveDocx_Helper::arrayDecorator($fonts) . - PHP_EOL . - PHP_EOL) -); - -print(PHP_EOL); - -unset($mailMerge); diff --git a/demos/Zend/Service/LiveDocx/MailMerge/supported-fonts/show-supported-fonts.php b/demos/Zend/Service/LiveDocx/MailMerge/supported-fonts/show-supported-fonts.php deleted file mode 100755 index 10f59c239b..0000000000 --- a/demos/Zend/Service/LiveDocx/MailMerge/supported-fonts/show-supported-fonts.php +++ /dev/null @@ -1,23 +0,0 @@ -setUsername(DEMOS_ZEND_SERVICE_LIVEDOCX_USERNAME) - ->setPassword(DEMOS_ZEND_SERVICE_LIVEDOCX_PASSWORD); - -system('clear'); - -print(Demos_Zend_Service_LiveDocx_Helper::wrapLine( - PHP_EOL . 'Supported Fonts' . - PHP_EOL . - PHP_EOL . 'The following fonts are installed on the backend server and may be used in templates. Fonts used in templates, which are NOT listed below, will be substituted. If you would like to use a font, which is not installed on the backend server, please contact your LiveDocx provider.' . - PHP_EOL . - PHP_EOL . Demos_Zend_Service_LiveDocx_Helper::arrayDecorator($mailMerge->getFontNames()) . - PHP_EOL . - PHP_EOL) -); - -unset($mailMerge); \ No newline at end of file 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 deleted file mode 100755 index 5780c2af38..0000000000 --- a/demos/Zend/Service/LiveDocx/MailMerge/supported-formats/show-supported-formats-cached.php +++ /dev/null @@ -1,71 +0,0 @@ - 2592000, // 30 days - 'automatic_serialization' => true -); - -$cacheBackendOptions = array( - 'cache_dir' => dirname(__FILE__) . '/cache' -); - -$cache = Zend_Cache::factory('Core', 'File', $cacheFrontendOptions, $cacheBackendOptions); - -if (! $formats = $cache->load($cacheId)) { - - // Cache miss. Connect to backend service (expensive). - - $mailMerge = new Zend_Service_LiveDocx_MailMerge(); - - $mailMerge->setUsername(DEMOS_ZEND_SERVICE_LIVEDOCX_USERNAME) - ->setPassword(DEMOS_ZEND_SERVICE_LIVEDOCX_PASSWORD); - - $formats = new StdClass(); - - $formats->template = $mailMerge->getTemplateFormats(); - $formats->document = $mailMerge->getDocumentFormats(); - $formats->imageImport = $mailMerge->getImageImportFormats(); - $formats->imageExport = $mailMerge->getImageExportFormats(); - - $cache->save($formats, $cacheId); - - unset($mailMerge); - -} else { - - // Cache hit. Continue. - -} - -unset($cache); - -printf("Supported TEMPLATE file formats (input) : %s%s", - Demos_Zend_Service_LiveDocx_Helper::arrayDecorator($formats->template), PHP_EOL); - -printf("Supported DOCUMENT file formats (output) : %s%s", - Demos_Zend_Service_LiveDocx_Helper::arrayDecorator($formats->document), PHP_EOL . PHP_EOL); - -printf("Supported IMAGE file formats (import) : %s%s", - Demos_Zend_Service_LiveDocx_Helper::arrayDecorator($formats->imageImport), PHP_EOL); - -printf("Supported IMAGE file formats (export) : %s%s", - Demos_Zend_Service_LiveDocx_Helper::arrayDecorator($formats->imageExport), PHP_EOL); - -print(PHP_EOL); \ No newline at end of file diff --git a/demos/Zend/Service/LiveDocx/MailMerge/supported-formats/show-supported-formats.php b/demos/Zend/Service/LiveDocx/MailMerge/supported-formats/show-supported-formats.php deleted file mode 100755 index 69db419f65..0000000000 --- a/demos/Zend/Service/LiveDocx/MailMerge/supported-formats/show-supported-formats.php +++ /dev/null @@ -1,35 +0,0 @@ -setUsername(DEMOS_ZEND_SERVICE_LIVEDOCX_USERNAME) - ->setPassword(DEMOS_ZEND_SERVICE_LIVEDOCX_PASSWORD); - -printf("Supported TEMPLATE file formats (input) : %s%s", - Demos_Zend_Service_LiveDocx_Helper::arrayDecorator($mailMerge->getTemplateFormats()), PHP_EOL); - -printf("Supported DOCUMENT file formats (output) : %s%s", - Demos_Zend_Service_LiveDocx_Helper::arrayDecorator($mailMerge->getDocumentFormats()), PHP_EOL . PHP_EOL); - -printf("Supported IMAGE file formats (import) : %s%s", - Demos_Zend_Service_LiveDocx_Helper::arrayDecorator($mailMerge->getImageImportFormats()), PHP_EOL); - -printf("Supported IMAGE file formats (export) : %s%s", - Demos_Zend_Service_LiveDocx_Helper::arrayDecorator($mailMerge->getImageExportFormats()), PHP_EOL); - -print PHP_EOL; - -unset($mailMerge); \ No newline at end of file diff --git a/demos/Zend/Service/LiveDocx/MailMerge/telephone-bill/generate-document.php b/demos/Zend/Service/LiveDocx/MailMerge/telephone-bill/generate-document.php deleted file mode 100755 index 29fe389441..0000000000 --- a/demos/Zend/Service/LiveDocx/MailMerge/telephone-bill/generate-document.php +++ /dev/null @@ -1,82 +0,0 @@ -setUsername(DEMOS_ZEND_SERVICE_LIVEDOCX_USERNAME) - ->setPassword(DEMOS_ZEND_SERVICE_LIVEDOCX_PASSWORD); - -/* - * ALTERNATIVE: Specify username and password in constructor - */ - -/* -$mailMerge = new Zend_Service_LiveDocx_MailMerge( - array ( - 'username' => DEMOS_ZEND_SERVICE_LIVEDOCX_USERNAME, - 'password' => DEMOS_ZEND_SERVICE_LIVEDOCX_PASSWORD - ) -); -*/ - -$mailMerge->setLocalTemplate('template.doc'); - - -$mailMerge->assign('customer_number', sprintf("#%'10s", rand(0,1000000000))) - ->assign('invoice_number', sprintf("#%'10s", rand(0,1000000000))) - ->assign('account_number', sprintf("#%'10s", rand(0,1000000000))); - - -$billData = array ( - 'phone' => '+22 (0)333 444 555', - 'date' => Zend_Date::now()->toString(Zend_Date::DATE_LONG), - 'name' => 'James Henry Brown', - 'service_phone' => '+22 (0)333 444 559', - 'service_fax' => '+22 (0)333 444 558', - 'month' => sprintf('%s %s', Zend_Date::now()->toString(Zend_Date::MONTH_NAME), - Zend_Date::now()->toString(Zend_Date::YEAR)), - 'monthly_fee' => '15.00', - 'total_net' => '19.60', - 'tax' => '19.00', - 'tax_value' => '3.72', - 'total' => '23.32' -); - -$mailMerge->assign($billData); - - -$billConnections = array( - array( - 'connection_number' => '+11 (0)222 333 441', - 'connection_duration' => '00:01:01', - 'fee' => '1.15' - ), - array( - 'connection_number' => '+11 (0)222 333 442', - 'connection_duration' => '00:01:02', - 'fee' => '1.15' - ), - array( - 'connection_number' => '+11 (0)222 333 443', - 'connection_duration' => '00:01:03', - 'fee' => '1.15' - ), - array( - 'connection_number' => '+11 (0)222 333 444', - 'connection_duration' => '00:01:04', - 'fee' => '1.15' - ) -); - -$mailMerge->assign('connection', $billConnections); - - -$mailMerge->createDocument(); - -$document = $mailMerge->retrieveDocument('pdf'); - -unset($mailMerge); - -file_put_contents('document.pdf', $document); diff --git a/demos/Zend/Service/LiveDocx/MailMerge/telephone-bill/template-screenshot.png b/demos/Zend/Service/LiveDocx/MailMerge/telephone-bill/template-screenshot.png deleted file mode 100755 index b90d27b669..0000000000 Binary files a/demos/Zend/Service/LiveDocx/MailMerge/telephone-bill/template-screenshot.png and /dev/null differ diff --git a/demos/Zend/Service/LiveDocx/MailMerge/telephone-bill/template.doc b/demos/Zend/Service/LiveDocx/MailMerge/telephone-bill/template.doc deleted file mode 100755 index 1da17f99cc..0000000000 Binary files a/demos/Zend/Service/LiveDocx/MailMerge/telephone-bill/template.doc and /dev/null differ diff --git a/demos/Zend/Service/LiveDocx/MailMerge/template-info/list-template-info.php b/demos/Zend/Service/LiveDocx/MailMerge/template-info/list-template-info.php deleted file mode 100755 index 9d1b737158..0000000000 --- a/demos/Zend/Service/LiveDocx/MailMerge/template-info/list-template-info.php +++ /dev/null @@ -1,80 +0,0 @@ -setUsername(DEMOS_ZEND_SERVICE_LIVEDOCX_USERNAME) - ->setPassword(DEMOS_ZEND_SERVICE_LIVEDOCX_PASSWORD); - -// ----------------------------------------------------------------------------- - -$templateName = 'template-1-text-field.docx'; - -$mailMerge->setLocalTemplate($templateName); - -printf('Field names in %s:%s', $templateName, PHP_EOL); - -$fieldNames = $mailMerge->getFieldNames(); -foreach ($fieldNames as $fieldName) { - printf('- %s%s', $fieldName, PHP_EOL); -} - -// ----------------------------------------------------------------------------- - -$templateName = 'template-2-text-fields.doc'; - -$mailMerge->setLocalTemplate($templateName); - -printf('%sField names in %s:%s', PHP_EOL, $templateName, PHP_EOL); - -$fieldNames = $mailMerge->getFieldNames(); -foreach ($fieldNames as $fieldName) { - printf('- %s%s', $fieldName, PHP_EOL); -} - -// ----------------------------------------------------------------------------- - -$templateName = 'template-block-fields.doc'; - -$mailMerge->setLocalTemplate($templateName); - -printf('%sField names in %s:%s', PHP_EOL, $templateName, PHP_EOL); - -$fieldNames = $mailMerge->getFieldNames(); -foreach ($fieldNames as $fieldName) { - printf('- %s%s', $fieldName, PHP_EOL); -} - -printf('%sBlock names in %s:%s', PHP_EOL, $templateName, PHP_EOL); - -$blockNames = $mailMerge->getBlockNames(); -foreach ($blockNames as $blockName) { - printf('- %s%s', $blockName, PHP_EOL); -} - -printf('%sBlock field names in %s:%s', PHP_EOL, $templateName, PHP_EOL); - -foreach ($blockNames as $blockName) { - $blockFieldNames = $mailMerge->getBlockFieldNames($blockName); - foreach ($blockFieldNames as $blockFieldName) { - printf('- %s::%s%s', $blockName, $blockFieldName, PHP_EOL); - } -} - -print(PHP_EOL); - -// ----------------------------------------------------------------------------- - -unset($mailMerge); \ No newline at end of file diff --git a/demos/Zend/Service/LiveDocx/MailMerge/template-info/template-1-text-field-screenshot.png b/demos/Zend/Service/LiveDocx/MailMerge/template-info/template-1-text-field-screenshot.png deleted file mode 100755 index 5eb07cf36a..0000000000 Binary files a/demos/Zend/Service/LiveDocx/MailMerge/template-info/template-1-text-field-screenshot.png and /dev/null differ diff --git a/demos/Zend/Service/LiveDocx/MailMerge/template-info/template-1-text-field.doc b/demos/Zend/Service/LiveDocx/MailMerge/template-info/template-1-text-field.doc deleted file mode 100644 index 294e01fd64..0000000000 Binary files a/demos/Zend/Service/LiveDocx/MailMerge/template-info/template-1-text-field.doc and /dev/null differ diff --git a/demos/Zend/Service/LiveDocx/MailMerge/template-info/template-1-text-field.docx b/demos/Zend/Service/LiveDocx/MailMerge/template-info/template-1-text-field.docx deleted file mode 100644 index 9a4a18dada..0000000000 Binary files a/demos/Zend/Service/LiveDocx/MailMerge/template-info/template-1-text-field.docx and /dev/null differ diff --git a/demos/Zend/Service/LiveDocx/MailMerge/template-info/template-2-text-fields-screenshot.png b/demos/Zend/Service/LiveDocx/MailMerge/template-info/template-2-text-fields-screenshot.png deleted file mode 100755 index 4d2fb29f60..0000000000 Binary files a/demos/Zend/Service/LiveDocx/MailMerge/template-info/template-2-text-fields-screenshot.png and /dev/null differ diff --git a/demos/Zend/Service/LiveDocx/MailMerge/template-info/template-2-text-fields.doc b/demos/Zend/Service/LiveDocx/MailMerge/template-info/template-2-text-fields.doc deleted file mode 100644 index 0bbb21990c..0000000000 Binary files a/demos/Zend/Service/LiveDocx/MailMerge/template-info/template-2-text-fields.doc and /dev/null differ diff --git a/demos/Zend/Service/LiveDocx/MailMerge/template-info/template-2-text-fields.docx b/demos/Zend/Service/LiveDocx/MailMerge/template-info/template-2-text-fields.docx deleted file mode 100644 index 37ba0c52b1..0000000000 Binary files a/demos/Zend/Service/LiveDocx/MailMerge/template-info/template-2-text-fields.docx and /dev/null differ diff --git a/demos/Zend/Service/LiveDocx/MailMerge/template-info/template-block-fields-screenshot.png b/demos/Zend/Service/LiveDocx/MailMerge/template-info/template-block-fields-screenshot.png deleted file mode 100755 index b90d27b669..0000000000 Binary files a/demos/Zend/Service/LiveDocx/MailMerge/template-info/template-block-fields-screenshot.png and /dev/null differ diff --git a/demos/Zend/Service/LiveDocx/MailMerge/template-info/template-block-fields.doc b/demos/Zend/Service/LiveDocx/MailMerge/template-info/template-block-fields.doc deleted file mode 100755 index 1da17f99cc..0000000000 Binary files a/demos/Zend/Service/LiveDocx/MailMerge/template-info/template-block-fields.doc and /dev/null differ diff --git a/demos/Zend/Service/LiveDocx/MailMerge/templates/delete-all.php b/demos/Zend/Service/LiveDocx/MailMerge/templates/delete-all.php deleted file mode 100755 index e695f1a66a..0000000000 --- a/demos/Zend/Service/LiveDocx/MailMerge/templates/delete-all.php +++ /dev/null @@ -1,29 +0,0 @@ -setUsername(DEMOS_ZEND_SERVICE_LIVEDOCX_USERNAME) - ->setPassword(DEMOS_ZEND_SERVICE_LIVEDOCX_PASSWORD); - -$counter = 1; -foreach ($mailMerge->listTemplates() as $result) { - printf('%d) %s', $counter, $result['filename']); - $mailMerge->deleteTemplate($result['filename']); - print(' - DELETED.' . PHP_EOL); - $counter++; -} - -print(PHP_EOL); - -unset($mailMerge); \ No newline at end of file diff --git a/demos/Zend/Service/LiveDocx/MailMerge/templates/download.php b/demos/Zend/Service/LiveDocx/MailMerge/templates/download.php deleted file mode 100755 index 47a8b421fd..0000000000 --- a/demos/Zend/Service/LiveDocx/MailMerge/templates/download.php +++ /dev/null @@ -1,30 +0,0 @@ -setUsername(DEMOS_ZEND_SERVICE_LIVEDOCX_USERNAME) - ->setPassword(DEMOS_ZEND_SERVICE_LIVEDOCX_PASSWORD); - -$counter = 1; -foreach ($mailMerge->listTemplates() as $result) { - printf('%d) %s', $counter, $result['filename']); - $template = $mailMerge->downloadTemplate($result['filename']); - file_put_contents('downloaded-' . $result['filename'], $template); - print(" - DOWNLOADED.\n"); - $counter++; -} - -print(PHP_EOL); - -unset($mailMerge); \ No newline at end of file diff --git a/demos/Zend/Service/LiveDocx/MailMerge/templates/list.php b/demos/Zend/Service/LiveDocx/MailMerge/templates/list.php deleted file mode 100755 index 6e849bd64f..0000000000 --- a/demos/Zend/Service/LiveDocx/MailMerge/templates/list.php +++ /dev/null @@ -1,23 +0,0 @@ -setUsername(DEMOS_ZEND_SERVICE_LIVEDOCX_USERNAME) - ->setPassword(DEMOS_ZEND_SERVICE_LIVEDOCX_PASSWORD); - -print(Demos_Zend_Service_LiveDocx_Helper::listDecorator($mailMerge->listTemplates())); - -unset($mailMerge); \ No newline at end of file diff --git a/demos/Zend/Service/LiveDocx/MailMerge/templates/template-1.docx b/demos/Zend/Service/LiveDocx/MailMerge/templates/template-1.docx deleted file mode 100755 index 5854b708bf..0000000000 Binary files a/demos/Zend/Service/LiveDocx/MailMerge/templates/template-1.docx and /dev/null differ diff --git a/demos/Zend/Service/LiveDocx/MailMerge/templates/template-2.docx b/demos/Zend/Service/LiveDocx/MailMerge/templates/template-2.docx deleted file mode 100755 index 5854b708bf..0000000000 Binary files a/demos/Zend/Service/LiveDocx/MailMerge/templates/template-2.docx and /dev/null differ diff --git a/demos/Zend/Service/LiveDocx/MailMerge/templates/template-exists.php b/demos/Zend/Service/LiveDocx/MailMerge/templates/template-exists.php deleted file mode 100755 index d3759316ba..0000000000 --- a/demos/Zend/Service/LiveDocx/MailMerge/templates/template-exists.php +++ /dev/null @@ -1,29 +0,0 @@ -setUsername(DEMOS_ZEND_SERVICE_LIVEDOCX_USERNAME) - ->setPassword(DEMOS_ZEND_SERVICE_LIVEDOCX_PASSWORD); - -print('Checking whether a template is available... '); -if (true === $mailMerge->templateExists('template-1.docx')) { - print('EXISTS. '); -} else { - print('DOES NOT EXIST. '); -} -print('DONE' . PHP_EOL); - -print(PHP_EOL); - -unset($mailMerge); \ No newline at end of file diff --git a/demos/Zend/Service/LiveDocx/MailMerge/templates/upload.php b/demos/Zend/Service/LiveDocx/MailMerge/templates/upload.php deleted file mode 100755 index f78a159d34..0000000000 --- a/demos/Zend/Service/LiveDocx/MailMerge/templates/upload.php +++ /dev/null @@ -1,29 +0,0 @@ -setUsername(DEMOS_ZEND_SERVICE_LIVEDOCX_USERNAME) - ->setPassword(DEMOS_ZEND_SERVICE_LIVEDOCX_PASSWORD); - -print('Uploading template... '); -$mailMerge->uploadTemplate('template-1.docx'); -print('DONE.' . PHP_EOL); - -print('Uploading template... '); -$mailMerge->uploadTemplate('template-2.docx'); -print('DONE.' . PHP_EOL); - -print(PHP_EOL); - -unset($mailMerge); \ No newline at end of file diff --git a/demos/Zend/Service/LiveDocx/check-environment.php b/demos/Zend/Service/LiveDocx/check-environment.php deleted file mode 100755 index f12862e57d..0000000000 --- a/demos/Zend/Service/LiveDocx/check-environment.php +++ /dev/null @@ -1,280 +0,0 @@ - 'IP address', - 'City' => 'city', - 'RegionName' => 'region', - 'CountryName' => 'country' -); - -if (false !== $geoData) { - $simplexml = new SimpleXMLElement($geoData); - foreach ($keys as $key => $value) { - printLine($counter, sprintf('Checking your %s (%s)', $keys[$key], $simplexml->$key), TEST_PASS); - $counter ++; - } -} else { - printLine($counter, 'Checking your geo data', TEST_FAIL); - $failed = true; -} - -// ----------------------------------------------------------------------------- - -$microtime = microtime(true); - -if (false !== file_get_contents(Zend_Service_LiveDocx_MailMerge::WSDL)) { - $duration = microtime(true) - $microtime; - $result = TEST_PASS; -} else { - $duration = -1; - $result = TEST_FAIL; - $failed = true; -} - -printLine($counter, sprintf('Checking backend WSDL (%01.2fs)', $duration), $result); - -$counter ++; - -// ----------------------------------------------------------------------------- - -if (defined('DEMOS_ZEND_SERVICE_LIVEDOCX_USERNAME') && - defined('DEMOS_ZEND_SERVICE_LIVEDOCX_PASSWORD')) { - $result = TEST_PASS; -} else { - $result = TEST_FAIL; - $failed = true; -} - -printLine($counter, 'Checking backend credentials are defined', $result); - -$counter ++; - -// ----------------------------------------------------------------------------- - -$errorMessage = null; - -try { - $microtime = microtime(true); - $mailMerge = new Zend_Service_LiveDocx_MailMerge( - array ( - 'username' => DEMOS_ZEND_SERVICE_LIVEDOCX_USERNAME, - 'password' => DEMOS_ZEND_SERVICE_LIVEDOCX_PASSWORD - ) - ); - $mailMerge->logIn(); - $duration = microtime(true) - $microtime; -} catch (Zend_Service_LiveDocx_Exception $e) { - $duration = -1; - $errorMessage = $e->getMessage(); -} - -if (is_null($errorMessage)) { - $result = TEST_PASS; -} else { - $result = TEST_FAIL; - $failed = true; -} - -printLine($counter, sprintf('Logging into backend service (%01.2fs)', $duration), $result); - -$counter ++; - -// ----------------------------------------------------------------------------- - -if (true === $failed) { - $message = 'One or more tests failed. The web server environment, in which this script is running, does not meet the requirements for Zend_Service_LiveDocx_*.'; -} else { - $message = 'Congratulations! All tests passed. The server environment, in which this script is running, is suitable for Zend_Service_LiveDocx_*.'; -} - -print(Demos_Zend_Service_LiveDocx_Helper::wrapLine(PHP_EOL . $message . PHP_EOL . PHP_EOL)); - -// ----------------------------------------------------------------------------- - -/** - * Print result line - * - * @param int $counter - * @param string $testString - * @param mixed $testResult - * @return void - */ -function printLine($counter, $testString, $testResult) -{ - $lineLength = Demos_Zend_Service_LiveDocx_Helper::LINE_LENGTH; - - // counter result - $padding = $lineLength - (4 + strlen(TEST_PASS)); - - $counter = sprintf('%2s: ', $counter); - $testString = str_pad($testString, $padding, '.', STR_PAD_RIGHT); - - printf('%s%s%s%s', $counter, $testString, $testResult, PHP_EOL); -} - -// ----------------------------------------------------------------------------- diff --git a/demos/Zend/Service/LiveDocx/common.php b/demos/Zend/Service/LiveDocx/common.php deleted file mode 100755 index 7abfaf3c3e..0000000000 --- a/demos/Zend/Service/LiveDocx/common.php +++ /dev/null @@ -1,27 +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 f811e3b90f..0000000000 --- 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 6203f0ba9b..0000000000 --- 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 2d7adb6afa..0000000000 --- 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 964396f5a0..0000000000 --- a/demos/Zend/Wildfire/application/controllers/ZendLogWriterFirebugController.php +++ /dev/null @@ -1,94 +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 testgroupedloggingAction() - { - $logger = Zend_Registry::get('logger'); - - Zend_Wildfire_Plugin_FirePhp::group("Collapsed Group", array('Collapsed' => true)); - $logger->log('Message in collapsed group', Zend_Log::DEBUG); - Zend_Wildfire_Plugin_FirePhp::groupEnd(); - - Zend_Wildfire_Plugin_FirePhp::group("Expanded Group", array('Collapsed' => false)); - $logger->log('Message in expanded group', Zend_Log::DEBUG); - Zend_Wildfire_Plugin_FirePhp::groupEnd(); - } - - 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 387f5369a8..0000000000 --- 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 bf000d245d..0000000000 --- a/demos/Zend/Wildfire/application/views/scripts/index/index.phtml +++ /dev/null @@ -1,58 +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 811241b903..0000000000 --- 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 4868c5b1ac..0000000000 --- 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 e69de29bb2..0000000000 diff --git a/demos/Zend/Wildfire/application/views/scripts/zend-log-writer-firebug/test-grouped-logging.phtml b/demos/Zend/Wildfire/application/views/scripts/zend-log-writer-firebug/test-grouped-logging.phtml deleted file mode 100644 index 15b2fad85f..0000000000 --- a/demos/Zend/Wildfire/application/views/scripts/zend-log-writer-firebug/test-grouped-logging.phtml +++ /dev/null @@ -1,16 +0,0 @@ - - - Zend_Wildfire Demos and Tests - - - - -Test Grouped Logging - - - \ No newline at end of file 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 dcc6d63af8..0000000000 --- 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 811241b903..0000000000 --- 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 6929734b2a..0000000000 --- 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 545b1cbfdf..0000000000 --- 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 4c9f4ac398..0000000000 --- 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(dirname(__FILE__)))).'/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 afa923774d..0000000000 --- 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(dirname(__FILE__)))).'/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 12dab18658..0000000000 --- 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(dirname(__FILE__)).'/application/controllers'); diff --git a/library/Zend/Auth.php b/library/Zend/Auth.php deleted file mode 100644 index 434d944fc5..0000000000 --- a/library/Zend/Auth.php +++ /dev/null @@ -1,169 +0,0 @@ -_storage) { - /** - * @see Zend_Auth_Storage_Session - */ - #require_once 'Zend/Auth/Storage/Session.php'; - $this->setStorage(new Zend_Auth_Storage_Session()); - } - - return $this->_storage; - } - - /** - * Sets the persistent storage handler - * - * @param Zend_Auth_Storage_Interface $storage - * @return Zend_Auth Provides a fluent interface - */ - public function setStorage(Zend_Auth_Storage_Interface $storage) - { - $this->_storage = $storage; - return $this; - } - - /** - * Authenticates against the supplied adapter - * - * @param Zend_Auth_Adapter_Interface $adapter - * @return Zend_Auth_Result - */ - public function authenticate(Zend_Auth_Adapter_Interface $adapter) - { - $result = $adapter->authenticate(); - - /** - * ZF-7546 - prevent multiple succesive calls from storing inconsistent results - * Ensure storage has clean state - */ - if ($this->hasIdentity()) { - $this->clearIdentity(); - } - - if ($result->isValid()) { - $this->getStorage()->write($result->getIdentity()); - } - - return $result; - } - - /** - * Returns true if and only if an identity is available from storage - * - * @return boolean - */ - public function hasIdentity() - { - return !$this->getStorage()->isEmpty(); - } - - /** - * Returns the identity from storage or null if no identity is available - * - * @return mixed|null - */ - public function getIdentity() - { - $storage = $this->getStorage(); - - if ($storage->isEmpty()) { - return null; - } - - return $storage->read(); - } - - /** - * Clears the identity from persistent storage - * - * @return void - */ - public function clearIdentity() - { - $this->getStorage()->clear(); - } -} diff --git a/library/Zend/Cache/Backend/Sqlite.php b/library/Zend/Cache/Backend/Sqlite.php deleted file mode 100644 index 22fac1f0eb..0000000000 --- a/library/Zend/Cache/Backend/Sqlite.php +++ /dev/null @@ -1,678 +0,0 @@ - (string) cache_db_complete_path : - * - the complete path (filename included) of the SQLITE database - * - * ====> (int) automatic_vacuum_factor : - * - Disable / Tune the automatic vacuum process - * - The automatic vacuum process defragment the database file (and make it smaller) - * when a clean() or delete() is called - * 0 => no automatic vacuum - * 1 => systematic vacuum (when delete() or clean() methods are called) - * x (integer) > 1 => automatic vacuum randomly 1 times on x clean() or delete() - * - * @var array Available options - */ - protected $_options = array( - 'cache_db_complete_path' => null, - 'automatic_vacuum_factor' => 10 - ); - - /** - * DB ressource - * - * @var mixed $_db - */ - private $_db = null; - - /** - * Boolean to store if the structure has benn checked or not - * - * @var boolean $_structureChecked - */ - private $_structureChecked = false; - - /** - * Constructor - * - * @param array $options Associative array of options - * @throws Zend_cache_Exception - * @return void - */ - public function __construct(array $options = array()) - { - parent::__construct($options); - if ($this->_options['cache_db_complete_path'] === null) { - Zend_Cache::throwException('cache_db_complete_path option has to set'); - } - if (!extension_loaded('sqlite')) { - Zend_Cache::throwException("Cannot use SQLite storage because the 'sqlite' extension is not loaded in the current PHP environment"); - } - $this->_getConnection(); - } - - /** - * Destructor - * - * @return void - */ - public function __destruct() - { - @sqlite_close($this->_getConnection()); - } - - /** - * Test if a cache is available for the given id and (if yes) return it (false else) - * - * @param string $id Cache id - * @param boolean $doNotTestCacheValidity If set to true, the cache validity won't be tested - * @return string|false Cached datas - */ - public function load($id, $doNotTestCacheValidity = false) - { - $this->_checkAndBuildStructure(); - $sql = "SELECT content FROM cache WHERE id='$id'"; - if (!$doNotTestCacheValidity) { - $sql = $sql . " AND (expire=0 OR expire>" . time() . ')'; - } - $result = $this->_query($sql); - $row = @sqlite_fetch_array($result); - if ($row) { - return $row['content']; - } - return false; - } - - /** - * Test if a cache is available or not (for the given id) - * - * @param string $id Cache id - * @return mixed|false (a cache is not available) or "last modified" timestamp (int) of the available cache record - */ - public function test($id) - { - $this->_checkAndBuildStructure(); - $sql = "SELECT lastModified FROM cache WHERE id='$id' AND (expire=0 OR expire>" . time() . ')'; - $result = $this->_query($sql); - $row = @sqlite_fetch_array($result); - if ($row) { - return ((int) $row['lastModified']); - } - return false; - } - - /** - * Save some string datas into a cache record - * - * Note : $data is always "string" (serialization is done by the - * core not by the backend) - * - * @param string $data Datas to cache - * @param string $id Cache id - * @param array $tags Array of strings, the cache record will be tagged by each string entry - * @param int $specificLifetime If != false, set a specific lifetime for this cache record (null => infinite lifetime) - * @throws Zend_Cache_Exception - * @return boolean True if no problem - */ - public function save($data, $id, $tags = array(), $specificLifetime = false) - { - $this->_checkAndBuildStructure(); - $lifetime = $this->getLifetime($specificLifetime); - $data = @sqlite_escape_string($data); - $mktime = time(); - if ($lifetime === null) { - $expire = 0; - } else { - $expire = $mktime + $lifetime; - } - $this->_query("DELETE FROM cache WHERE id='$id'"); - $sql = "INSERT INTO cache (id, content, lastModified, expire) VALUES ('$id', '$data', $mktime, $expire)"; - $res = $this->_query($sql); - if (!$res) { - $this->_log("Zend_Cache_Backend_Sqlite::save() : impossible to store the cache id=$id"); - return false; - } - $res = true; - foreach ($tags as $tag) { - $res = $this->_registerTag($id, $tag) && $res; - } - return $res; - } - - /** - * Remove a cache record - * - * @param string $id Cache id - * @return boolean True if no problem - */ - public function remove($id) - { - $this->_checkAndBuildStructure(); - $res = $this->_query("SELECT COUNT(*) AS nbr FROM cache WHERE id='$id'"); - $result1 = @sqlite_fetch_single($res); - $result2 = $this->_query("DELETE FROM cache WHERE id='$id'"); - $result3 = $this->_query("DELETE FROM tag WHERE id='$id'"); - $this->_automaticVacuum(); - return ($result1 && $result2 && $result3); - } - - /** - * Clean some cache records - * - * Available modes are : - * Zend_Cache::CLEANING_MODE_ALL (default) => remove all cache entries ($tags is not used) - * Zend_Cache::CLEANING_MODE_OLD => remove too old cache entries ($tags is not used) - * Zend_Cache::CLEANING_MODE_MATCHING_TAG => remove cache entries matching all given tags - * ($tags can be an array of strings or a single string) - * Zend_Cache::CLEANING_MODE_NOT_MATCHING_TAG => remove cache entries not {matching one of the given tags} - * ($tags can be an array of strings or a single string) - * Zend_Cache::CLEANING_MODE_MATCHING_ANY_TAG => remove cache entries matching any given tags - * ($tags can be an array of strings or a single string) - * - * @param string $mode Clean mode - * @param array $tags Array of tags - * @return boolean True if no problem - */ - public function clean($mode = Zend_Cache::CLEANING_MODE_ALL, $tags = array()) - { - $this->_checkAndBuildStructure(); - $return = $this->_clean($mode, $tags); - $this->_automaticVacuum(); - return $return; - } - - /** - * Return an array of stored cache ids - * - * @return array array of stored cache ids (string) - */ - public function getIds() - { - $this->_checkAndBuildStructure(); - $res = $this->_query("SELECT id FROM cache WHERE (expire=0 OR expire>" . time() . ")"); - $result = array(); - while ($id = @sqlite_fetch_single($res)) { - $result[] = $id; - } - return $result; - } - - /** - * Return an array of stored tags - * - * @return array array of stored tags (string) - */ - public function getTags() - { - $this->_checkAndBuildStructure(); - $res = $this->_query("SELECT DISTINCT(name) AS name FROM tag"); - $result = array(); - while ($id = @sqlite_fetch_single($res)) { - $result[] = $id; - } - return $result; - } - - /** - * Return an array of stored cache ids which match given tags - * - * In case of multiple tags, a logical AND is made between tags - * - * @param array $tags array of tags - * @return array array of matching cache ids (string) - */ - public function getIdsMatchingTags($tags = array()) - { - $first = true; - $ids = array(); - foreach ($tags as $tag) { - $res = $this->_query("SELECT DISTINCT(id) AS id FROM tag WHERE name='$tag'"); - if (!$res) { - return array(); - } - $rows = @sqlite_fetch_all($res, SQLITE_ASSOC); - $ids2 = array(); - foreach ($rows as $row) { - $ids2[] = $row['id']; - } - if ($first) { - $ids = $ids2; - $first = false; - } else { - $ids = array_intersect($ids, $ids2); - } - } - $result = array(); - foreach ($ids as $id) { - $result[] = $id; - } - return $result; - } - - /** - * Return an array of stored cache ids which don't match given tags - * - * In case of multiple tags, a logical OR is made between tags - * - * @param array $tags array of tags - * @return array array of not matching cache ids (string) - */ - public function getIdsNotMatchingTags($tags = array()) - { - $res = $this->_query("SELECT id FROM cache"); - $rows = @sqlite_fetch_all($res, SQLITE_ASSOC); - $result = array(); - foreach ($rows as $row) { - $id = $row['id']; - $matching = false; - foreach ($tags as $tag) { - $res = $this->_query("SELECT COUNT(*) AS nbr FROM tag WHERE name='$tag' AND id='$id'"); - if (!$res) { - return array(); - } - $nbr = (int) @sqlite_fetch_single($res); - if ($nbr > 0) { - $matching = true; - } - } - if (!$matching) { - $result[] = $id; - } - } - return $result; - } - - /** - * Return an array of stored cache ids which match any given tags - * - * In case of multiple tags, a logical AND is made between tags - * - * @param array $tags array of tags - * @return array array of any matching cache ids (string) - */ - public function getIdsMatchingAnyTags($tags = array()) - { - $first = true; - $ids = array(); - foreach ($tags as $tag) { - $res = $this->_query("SELECT DISTINCT(id) AS id FROM tag WHERE name='$tag'"); - if (!$res) { - return array(); - } - $rows = @sqlite_fetch_all($res, SQLITE_ASSOC); - $ids2 = array(); - foreach ($rows as $row) { - $ids2[] = $row['id']; - } - if ($first) { - $ids = $ids2; - $first = false; - } else { - $ids = array_merge($ids, $ids2); - } - } - $result = array(); - foreach ($ids as $id) { - $result[] = $id; - } - return $result; - } - - /** - * Return the filling percentage of the backend storage - * - * @throws Zend_Cache_Exception - * @return int integer between 0 and 100 - */ - public function getFillingPercentage() - { - $dir = dirname($this->_options['cache_db_complete_path']); - $free = disk_free_space($dir); - $total = disk_total_space($dir); - if ($total == 0) { - Zend_Cache::throwException('can\'t get disk_total_space'); - } else { - if ($free >= $total) { - return 100; - } - return ((int) (100. * ($total - $free) / $total)); - } - } - - /** - * Return an array of metadatas for the given cache id - * - * The array must include these keys : - * - expire : the expire timestamp - * - tags : a string array of tags - * - mtime : timestamp of last modification time - * - * @param string $id cache id - * @return array array of metadatas (false if the cache id is not found) - */ - public function getMetadatas($id) - { - $tags = array(); - $res = $this->_query("SELECT name FROM tag WHERE id='$id'"); - if ($res) { - $rows = @sqlite_fetch_all($res, SQLITE_ASSOC); - foreach ($rows as $row) { - $tags[] = $row['name']; - } - } - $this->_query('CREATE TABLE cache (id TEXT PRIMARY KEY, content BLOB, lastModified INTEGER, expire INTEGER)'); - $res = $this->_query("SELECT lastModified,expire FROM cache WHERE id='$id'"); - if (!$res) { - return false; - } - $row = @sqlite_fetch_array($res, SQLITE_ASSOC); - return array( - 'tags' => $tags, - 'mtime' => $row['lastModified'], - 'expire' => $row['expire'] - ); - } - - /** - * Give (if possible) an extra lifetime to the given cache id - * - * @param string $id cache id - * @param int $extraLifetime - * @return boolean true if ok - */ - public function touch($id, $extraLifetime) - { - $sql = "SELECT expire FROM cache WHERE id='$id' AND (expire=0 OR expire>" . time() . ')'; - $res = $this->_query($sql); - if (!$res) { - return false; - } - $expire = @sqlite_fetch_single($res); - $newExpire = $expire + $extraLifetime; - $res = $this->_query("UPDATE cache SET lastModified=" . time() . ", expire=$newExpire WHERE id='$id'"); - if ($res) { - return true; - } else { - return false; - } - } - - /** - * Return an associative array of capabilities (booleans) of the backend - * - * The array must include these keys : - * - automatic_cleaning (is automating cleaning necessary) - * - tags (are tags supported) - * - expired_read (is it possible to read expired cache records - * (for doNotTestCacheValidity option for example)) - * - priority does the backend deal with priority when saving - * - infinite_lifetime (is infinite lifetime can work with this backend) - * - get_list (is it possible to get the list of cache ids and the complete list of tags) - * - * @return array associative of with capabilities - */ - public function getCapabilities() - { - return array( - 'automatic_cleaning' => true, - 'tags' => true, - 'expired_read' => true, - 'priority' => false, - 'infinite_lifetime' => true, - 'get_list' => true - ); - } - - /** - * PUBLIC METHOD FOR UNIT TESTING ONLY ! - * - * Force a cache record to expire - * - * @param string $id Cache id - */ - public function ___expire($id) - { - $time = time() - 1; - $this->_query("UPDATE cache SET lastModified=$time, expire=$time WHERE id='$id'"); - } - - /** - * Return the connection resource - * - * If we are not connected, the connection is made - * - * @throws Zend_Cache_Exception - * @return resource Connection resource - */ - private function _getConnection() - { - if (is_resource($this->_db)) { - return $this->_db; - } else { - $this->_db = @sqlite_open($this->_options['cache_db_complete_path']); - if (!(is_resource($this->_db))) { - Zend_Cache::throwException("Impossible to open " . $this->_options['cache_db_complete_path'] . " cache DB file"); - } - return $this->_db; - } - } - - /** - * Execute an SQL query silently - * - * @param string $query SQL query - * @return mixed|false query results - */ - private function _query($query) - { - $db = $this->_getConnection(); - if (is_resource($db)) { - $res = @sqlite_query($db, $query); - if ($res === false) { - return false; - } else { - return $res; - } - } - return false; - } - - /** - * Deal with the automatic vacuum process - * - * @return void - */ - private function _automaticVacuum() - { - if ($this->_options['automatic_vacuum_factor'] > 0) { - $rand = rand(1, $this->_options['automatic_vacuum_factor']); - if ($rand == 1) { - $this->_query('VACUUM'); - } - } - } - - /** - * Register a cache id with the given tag - * - * @param string $id Cache id - * @param string $tag Tag - * @return boolean True if no problem - */ - private function _registerTag($id, $tag) { - $res = $this->_query("DELETE FROM TAG WHERE name='$tag' AND id='$id'"); - $res = $this->_query("INSERT INTO tag (name, id) VALUES ('$tag', '$id')"); - if (!$res) { - $this->_log("Zend_Cache_Backend_Sqlite::_registerTag() : impossible to register tag=$tag on id=$id"); - return false; - } - return true; - } - - /** - * Build the database structure - * - * @return false - */ - private function _buildStructure() - { - $this->_query('DROP INDEX tag_id_index'); - $this->_query('DROP INDEX tag_name_index'); - $this->_query('DROP INDEX cache_id_expire_index'); - $this->_query('DROP TABLE version'); - $this->_query('DROP TABLE cache'); - $this->_query('DROP TABLE tag'); - $this->_query('CREATE TABLE version (num INTEGER PRIMARY KEY)'); - $this->_query('CREATE TABLE cache (id TEXT PRIMARY KEY, content BLOB, lastModified INTEGER, expire INTEGER)'); - $this->_query('CREATE TABLE tag (name TEXT, id TEXT)'); - $this->_query('CREATE INDEX tag_id_index ON tag(id)'); - $this->_query('CREATE INDEX tag_name_index ON tag(name)'); - $this->_query('CREATE INDEX cache_id_expire_index ON cache(id, expire)'); - $this->_query('INSERT INTO version (num) VALUES (1)'); - } - - /** - * Check if the database structure is ok (with the good version) - * - * @return boolean True if ok - */ - private function _checkStructureVersion() - { - $result = $this->_query("SELECT num FROM version"); - if (!$result) return false; - $row = @sqlite_fetch_array($result); - if (!$row) { - return false; - } - if (((int) $row['num']) != 1) { - // old cache structure - $this->_log('Zend_Cache_Backend_Sqlite::_checkStructureVersion() : old cache structure version detected => the cache is going to be dropped'); - return false; - } - return true; - } - - /** - * Clean some cache records - * - * Available modes are : - * Zend_Cache::CLEANING_MODE_ALL (default) => remove all cache entries ($tags is not used) - * Zend_Cache::CLEANING_MODE_OLD => remove too old cache entries ($tags is not used) - * Zend_Cache::CLEANING_MODE_MATCHING_TAG => remove cache entries matching all given tags - * ($tags can be an array of strings or a single string) - * Zend_Cache::CLEANING_MODE_NOT_MATCHING_TAG => remove cache entries not {matching one of the given tags} - * ($tags can be an array of strings or a single string) - * Zend_Cache::CLEANING_MODE_MATCHING_ANY_TAG => remove cache entries matching any given tags - * ($tags can be an array of strings or a single string) - * - * @param string $mode Clean mode - * @param array $tags Array of tags - * @return boolean True if no problem - */ - private function _clean($mode = Zend_Cache::CLEANING_MODE_ALL, $tags = array()) - { - switch ($mode) { - case Zend_Cache::CLEANING_MODE_ALL: - $res1 = $this->_query('DELETE FROM cache'); - $res2 = $this->_query('DELETE FROM tag'); - return $res1 && $res2; - break; - case Zend_Cache::CLEANING_MODE_OLD: - $mktime = time(); - $res1 = $this->_query("DELETE FROM tag WHERE id IN (SELECT id FROM cache WHERE expire>0 AND expire<=$mktime)"); - $res2 = $this->_query("DELETE FROM cache WHERE expire>0 AND expire<=$mktime"); - return $res1 && $res2; - break; - case Zend_Cache::CLEANING_MODE_MATCHING_TAG: - $ids = $this->getIdsMatchingTags($tags); - $result = true; - foreach ($ids as $id) { - $result = $this->remove($id) && $result; - } - return $result; - break; - case Zend_Cache::CLEANING_MODE_NOT_MATCHING_TAG: - $ids = $this->getIdsNotMatchingTags($tags); - $result = true; - foreach ($ids as $id) { - $result = $this->remove($id) && $result; - } - return $result; - break; - case Zend_Cache::CLEANING_MODE_MATCHING_ANY_TAG: - $ids = $this->getIdsMatchingAnyTags($tags); - $result = true; - foreach ($ids as $id) { - $result = $this->remove($id) && $result; - } - return $result; - break; - default: - break; - } - return false; - } - - /** - * Check if the database structure is ok (with the good version), if no : build it - * - * @throws Zend_Cache_Exception - * @return boolean True if ok - */ - private function _checkAndBuildStructure() - { - if (!($this->_structureChecked)) { - if (!$this->_checkStructureVersion()) { - $this->_buildStructure(); - if (!$this->_checkStructureVersion()) { - Zend_Cache::throwException("Impossible to build cache structure in " . $this->_options['cache_db_complete_path']); - } - } - $this->_structureChecked = true; - } - return true; - } - -} diff --git a/library/Zend/Captcha/Adapter.php b/library/Zend/Captcha/Adapter.php deleted file mode 100644 index 70835f9fde..0000000000 --- a/library/Zend/Captcha/Adapter.php +++ /dev/null @@ -1,76 +0,0 @@ -_name; - } - - /** - * Set name - * - * @param string $name - * @return Zend_Captcha_Adapter - */ - public function setName($name) - { - $this->_name = $name; - return $this; - } - - /** - * Constructor - * - * @param array|Zend_Config $options - */ - public function __construct($options = null) - { - // Set options - if (is_array($options)) { - $this->setOptions($options); - } else if ($options instanceof Zend_Config) { - $this->setConfig($options); - } - } - - /** - * Set single option for the object - * - * @param string $key - * @param string $value - * @return Zend_Form_Element - */ - public function setOption($key, $value) - { - if (in_array(strtolower($key), $this->_skipOptions)) { - return $this; - } - - $method = 'set' . ucfirst ($key); - if (method_exists ($this, $method)) { - // Setter exists; use it - $this->$method ($value); - $this->_options[$key] = $value; - } elseif (property_exists($this, $key)) { - // Assume it's metadata - $this->$key = $value; - $this->_options[$key] = $value; - } - return $this; - } - - /** - * Set object state from options array - * - * @param array $options - * @return Zend_Form_Element - */ - public function setOptions($options = null) - { - foreach ($options as $key => $value) { - $this->setOption($key, $value); - } - return $this; - } - - /** - * Retrieve options representing object state - * - * @return array - */ - public function getOptions() - { - return $this->_options; - } - - /** - * Set object state from config object - * - * @param Zend_Config $config - * @return Zend_Captcha_Base - */ - public function setConfig(Zend_Config $config) - { - return $this->setOptions($config->toArray()); - } - - /** - * Get optional decorator - * - * By default, return null, indicating no extra decorator needed. - * - * @return null - */ - public function getDecorator() - { - return null; - } -} diff --git a/library/Zend/Captcha/Dumb.php b/library/Zend/Captcha/Dumb.php deleted file mode 100644 index 803f15e3d5..0000000000 --- a/library/Zend/Captcha/Dumb.php +++ /dev/null @@ -1,75 +0,0 @@ -_label = $label; - } - - /** - * Retrieve the label for the CAPTCHA - * @return string - */ - public function getLabel() - { - return $this->_label; - } - /** - * Render the captcha - * - * @param Zend_View_Interface $view - * @param mixed $element - * @return string - */ - public function render(Zend_View_Interface $view = null, $element = null) - { - return $this->getLabel() . ': ' - . strrev($this->getWord()) - . ''; - } -} diff --git a/library/Zend/Captcha/Exception.php b/library/Zend/Captcha/Exception.php deleted file mode 100755 index 71d7555883..0000000000 --- a/library/Zend/Captcha/Exception.php +++ /dev/null @@ -1,37 +0,0 @@ -_figlet = new Zend_Text_Figlet($options); - } - - /** - * Generate new captcha - * - * @return string - */ - public function generate() - { - $this->_useNumbers = false; - return parent::generate(); - } - - /** - * Display the captcha - * - * @param Zend_View_Interface $view - * @param mixed $element - * @return string - */ - public function render(Zend_View_Interface $view = null, $element = null) - { - return '
'
-             . $this->_figlet->render($this->getWord())
-             . "
\n"; - } -} diff --git a/library/Zend/Captcha/Image.php b/library/Zend/Captcha/Image.php deleted file mode 100644 index 542d56926b..0000000000 --- a/library/Zend/Captcha/Image.php +++ /dev/null @@ -1,625 +0,0 @@ -_imgAlt; - } - /** - * @return string - */ - public function getStartImage () - { - return $this->_startImage; - } - /** - * @return int - */ - public function getDotNoiseLevel () - { - return $this->_dotNoiseLevel; - } - /** - * @return int - */ - public function getLineNoiseLevel () - { - return $this->_lineNoiseLevel; - } - /** - * Get captcha expiration - * - * @return int - */ - public function getExpiration() - { - return $this->_expiration; - } - - /** - * Get garbage collection frequency - * - * @return int - */ - public function getGcFreq() - { - return $this->_gcFreq; - } - /** - * Get font to use when generating captcha - * - * @return string - */ - public function getFont() - { - return $this->_font; - } - - /** - * Get font size - * - * @return int - */ - public function getFontSize() - { - return $this->_fsize; - } - - /** - * Get captcha image height - * - * @return int - */ - public function getHeight() - { - return $this->_height; - } - - /** - * Get captcha image directory - * - * @return string - */ - public function getImgDir() - { - return $this->_imgDir; - } - /** - * Get captcha image base URL - * - * @return string - */ - public function getImgUrl() - { - return $this->_imgUrl; - } - /** - * Get captcha image file suffix - * - * @return string - */ - public function getSuffix() - { - return $this->_suffix; - } - /** - * Get captcha image width - * - * @return int - */ - public function getWidth() - { - return $this->_width; - } - - /** - * Set start image - * - * @param string $startImage - * @return Zend_Captcha_Image - */ - public function setStartImage ($startImage) - { - $this->_startImage = $startImage; - return $this; - } - - /** - * Set dot noise level - * - * @param int $dotNoiseLevel - * @return Zend_Captcha_Image - */ - public function setDotNoiseLevel ($dotNoiseLevel) - { - $this->_dotNoiseLevel = $dotNoiseLevel; - return $this; - } - - /** - * Set line noise level - * - * @param int $lineNoiseLevel - * @return Zend_Captcha_Image - */ - public function setLineNoiseLevel ($lineNoiseLevel) - { - $this->_lineNoiseLevel = $lineNoiseLevel; - return $this; - } - - /** - * Set captcha expiration - * - * @param int $expiration - * @return Zend_Captcha_Image - */ - public function setExpiration($expiration) - { - $this->_expiration = $expiration; - return $this; - } - - /** - * Set garbage collection frequency - * - * @param int $gcFreq - * @return Zend_Captcha_Image - */ - public function setGcFreq($gcFreq) - { - $this->_gcFreq = $gcFreq; - return $this; - } - - /** - * Set captcha font - * - * @param string $font - * @return Zend_Captcha_Image - */ - public function setFont($font) - { - $this->_font = $font; - return $this; - } - - /** - * Set captcha font size - * - * @param int $fsize - * @return Zend_Captcha_Image - */ - public function setFontSize($fsize) - { - $this->_fsize = $fsize; - return $this; - } - - /** - * Set captcha image height - * - * @param int $height - * @return Zend_Captcha_Image - */ - public function setHeight($height) - { - $this->_height = $height; - return $this; - } - - /** - * Set captcha image storage directory - * - * @param string $imgDir - * @return Zend_Captcha_Image - */ - public function setImgDir($imgDir) - { - $this->_imgDir = rtrim($imgDir, "/\\") . '/'; - return $this; - } - - /** - * Set captcha image base URL - * - * @param string $imgUrl - * @return Zend_Captcha_Image - */ - public function setImgUrl($imgUrl) - { - $this->_imgUrl = rtrim($imgUrl, "/\\") . '/'; - return $this; - } - - /** - * Set image alternative text - * - * @param string $imgAlt - * @return Zend_Captcha_Image - */ - public function setImgAlt ($imgAlt) - { - $this->_imgAlt = $imgAlt; - return $this; - } - - /** - * Set captch image filename suffix - * - * @param string $suffix - * @return Zend_Captcha_Image - */ - public function setSuffix($suffix) - { - $this->_suffix = $suffix; - return $this; - } - - /** - * Set captcha image width - * - * @param int $width - * @return Zend_Captcha_Image - */ - public function setWidth($width) - { - $this->_width = $width; - return $this; - } - - /** - * Generate random frequency - * - * @return float - */ - protected function _randomFreq() - { - return mt_rand(700000, 1000000) / 15000000; - } - - /** - * Generate random phase - * - * @return float - */ - protected function _randomPhase() - { - // random phase from 0 to pi - return mt_rand(0, 3141592) / 1000000; - } - - /** - * Generate random character size - * - * @return int - */ - protected function _randomSize() - { - return mt_rand(300, 700) / 100; - } - - /** - * Generate captcha - * - * @return string captcha ID - */ - public function generate() - { - $id = parent::generate(); - $tries = 5; - // If there's already such file, try creating a new ID - while($tries-- && file_exists($this->getImgDir() . $id . $this->getSuffix())) { - $id = $this->_generateRandomId(); - $this->_setId($id); - } - $this->_generateImage($id, $this->getWord()); - - if (mt_rand(1, $this->getGcFreq()) == 1) { - $this->_gc(); - } - return $id; - } - - /** - * Generate image captcha - * - * Override this function if you want different image generator - * Wave transform from http://www.captcha.ru/captchas/multiwave/ - * - * @param string $id Captcha ID - * @param string $word Captcha word - * @throws Zend_Captcha_Exception - */ - protected function _generateImage($id, $word) - { - if (!extension_loaded("gd")) { - #require_once 'Zend/Captcha/Exception.php'; - throw new Zend_Captcha_Exception("Image CAPTCHA requires GD extension"); - } - - if (!function_exists("imagepng")) { - #require_once 'Zend/Captcha/Exception.php'; - throw new Zend_Captcha_Exception("Image CAPTCHA requires PNG support"); - } - - if (!function_exists("imageftbbox")) { - #require_once 'Zend/Captcha/Exception.php'; - throw new Zend_Captcha_Exception("Image CAPTCHA requires FT fonts support"); - } - - $font = $this->getFont(); - - if (empty($font)) { - #require_once 'Zend/Captcha/Exception.php'; - throw new Zend_Captcha_Exception("Image CAPTCHA requires font"); - } - - $w = $this->getWidth(); - $h = $this->getHeight(); - $fsize = $this->getFontSize(); - - $img_file = $this->getImgDir() . $id . $this->getSuffix(); - if(empty($this->_startImage)) { - $img = imagecreatetruecolor($w, $h); - } else { - $img = imagecreatefrompng($this->_startImage); - if(!$img) { - #require_once 'Zend/Captcha/Exception.php'; - throw new Zend_Captcha_Exception("Can not load start image"); - } - $w = imagesx($img); - $h = imagesy($img); - } - $text_color = imagecolorallocate($img, 0, 0, 0); - $bg_color = imagecolorallocate($img, 255, 255, 255); - imagefilledrectangle($img, 0, 0, $w-1, $h-1, $bg_color); - $textbox = imageftbbox($fsize, 0, $font, $word); - $x = ($w - ($textbox[2] - $textbox[0])) / 2; - $y = ($h - ($textbox[7] - $textbox[1])) / 2; - imagefttext($img, $fsize, 0, $x, $y, $text_color, $font, $word); - - // generate noise - for ($i=0; $i<$this->_dotNoiseLevel; $i++) { - imagefilledellipse($img, mt_rand(0,$w), mt_rand(0,$h), 2, 2, $text_color); - } - for($i=0; $i<$this->_lineNoiseLevel; $i++) { - imageline($img, mt_rand(0,$w), mt_rand(0,$h), mt_rand(0,$w), mt_rand(0,$h), $text_color); - } - - // transformed image - $img2 = imagecreatetruecolor($w, $h); - $bg_color = imagecolorallocate($img2, 255, 255, 255); - imagefilledrectangle($img2, 0, 0, $w-1, $h-1, $bg_color); - // apply wave transforms - $freq1 = $this->_randomFreq(); - $freq2 = $this->_randomFreq(); - $freq3 = $this->_randomFreq(); - $freq4 = $this->_randomFreq(); - - $ph1 = $this->_randomPhase(); - $ph2 = $this->_randomPhase(); - $ph3 = $this->_randomPhase(); - $ph4 = $this->_randomPhase(); - - $szx = $this->_randomSize(); - $szy = $this->_randomSize(); - - for ($x = 0; $x < $w; $x++) { - for ($y = 0; $y < $h; $y++) { - $sx = $x + (sin($x*$freq1 + $ph1) + sin($y*$freq3 + $ph3)) * $szx; - $sy = $y + (sin($x*$freq2 + $ph2) + sin($y*$freq4 + $ph4)) * $szy; - - if ($sx < 0 || $sy < 0 || $sx >= $w - 1 || $sy >= $h - 1) { - continue; - } else { - $color = (imagecolorat($img, $sx, $sy) >> 16) & 0xFF; - $color_x = (imagecolorat($img, $sx + 1, $sy) >> 16) & 0xFF; - $color_y = (imagecolorat($img, $sx, $sy + 1) >> 16) & 0xFF; - $color_xy = (imagecolorat($img, $sx + 1, $sy + 1) >> 16) & 0xFF; - } - if ($color == 255 && $color_x == 255 && $color_y == 255 && $color_xy == 255) { - // ignore background - continue; - } elseif ($color == 0 && $color_x == 0 && $color_y == 0 && $color_xy == 0) { - // transfer inside of the image as-is - $newcolor = 0; - } else { - // do antialiasing for border items - $frac_x = $sx-floor($sx); - $frac_y = $sy-floor($sy); - $frac_x1 = 1-$frac_x; - $frac_y1 = 1-$frac_y; - - $newcolor = $color * $frac_x1 * $frac_y1 - + $color_x * $frac_x * $frac_y1 - + $color_y * $frac_x1 * $frac_y - + $color_xy * $frac_x * $frac_y; - } - imagesetpixel($img2, $x, $y, imagecolorallocate($img2, $newcolor, $newcolor, $newcolor)); - } - } - - // generate noise - for ($i=0; $i<$this->_dotNoiseLevel; $i++) { - imagefilledellipse($img2, mt_rand(0,$w), mt_rand(0,$h), 2, 2, $text_color); - } - for ($i=0; $i<$this->_lineNoiseLevel; $i++) { - imageline($img2, mt_rand(0,$w), mt_rand(0,$h), mt_rand(0,$w), mt_rand(0,$h), $text_color); - } - - imagepng($img2, $img_file); - imagedestroy($img); - imagedestroy($img2); - } - - /** - * Remove old files from image directory - */ - protected function _gc() - { - $expire = time() - $this->getExpiration(); - $imgdir = $this->getImgDir(); - if(!$imgdir || strlen($imgdir) < 2) { - // safety guard - return; - } - $suffixLength = strlen($this->_suffix); - foreach (new DirectoryIterator($imgdir) as $file) { - if (!$file->isDot() && !$file->isDir()) { - if (file_exists($file->getPathname()) && $file->getMTime() < $expire) { - // only deletes files ending with $this->_suffix - if (substr($file->getFilename(), -($suffixLength)) == $this->_suffix) { - unlink($file->getPathname()); - } - } - } - } - } - - /** - * Display the captcha - * - * @param Zend_View_Interface $view - * @param mixed $element - * @return string - */ - public function render(Zend_View_Interface $view = null, $element = null) - { - $endTag = ' />'; - if (($view instanceof Zend_View_Abstract) && !$view->doctype()->isXhtml()) { - $endTag = '>'; - } - return '' . $this->getImgAlt()
-             . ' 'Missing captcha fields', - self::ERR_CAPTCHA => 'Failed to validate captcha', - self::BAD_CAPTCHA => 'Captcha value is wrong: %value%', - ); - - /** - * Retrieve ReCaptcha Private key - * - * @return string - */ - public function getPrivkey() - { - return $this->getService()->getPrivateKey(); - } - - /** - * Retrieve ReCaptcha Public key - * - * @return string - */ - public function getPubkey() - { - return $this->getService()->getPublicKey(); - } - - /** - * Set ReCaptcha Private key - * - * @param string $privkey - * @return Zend_Captcha_ReCaptcha - */ - public function setPrivkey($privkey) - { - $this->getService()->setPrivateKey($privkey); - return $this; - } - - /** - * Set ReCaptcha public key - * - * @param string $pubkey - * @return Zend_Captcha_ReCaptcha - */ - public function setPubkey($pubkey) - { - $this->getService()->setPublicKey($pubkey); - return $this; - } - - /** - * Constructor - * - * @param array|Zend_Config $options - */ - public function __construct($options = null) - { - $this->setService(new Zend_Service_ReCaptcha()); - $this->_serviceParams = $this->getService()->getParams(); - $this->_serviceOptions = $this->getService()->getOptions(); - - parent::__construct($options); - - if ($options instanceof Zend_Config) { - $options = $options->toArray(); - } - if (!empty($options)) { - $this->setOptions($options); - } - } - - /** - * Set service object - * - * @param Zend_Service_ReCaptcha $service - * @return Zend_Captcha_ReCaptcha - */ - public function setService(Zend_Service_ReCaptcha $service) - { - $this->_service = $service; - return $this; - } - - /** - * Retrieve ReCaptcha service object - * - * @return Zend_Service_ReCaptcha - */ - public function getService() - { - return $this->_service; - } - - /** - * Set option - * - * If option is a service parameter, proxies to the service. The same - * goes for any service options (distinct from service params) - * - * @param string $key - * @param mixed $value - * @return Zend_Captcha_ReCaptcha - */ - public function setOption($key, $value) - { - $service = $this->getService(); - if (isset($this->_serviceParams[$key])) { - $service->setParam($key, $value); - return $this; - } - if (isset($this->_serviceOptions[$key])) { - $service->setOption($key, $value); - return $this; - } - return parent::setOption($key, $value); - } - - /** - * Generate captcha - * - * @see Zend_Form_Captcha_Adapter::generate() - * @return string - */ - public function generate() - { - return ""; - } - - /** - * Validate captcha - * - * @see Zend_Validate_Interface::isValid() - * @param mixed $value - * @param array|null $context - * @return boolean - */ - public function isValid($value, $context = null) - { - if (!is_array($value) && !is_array($context)) { - $this->_error(self::MISSING_VALUE); - return false; - } - - if (!is_array($value) && is_array($context)) { - $value = $context; - } - - if (empty($value[$this->_CHALLENGE]) || empty($value[$this->_RESPONSE])) { - $this->_error(self::MISSING_VALUE); - return false; - } - - $service = $this->getService(); - - $res = $service->verify($value[$this->_CHALLENGE], $value[$this->_RESPONSE]); - - if (!$res) { - $this->_error(self::ERR_CAPTCHA); - return false; - } - - if (!$res->isValid()) { - $this->_error(self::BAD_CAPTCHA, $res->getErrorCode()); - $service->setParam('error', $res->getErrorCode()); - return false; - } - - return true; - } - - /** - * Render captcha - * - * @param Zend_View_Interface $view - * @param mixed $element - * @return string - */ - public function render(Zend_View_Interface $view = null, $element = null) - { - $name = null; - if ($element instanceof Zend_Form_Element) { - $name = $element->getBelongsTo(); - } - return $this->getService()->getHTML($name); - } - - /** - * Get captcha decorator - * - * @return string - */ - public function getDecorator() - { - return "Captcha_ReCaptcha"; - } -} diff --git a/library/Zend/Captcha/Word.php b/library/Zend/Captcha/Word.php deleted file mode 100644 index 528bcc2eac..0000000000 --- a/library/Zend/Captcha/Word.php +++ /dev/null @@ -1,424 +0,0 @@ - 'Empty captcha value', - self::MISSING_ID => 'Captcha ID field is missing', - self::BAD_CAPTCHA => 'Captcha value is wrong', - ); - - /** - * Length of the word to generate - * - * @var integer - */ - protected $_wordlen = 8; - - /** - * Retrieve session class to utilize - * - * @return string - */ - public function getSessionClass() - { - return $this->_sessionClass; - } - - /** - * Set session class for persistence - * - * @param string $_sessionClass - * @return Zend_Captcha_Word - */ - public function setSessionClass($_sessionClass) - { - $this->_sessionClass = $_sessionClass; - return $this; - } - - /** - * Retrieve word length to use when genrating captcha - * - * @return integer - */ - public function getWordlen() - { - return $this->_wordlen; - } - - /** - * Set word length of captcha - * - * @param integer $wordlen - * @return Zend_Captcha_Word - */ - public function setWordlen($wordlen) - { - $this->_wordlen = $wordlen; - return $this; - } - - /** - * Retrieve captcha ID - * - * @return string - */ - public function getId() - { - if (null === $this->_id) { - $this->_setId($this->_generateRandomId()); - } - return $this->_id; - } - - /** - * Set captcha identifier - * - * @param string $id - * @return Zend_Captcha_Word - */ - protected function _setId($id) - { - $this->_id = $id; - return $this; - } - - /** - * Set timeout for session token - * - * @param int $ttl - * @return Zend_Captcha_Word - */ - public function setTimeout($ttl) - { - $this->_timeout = (int) $ttl; - return $this; - } - - /** - * Get session token timeout - * - * @return int - */ - public function getTimeout() - { - return $this->_timeout; - } - - /** - * Sets if session should be preserved on generate() - * - * @param bool $keepSession Should session be kept on generate()? - * @return Zend_Captcha_Word - */ - public function setKeepSession($keepSession) - { - $this->_keepSession = $keepSession; - return $this; - } - - /** - * Numbers should be included in the pattern? - * - * @return bool - */ - public function getUseNumbers() - { - return $this->_useNumbers; - } - - /** - * Set if numbers should be included in the pattern - * - * @param bool $_useNumbers numbers should be included in the pattern? - * @return Zend_Captcha_Word - */ - public function setUseNumbers($_useNumbers) - { - $this->_useNumbers = $_useNumbers; - return $this; - } - - /** - * Get session object - * - * @return Zend_Session_Namespace - */ - public function getSession() - { - if (!isset($this->_session) || (null === $this->_session)) { - $id = $this->getId(); - if (!class_exists($this->_sessionClass)) { - #require_once 'Zend/Loader.php'; - Zend_Loader::loadClass($this->_sessionClass); - } - $this->_session = new $this->_sessionClass('Zend_Form_Captcha_' . $id); - $this->_session->setExpirationHops(1, null, true); - $this->_session->setExpirationSeconds($this->getTimeout()); - } - return $this->_session; - } - - /** - * Set session namespace object - * - * @param Zend_Session_Namespace $session - * @return Zend_Captcha_Word - */ - public function setSession(Zend_Session_Namespace $session) - { - $this->_session = $session; - if ($session) { - $this->_keepSession = true; - } - return $this; - } - - /** - * Get captcha word - * - * @return string - */ - public function getWord() - { - if (empty($this->_word)) { - $session = $this->getSession(); - $this->_word = $session->word; - } - return $this->_word; - } - - /** - * Set captcha word - * - * @param string $word - * @return Zend_Captcha_Word - */ - protected function _setWord($word) - { - $session = $this->getSession(); - $session->word = $word; - $this->_word = $word; - return $this; - } - - /** - * Generate new random word - * - * @return string - */ - protected function _generateWord() - { - $word = ''; - $wordLen = $this->getWordLen(); - $vowels = $this->_useNumbers ? self::$VN : self::$V; - $consonants = $this->_useNumbers ? self::$CN : self::$C; - - $totIndexCon = count($consonants) - 1; - $totIndexVow = count($vowels) - 1; - for ($i=0; $i < $wordLen; $i = $i + 2) { - // generate word with mix of vowels and consonants - $consonant = $consonants[Zend_Crypt_Math::randInteger(0, $totIndexCon, true)]; - $vowel = $vowels[Zend_Crypt_Math::randInteger(0, $totIndexVow, true)]; - $word .= $consonant . $vowel; - } - - if (strlen($word) > $wordLen) { - $word = substr($word, 0, $wordLen); - } - - return $word; - } - - /** - * Generate new session ID and new word - * - * @return string session ID - */ - public function generate() - { - if (!$this->_keepSession) { - $this->_session = null; - } - $id = $this->_generateRandomId(); - $this->_setId($id); - $word = $this->_generateWord(); - $this->_setWord($word); - return $id; - } - - protected function _generateRandomId() - { - return md5(Zend_Crypt_Math::randBytes(32)); - } - - /** - * Validate the word - * - * @see Zend_Validate_Interface::isValid() - * @param mixed $value - * @param array|null $context - * @return boolean - */ - public function isValid($value, $context = null) - { - if (!is_array($value) && !is_array($context)) { - $this->_error(self::MISSING_VALUE); - return false; - } - if (!is_array($value) && is_array($context)) { - $value = $context; - } - - $name = $this->getName(); - - if (isset($value[$name])) { - $value = $value[$name]; - } - - if (!isset($value['input'])) { - $this->_error(self::MISSING_VALUE); - return false; - } - $input = strtolower($value['input']); - $this->_setValue($input); - - if (!isset($value['id'])) { - $this->_error(self::MISSING_ID); - return false; - } - - $this->_id = $value['id']; - if ($input !== $this->getWord()) { - $this->_error(self::BAD_CAPTCHA); - return false; - } - - return true; - } - - /** - * Get captcha decorator - * - * @return string - */ - public function getDecorator() - { - return "Captcha_Word"; - } -} diff --git a/library/Zend/Controller/Action.php b/library/Zend/Controller/Action.php deleted file mode 100644 index 3821a779d2..0000000000 --- a/library/Zend/Controller/Action.php +++ /dev/null @@ -1,798 +0,0 @@ -setRequest($request) - ->setResponse($response) - ->_setInvokeArgs($invokeArgs); - $this->_helper = new Zend_Controller_Action_HelperBroker($this); - $this->init(); - } - - /** - * Initialize object - * - * Called from {@link __construct()} as final step of object instantiation. - * - * @return void - */ - public function init() - { - } - - /** - * Initialize View object - * - * Initializes {@link $view} if not otherwise a Zend_View_Interface. - * - * If {@link $view} is not otherwise set, instantiates a new Zend_View - * object, using the 'views' subdirectory at the same level as the - * controller directory for the current module as the base directory. - * It uses this to set the following: - * - script path = views/scripts/ - * - helper path = views/helpers/ - * - filter path = views/filters/ - * - * @return Zend_View_Interface - * @throws Zend_Controller_Exception if base view directory does not exist - */ - public function initView() - { - if (!$this->getInvokeArg('noViewRenderer') && $this->_helper->hasHelper('viewRenderer')) { - return $this->view; - } - - #require_once 'Zend/View/Interface.php'; - if (isset($this->view) && ($this->view instanceof Zend_View_Interface)) { - return $this->view; - } - - $request = $this->getRequest(); - $module = $request->getModuleName(); - $dirs = $this->getFrontController()->getControllerDirectory(); - if (empty($module) || !isset($dirs[$module])) { - $module = $this->getFrontController()->getDispatcher()->getDefaultModule(); - } - $baseDir = dirname($dirs[$module]) . DIRECTORY_SEPARATOR . 'views'; - if (!file_exists($baseDir) || !is_dir($baseDir)) { - #require_once 'Zend/Controller/Exception.php'; - throw new Zend_Controller_Exception('Missing base view directory ("' . $baseDir . '")'); - } - - #require_once 'Zend/View.php'; - $this->view = new Zend_View(array('basePath' => $baseDir)); - - return $this->view; - } - - /** - * Render a view - * - * Renders a view. By default, views are found in the view script path as - * /.phtml. You may change the script suffix by - * resetting {@link $viewSuffix}. You may omit the controller directory - * prefix by specifying boolean true for $noController. - * - * By default, the rendered contents are appended to the response. You may - * specify the named body content segment to set by specifying a $name. - * - * @see Zend_Controller_Response_Abstract::appendBody() - * @param string|null $action Defaults to action registered in request object - * @param string|null $name Response object named path segment to use; defaults to null - * @param bool $noController Defaults to false; i.e. use controller name as subdir in which to search for view script - * @return void - */ - public function render($action = null, $name = null, $noController = false) - { - if (!$this->getInvokeArg('noViewRenderer') && $this->_helper->hasHelper('viewRenderer')) { - return $this->_helper->viewRenderer->render($action, $name, $noController); - } - - $view = $this->initView(); - $script = $this->getViewScript($action, $noController); - - $this->getResponse()->appendBody( - $view->render($script), - $name - ); - } - - /** - * Render a given view script - * - * Similar to {@link render()}, this method renders a view script. Unlike render(), - * however, it does not autodetermine the view script via {@link getViewScript()}, - * but instead renders the script passed to it. Use this if you know the - * exact view script name and path you wish to use, or if using paths that do not - * conform to the spec defined with getViewScript(). - * - * By default, the rendered contents are appended to the response. You may - * specify the named body content segment to set by specifying a $name. - * - * @param string $script - * @param string $name - * @return void - */ - public function renderScript($script, $name = null) - { - if (!$this->getInvokeArg('noViewRenderer') && $this->_helper->hasHelper('viewRenderer')) { - return $this->_helper->viewRenderer->renderScript($script, $name); - } - - $view = $this->initView(); - $this->getResponse()->appendBody( - $view->render($script), - $name - ); - } - - /** - * Construct view script path - * - * Used by render() to determine the path to the view script. - * - * @param string $action Defaults to action registered in request object - * @param bool $noController Defaults to false; i.e. use controller name as subdir in which to search for view script - * @return string - * @throws Zend_Controller_Exception with bad $action - */ - public function getViewScript($action = null, $noController = null) - { - if (!$this->getInvokeArg('noViewRenderer') && $this->_helper->hasHelper('viewRenderer')) { - $viewRenderer = $this->_helper->getHelper('viewRenderer'); - if (null !== $noController) { - $viewRenderer->setNoController($noController); - } - return $viewRenderer->getViewScript($action); - } - - $request = $this->getRequest(); - if (null === $action) { - $action = $request->getActionName(); - } elseif (!is_string($action)) { - #require_once 'Zend/Controller/Exception.php'; - throw new Zend_Controller_Exception('Invalid action specifier for view render'); - } - - if (null === $this->_delimiters) { - $dispatcher = Zend_Controller_Front::getInstance()->getDispatcher(); - $wordDelimiters = $dispatcher->getWordDelimiter(); - $pathDelimiters = $dispatcher->getPathDelimiter(); - $this->_delimiters = array_unique(array_merge($wordDelimiters, (array) $pathDelimiters)); - } - - $action = str_replace($this->_delimiters, '-', $action); - $script = $action . '.' . $this->viewSuffix; - - if (!$noController) { - $controller = $request->getControllerName(); - $controller = str_replace($this->_delimiters, '-', $controller); - $script = $controller . DIRECTORY_SEPARATOR . $script; - } - - return $script; - } - - /** - * Return the Request object - * - * @return Zend_Controller_Request_Abstract - */ - public function getRequest() - { - return $this->_request; - } - - /** - * Set the Request object - * - * @param Zend_Controller_Request_Abstract $request - * @return Zend_Controller_Action - */ - public function setRequest(Zend_Controller_Request_Abstract $request) - { - $this->_request = $request; - return $this; - } - - /** - * Return the Response object - * - * @return Zend_Controller_Response_Abstract - */ - public function getResponse() - { - return $this->_response; - } - - /** - * Set the Response object - * - * @param Zend_Controller_Response_Abstract $response - * @return Zend_Controller_Action - */ - public function setResponse(Zend_Controller_Response_Abstract $response) - { - $this->_response = $response; - return $this; - } - - /** - * Set invocation arguments - * - * @param array $args - * @return Zend_Controller_Action - */ - protected function _setInvokeArgs(array $args = array()) - { - $this->_invokeArgs = $args; - return $this; - } - - /** - * Return the array of constructor arguments (minus the Request object) - * - * @return array - */ - public function getInvokeArgs() - { - return $this->_invokeArgs; - } - - /** - * Return a single invocation argument - * - * @param string $key - * @return mixed - */ - public function getInvokeArg($key) - { - if (isset($this->_invokeArgs[$key])) { - return $this->_invokeArgs[$key]; - } - - return null; - } - - /** - * Get a helper by name - * - * @param string $helperName - * @return Zend_Controller_Action_Helper_Abstract - */ - public function getHelper($helperName) - { - return $this->_helper->{$helperName}; - } - - /** - * Get a clone of a helper by name - * - * @param string $helperName - * @return Zend_Controller_Action_Helper_Abstract - */ - public function getHelperCopy($helperName) - { - return clone $this->_helper->{$helperName}; - } - - /** - * Set the front controller instance - * - * @param Zend_Controller_Front $front - * @return Zend_Controller_Action - */ - public function setFrontController(Zend_Controller_Front $front) - { - $this->_frontController = $front; - return $this; - } - - /** - * Retrieve Front Controller - * - * @return Zend_Controller_Front - */ - public function getFrontController() - { - // Used cache version if found - if (null !== $this->_frontController) { - return $this->_frontController; - } - - // Grab singleton instance, if class has been loaded - if (class_exists('Zend_Controller_Front')) { - $this->_frontController = Zend_Controller_Front::getInstance(); - return $this->_frontController; - } - - // Throw exception in all other cases - #require_once 'Zend/Controller/Exception.php'; - throw new Zend_Controller_Exception('Front controller class has not been loaded'); - } - - /** - * Pre-dispatch routines - * - * Called before action method. If using class with - * {@link Zend_Controller_Front}, it may modify the - * {@link $_request Request object} and reset its dispatched flag in order - * to skip processing the current action. - * - * @return void - */ - public function preDispatch() - { - } - - /** - * Post-dispatch routines - * - * Called after action method execution. If using class with - * {@link Zend_Controller_Front}, it may modify the - * {@link $_request Request object} and reset its dispatched flag in order - * to process an additional action. - * - * Common usages for postDispatch() include rendering content in a sitewide - * template, link url correction, setting headers, etc. - * - * @return void - */ - public function postDispatch() - { - } - - /** - * Proxy for undefined methods. Default behavior is to throw an - * exception on undefined methods, however this function can be - * overridden to implement magic (dynamic) actions, or provide run-time - * dispatching. - * - * @param string $methodName - * @param array $args - * @return void - * @throws Zend_Controller_Action_Exception - */ - public function __call($methodName, $args) - { - #require_once 'Zend/Controller/Action/Exception.php'; - if ('Action' == substr($methodName, -6)) { - $action = substr($methodName, 0, strlen($methodName) - 6); - throw new Zend_Controller_Action_Exception(sprintf('Action "%s" does not exist and was not trapped in __call()', $action), 404); - } - - throw new Zend_Controller_Action_Exception(sprintf('Method "%s" does not exist and was not trapped in __call()', $methodName), 500); - } - - /** - * Dispatch the requested action - * - * @param string $action Method name of action - * @return void - */ - public function dispatch($action) - { - // Notify helpers of action preDispatch state - $this->_helper->notifyPreDispatch(); - - $this->preDispatch(); - if ($this->getRequest()->isDispatched()) { - if (null === $this->_classMethods) { - $this->_classMethods = get_class_methods($this); - } - - // If pre-dispatch hooks introduced a redirect then stop dispatch - // @see ZF-7496 - if (!($this->getResponse()->isRedirect())) { - // preDispatch() didn't change the action, so we can continue - if ($this->getInvokeArg('useCaseSensitiveActions') || in_array($action, $this->_classMethods)) { - if ($this->getInvokeArg('useCaseSensitiveActions')) { - trigger_error('Using case sensitive actions without word separators is deprecated; please do not rely on this "feature"'); - } - $this->$action(); - } else { - $this->__call($action, array()); - } - } - $this->postDispatch(); - } - - // whats actually important here is that this action controller is - // shutting down, regardless of dispatching; notify the helpers of this - // state - $this->_helper->notifyPostDispatch(); - } - - /** - * Call the action specified in the request object, and return a response - * - * Not used in the Action Controller implementation, but left for usage in - * Page Controller implementations. Dispatches a method based on the - * request. - * - * Returns a Zend_Controller_Response_Abstract object, instantiating one - * prior to execution if none exists in the controller. - * - * {@link preDispatch()} is called prior to the action, - * {@link postDispatch()} is called following it. - * - * @param null|Zend_Controller_Request_Abstract $request Optional request - * object to use - * @param null|Zend_Controller_Response_Abstract $response Optional response - * object to use - * @return Zend_Controller_Response_Abstract - */ - public function run(Zend_Controller_Request_Abstract $request = null, Zend_Controller_Response_Abstract $response = null) - { - if (null !== $request) { - $this->setRequest($request); - } else { - $request = $this->getRequest(); - } - - if (null !== $response) { - $this->setResponse($response); - } - - $action = $request->getActionName(); - if (empty($action)) { - $action = 'index'; - } - $action = $action . 'Action'; - - $request->setDispatched(true); - $this->dispatch($action); - - return $this->getResponse(); - } - - /** - * Gets a parameter from the {@link $_request Request object}. If the - * parameter does not exist, NULL will be returned. - * - * If the parameter does not exist and $default is set, then - * $default will be returned instead of NULL. - * - * @param string $paramName - * @param mixed $default - * @return mixed - */ - protected function _getParam($paramName, $default = null) - { - return $this->getParam($paramName, $default); - } - - /** - * Gets a parameter from the {@link $_request Request object}. If the - * parameter does not exist, NULL will be returned. - * - * If the parameter does not exist and $default is set, then - * $default will be returned instead of NULL. - * - * @param string $paramName - * @param mixed $default - * @return mixed - */ - public function getParam($paramName, $default = null) - { - $value = $this->getRequest()->getParam($paramName); - if ((null === $value || '' === $value) && (null !== $default)) { - $value = $default; - } - - return $value; - } - - /** - * Set a parameter in the {@link $_request Request object}. - * - * @param string $paramName - * @param mixed $value - * @return Zend_Controller_Action - * @deprecated Deprecated as of Zend Framework 1.7. Use - * setParam() instead. - */ - protected function _setParam($paramName, $value) - { - return $this->setParam($paramName, $value); - } - - /** - * Set a parameter in the {@link $_request Request object}. - * - * @param string $paramName - * @param mixed $value - * @return Zend_Controller_Action - */ - public function setParam($paramName, $value) - { - $this->getRequest()->setParam($paramName, $value); - - return $this; - } - - /** - * Determine whether a given parameter exists in the - * {@link $_request Request object}. - * - * @param string $paramName - * @return boolean - * @deprecated Deprecated as of Zend Framework 1.7. Use - * hasParam() instead. - */ - protected function _hasParam($paramName) - { - return $this->hasParam($paramName); - } - - /** - * Determine whether a given parameter exists in the - * {@link $_request Request object}. - * - * @param string $paramName - * @return boolean - */ - public function hasParam($paramName) - { - return null !== $this->getRequest()->getParam($paramName); - } - - /** - * Return all parameters in the {@link $_request Request object} - * as an associative array. - * - * @return array - * @deprecated Deprecated as of Zend Framework 1.7. Use - * getAllParams() instead. - */ - protected function _getAllParams() - { - return $this->getAllParams(); - } - - /** - * Return all parameters in the {@link $_request Request object} - * as an associative array. - * - * @return array - */ - public function getAllParams() - { - return $this->getRequest()->getParams(); - } - - - /** - * Forward to another controller/action. - * - * It is important to supply the unformatted names, i.e. "article" - * rather than "ArticleController". The dispatcher will do the - * appropriate formatting when the request is received. - * - * If only an action name is provided, forwards to that action in this - * controller. - * - * If an action and controller are specified, forwards to that action and - * controller in this module. - * - * Specifying an action, controller, and module is the most specific way to - * forward. - * - * A fourth argument, $params, will be used to set the request parameters. - * If either the controller or module are unnecessary for forwarding, - * simply pass null values for them before specifying the parameters. - * - * @param string $action - * @param string $controller - * @param string $module - * @param array $params - * @return void - * @deprecated Deprecated as of Zend Framework 1.7. Use - * forward() instead. - */ - final protected function _forward($action, $controller = null, $module = null, array $params = null) - { - $this->forward($action, $controller, $module, $params); - } - - /** - * Forward to another controller/action. - * - * It is important to supply the unformatted names, i.e. "article" - * rather than "ArticleController". The dispatcher will do the - * appropriate formatting when the request is received. - * - * If only an action name is provided, forwards to that action in this - * controller. - * - * If an action and controller are specified, forwards to that action and - * controller in this module. - * - * Specifying an action, controller, and module is the most specific way to - * forward. - * - * A fourth argument, $params, will be used to set the request parameters. - * If either the controller or module are unnecessary for forwarding, - * simply pass null values for them before specifying the parameters. - * - * @param string $action - * @param string $controller - * @param string $module - * @param array $params - * @return void - */ - final public function forward($action, $controller = null, $module = null, array $params = null) - { - $request = $this->getRequest(); - - if (null !== $params) { - $request->setParams($params); - } - - if (null !== $controller) { - $request->setControllerName($controller); - - // Module should only be reset if controller has been specified - if (null !== $module) { - $request->setModuleName($module); - } - } - - $request->setActionName($action) - ->setDispatched(false); - } - - /** - * Redirect to another URL - * - * Proxies to {@link Zend_Controller_Action_Helper_Redirector::gotoUrl()}. - * - * @param string $url - * @param array $options Options to be used when redirecting - * @return void - * @deprecated Deprecated as of Zend Framework 1.7. Use - * redirect() instead. - */ - protected function _redirect($url, array $options = array()) - { - $this->redirect($url, $options); - } - - /** - * Redirect to another URL - * - * Proxies to {@link Zend_Controller_Action_Helper_Redirector::gotoUrl()}. - * - * @param string $url - * @param array $options Options to be used when redirecting - * @return void - */ - public function redirect($url, array $options = array()) - { - $this->_helper->redirector->gotoUrl($url, $options); - } -} diff --git a/library/Zend/Controller/Action/Exception.php b/library/Zend/Controller/Action/Exception.php deleted file mode 100644 index 5c3a23afce..0000000000 --- a/library/Zend/Controller/Action/Exception.php +++ /dev/null @@ -1,38 +0,0 @@ -_actionController = $actionController; - return $this; - } - - /** - * Retrieve current action controller - * - * @return Zend_Controller_Action - */ - public function getActionController() - { - return $this->_actionController; - } - - /** - * Retrieve front controller instance - * - * @return Zend_Controller_Front - */ - public function getFrontController() - { - return Zend_Controller_Front::getInstance(); - } - - /** - * Hook into action controller initialization - * - * @return void - */ - public function init() - { - } - - /** - * Hook into action controller preDispatch() workflow - * - * @return void - */ - public function preDispatch() - { - } - - /** - * Hook into action controller postDispatch() workflow - * - * @return void - */ - public function postDispatch() - { - } - - /** - * getRequest() - - * - * @return Zend_Controller_Request_Abstract $request - */ - public function getRequest() - { - $controller = $this->getActionController(); - if (null === $controller) { - $controller = $this->getFrontController(); - } - - return $controller->getRequest(); - } - - /** - * getResponse() - - * - * @return Zend_Controller_Response_Abstract $response - */ - public function getResponse() - { - $controller = $this->getActionController(); - if (null === $controller) { - $controller = $this->getFrontController(); - } - - return $controller->getResponse(); - } - - /** - * getName() - * - * @return string - */ - public function getName() - { - $fullClassName = get_class($this); - if (strpos($fullClassName, '_') !== false) { - $helperName = strrchr($fullClassName, '_'); - return ltrim($helperName, '_'); - } elseif (strpos($fullClassName, '\\') !== false) { - $helperName = strrchr($fullClassName, '\\'); - return ltrim($helperName, '\\'); - } else { - return $fullClassName; - } - } -} diff --git a/library/Zend/Controller/Action/Helper/ActionStack.php b/library/Zend/Controller/Action/Helper/ActionStack.php deleted file mode 100644 index 75dd0ae2bb..0000000000 --- a/library/Zend/Controller/Action/Helper/ActionStack.php +++ /dev/null @@ -1,138 +0,0 @@ -hasPlugin('Zend_Controller_Plugin_ActionStack')) { - /** - * @see Zend_Controller_Plugin_ActionStack - */ - #require_once 'Zend/Controller/Plugin/ActionStack.php'; - $this->_actionStack = new Zend_Controller_Plugin_ActionStack(); - $front->registerPlugin($this->_actionStack, 97); - } else { - $this->_actionStack = $front->getPlugin('Zend_Controller_Plugin_ActionStack'); - } - } - - /** - * Push onto the stack - * - * @param Zend_Controller_Request_Abstract $next - * @return Zend_Controller_Action_Helper_ActionStack Provides a fluent interface - */ - public function pushStack(Zend_Controller_Request_Abstract $next) - { - $this->_actionStack->pushStack($next); - return $this; - } - - /** - * Push a new action onto the stack - * - * @param string $action - * @param string $controller - * @param string $module - * @param array $params - * @throws Zend_Controller_Action_Exception - * @return Zend_Controller_Action_Helper_ActionStack - */ - public function actionToStack($action, $controller = null, $module = null, array $params = array()) - { - if ($action instanceof Zend_Controller_Request_Abstract) { - return $this->pushStack($action); - } elseif (!is_string($action)) { - /** - * @see Zend_Controller_Action_Exception - */ - #require_once 'Zend/Controller/Action/Exception.php'; - throw new Zend_Controller_Action_Exception('ActionStack requires either a request object or minimally a string action'); - } - - $request = $this->getRequest(); - - if ($request instanceof Zend_Controller_Request_Abstract === false){ - /** - * @see Zend_Controller_Action_Exception - */ - #require_once 'Zend/Controller/Action/Exception.php'; - throw new Zend_Controller_Action_Exception('Request object not set yet'); - } - - $controller = (null === $controller) ? $request->getControllerName() : $controller; - $module = (null === $module) ? $request->getModuleName() : $module; - - /** - * @see Zend_Controller_Request_Simple - */ - #require_once 'Zend/Controller/Request/Simple.php'; - $newRequest = new Zend_Controller_Request_Simple($action, $controller, $module, $params); - - return $this->pushStack($newRequest); - } - - /** - * Perform helper when called as $this->_helper->actionStack() from an action controller - * - * Proxies to {@link simple()} - * - * @param string $action - * @param string $controller - * @param string $module - * @param array $params - * @return boolean - */ - public function direct($action, $controller = null, $module = null, array $params = array()) - { - return $this->actionToStack($action, $controller, $module, $params); - } -} diff --git a/library/Zend/Controller/Action/Helper/AjaxContext.php b/library/Zend/Controller/Action/Helper/AjaxContext.php deleted file mode 100644 index 3b6e4bbaa4..0000000000 --- a/library/Zend/Controller/Action/Helper/AjaxContext.php +++ /dev/null @@ -1,80 +0,0 @@ -addContext('html', array('suffix' => 'ajax')); - } - - /** - * Initialize AJAX context switching - * - * Checks for XHR requests; if detected, attempts to perform context switch. - * - * @param string $format - * @return void - */ - public function initContext($format = null) - { - $this->_currentContext = null; - - $request = $this->getRequest(); - if (!method_exists($request, 'isXmlHttpRequest') || - !$this->getRequest()->isXmlHttpRequest()) - { - return; - } - - return parent::initContext($format); - } -} diff --git a/library/Zend/Controller/Action/Helper/AutoComplete/Abstract.php b/library/Zend/Controller/Action/Helper/AutoComplete/Abstract.php deleted file mode 100644 index 6b550a3b32..0000000000 --- a/library/Zend/Controller/Action/Helper/AutoComplete/Abstract.php +++ /dev/null @@ -1,149 +0,0 @@ -disableLayout(); - } - - Zend_Controller_Action_HelperBroker::getStaticHelper('viewRenderer')->setNoRender(true); - - return $this; - } - - /** - * Encode data to JSON - * - * @param mixed $data - * @param bool $keepLayouts - * @throws Zend_Controller_Action_Exception - * @return string - */ - public function encodeJson($data, $keepLayouts = false) - { - if ($this->validateData($data)) { - return Zend_Controller_Action_HelperBroker::getStaticHelper('Json')->encodeJson($data, $keepLayouts); - } - - /** - * @see Zend_Controller_Action_Exception - */ - #require_once 'Zend/Controller/Action/Exception.php'; - throw new Zend_Controller_Action_Exception('Invalid data passed for autocompletion'); - } - - /** - * Send autocompletion data - * - * Calls prepareAutoCompletion, populates response body with this - * information, and sends response. - * - * @param mixed $data - * @param bool $keepLayouts - * @return string|void - */ - public function sendAutoCompletion($data, $keepLayouts = false) - { - $data = $this->prepareAutoCompletion($data, $keepLayouts); - - $response = $this->getResponse(); - $response->setBody($data); - - if (!$this->suppressExit) { - $response->sendResponse(); - exit; - } - - return $data; - } - - /** - * Strategy pattern: allow calling helper as broker method - * - * Prepares autocompletion data and, if $sendNow is true, immediately sends - * response. - * - * @param mixed $data - * @param bool $sendNow - * @param bool $keepLayouts - * @return string|void - */ - public function direct($data, $sendNow = true, $keepLayouts = false) - { - if ($sendNow) { - return $this->sendAutoCompletion($data, $keepLayouts); - } - - return $this->prepareAutoCompletion($data, $keepLayouts); - } -} diff --git a/library/Zend/Controller/Action/Helper/AutoCompleteDojo.php b/library/Zend/Controller/Action/Helper/AutoCompleteDojo.php deleted file mode 100644 index 8c8a764c7a..0000000000 --- a/library/Zend/Controller/Action/Helper/AutoCompleteDojo.php +++ /dev/null @@ -1,87 +0,0 @@ - $value) { - $items[] = array('label' => $value, 'name' => $value); - } - $data = new Zend_Dojo_Data('name', $items); - } - - if (!$keepLayouts) { - #require_once 'Zend/Controller/Action/HelperBroker.php'; - Zend_Controller_Action_HelperBroker::getStaticHelper('viewRenderer')->setNoRender(true); - - #require_once 'Zend/Layout.php'; - $layout = Zend_Layout::getMvcInstance(); - if ($layout instanceof Zend_Layout) { - $layout->disableLayout(); - } - } - - $response = Zend_Controller_Front::getInstance()->getResponse(); - $response->setHeader('Content-Type', 'application/json'); - - return $data->toJson(); - } -} diff --git a/library/Zend/Controller/Action/Helper/AutoCompleteScriptaculous.php b/library/Zend/Controller/Action/Helper/AutoCompleteScriptaculous.php deleted file mode 100644 index d7d5e1e17a..0000000000 --- a/library/Zend/Controller/Action/Helper/AutoCompleteScriptaculous.php +++ /dev/null @@ -1,82 +0,0 @@ -validateData($data)) { - /** - * @see Zend_Controller_Action_Exception - */ - #require_once 'Zend/Controller/Action/Exception.php'; - throw new Zend_Controller_Action_Exception('Invalid data passed for autocompletion'); - } - - $data = (array) $data; - $data = '
  • ' . implode('
  • ', $data) . '
'; - - if (!$keepLayouts) { - $this->disableLayouts(); - } - - return $data; - } -} diff --git a/library/Zend/Controller/Action/Helper/Cache.php b/library/Zend/Controller/Action/Helper/Cache.php deleted file mode 100644 index ee9ed61b6d..0000000000 --- a/library/Zend/Controller/Action/Helper/Cache.php +++ /dev/null @@ -1,289 +0,0 @@ -getRequest()->getControllerName(); - $actions = array_unique($actions); - if (!isset($this->_caching[$controller])) { - $this->_caching[$controller] = array(); - } - if (!empty($tags)) { - $tags = array_unique($tags); - if (!isset($this->_tags[$controller])) { - $this->_tags[$controller] = array(); - } - } - foreach ($actions as $action) { - $this->_caching[$controller][] = $action; - if (!empty($tags)) { - $this->_tags[$controller][$action] = array(); - foreach ($tags as $tag) { - $this->_tags[$controller][$action][] = $tag; - } - } - } - if ($extension) { - if (!isset($this->_extensions[$controller])) { - $this->_extensions[$controller] = array(); - } - foreach ($actions as $action) { - $this->_extensions[$controller][$action] = $extension; - } - } - } - - /** - * Remove a specific page cache static file based on its - * relative URL from the application's public directory. - * The file extension is not required here; usually matches - * the original REQUEST_URI that was cached. - * - * @param string $relativeUrl - * @param bool $recursive - * @return mixed - */ - public function removePage($relativeUrl, $recursive = false) - { - $cache = $this->getCache(Zend_Cache_Manager::PAGECACHE); - $encodedCacheId = $this->_encodeCacheId($relativeUrl); - - if ($recursive) { - $backend = $cache->getBackend(); - if (($backend instanceof Zend_Cache_Backend) - && method_exists($backend, 'removeRecursively') - ) { - $result = $backend->removeRecursively($encodedCacheId); - if (is_null($result) ) { - $result = $backend->removeRecursively($relativeUrl); - } - return $result; - } - } - - $result = $cache->remove($encodedCacheId); - if (is_null($result) ) { - $result = $cache->remove($relativeUrl); - } - return $result; - } - - /** - * Remove a specific page cache static file based on its - * relative URL from the application's public directory. - * The file extension is not required here; usually matches - * the original REQUEST_URI that was cached. - * - * @param array $tags - * @return mixed - */ - public function removePagesTagged(array $tags) - { - return $this->getCache(Zend_Cache_Manager::PAGECACHE) - ->clean(Zend_Cache::CLEANING_MODE_MATCHING_ANY_TAG, $tags); - } - - /** - * Commence page caching for any cacheable actions - * - * @return void - */ - public function preDispatch() - { - $controller = $this->getRequest()->getControllerName(); - $action = $this->getRequest()->getActionName(); - $stats = ob_get_status(true); - foreach ($stats as $status) { - if ($status['name'] == 'Zend_Cache_Frontend_Page::_flush' - || $status['name'] == 'Zend_Cache_Frontend_Capture::_flush') { - $obStarted = true; - } - } - if (!isset($obStarted) && isset($this->_caching[$controller]) && - in_array($action, $this->_caching[$controller])) { - $reqUri = $this->getRequest()->getRequestUri(); - $tags = array(); - if (isset($this->_tags[$controller][$action]) - && !empty($this->_tags[$controller][$action])) { - $tags = array_unique($this->_tags[$controller][$action]); - } - $extension = null; - if (isset($this->_extensions[$controller][$action])) { - $extension = $this->_extensions[$controller][$action]; - } - $this->getCache(Zend_Cache_Manager::PAGECACHE) - ->start($this->_encodeCacheId($reqUri), $tags, $extension); - } - } - - /** - * Encode a Cache ID as hexadecimal. This is a workaround because Backend ID validation - * is trapped in the Frontend classes. Will try to get this reversed for ZF 2.0 - * because it's a major annoyance to have IDs so restricted! - * - * @return string - * @param string $requestUri - */ - protected function _encodeCacheId($requestUri) - { - return bin2hex($requestUri); - } - - /** - * Set an instance of the Cache Manager for this helper - * - * @param Zend_Cache_Manager $manager - * @return void - */ - public function setManager(Zend_Cache_Manager $manager) - { - $this->_manager = $manager; - return $this; - } - - /** - * Get the Cache Manager instance or instantiate the object if not - * exists. Attempts to load from bootstrap if available. - * - * @return Zend_Cache_Manager - */ - public function getManager() - { - if ($this->_manager !== null) { - return $this->_manager; - } - $front = Zend_Controller_Front::getInstance(); - if ($front->getParam('bootstrap') - && $front->getParam('bootstrap')->getResource('CacheManager')) { - return $front->getParam('bootstrap') - ->getResource('CacheManager'); - } - $this->_manager = new Zend_Cache_Manager; - return $this->_manager; - } - - /** - * Return a list of actions for the current Controller marked for - * caching - * - * @return array - */ - public function getCacheableActions() - { - return $this->_caching; - } - - /** - * Return a list of tags set for all cacheable actions - * - * @return array - */ - public function getCacheableTags() - { - return $this->_tags; - } - - /** - * Proxy non-matched methods back to Zend_Cache_Manager where - * appropriate - * - * @param string $method - * @param array $args - * @return mixed - */ - public function __call($method, $args) - { - if (method_exists($this->getManager(), $method)) { - return call_user_func_array( - array($this->getManager(), $method), $args - ); - } - throw new Zend_Controller_Action_Exception('Method does not exist:' - . $method); - } - -} diff --git a/library/Zend/Controller/Action/Helper/ContextSwitch.php b/library/Zend/Controller/Action/Helper/ContextSwitch.php deleted file mode 100644 index 608a80e1bd..0000000000 --- a/library/Zend/Controller/Action/Helper/ContextSwitch.php +++ /dev/null @@ -1,1394 +0,0 @@ -setConfig($options); - } elseif (is_array($options)) { - $this->setOptions($options); - } - - if (empty($this->_contexts)) { - $this->addContexts(array( - 'json' => array( - 'suffix' => 'json', - 'headers' => array('Content-Type' => 'application/json'), - 'callbacks' => array( - 'init' => 'initJsonContext', - 'post' => 'postJsonContext' - ) - ), - 'xml' => array( - 'suffix' => 'xml', - 'headers' => array('Content-Type' => 'application/xml'), - ) - )); - } - - $this->init(); - } - - /** - * Initialize at start of action controller - * - * Reset the view script suffix to the original state, or store the - * original state. - * - * @return void - */ - public function init() - { - if (null === $this->_viewSuffixOrig) { - $this->_viewSuffixOrig = $this->_getViewRenderer()->getViewSuffix(); - } else { - $this->_getViewRenderer()->setViewSuffix($this->_viewSuffixOrig); - } - } - - /** - * Configure object from array of options - * - * @param array $options - * @return Zend_Controller_Action_Helper_ContextSwitch Provides a fluent interface - */ - public function setOptions(array $options) - { - if (isset($options['contexts'])) { - $this->setContexts($options['contexts']); - unset($options['contexts']); - } - - foreach ($options as $key => $value) { - $method = 'set' . ucfirst($key); - if (in_array($method, $this->_unconfigurable)) { - continue; - } - - if (in_array($method, $this->_specialConfig)) { - $method = '_' . $method; - } - - if (method_exists($this, $method)) { - $this->$method($value); - } - } - return $this; - } - - /** - * Set object state from config object - * - * @param Zend_Config $config - * @return Zend_Controller_Action_Helper_ContextSwitch Provides a fluent interface - */ - public function setConfig(Zend_Config $config) - { - return $this->setOptions($config->toArray()); - } - - /** - * Strategy pattern: return object - * - * @return Zend_Controller_Action_Helper_ContextSwitch Provides a fluent interface - */ - public function direct() - { - return $this; - } - - /** - * Initialize context detection and switching - * - * @param mixed $format - * @throws Zend_Controller_Action_Exception - * @return void - */ - public function initContext($format = null) - { - $this->_currentContext = null; - - $controller = $this->getActionController(); - $request = $this->getRequest(); - $action = $request->getActionName(); - - // Return if no context switching enabled, or no context switching - // enabled for this action - $contexts = $this->getActionContexts($action); - if (empty($contexts)) { - return; - } - - // Return if no context parameter provided - if (!$context = $request->getParam($this->getContextParam())) { - if ($format === null) { - return; - } - $context = $format; - $format = null; - } - - // Check if context allowed by action controller - if (!$this->hasActionContext($action, $context)) { - return; - } - - // Return if invalid context parameter provided and no format or invalid - // format provided - if (!$this->hasContext($context)) { - if (empty($format) || !$this->hasContext($format)) { - - return; - } - } - - // Use provided format if passed - if (!empty($format) && $this->hasContext($format)) { - $context = $format; - } - - $suffix = $this->getSuffix($context); - - $this->_getViewRenderer()->setViewSuffix($suffix); - - $headers = $this->getHeaders($context); - if (!empty($headers)) { - $response = $this->getResponse(); - foreach ($headers as $header => $content) { - $response->setHeader($header, $content); - } - } - - if ($this->getAutoDisableLayout()) { - /** - * @see Zend_Layout - */ - #require_once 'Zend/Layout.php'; - $layout = Zend_Layout::getMvcInstance(); - if (null !== $layout) { - $layout->disableLayout(); - } - } - - if (null !== ($callback = $this->getCallback($context, self::TRIGGER_INIT))) { - if (is_string($callback) && method_exists($this, $callback)) { - $this->$callback(); - } elseif (is_string($callback) && function_exists($callback)) { - $callback(); - } elseif (is_array($callback)) { - call_user_func($callback); - } else { - /** - * @see Zend_Controller_Action_Exception - */ - #require_once 'Zend/Controller/Action/Exception.php'; - throw new Zend_Controller_Action_Exception(sprintf('Invalid context callback registered for context "%s"', $context)); - } - } - - $this->_currentContext = $context; - } - - /** - * JSON context extra initialization - * - * Turns off viewRenderer auto-rendering - * - * @return void - */ - public function initJsonContext() - { - if (!$this->getAutoJsonSerialization()) { - return; - } - - $viewRenderer = Zend_Controller_Action_HelperBroker::getStaticHelper('viewRenderer'); - $view = $viewRenderer->view; - if ($view instanceof Zend_View_Interface) { - $viewRenderer->setNoRender(true); - } - } - - /** - * Should JSON contexts auto-serialize? - * - * @param boolean $flag - * @return Zend_Controller_Action_Helper_ContextSwitch Provides a fluent interface - */ - public function setAutoJsonSerialization($flag) - { - $this->_autoJsonSerialization = (bool) $flag; - return $this; - } - - /** - * Get JSON context auto-serialization flag - * - * @return boolean - */ - public function getAutoJsonSerialization() - { - return $this->_autoJsonSerialization; - } - - /** - * Set suffix from array - * - * @param array $spec - * @return Zend_Controller_Action_Helper_ContextSwitch Provides a fluent interface - */ - protected function _setSuffix(array $spec) - { - foreach ($spec as $context => $suffixInfo) { - if (!is_string($context)) { - $context = null; - } - - if (is_string($suffixInfo)) { - $this->setSuffix($context, $suffixInfo); - continue; - } elseif (is_array($suffixInfo)) { - if (isset($suffixInfo['suffix'])) { - $suffix = $suffixInfo['suffix']; - $prependViewRendererSuffix = true; - - if ((null === $context) && isset($suffixInfo['context'])) { - $context = $suffixInfo['context']; - } - - if (isset($suffixInfo['prependViewRendererSuffix'])) { - $prependViewRendererSuffix = $suffixInfo['prependViewRendererSuffix']; - } - - $this->setSuffix($context, $suffix, $prependViewRendererSuffix); - continue; - } - - $count = count($suffixInfo); - switch (true) { - case (($count < 2) && (null === $context)): - /** - * @see Zend_Controller_Action_Exception - */ - #require_once 'Zend/Controller/Action/Exception.php'; - throw new Zend_Controller_Action_Exception('Invalid suffix information provided in config'); - case ($count < 2): - $suffix = array_shift($suffixInfo); - $this->setSuffix($context, $suffix); - break; - case (($count < 3) && (null === $context)): - $context = array_shift($suffixInfo); - $suffix = array_shift($suffixInfo); - $this->setSuffix($context, $suffix); - break; - case (($count == 3) && (null === $context)): - $context = array_shift($suffixInfo); - $suffix = array_shift($suffixInfo); - $prependViewRendererSuffix = array_shift($suffixInfo); - $this->setSuffix($context, $suffix, $prependViewRendererSuffix); - break; - case ($count >= 2): - $suffix = array_shift($suffixInfo); - $prependViewRendererSuffix = array_shift($suffixInfo); - $this->setSuffix($context, $suffix, $prependViewRendererSuffix); - break; - } - } - } - return $this; - } - - /** - * Customize view script suffix to use when switching context. - * - * Passing an empty suffix value to the setters disables the view script - * suffix change. - * - * @param string $context Context type for which to set suffix - * @param string $suffix Suffix to use - * @param boolean $prependViewRendererSuffix Whether or not to prepend the new suffix to the viewrenderer suffix - * @throws Zend_Controller_Action_Exception - * @return Zend_Controller_Action_Helper_ContextSwitch Provides a fluent interface - */ - public function setSuffix($context, $suffix, $prependViewRendererSuffix = true) - { - if (!isset($this->_contexts[$context])) { - /** - * @see Zend_Controller_Action_Exception - */ - #require_once 'Zend/Controller/Action/Exception.php'; - throw new Zend_Controller_Action_Exception(sprintf('Cannot set suffix; invalid context type "%s"', $context)); - } - - if (empty($suffix)) { - $suffix = ''; - } - - if (is_array($suffix)) { - if (isset($suffix['prependViewRendererSuffix'])) { - $prependViewRendererSuffix = $suffix['prependViewRendererSuffix']; - } - if (isset($suffix['suffix'])) { - $suffix = $suffix['suffix']; - } else { - $suffix = ''; - } - } - - $suffix = (string) $suffix; - - if ($prependViewRendererSuffix) { - if (empty($suffix)) { - $suffix = $this->_getViewRenderer()->getViewSuffix(); - } else { - $suffix .= '.' . $this->_getViewRenderer()->getViewSuffix(); - } - } - - $this->_contexts[$context]['suffix'] = $suffix; - return $this; - } - - /** - * Retrieve suffix for given context type - * - * @param string $type Context type - * @throws Zend_Controller_Action_Exception - * @return string - */ - public function getSuffix($type) - { - if (!isset($this->_contexts[$type])) { - /** - * @see Zend_Controller_Action_Exception - */ - #require_once 'Zend/Controller/Action/Exception.php'; - throw new Zend_Controller_Action_Exception(sprintf('Cannot retrieve suffix; invalid context type "%s"', $type)); - } - - return $this->_contexts[$type]['suffix']; - } - - /** - * Does the given context exist? - * - * @param string $context - * @param boolean $throwException - * @throws Zend_Controller_Action_Exception if context does not exist and throwException is true - * @return bool - */ - public function hasContext($context, $throwException = false) - { - if (is_string($context)) { - if (isset($this->_contexts[$context])) { - return true; - } - } elseif (is_array($context)) { - $error = false; - foreach ($context as $test) { - if (!isset($this->_contexts[$test])) { - $error = (string) $test; - break; - } - } - if (false === $error) { - return true; - } - $context = $error; - } elseif (true === $context) { - return true; - } - - if ($throwException) { - /** - * @see Zend_Controller_Action_Exception - */ - #require_once 'Zend/Controller/Action/Exception.php'; - throw new Zend_Controller_Action_Exception(sprintf('Context "%s" does not exist', $context)); - } - - return false; - } - - /** - * Add header to context - * - * @param string $context - * @param string $header - * @param string $content - * @throws Zend_Controller_Action_Exception - * @return Zend_Controller_Action_Helper_ContextSwitch Provides a fluent interface - */ - public function addHeader($context, $header, $content) - { - $context = (string) $context; - $this->hasContext($context, true); - - $header = (string) $header; - $content = (string) $content; - - if (isset($this->_contexts[$context]['headers'][$header])) { - /** - * @see Zend_Controller_Action_Exception - */ - #require_once 'Zend/Controller/Action/Exception.php'; - throw new Zend_Controller_Action_Exception(sprintf('Cannot add "%s" header to context "%s": already exists', $header, $context)); - } - - $this->_contexts[$context]['headers'][$header] = $content; - return $this; - } - - /** - * Customize response header to use when switching context - * - * Passing an empty header value to the setters disables the response - * header. - * - * @param string $type Context type for which to set suffix - * @param string $header Header to set - * @param string $content Header content - * @return Zend_Controller_Action_Helper_ContextSwitch Provides a fluent interface - */ - public function setHeader($context, $header, $content) - { - $this->hasContext($context, true); - $context = (string) $context; - $header = (string) $header; - $content = (string) $content; - - $this->_contexts[$context]['headers'][$header] = $content; - return $this; - } - - /** - * Add multiple headers at once for a given context - * - * @param string $context - * @param array $headers - * @return Zend_Controller_Action_Helper_ContextSwitch Provides a fluent interface - */ - public function addHeaders($context, array $headers) - { - foreach ($headers as $header => $content) { - $this->addHeader($context, $header, $content); - } - - return $this; - } - - /** - * Set headers from context => headers pairs - * - * @param array $options - * @return Zend_Controller_Action_Helper_ContextSwitch Provides a fluent interface - */ - protected function _setHeaders(array $options) - { - foreach ($options as $context => $headers) { - if (!is_array($headers)) { - continue; - } - $this->setHeaders($context, $headers); - } - - return $this; - } - - /** - * Set multiple headers at once for a given context - * - * @param string $context - * @param array $headers - * @return Zend_Controller_Action_Helper_ContextSwitch Provides a fluent interface - */ - public function setHeaders($context, array $headers) - { - $this->clearHeaders($context); - foreach ($headers as $header => $content) { - $this->setHeader($context, $header, $content); - } - - return $this; - } - - /** - * Retrieve context header - * - * Returns the value of a given header for a given context type - * - * @param string $context - * @param string $header - * @return string|null - */ - public function getHeader($context, $header) - { - $this->hasContext($context, true); - $context = (string) $context; - $header = (string) $header; - if (isset($this->_contexts[$context]['headers'][$header])) { - return $this->_contexts[$context]['headers'][$header]; - } - - return null; - } - - /** - * Retrieve context headers - * - * Returns all headers for a context as key/value pairs - * - * @param string $context - * @return array - */ - public function getHeaders($context) - { - $this->hasContext($context, true); - $context = (string) $context; - return $this->_contexts[$context]['headers']; - } - - /** - * Remove a single header from a context - * - * @param string $context - * @param string $header - * @return boolean - */ - public function removeHeader($context, $header) - { - $this->hasContext($context, true); - $context = (string) $context; - $header = (string) $header; - if (isset($this->_contexts[$context]['headers'][$header])) { - unset($this->_contexts[$context]['headers'][$header]); - return true; - } - - return false; - } - - /** - * Clear all headers for a given context - * - * @param string $context - * @return Zend_Controller_Action_Helper_ContextSwitch Provides a fluent interface - */ - public function clearHeaders($context) - { - $this->hasContext($context, true); - $context = (string) $context; - $this->_contexts[$context]['headers'] = array(); - return $this; - } - - /** - * Validate trigger and return in normalized form - * - * @param string $trigger - * @throws Zend_Controller_Action_Exception - * @return string - */ - protected function _validateTrigger($trigger) - { - $trigger = strtoupper($trigger); - if ('TRIGGER_' !== substr($trigger, 0, 8)) { - $trigger = 'TRIGGER_' . $trigger; - } - - if (!in_array($trigger, array(self::TRIGGER_INIT, self::TRIGGER_POST))) { - /** - * @see Zend_Controller_Action_Exception - */ - #require_once 'Zend/Controller/Action/Exception.php'; - throw new Zend_Controller_Action_Exception(sprintf('Invalid trigger "%s"', $trigger)); - } - - return $trigger; - } - - /** - * Set a callback for a given context and trigger - * - * @param string $context - * @param string $trigger - * @param string|array $callback - * @throws Zend_Controller_Action_Exception - * @return Zend_Controller_Action_Helper_ContextSwitch Provides a fluent interface - */ - public function setCallback($context, $trigger, $callback) - { - $this->hasContext($context, true); - $trigger = $this->_validateTrigger($trigger); - - if (!is_string($callback)) { - if (!is_array($callback) || (2 != count($callback))) { - /** - * @see Zend_Controller_Action_Exception - */ - #require_once 'Zend/Controller/Action/Exception.php'; - throw new Zend_Controller_Action_Exception('Invalid callback specified'); - } - } - - $this->_contexts[$context]['callbacks'][$trigger] = $callback; - return $this; - } - - /** - * Set callbacks from array of context => callbacks pairs - * - * @param array $options - * @return Zend_Controller_Action_Helper_ContextSwitch Provides a fluent interface - */ - protected function _setCallbacks(array $options) - { - foreach ($options as $context => $callbacks) { - if (!is_array($callbacks)) { - continue; - } - - $this->setCallbacks($context, $callbacks); - } - return $this; - } - - /** - * Set callbacks for a given context - * - * Callbacks should be in trigger/callback pairs. - * - * @param string $context - * @param array $callbacks - * @return Zend_Controller_Action_Helper_ContextSwitch Provides a fluent interface - */ - public function setCallbacks($context, array $callbacks) - { - $this->hasContext($context, true); - $context = (string) $context; - if (!isset($this->_contexts[$context]['callbacks'])) { - $this->_contexts[$context]['callbacks'] = array(); - } - - foreach ($callbacks as $trigger => $callback) { - $this->setCallback($context, $trigger, $callback); - } - return $this; - } - - /** - * Get a single callback for a given context and trigger - * - * @param string $context - * @param string $trigger - * @return string|array|null - */ - public function getCallback($context, $trigger) - { - $this->hasContext($context, true); - $trigger = $this->_validateTrigger($trigger); - if (isset($this->_contexts[$context]['callbacks'][$trigger])) { - return $this->_contexts[$context]['callbacks'][$trigger]; - } - - return null; - } - - /** - * Get all callbacks for a given context - * - * @param string $context - * @return array - */ - public function getCallbacks($context) - { - $this->hasContext($context, true); - return $this->_contexts[$context]['callbacks']; - } - - /** - * Clear a callback for a given context and trigger - * - * @param string $context - * @param string $trigger - * @return boolean - */ - public function removeCallback($context, $trigger) - { - $this->hasContext($context, true); - $trigger = $this->_validateTrigger($trigger); - if (isset($this->_contexts[$context]['callbacks'][$trigger])) { - unset($this->_contexts[$context]['callbacks'][$trigger]); - return true; - } - - return false; - } - - /** - * Clear all callbacks for a given context - * - * @param string $context - * @return Zend_Controller_Action_Helper_ContextSwitch Provides a fluent interface - */ - public function clearCallbacks($context) - { - $this->hasContext($context, true); - $this->_contexts[$context]['callbacks'] = array(); - return $this; - } - - /** - * Set name of parameter to use when determining context format - * - * @param string $name - * @return Zend_Controller_Action_Helper_ContextSwitch Provides a fluent interface - */ - public function setContextParam($name) - { - $this->_contextParam = (string) $name; - return $this; - } - - /** - * Return context format request parameter name - * - * @return string - */ - public function getContextParam() - { - return $this->_contextParam; - } - - /** - * Indicate default context to use when no context format provided - * - * @param string $type - * @throws Zend_Controller_Action_Exception - * @return Zend_Controller_Action_Helper_ContextSwitch Provides a fluent interface - */ - public function setDefaultContext($type) - { - if (!isset($this->_contexts[$type])) { - /** - * @see Zend_Controller_Action_Exception - */ - #require_once 'Zend/Controller/Action/Exception.php'; - throw new Zend_Controller_Action_Exception(sprintf('Cannot set default context; invalid context type "%s"', $type)); - } - - $this->_defaultContext = $type; - return $this; - } - - /** - * Return default context - * - * @return string - */ - public function getDefaultContext() - { - return $this->_defaultContext; - } - - /** - * Set flag indicating if layout should be disabled - * - * @param boolean $flag - * @return Zend_Controller_Action_Helper_ContextSwitch Provides a fluent interface - */ - public function setAutoDisableLayout($flag) - { - $this->_disableLayout = ($flag) ? true : false; - return $this; - } - - /** - * Retrieve auto layout disable flag - * - * @return boolean - */ - public function getAutoDisableLayout() - { - return $this->_disableLayout; - } - - /** - * Add new context - * - * @param string $context Context type - * @param array $spec Context specification - * @throws Zend_Controller_Action_Exception - * @return Zend_Controller_Action_Helper_ContextSwitch Provides a fluent interface - */ - public function addContext($context, array $spec) - { - if ($this->hasContext($context)) { - /** - * @see Zend_Controller_Action_Exception - */ - #require_once 'Zend/Controller/Action/Exception.php'; - throw new Zend_Controller_Action_Exception(sprintf('Cannot add context "%s"; already exists', $context)); - } - $context = (string) $context; - - $this->_contexts[$context] = array(); - - $this->setSuffix($context, (isset($spec['suffix']) ? $spec['suffix'] : '')) - ->setHeaders($context, (isset($spec['headers']) ? $spec['headers'] : array())) - ->setCallbacks($context, (isset($spec['callbacks']) ? $spec['callbacks'] : array())); - return $this; - } - - /** - * Overwrite existing context - * - * @param string $context Context type - * @param array $spec Context specification - * @return Zend_Controller_Action_Helper_ContextSwitch Provides a fluent interface - */ - public function setContext($context, array $spec) - { - $this->removeContext($context); - return $this->addContext($context, $spec); - } - - /** - * Add multiple contexts - * - * @param array $contexts - * @return Zend_Controller_Action_Helper_ContextSwitch Provides a fluent interface - */ - public function addContexts(array $contexts) - { - foreach ($contexts as $context => $spec) { - $this->addContext($context, $spec); - } - return $this; - } - - /** - * Set multiple contexts, after first removing all - * - * @param array $contexts - * @return Zend_Controller_Action_Helper_ContextSwitch Provides a fluent interface - */ - public function setContexts(array $contexts) - { - $this->clearContexts(); - foreach ($contexts as $context => $spec) { - $this->addContext($context, $spec); - } - return $this; - } - - /** - * Retrieve context specification - * - * @param string $context - * @return array|null - */ - public function getContext($context) - { - if ($this->hasContext($context)) { - return $this->_contexts[(string) $context]; - } - return null; - } - - /** - * Retrieve context definitions - * - * @return array - */ - public function getContexts() - { - return $this->_contexts; - } - - /** - * Remove a context - * - * @param string $context - * @return boolean - */ - public function removeContext($context) - { - if ($this->hasContext($context)) { - unset($this->_contexts[(string) $context]); - return true; - } - return false; - } - - /** - * Remove all contexts - * - * @return Zend_Controller_Action_Helper_ContextSwitch Provides a fluent interface - */ - public function clearContexts() - { - $this->_contexts = array(); - return $this; - } - - /** - * Return current context, if any - * - * @return null|string - */ - public function getCurrentContext() - { - return $this->_currentContext; - } - - /** - * Post dispatch processing - * - * Execute postDispatch callback for current context, if available - * - * @throws Zend_Controller_Action_Exception - * @return void - */ - public function postDispatch() - { - $context = $this->getCurrentContext(); - if (null !== $context) { - if (null !== ($callback = $this->getCallback($context, self::TRIGGER_POST))) { - if (is_string($callback) && method_exists($this, $callback)) { - $this->$callback(); - } elseif (is_string($callback) && function_exists($callback)) { - $callback(); - } elseif (is_array($callback)) { - call_user_func($callback); - } else { - /** - * @see Zend_Controller_Action_Exception - */ - #require_once 'Zend/Controller/Action/Exception.php'; - throw new Zend_Controller_Action_Exception(sprintf('Invalid postDispatch context callback registered for context "%s"', $context)); - } - } - } - } - - /** - * JSON post processing - * - * JSON serialize view variables to response body - * - * @return void - */ - public function postJsonContext() - { - if (!$this->getAutoJsonSerialization()) { - return; - } - - $viewRenderer = Zend_Controller_Action_HelperBroker::getStaticHelper('viewRenderer'); - $view = $viewRenderer->view; - if ($view instanceof Zend_View_Interface) { - /** - * @see Zend_Json - */ - if(method_exists($view, 'getVars')) { - #require_once 'Zend/Json.php'; - $vars = Zend_Json::encode($view->getVars()); - $this->getResponse()->setBody($vars); - } else { - #require_once 'Zend/Controller/Action/Exception.php'; - throw new Zend_Controller_Action_Exception('View does not implement the getVars() method needed to encode the view into JSON'); - } - } - } - - /** - * Add one or more contexts to an action - * - * @param string $action - * @param string|array $context - * @return Zend_Controller_Action_Helper_ContextSwitch|void Provides a fluent interface - */ - public function addActionContext($action, $context) - { - $this->hasContext($context, true); - $controller = $this->getActionController(); - if (null === $controller) { - return; - } - $action = (string) $action; - $contextKey = $this->_contextKey; - - if (!isset($controller->$contextKey)) { - $controller->$contextKey = array(); - } - - if (true === $context) { - $contexts = $this->getContexts(); - $controller->{$contextKey}[$action] = array_keys($contexts); - return $this; - } - - $context = (array) $context; - if (!isset($controller->{$contextKey}[$action])) { - $controller->{$contextKey}[$action] = $context; - } else { - $controller->{$contextKey}[$action] = array_merge( - $controller->{$contextKey}[$action], - $context - ); - } - - return $this; - } - - /** - * Set a context as available for a given controller action - * - * @param string $action - * @param string|array $context - * @return Zend_Controller_Action_Helper_ContextSwitch|void Provides a fluent interface - */ - public function setActionContext($action, $context) - { - $this->hasContext($context, true); - $controller = $this->getActionController(); - if (null === $controller) { - return; - } - $action = (string) $action; - $contextKey = $this->_contextKey; - - if (!isset($controller->$contextKey)) { - $controller->$contextKey = array(); - } - - if (true === $context) { - $contexts = $this->getContexts(); - $controller->{$contextKey}[$action] = array_keys($contexts); - } else { - $controller->{$contextKey}[$action] = (array) $context; - } - - return $this; - } - - /** - * Add multiple action/context pairs at once - * - * @param array $contexts - * @return Zend_Controller_Action_Helper_ContextSwitch Provides a fluent interface - */ - public function addActionContexts(array $contexts) - { - foreach ($contexts as $action => $context) { - $this->addActionContext($action, $context); - } - return $this; - } - - /** - * Overwrite and set multiple action contexts at once - * - * @param array $contexts - * @return Zend_Controller_Action_Helper_ContextSwitch Provides a fluent interface - */ - public function setActionContexts(array $contexts) - { - foreach ($contexts as $action => $context) { - $this->setActionContext($action, $context); - } - return $this; - } - - /** - * Does a particular controller action have the given context(s)? - * - * @param string $action - * @param string|array $context - * @throws Zend_Controller_Action_Exception - * @return boolean - */ - public function hasActionContext($action, $context) - { - $this->hasContext($context, true); - $controller = $this->getActionController(); - if (null === $controller) { - return false; - } - $action = (string) $action; - $contextKey = $this->_contextKey; - - if (!isset($controller->{$contextKey})) { - return false; - } - - $allContexts = $controller->{$contextKey}; - - if (!is_array($allContexts)) { - /** - * @see Zend_Controller_Action_Exception - */ - #require_once 'Zend/Controller/Action/Exception.php'; - throw new Zend_Controller_Action_Exception("Invalid contexts found for controller"); - } - - if (!isset($allContexts[$action])) { - return false; - } - - if (true === $allContexts[$action]) { - return true; - } - - $contexts = $allContexts[$action]; - - if (!is_array($contexts)) { - /** - * @see Zend_Controller_Action_Exception - */ - #require_once 'Zend/Controller/Action/Exception.php'; - throw new Zend_Controller_Action_Exception(sprintf("Invalid contexts found for action '%s'", $action)); - } - - if (is_string($context) && in_array($context, $contexts)) { - return true; - } elseif (is_array($context)) { - $found = true; - foreach ($context as $test) { - if (!in_array($test, $contexts)) { - $found = false; - break; - } - } - return $found; - } - - return false; - } - - /** - * Get contexts for a given action or all actions in the controller - * - * @param string $action - * @return array - */ - public function getActionContexts($action = null) - { - $controller = $this->getActionController(); - if (null === $controller) { - return array(); - } - $contextKey = $this->_contextKey; - - if (!isset($controller->$contextKey)) { - return array(); - } - - if (null !== $action) { - $action = (string) $action; - if (isset($controller->{$contextKey}[$action])) { - return $controller->{$contextKey}[$action]; - } else { - return array(); - } - } - - return $controller->$contextKey; - } - - /** - * Remove one or more contexts for a given controller action - * - * @param string $action - * @param string|array $context - * @return boolean - */ - public function removeActionContext($action, $context) - { - if ($this->hasActionContext($action, $context)) { - $controller = $this->getActionController(); - $contextKey = $this->_contextKey; - $action = (string) $action; - $contexts = $controller->$contextKey; - $actionContexts = $contexts[$action]; - $contexts = (array) $context; - foreach ($contexts as $context) { - $index = array_search($context, $actionContexts); - if (false !== $index) { - unset($controller->{$contextKey}[$action][$index]); - } - } - return true; - } - return false; - } - - /** - * Clear all contexts for a given controller action or all actions - * - * @param string $action - * @return Zend_Controller_Action_Helper_ContextSwitch Provides a fluent interface - */ - public function clearActionContexts($action = null) - { - $controller = $this->getActionController(); - $contextKey = $this->_contextKey; - - if (!isset($controller->$contextKey) || empty($controller->$contextKey)) { - return $this; - } - - if (null === $action) { - $controller->$contextKey = array(); - return $this; - } - - $action = (string) $action; - if (isset($controller->{$contextKey}[$action])) { - unset($controller->{$contextKey}[$action]); - } - - return $this; - } - - /** - * Retrieve ViewRenderer - * - * @return Zend_Controller_Action_Helper_ViewRenderer Provides a fluent interface - */ - protected function _getViewRenderer() - { - if (null === $this->_viewRenderer) { - $this->_viewRenderer = Zend_Controller_Action_HelperBroker::getStaticHelper('viewRenderer'); - } - - return $this->_viewRenderer; - } -} - diff --git a/library/Zend/Controller/Action/Helper/FlashMessenger.php b/library/Zend/Controller/Action/Helper/FlashMessenger.php deleted file mode 100644 index 307606aef9..0000000000 --- a/library/Zend/Controller/Action/Helper/FlashMessenger.php +++ /dev/null @@ -1,313 +0,0 @@ -getName()); - foreach (self::$_session as $namespace => $messages) { - self::$_messages[$namespace] = $messages; - unset(self::$_session->{$namespace}); - } - } - } - - /** - * postDispatch() - runs after action is dispatched, in this - * case, it is resetting the namespace in case we have forwarded to a different - * action, Flashmessage will be 'clean' (default namespace) - * - * @return Zend_Controller_Action_Helper_FlashMessenger Provides a fluent interface - */ - public function postDispatch() - { - $this->resetNamespace(); - return $this; - } - - /** - * setNamespace() - change the namespace messages are added to, useful for - * per action controller messaging between requests - * - * @param string $namespace - * @return Zend_Controller_Action_Helper_FlashMessenger Provides a fluent interface - */ - public function setNamespace($namespace = 'default') - { - $this->_namespace = $namespace; - return $this; - } - - /** - * getNamespace() - return the current namepsace - * - * @return string - */ - public function getNamespace() - { - return $this->_namespace; - } - - /** - * resetNamespace() - reset the namespace to the default - * - * @return Zend_Controller_Action_Helper_FlashMessenger Provides a fluent interface - */ - public function resetNamespace() - { - $this->setNamespace(); - return $this; - } - - /** - * addMessage() - Add a message to flash message - * - * @param string $message - * @return Zend_Controller_Action_Helper_FlashMessenger Provides a fluent interface - */ - public function addMessage($message, $namespace = null) - { - if (!is_string($namespace) || $namespace == '') { - $namespace = $this->getNamespace(); - } - - if (self::$_messageAdded === false) { - self::$_session->setExpirationHops(1, null, true); - } - - if (!is_array(self::$_session->{$namespace})) { - self::$_session->{$namespace} = array(); - } - - self::$_session->{$namespace}[] = $message; - self::$_messageAdded = true; - - return $this; - } - - /** - * hasMessages() - Wether a specific namespace has messages - * - * @return boolean - */ - public function hasMessages($namespace = null) - { - if (!is_string($namespace) || $namespace == '') { - $namespace = $this->getNamespace(); - } - - return isset(self::$_messages[$namespace]); - } - - /** - * getMessages() - Get messages from a specific namespace - * - * @return array - */ - public function getMessages($namespace = null) - { - if (!is_string($namespace) || $namespace == '') { - $namespace = $this->getNamespace(); - } - - if ($this->hasMessages($namespace)) { - return self::$_messages[$namespace]; - } - - return array(); - } - - /** - * Clear all messages from the previous request & current namespace - * - * @return boolean True if messages were cleared, false if none existed - */ - public function clearMessages($namespace = null) - { - if (!is_string($namespace) || $namespace == '') { - $namespace = $this->getNamespace(); - } - - if ($this->hasMessages($namespace)) { - unset(self::$_messages[$namespace]); - return true; - } - - return false; - } - - /** - * hasCurrentMessages() - check to see if messages have been added to current - * namespace within this request - * - * @return boolean - */ - public function hasCurrentMessages($namespace = null) - { - if (!is_string($namespace) || $namespace == '') { - $namespace = $this->getNamespace(); - } - - return isset(self::$_session->{$namespace}); - } - - /** - * getCurrentMessages() - get messages that have been added to the current - * namespace within this request - * - * @return array - */ - public function getCurrentMessages($namespace = null) - { - if (!is_string($namespace) || $namespace == '') { - $namespace = $this->getNamespace(); - } - - if ($this->hasCurrentMessages($namespace)) { - return self::$_session->{$namespace}; - } - - return array(); - } - - /** - * clear messages from the current request & current namespace - * - * @return boolean - */ - public function clearCurrentMessages($namespace = null) - { - if (!is_string($namespace) || $namespace == '') { - $namespace = $this->getNamespace(); - } - - if ($this->hasCurrentMessages($namespace)) { - unset(self::$_session->{$namespace}); - return true; - } - - return false; - } - - /** - * getIterator() - complete the IteratorAggregate interface, for iterating - * - * @return ArrayObject - */ - public function getIterator($namespace = null) - { - if (!is_string($namespace) || $namespace == '') { - $namespace = $this->getNamespace(); - } - - if ($this->hasMessages($namespace)) { - return new ArrayObject($this->getMessages($namespace)); - } - - return new ArrayObject(); - } - - /** - * count() - Complete the countable interface - * - * @return int - */ - public function count($namespace = null) - { - if (!is_string($namespace) || $namespace == '') { - $namespace = $this->getNamespace(); - } - - if ($this->hasMessages($namespace)) { - return count($this->getMessages($namespace)); - } - - return 0; - } - - /** - * Strategy pattern: proxy to addMessage() - * - * @param string $message - * @return void - */ - public function direct($message, $namespace=NULL) - { - return $this->addMessage($message, $namespace); - } -} diff --git a/library/Zend/Controller/Action/Helper/Json.php b/library/Zend/Controller/Action/Helper/Json.php deleted file mode 100644 index 66c3ae9c01..0000000000 --- a/library/Zend/Controller/Action/Helper/Json.php +++ /dev/null @@ -1,133 +0,0 @@ -true|false - * if $keepLayouts and parmas for Zend_Json::encode are required - * then, the array can contains a 'keepLayout'=>true|false and/or 'encodeData'=>true|false - * that will not be passed to Zend_Json::encode method but will be passed - * to Zend_View_Helper_Json - * @throws Zend_Controller_Action_Helper_Json - * @return string - */ - public function encodeJson($data, $keepLayouts = false, $encodeData = true) - { - /** - * @see Zend_View_Helper_Json - */ - #require_once 'Zend/View/Helper/Json.php'; - $jsonHelper = new Zend_View_Helper_Json(); - $data = $jsonHelper->json($data, $keepLayouts, $encodeData); - - if (!$keepLayouts) { - /** - * @see Zend_Controller_Action_HelperBroker - */ - #require_once 'Zend/Controller/Action/HelperBroker.php'; - Zend_Controller_Action_HelperBroker::getStaticHelper('viewRenderer')->setNoRender(true); - } - - return $data; - } - - /** - * Encode JSON response and immediately send - * - * @param mixed $data - * @param boolean|array $keepLayouts - * @param $encodeData Encode $data as JSON? - * NOTE: if boolean, establish $keepLayouts to true|false - * if array, admit params for Zend_Json::encode as enableJsonExprFinder=>true|false - * if $keepLayouts and parmas for Zend_Json::encode are required - * then, the array can contains a 'keepLayout'=>true|false and/or 'encodeData'=>true|false - * that will not be passed to Zend_Json::encode method but will be passed - * to Zend_View_Helper_Json - * @return string|void - */ - public function sendJson($data, $keepLayouts = false, $encodeData = true) - { - $data = $this->encodeJson($data, $keepLayouts, $encodeData); - $response = $this->getResponse(); - $response->setBody($data); - - if (!$this->suppressExit) { - $response->sendResponse(); - exit; - } - - return $data; - } - - /** - * Strategy pattern: call helper as helper broker method - * - * Allows encoding JSON. If $sendNow is true, immediately sends JSON - * response. - * - * @param mixed $data - * @param boolean $sendNow - * @param boolean $keepLayouts - * @param boolean $encodeData Encode $data as JSON? - * @return string|void - */ - public function direct($data, $sendNow = true, $keepLayouts = false, $encodeData = true) - { - if ($sendNow) { - return $this->sendJson($data, $keepLayouts, $encodeData); - } - return $this->encodeJson($data, $keepLayouts, $encodeData); - } -} diff --git a/library/Zend/Controller/Action/Helper/Redirector.php b/library/Zend/Controller/Action/Helper/Redirector.php deleted file mode 100644 index ec4a2ea180..0000000000 --- a/library/Zend/Controller/Action/Helper/Redirector.php +++ /dev/null @@ -1,534 +0,0 @@ -_code; - } - - /** - * Validate HTTP status redirect code - * - * @param int $code - * @throws Zend_Controller_Action_Exception on invalid HTTP status code - * @return true - */ - protected function _checkCode($code) - { - $code = (int)$code; - if ((300 > $code) || (307 < $code) || (304 == $code) || (306 == $code)) { - #require_once 'Zend/Controller/Action/Exception.php'; - throw new Zend_Controller_Action_Exception('Invalid redirect HTTP status code (' . $code . ')'); - } - - return true; - } - - /** - * Set HTTP status code for {@link _redirect()} behaviour - * - * @param int $code - * @return Zend_Controller_Action_Helper_Redirector Provides a fluent interface - */ - public function setCode($code) - { - $this->_checkCode($code); - $this->_code = $code; - return $this; - } - - /** - * Retrieve flag for whether or not {@link _redirect()} will exit when finished. - * - * @return boolean - */ - public function getExit() - { - return $this->_exit; - } - - /** - * Set exit flag for {@link _redirect()} behaviour - * - * @param boolean $flag - * @return Zend_Controller_Action_Helper_Redirector Provides a fluent interface - */ - public function setExit($flag) - { - $this->_exit = ($flag) ? true : false; - return $this; - } - - /** - * Retrieve flag for whether or not {@link _redirect()} will prepend the - * base URL on relative URLs - * - * @return boolean - */ - public function getPrependBase() - { - return $this->_prependBase; - } - - /** - * Set 'prepend base' flag for {@link _redirect()} behaviour - * - * @param boolean $flag - * @return Zend_Controller_Action_Helper_Redirector Provides a fluent interface - */ - public function setPrependBase($flag) - { - $this->_prependBase = ($flag) ? true : false; - return $this; - } - - /** - * Retrieve flag for whether or not {@link redirectAndExit()} shall close the session before - * exiting. - * - * @return boolean - */ - public function getCloseSessionOnExit() - { - return $this->_closeSessionOnExit; - } - - /** - * Set flag for whether or not {@link redirectAndExit()} shall close the session before exiting. - * - * @param boolean $flag - * @return Zend_Controller_Action_Helper_Redirector Provides a fluent interface - */ - public function setCloseSessionOnExit($flag) - { - $this->_closeSessionOnExit = ($flag) ? true : false; - return $this; - } - - /** - * Return use absolute URI flag - * - * @return boolean - */ - public function getUseAbsoluteUri() - { - return $this->_useAbsoluteUri; - } - - /** - * Set use absolute URI flag - * - * @param boolean $flag - * @return Zend_Controller_Action_Helper_Redirector Provides a fluent interface - */ - public function setUseAbsoluteUri($flag = true) - { - $this->_useAbsoluteUri = ($flag) ? true : false; - return $this; - } - - /** - * Set redirect in response object - * - * @return void - */ - protected function _redirect($url) - { - if ($this->getUseAbsoluteUri() && !preg_match('#^(https?|ftp)://#', $url)) { - $host = (isset($_SERVER['HTTP_HOST'])?$_SERVER['HTTP_HOST']:''); - $proto = (isset($_SERVER['HTTPS'])&&$_SERVER['HTTPS']!=="off") ? 'https' : 'http'; - $port = (isset($_SERVER['SERVER_PORT'])?$_SERVER['SERVER_PORT']:80); - $uri = $proto . '://' . $host; - if ((('http' == $proto) && (80 != $port)) || (('https' == $proto) && (443 != $port))) { - // do not append if HTTP_HOST already contains port - if (strrchr($host, ':') === false) { - $uri .= ':' . $port; - } - } - $url = $uri . '/' . ltrim($url, '/'); - } - $this->_redirectUrl = $url; - $this->getResponse()->setRedirect($url, $this->getCode()); - } - - /** - * Retrieve currently set URL for redirect - * - * @return string - */ - public function getRedirectUrl() - { - return $this->_redirectUrl; - } - - /** - * Determine if the baseUrl should be prepended, and prepend if necessary - * - * @param string $url - * @return string - */ - protected function _prependBase($url) - { - if ($this->getPrependBase()) { - $request = $this->getRequest(); - if ($request instanceof Zend_Controller_Request_Http) { - $base = rtrim($request->getBaseUrl(), '/'); - if (!empty($base) && ('/' != $base)) { - $url = $base . '/' . ltrim($url, '/'); - } else { - $url = '/' . ltrim($url, '/'); - } - } - } - - return $url; - } - - /** - * Set a redirect URL of the form /module/controller/action/params - * - * @param string $action - * @param string $controller - * @param string $module - * @param array $params - * @return void - */ - public function setGotoSimple($action, $controller = null, $module = null, array $params = array()) - { - $dispatcher = $this->getFrontController()->getDispatcher(); - $request = $this->getRequest(); - $curModule = $request->getModuleName(); - $useDefaultController = false; - - if (null === $controller && null !== $module) { - $useDefaultController = true; - } - - if (null === $module) { - $module = $curModule; - } - - if ($module == $dispatcher->getDefaultModule()) { - $module = ''; - } - - if (null === $controller && !$useDefaultController) { - $controller = $request->getControllerName(); - if (empty($controller)) { - $controller = $dispatcher->getDefaultControllerName(); - } - } - - $params[$request->getModuleKey()] = $module; - $params[$request->getControllerKey()] = $controller; - $params[$request->getActionKey()] = $action; - - $router = $this->getFrontController()->getRouter(); - $url = $router->assemble($params, 'default', true); - - $this->_redirect($url); - } - - /** - * Build a URL based on a route - * - * @param array $urlOptions - * @param string $name Route name - * @param boolean $reset - * @param boolean $encode - * @return void - */ - public function setGotoRoute(array $urlOptions = array(), $name = null, $reset = false, $encode = true) - { - $router = $this->getFrontController()->getRouter(); - $url = $router->assemble($urlOptions, $name, $reset, $encode); - - $this->_redirect($url); - } - - /** - * Set a redirect URL string - * - * By default, emits a 302 HTTP status header, prepends base URL as defined - * in request object if url is relative, and halts script execution by - * calling exit(). - * - * $options is an optional associative array that can be used to control - * redirect behaviour. The available option keys are: - * - exit: boolean flag indicating whether or not to halt script execution when done - * - prependBase: boolean flag indicating whether or not to prepend the base URL when a relative URL is provided - * - code: integer HTTP status code to use with redirect. Should be between 300 and 307. - * - * _redirect() sets the Location header in the response object. If you set - * the exit flag to false, you can override this header later in code - * execution. - * - * If the exit flag is true (true by default), _redirect() will write and - * close the current session, if any. - * - * @param string $url - * @param array $options - * @return void - */ - public function setGotoUrl($url, array $options = array()) - { - // prevent header injections - $url = str_replace(array("\n", "\r"), '', $url); - - if (null !== $options) { - if (isset($options['exit'])) { - $this->setExit(($options['exit']) ? true : false); - } - if (isset($options['prependBase'])) { - $this->setPrependBase(($options['prependBase']) ? true : false); - } - if (isset($options['code'])) { - $this->setCode($options['code']); - } - } - - // If relative URL, decide if we should prepend base URL - if (!preg_match('|^[a-z]+://|', $url)) { - $url = $this->_prependBase($url); - } - - $this->_redirect($url); - } - - /** - * Perform a redirect to an action/controller/module with params - * - * @param string $action - * @param string $controller - * @param string $module - * @param array $params - * @return void - */ - public function gotoSimple($action, $controller = null, $module = null, array $params = array()) - { - $this->setGotoSimple($action, $controller, $module, $params); - - if ($this->getExit()) { - $this->redirectAndExit(); - } - } - - /** - * Perform a redirect to an action/controller/module with params, forcing an immdiate exit - * - * @param mixed $action - * @param mixed $controller - * @param mixed $module - * @param array $params - * @return void - */ - public function gotoSimpleAndExit($action, $controller = null, $module = null, array $params = array()) - { - $this->setGotoSimple($action, $controller, $module, $params); - $this->redirectAndExit(); - } - - /** - * Redirect to a route-based URL - * - * Uses route's assemble method to build the URL; route is specified by $name; - * default route is used if none provided. - * - * @param array $urlOptions Array of key/value pairs used to assemble URL - * @param string $name - * @param boolean $reset - * @param boolean $encode - * @return void - */ - public function gotoRoute(array $urlOptions = array(), $name = null, $reset = false, $encode = true) - { - $this->setGotoRoute($urlOptions, $name, $reset, $encode); - - if ($this->getExit()) { - $this->redirectAndExit(); - } - } - - /** - * Redirect to a route-based URL, and immediately exit - * - * Uses route's assemble method to build the URL; route is specified by $name; - * default route is used if none provided. - * - * @param array $urlOptions Array of key/value pairs used to assemble URL - * @param string $name - * @param boolean $reset - * @return void - */ - public function gotoRouteAndExit(array $urlOptions = array(), $name = null, $reset = false) - { - $this->setGotoRoute($urlOptions, $name, $reset); - $this->redirectAndExit(); - } - - /** - * Perform a redirect to a url - * - * @param string $url - * @param array $options - * @return void - */ - public function gotoUrl($url, array $options = array()) - { - $this->setGotoUrl($url, $options); - - if ($this->getExit()) { - $this->redirectAndExit(); - } - } - - /** - * Set a URL string for a redirect, perform redirect, and immediately exit - * - * @param string $url - * @param array $options - * @return void - */ - public function gotoUrlAndExit($url, array $options = array()) - { - $this->setGotoUrl($url, $options); - $this->redirectAndExit(); - } - - /** - * exit(): Perform exit for redirector - * - * @return void - */ - public function redirectAndExit() - { - if ($this->getCloseSessionOnExit()) { - // Close session, if started - if (class_exists('Zend_Session', false) && Zend_Session::isStarted()) { - Zend_Session::writeClose(); - } elseif (isset($_SESSION)) { - session_write_close(); - } - } - - $this->getResponse()->sendHeaders(); - exit(); - } - - /** - * direct(): Perform helper when called as - * $this->_helper->redirector($action, $controller, $module, $params) - * - * @param string $action - * @param string $controller - * @param string $module - * @param array $params - * @return void - */ - public function direct($action, $controller = null, $module = null, array $params = array()) - { - $this->gotoSimple($action, $controller, $module, $params); - } - - /** - * Overloading - * - * Overloading for old 'goto', 'setGoto', and 'gotoAndExit' methods - * - * @param string $method - * @param array $args - * @return mixed - * @throws Zend_Controller_Action_Exception for invalid methods - */ - public function __call($method, $args) - { - $method = strtolower($method); - if ('goto' == $method) { - return call_user_func_array(array($this, 'gotoSimple'), $args); - } - if ('setgoto' == $method) { - return call_user_func_array(array($this, 'setGotoSimple'), $args); - } - if ('gotoandexit' == $method) { - return call_user_func_array(array($this, 'gotoSimpleAndExit'), $args); - } - - #require_once 'Zend/Controller/Action/Exception.php'; - throw new Zend_Controller_Action_Exception(sprintf('Invalid method "%s" called on redirector', $method)); - } -} diff --git a/library/Zend/Controller/Action/Helper/Url.php b/library/Zend/Controller/Action/Helper/Url.php deleted file mode 100644 index 496d2ce19e..0000000000 --- a/library/Zend/Controller/Action/Helper/Url.php +++ /dev/null @@ -1,117 +0,0 @@ -getRequest(); - - if (null === $controller) { - $controller = $request->getControllerName(); - } - - if (null === $module) { - $module = $request->getModuleName(); - } - - $url = $controller . '/' . $action; - if ($module != $this->getFrontController()->getDispatcher()->getDefaultModule()) { - $url = $module . '/' . $url; - } - - if ('' !== ($baseUrl = $this->getFrontController()->getBaseUrl())) { - $url = $baseUrl . '/' . $url; - } - - if (null !== $params) { - $paramPairs = array(); - foreach ($params as $key => $value) { - $paramPairs[] = urlencode($key) . '/' . urlencode($value); - } - $paramString = implode('/', $paramPairs); - $url .= '/' . $paramString; - } - - $url = '/' . ltrim($url, '/'); - - return $url; - } - - /** - * Assembles a URL based on a given route - * - * This method will typically be used for more complex operations, as it - * ties into the route objects registered with the router. - * - * @param array $urlOptions Options passed to the assemble method of the Route object. - * @param mixed $name The name of a Route to use. If null it will use the current Route - * @param boolean $reset - * @param boolean $encode - * @return string Url for the link href attribute. - */ - public function url($urlOptions = array(), $name = null, $reset = false, $encode = true) - { - $router = $this->getFrontController()->getRouter(); - return $router->assemble($urlOptions, $name, $reset, $encode); - } - - /** - * Perform helper when called as $this->_helper->url() from an action controller - * - * Proxies to {@link simple()} - * - * @param string $action - * @param string $controller - * @param string $module - * @param array $params - * @return string - */ - public function direct($action, $controller = null, $module = null, array $params = null) - { - return $this->simple($action, $controller, $module, $params); - } -} diff --git a/library/Zend/Controller/Action/Helper/ViewRenderer.php b/library/Zend/Controller/Action/Helper/ViewRenderer.php deleted file mode 100644 index b56f755e98..0000000000 --- a/library/Zend/Controller/Action/Helper/ViewRenderer.php +++ /dev/null @@ -1,1004 +0,0 @@ - - * // In your bootstrap: - * Zend_Controller_Action_HelperBroker::addHelper(new Zend_Controller_Action_Helper_ViewRenderer()); - * - * // In your action controller methods: - * $viewHelper = $this->_helper->getHelper('view'); - * - * // Don't use controller subdirectories - * $viewHelper->setNoController(true); - * - * // Specify a different script to render: - * $this->_helper->viewRenderer('form'); - * - * - * - * @uses Zend_Controller_Action_Helper_Abstract - * @package Zend_Controller - * @subpackage Zend_Controller_Action_Helper - * @copyright Copyright (c) 2005-2015 Zend Technologies USA Inc. (http://www.zend.com) - * @license http://framework.zend.com/license/new-bsd New BSD License - */ -class Zend_Controller_Action_Helper_ViewRenderer extends Zend_Controller_Action_Helper_Abstract -{ - /** - * @var Zend_View_Interface - */ - public $view; - - /** - * Word delimiters - * @var array - */ - protected $_delimiters; - - /** - * @var Zend_Filter_Inflector - */ - protected $_inflector; - - /** - * Inflector target - * @var string - */ - protected $_inflectorTarget = ''; - - /** - * Current module directory - * @var string - */ - protected $_moduleDir = ''; - - /** - * Whether or not to autorender using controller name as subdirectory; - * global setting (not reset at next invocation) - * @var boolean - */ - protected $_neverController = false; - - /** - * Whether or not to autorender postDispatch; global setting (not reset at - * next invocation) - * @var boolean - */ - protected $_neverRender = false; - - /** - * Whether or not to use a controller name as a subdirectory when rendering - * @var boolean - */ - protected $_noController = false; - - /** - * Whether or not to autorender postDispatch; per controller/action setting (reset - * at next invocation) - * @var boolean - */ - protected $_noRender = false; - - /** - * Characters representing path delimiters in the controller - * @var string|array - */ - protected $_pathDelimiters; - - /** - * Which named segment of the response to utilize - * @var string - */ - protected $_responseSegment = null; - - /** - * Which action view script to render - * @var string - */ - protected $_scriptAction = null; - - /** - * View object basePath - * @var string - */ - protected $_viewBasePathSpec = ':moduleDir/views'; - - /** - * View script path specification string - * @var string - */ - protected $_viewScriptPathSpec = ':controller/:action.:suffix'; - - /** - * View script path specification string, minus controller segment - * @var string - */ - protected $_viewScriptPathNoControllerSpec = ':action.:suffix'; - - /** - * View script suffix - * @var string - */ - protected $_viewSuffix = 'phtml'; - - /** - * Constructor - * - * Optionally set view object and options. - * - * @param Zend_View_Interface $view - * @param array $options - * @return void - */ - public function __construct(Zend_View_Interface $view = null, array $options = array()) - { - if (null !== $view) { - $this->setView($view); - } - - if (!empty($options)) { - $this->_setOptions($options); - } - } - - /** - * Clone - also make sure the view is cloned. - * - * @return void - */ - public function __clone() - { - if (isset($this->view) && $this->view instanceof Zend_View_Interface) { - $this->view = clone $this->view; - - } - } - - /** - * Set the view object - * - * @param Zend_View_Interface $view - * @return Zend_Controller_Action_Helper_ViewRenderer Provides a fluent interface - */ - public function setView(Zend_View_Interface $view) - { - $this->view = $view; - return $this; - } - - /** - * Get current module name - * - * @return string - */ - public function getModule() - { - $request = $this->getRequest(); - $module = $request->getModuleName(); - if (null === $module) { - $module = $this->getFrontController()->getDispatcher()->getDefaultModule(); - } - - return $module; - } - - /** - * Get module directory - * - * @throws Zend_Controller_Action_Exception - * @return string - */ - public function getModuleDirectory() - { - $module = $this->getModule(); - $moduleDir = $this->getFrontController()->getControllerDirectory($module); - if ((null === $moduleDir) || is_array($moduleDir)) { - /** - * @see Zend_Controller_Action_Exception - */ - #require_once 'Zend/Controller/Action/Exception.php'; - throw new Zend_Controller_Action_Exception('ViewRenderer cannot locate module directory for module "' . $module . '"'); - } - $this->_moduleDir = dirname($moduleDir); - return $this->_moduleDir; - } - - /** - * Get inflector - * - * @return Zend_Filter_Inflector - */ - public function getInflector() - { - if (null === $this->_inflector) { - /** - * @see Zend_Filter_Inflector - */ - #require_once 'Zend/Filter/Inflector.php'; - /** - * @see Zend_Filter_PregReplace - */ - #require_once 'Zend/Filter/PregReplace.php'; - /** - * @see Zend_Filter_Word_UnderscoreToSeparator - */ - #require_once 'Zend/Filter/Word/UnderscoreToSeparator.php'; - $this->_inflector = new Zend_Filter_Inflector(); - $this->_inflector->setStaticRuleReference('moduleDir', $this->_moduleDir) // moduleDir must be specified before the less specific 'module' - ->addRules(array( - ':module' => array('Word_CamelCaseToDash', 'StringToLower'), - ':controller' => array('Word_CamelCaseToDash', new Zend_Filter_Word_UnderscoreToSeparator('/'), 'StringToLower', new Zend_Filter_PregReplace('/\./', '-')), - ':action' => array('Word_CamelCaseToDash', new Zend_Filter_PregReplace('#[^a-z0-9' . preg_quote('/', '#') . ']+#i', '-'), 'StringToLower'), - )) - ->setStaticRuleReference('suffix', $this->_viewSuffix) - ->setTargetReference($this->_inflectorTarget); - } - - // Ensure that module directory is current - $this->getModuleDirectory(); - - return $this->_inflector; - } - - /** - * Set inflector - * - * @param Zend_Filter_Inflector $inflector - * @param boolean $reference Whether the moduleDir, target, and suffix should be set as references to ViewRenderer properties - * @return Zend_Controller_Action_Helper_ViewRenderer Provides a fluent interface - */ - public function setInflector(Zend_Filter_Inflector $inflector, $reference = false) - { - $this->_inflector = $inflector; - if ($reference) { - $this->_inflector->setStaticRuleReference('suffix', $this->_viewSuffix) - ->setStaticRuleReference('moduleDir', $this->_moduleDir) - ->setTargetReference($this->_inflectorTarget); - } - return $this; - } - - /** - * Set inflector target - * - * @param string $target - * @return void - */ - protected function _setInflectorTarget($target) - { - $this->_inflectorTarget = (string) $target; - } - - /** - * Set internal module directory representation - * - * @param string $dir - * @return void - */ - protected function _setModuleDir($dir) - { - $this->_moduleDir = (string) $dir; - } - - /** - * Get internal module directory representation - * - * @return string - */ - protected function _getModuleDir() - { - return $this->_moduleDir; - } - - /** - * Generate a class prefix for helper and filter classes - * - * @return string - */ - protected function _generateDefaultPrefix() - { - $default = 'Zend_View'; - if (null === $this->_actionController) { - return $default; - } - - $class = get_class($this->_actionController); - - if (!strstr($class, '_')) { - return $default; - } - - $module = $this->getModule(); - if ('default' == $module) { - return $default; - } - - $prefix = substr($class, 0, strpos($class, '_')) . '_View'; - - return $prefix; - } - - /** - * Retrieve base path based on location of current action controller - * - * @return string - */ - protected function _getBasePath() - { - if (null === $this->_actionController) { - return './views'; - } - - $inflector = $this->getInflector(); - $this->_setInflectorTarget($this->getViewBasePathSpec()); - - $dispatcher = $this->getFrontController()->getDispatcher(); - $request = $this->getRequest(); - - $parts = array( - 'module' => (($moduleName = $request->getModuleName()) != '') ? $dispatcher->formatModuleName($moduleName) : $moduleName, - 'controller' => $request->getControllerName(), - 'action' => $dispatcher->formatActionName($request->getActionName()) - ); - - $path = $inflector->filter($parts); - return $path; - } - - /** - * Set options - * - * @param array $options - * @return Zend_Controller_Action_Helper_ViewRenderer Provides a fluent interface - */ - protected function _setOptions(array $options) - { - foreach ($options as $key => $value) - { - switch ($key) { - case 'neverRender': - case 'neverController': - case 'noController': - case 'noRender': - $property = '_' . $key; - $this->{$property} = ($value) ? true : false; - break; - case 'responseSegment': - case 'scriptAction': - case 'viewBasePathSpec': - case 'viewScriptPathSpec': - case 'viewScriptPathNoControllerSpec': - case 'viewSuffix': - $property = '_' . $key; - $this->{$property} = (string) $value; - break; - default: - break; - } - } - - return $this; - } - - /** - * Initialize the view object - * - * $options may contain the following keys: - * - neverRender - flag dis/enabling postDispatch() autorender (affects all subsequent calls) - * - noController - flag indicating whether or not to look for view scripts in subdirectories named after the controller - * - noRender - flag indicating whether or not to autorender postDispatch() - * - responseSegment - which named response segment to render a view script to - * - scriptAction - what action script to render - * - viewBasePathSpec - specification to use for determining view base path - * - viewScriptPathSpec - specification to use for determining view script paths - * - viewScriptPathNoControllerSpec - specification to use for determining view script paths when noController flag is set - * - viewSuffix - what view script filename suffix to use - * - * @param string $path - * @param string $prefix - * @param array $options - * @throws Zend_Controller_Action_Exception - * @return void - */ - public function initView($path = null, $prefix = null, array $options = array()) - { - if (null === $this->view) { - $this->setView(new Zend_View()); - } - - // Reset some flags every time - $options['noController'] = (isset($options['noController'])) ? $options['noController'] : false; - $options['noRender'] = (isset($options['noRender'])) ? $options['noRender'] : false; - $this->_scriptAction = null; - $this->_responseSegment = null; - - // Set options first; may be used to determine other initializations - $this->_setOptions($options); - - // Get base view path - if (empty($path)) { - $path = $this->_getBasePath(); - if (empty($path)) { - /** - * @see Zend_Controller_Action_Exception - */ - #require_once 'Zend/Controller/Action/Exception.php'; - throw new Zend_Controller_Action_Exception('ViewRenderer initialization failed: retrieved view base path is empty'); - } - } - - if (null === $prefix) { - $prefix = $this->_generateDefaultPrefix(); - } - - // Determine if this path has already been registered - $currentPaths = $this->view->getScriptPaths(); - $path = str_replace(array('/', '\\'), '/', $path); - $pathExists = false; - foreach ($currentPaths as $tmpPath) { - $tmpPath = str_replace(array('/', '\\'), '/', $tmpPath); - if (strstr($tmpPath, $path)) { - $pathExists = true; - break; - } - } - if (!$pathExists) { - $this->view->addBasePath($path, $prefix); - } - - // Register view with action controller (unless already registered) - if ((null !== $this->_actionController) && (null === $this->_actionController->view)) { - $this->_actionController->view = $this->view; - $this->_actionController->viewSuffix = $this->_viewSuffix; - } - } - - /** - * init - initialize view - * - * @return void - */ - public function init() - { - if ($this->getFrontController()->getParam('noViewRenderer')) { - return; - } - - $this->initView(); - } - - /** - * Set view basePath specification - * - * Specification can contain one or more of the following: - * - :moduleDir - current module directory - * - :controller - name of current controller in the request - * - :action - name of current action in the request - * - :module - name of current module in the request - * - * @param string $path - * @return Zend_Controller_Action_Helper_ViewRenderer Provides a fluent interface - */ - public function setViewBasePathSpec($path) - { - $this->_viewBasePathSpec = (string) $path; - return $this; - } - - /** - * Retrieve the current view basePath specification string - * - * @return string - */ - public function getViewBasePathSpec() - { - return $this->_viewBasePathSpec; - } - - /** - * Set view script path specification - * - * Specification can contain one or more of the following: - * - :moduleDir - current module directory - * - :controller - name of current controller in the request - * - :action - name of current action in the request - * - :module - name of current module in the request - * - * @param string $path - * @return Zend_Controller_Action_Helper_ViewRenderer Provides a fluent interface - */ - public function setViewScriptPathSpec($path) - { - $this->_viewScriptPathSpec = (string) $path; - return $this; - } - - /** - * Retrieve the current view script path specification string - * - * @return string - */ - public function getViewScriptPathSpec() - { - return $this->_viewScriptPathSpec; - } - - /** - * Set view script path specification (no controller variant) - * - * Specification can contain one or more of the following: - * - :moduleDir - current module directory - * - :controller - name of current controller in the request - * - :action - name of current action in the request - * - :module - name of current module in the request - * - * :controller will likely be ignored in this variant. - * - * @param string $path - * @return Zend_Controller_Action_Helper_ViewRenderer Provides a fluent interface - */ - public function setViewScriptPathNoControllerSpec($path) - { - $this->_viewScriptPathNoControllerSpec = (string) $path; - return $this; - } - - /** - * Retrieve the current view script path specification string (no controller variant) - * - * @return string - */ - public function getViewScriptPathNoControllerSpec() - { - return $this->_viewScriptPathNoControllerSpec; - } - - /** - * Get a view script based on an action and/or other variables - * - * Uses values found in current request if no values passed in $vars. - * - * If {@link $_noController} is set, uses {@link $_viewScriptPathNoControllerSpec}; - * otherwise, uses {@link $_viewScriptPathSpec}. - * - * @param string $action - * @param array $vars - * @return string - */ - public function getViewScript($action = null, array $vars = array()) - { - $request = $this->getRequest(); - if ((null === $action) && (!isset($vars['action']))) { - $action = $this->getScriptAction(); - if (null === $action) { - $action = $request->getActionName(); - } - $vars['action'] = $action; - } elseif (null !== $action) { - $vars['action'] = $action; - } - - $replacePattern = array('/[^a-z0-9]+$/i', '/^[^a-z0-9]+/i'); - $vars['action'] = preg_replace($replacePattern, '', $vars['action']); - - $inflector = $this->getInflector(); - if ($this->getNoController() || $this->getNeverController()) { - $this->_setInflectorTarget($this->getViewScriptPathNoControllerSpec()); - } else { - $this->_setInflectorTarget($this->getViewScriptPathSpec()); - } - return $this->_translateSpec($vars); - } - - /** - * Set the neverRender flag (i.e., globally dis/enable autorendering) - * - * @param boolean $flag - * @return Zend_Controller_Action_Helper_ViewRenderer Provides a fluent interface - */ - public function setNeverRender($flag = true) - { - $this->_neverRender = ($flag) ? true : false; - return $this; - } - - /** - * Retrieve neverRender flag value - * - * @return boolean - */ - public function getNeverRender() - { - return $this->_neverRender; - } - - /** - * Set the noRender flag (i.e., whether or not to autorender) - * - * @param boolean $flag - * @return Zend_Controller_Action_Helper_ViewRenderer Provides a fluent interface - */ - public function setNoRender($flag = true) - { - $this->_noRender = ($flag) ? true : false; - return $this; - } - - /** - * Retrieve noRender flag value - * - * @return boolean - */ - public function getNoRender() - { - return $this->_noRender; - } - - /** - * Set the view script to use - * - * @param string $name - * @return Zend_Controller_Action_Helper_ViewRenderer Provides a fluent interface - */ - public function setScriptAction($name) - { - $this->_scriptAction = (string) $name; - return $this; - } - - /** - * Retrieve view script name - * - * @return string - */ - public function getScriptAction() - { - return $this->_scriptAction; - } - - /** - * Set the response segment name - * - * @param string $name - * @return Zend_Controller_Action_Helper_ViewRenderer Provides a fluent interface - */ - public function setResponseSegment($name) - { - if (null === $name) { - $this->_responseSegment = null; - } else { - $this->_responseSegment = (string) $name; - } - - return $this; - } - - /** - * Retrieve named response segment name - * - * @return string - */ - public function getResponseSegment() - { - return $this->_responseSegment; - } - - /** - * Set the noController flag (i.e., whether or not to render into controller subdirectories) - * - * @param boolean $flag - * @return Zend_Controller_Action_Helper_ViewRenderer Provides a fluent interface - */ - public function setNoController($flag = true) - { - $this->_noController = ($flag) ? true : false; - return $this; - } - - /** - * Retrieve noController flag value - * - * @return boolean - */ - public function getNoController() - { - return $this->_noController; - } - - /** - * Set the neverController flag (i.e., whether or not to render into controller subdirectories) - * - * @param boolean $flag - * @return Zend_Controller_Action_Helper_ViewRenderer Provides a fluent interface - */ - public function setNeverController($flag = true) - { - $this->_neverController = ($flag) ? true : false; - return $this; - } - - /** - * Retrieve neverController flag value - * - * @return boolean - */ - public function getNeverController() - { - return $this->_neverController; - } - - /** - * Set view script suffix - * - * @param string $suffix - * @return Zend_Controller_Action_Helper_ViewRenderer Provides a fluent interface - */ - public function setViewSuffix($suffix) - { - $this->_viewSuffix = (string) $suffix; - return $this; - } - - /** - * Get view script suffix - * - * @return string - */ - public function getViewSuffix() - { - return $this->_viewSuffix; - } - - /** - * Set options for rendering a view script - * - * @param string $action View script to render - * @param string $name Response named segment to render to - * @param boolean $noController Whether or not to render within a subdirectory named after the controller - * @return Zend_Controller_Action_Helper_ViewRenderer Provides a fluent interface - */ - public function setRender($action = null, $name = null, $noController = null) - { - if (null !== $action) { - $this->setScriptAction($action); - } - - if (null !== $name) { - $this->setResponseSegment($name); - } - - if (null !== $noController) { - $this->setNoController($noController); - } - - return $this; - } - - /** - * Inflect based on provided vars - * - * Allowed variables are: - * - :moduleDir - current module directory - * - :module - current module name - * - :controller - current controller name - * - :action - current action name - * - :suffix - view script file suffix - * - * @param array $vars - * @return string - */ - protected function _translateSpec(array $vars = array()) - { - $inflector = $this->getInflector(); - $request = $this->getRequest(); - $dispatcher = $this->getFrontController()->getDispatcher(); - - // Format module name - $module = $dispatcher->formatModuleName($request->getModuleName()); - - // Format controller name - #require_once 'Zend/Filter/Word/CamelCaseToDash.php'; - $filter = new Zend_Filter_Word_CamelCaseToDash(); - $controller = $filter->filter($request->getControllerName()); - $controller = $dispatcher->formatControllerName($controller); - if ('Controller' == substr($controller, -10)) { - $controller = substr($controller, 0, -10); - } - - // Format action name - $action = $dispatcher->formatActionName($request->getActionName()); - - $params = compact('module', 'controller', 'action'); - foreach ($vars as $key => $value) { - switch ($key) { - case 'module': - case 'controller': - case 'action': - case 'moduleDir': - case 'suffix': - $params[$key] = (string) $value; - break; - default: - break; - } - } - - if (isset($params['suffix'])) { - $origSuffix = $this->getViewSuffix(); - $this->setViewSuffix($params['suffix']); - } - if (isset($params['moduleDir'])) { - $origModuleDir = $this->_getModuleDir(); - $this->_setModuleDir($params['moduleDir']); - } - - $filtered = $inflector->filter($params); - - if (isset($params['suffix'])) { - $this->setViewSuffix($origSuffix); - } - if (isset($params['moduleDir'])) { - $this->_setModuleDir($origModuleDir); - } - - return $filtered; - } - - /** - * Render a view script (optionally to a named response segment) - * - * Sets the noRender flag to true when called. - * - * @param string $script - * @param string $name - * @return void - */ - public function renderScript($script, $name = null) - { - if (null === $name) { - $name = $this->getResponseSegment(); - } - - $this->getResponse()->appendBody( - $this->view->render($script), - $name - ); - - $this->setNoRender(); - } - - /** - * Render a view based on path specifications - * - * Renders a view based on the view script path specifications. - * - * @param string $action - * @param string $name - * @param boolean $noController - * @return void - */ - public function render($action = null, $name = null, $noController = null) - { - $this->setRender($action, $name, $noController); - $path = $this->getViewScript(); - $this->renderScript($path, $name); - } - - /** - * Render a script based on specification variables - * - * Pass an action, and one or more specification variables (view script suffix) - * to determine the view script path, and render that script. - * - * @param string $action - * @param array $vars - * @param string $name - * @return void - */ - public function renderBySpec($action = null, array $vars = array(), $name = null) - { - if (null !== $name) { - $this->setResponseSegment($name); - } - - $path = $this->getViewScript($action, $vars); - - $this->renderScript($path); - } - - /** - * postDispatch - auto render a view - * - * Only autorenders if: - * - _noRender is false - * - action controller is present - * - request has not been re-dispatched (i.e., _forward() has not been called) - * - response is not a redirect - * - * @return void - */ - public function postDispatch() - { - if ($this->_shouldRender()) { - $this->render(); - } - } - - /** - * Should the ViewRenderer render a view script? - * - * @return boolean - */ - protected function _shouldRender() - { - return (!$this->getFrontController()->getParam('noViewRenderer') - && !$this->_neverRender - && !$this->_noRender - && (null !== $this->_actionController) - && $this->getRequest()->isDispatched() - && !$this->getResponse()->isRedirect() - ); - } - - /** - * Use this helper as a method; proxies to setRender() - * - * @param string $action - * @param string $name - * @param boolean $noController - * @return void - */ - public function direct($action = null, $name = null, $noController = null) - { - $this->setRender($action, $name, $noController); - } -} diff --git a/library/Zend/Controller/Action/HelperBroker.php b/library/Zend/Controller/Action/HelperBroker.php deleted file mode 100644 index 8f5b0e74f9..0000000000 --- a/library/Zend/Controller/Action/HelperBroker.php +++ /dev/null @@ -1,381 +0,0 @@ - 'Zend/Controller/Action/Helper/', - )); - } - return self::$_pluginLoader; - } - - /** - * addPrefix() - Add repository of helpers by prefix - * - * @param string $prefix - */ - static public function addPrefix($prefix) - { - $prefix = rtrim($prefix, '_'); - $path = str_replace('_', DIRECTORY_SEPARATOR, $prefix); - self::getPluginLoader()->addPrefixPath($prefix, $path); - } - - /** - * addPath() - Add path to repositories where Action_Helpers could be found. - * - * @param string $path - * @param string $prefix Optional; defaults to 'Zend_Controller_Action_Helper' - * @return void - */ - static public function addPath($path, $prefix = 'Zend_Controller_Action_Helper') - { - self::getPluginLoader()->addPrefixPath($prefix, $path); - } - - /** - * addHelper() - Add helper objects - * - * @param Zend_Controller_Action_Helper_Abstract $helper - * @return void - */ - static public function addHelper(Zend_Controller_Action_Helper_Abstract $helper) - { - self::getStack()->push($helper); - return; - } - - /** - * resetHelpers() - * - * @return void - */ - static public function resetHelpers() - { - self::$_stack = null; - return; - } - - /** - * Retrieve or initialize a helper statically - * - * Retrieves a helper object statically, loading on-demand if the helper - * does not already exist in the stack. Always returns a helper, unless - * the helper class cannot be found. - * - * @param string $name - * @return Zend_Controller_Action_Helper_Abstract - */ - public static function getStaticHelper($name) - { - $name = self::_normalizeHelperName($name); - $stack = self::getStack(); - - if (!isset($stack->{$name})) { - self::_loadHelper($name); - } - - return $stack->{$name}; - } - - /** - * getExistingHelper() - get helper by name - * - * Static method to retrieve helper object. Only retrieves helpers already - * initialized with the broker (either via addHelper() or on-demand loading - * via getHelper()). - * - * Throws an exception if the referenced helper does not exist in the - * stack; use {@link hasHelper()} to check if the helper is registered - * prior to retrieving it. - * - * @param string $name - * @return Zend_Controller_Action_Helper_Abstract - * @throws Zend_Controller_Action_Exception - */ - public static function getExistingHelper($name) - { - $name = self::_normalizeHelperName($name); - $stack = self::getStack(); - - if (!isset($stack->{$name})) { - #require_once 'Zend/Controller/Action/Exception.php'; - throw new Zend_Controller_Action_Exception('Action helper "' . $name . '" has not been registered with the helper broker'); - } - - return $stack->{$name}; - } - - /** - * Return all registered helpers as helper => object pairs - * - * @return array - */ - public static function getExistingHelpers() - { - return self::getStack()->getHelpersByName(); - } - - /** - * Is a particular helper loaded in the broker? - * - * @param string $name - * @return boolean - */ - public static function hasHelper($name) - { - $name = self::_normalizeHelperName($name); - return isset(self::getStack()->{$name}); - } - - /** - * Remove a particular helper from the broker - * - * @param string $name - * @return boolean - */ - public static function removeHelper($name) - { - $name = self::_normalizeHelperName($name); - $stack = self::getStack(); - if (isset($stack->{$name})) { - unset($stack->{$name}); - } - - return false; - } - - /** - * Lazy load the priority stack and return it - * - * @return Zend_Controller_Action_HelperBroker_PriorityStack - */ - public static function getStack() - { - if (self::$_stack == null) { - self::$_stack = new Zend_Controller_Action_HelperBroker_PriorityStack(); - } - - return self::$_stack; - } - - /** - * Constructor - * - * @param Zend_Controller_Action $actionController - * @return void - */ - public function __construct(Zend_Controller_Action $actionController) - { - $this->_actionController = $actionController; - foreach (self::getStack() as $helper) { - $helper->setActionController($actionController); - $helper->init(); - } - } - - /** - * notifyPreDispatch() - called by action controller dispatch method - * - * @return void - */ - public function notifyPreDispatch() - { - foreach (self::getStack() as $helper) { - $helper->preDispatch(); - } - } - - /** - * notifyPostDispatch() - called by action controller dispatch method - * - * @return void - */ - public function notifyPostDispatch() - { - foreach (self::getStack() as $helper) { - $helper->postDispatch(); - } - } - - /** - * getHelper() - get helper by name - * - * @param string $name - * @return Zend_Controller_Action_Helper_Abstract - */ - public function getHelper($name) - { - $name = self::_normalizeHelperName($name); - $stack = self::getStack(); - - if (!isset($stack->{$name})) { - self::_loadHelper($name); - } - - $helper = $stack->{$name}; - - $initialize = false; - if (null === ($actionController = $helper->getActionController())) { - $initialize = true; - } elseif ($actionController !== $this->_actionController) { - $initialize = true; - } - - if ($initialize) { - $helper->setActionController($this->_actionController) - ->init(); - } - - return $helper; - } - - /** - * Method overloading - * - * @param string $method - * @param array $args - * @return mixed - * @throws Zend_Controller_Action_Exception if helper does not have a direct() method - */ - public function __call($method, $args) - { - $helper = $this->getHelper($method); - if (!method_exists($helper, 'direct')) { - #require_once 'Zend/Controller/Action/Exception.php'; - throw new Zend_Controller_Action_Exception('Helper "' . $method . '" does not support overloading via direct()'); - } - return call_user_func_array(array($helper, 'direct'), $args); - } - - /** - * Retrieve helper by name as object property - * - * @param string $name - * @return Zend_Controller_Action_Helper_Abstract - */ - public function __get($name) - { - return $this->getHelper($name); - } - - /** - * Normalize helper name for lookups - * - * @param string $name - * @return string - */ - protected static function _normalizeHelperName($name) - { - if (strpos($name, '_') !== false) { - $name = str_replace(' ', '', ucwords(str_replace('_', ' ', $name))); - } - - return ucfirst($name); - } - - /** - * Load a helper - * - * @param string $name - * @return void - */ - protected static function _loadHelper($name) - { - try { - $class = self::getPluginLoader()->load($name); - } catch (Zend_Loader_PluginLoader_Exception $e) { - #require_once 'Zend/Controller/Action/Exception.php'; - throw new Zend_Controller_Action_Exception('Action Helper by name ' . $name . ' not found', 0, $e); - } - - $helper = new $class(); - - if (!$helper instanceof Zend_Controller_Action_Helper_Abstract) { - #require_once 'Zend/Controller/Action/Exception.php'; - throw new Zend_Controller_Action_Exception('Helper name ' . $name . ' -> class ' . $class . ' is not of type Zend_Controller_Action_Helper_Abstract'); - } - - self::getStack()->push($helper); - } -} diff --git a/library/Zend/Controller/Action/HelperBroker/PriorityStack.php b/library/Zend/Controller/Action/HelperBroker/PriorityStack.php deleted file mode 100644 index 24630fdc47..0000000000 --- a/library/Zend/Controller/Action/HelperBroker/PriorityStack.php +++ /dev/null @@ -1,280 +0,0 @@ -_helpersByNameRef)) { - return false; - } - - return $this->_helpersByNameRef[$helperName]; - } - - /** - * Magic property overloading for returning if helper is set by name - * - * @param string $helperName The helper name - * @return Zend_Controller_Action_Helper_Abstract - */ - public function __isset($helperName) - { - return array_key_exists($helperName, $this->_helpersByNameRef); - } - - /** - * Magic property overloading for unsetting if helper is exists by name - * - * @param string $helperName The helper name - * @return Zend_Controller_Action_Helper_Abstract - */ - public function __unset($helperName) - { - return $this->offsetUnset($helperName); - } - - /** - * push helper onto the stack - * - * @param Zend_Controller_Action_Helper_Abstract $helper - * @return Zend_Controller_Action_HelperBroker_PriorityStack - */ - public function push(Zend_Controller_Action_Helper_Abstract $helper) - { - $this->offsetSet($this->getNextFreeHigherPriority(), $helper); - return $this; - } - - /** - * Return something iterable - * - * @return array - */ - public function getIterator() - { - return new ArrayObject($this->_helpersByPriority); - } - - /** - * offsetExists() - * - * @param int|string $priorityOrHelperName - * @return Zend_Controller_Action_HelperBroker_PriorityStack - */ - public function offsetExists($priorityOrHelperName) - { - if (is_string($priorityOrHelperName)) { - return array_key_exists($priorityOrHelperName, $this->_helpersByNameRef); - } else { - return array_key_exists($priorityOrHelperName, $this->_helpersByPriority); - } - } - - /** - * offsetGet() - * - * @param int|string $priorityOrHelperName - * @return Zend_Controller_Action_HelperBroker_PriorityStack - */ - public function offsetGet($priorityOrHelperName) - { - if (!$this->offsetExists($priorityOrHelperName)) { - #require_once 'Zend/Controller/Action/Exception.php'; - throw new Zend_Controller_Action_Exception('A helper with priority ' . $priorityOrHelperName . ' does not exist.'); - } - - if (is_string($priorityOrHelperName)) { - return $this->_helpersByNameRef[$priorityOrHelperName]; - } else { - return $this->_helpersByPriority[$priorityOrHelperName]; - } - } - - /** - * offsetSet() - * - * @param int $priority - * @param Zend_Controller_Action_Helper_Abstract $helper - * @return Zend_Controller_Action_HelperBroker_PriorityStack - */ - public function offsetSet($priority, $helper) - { - $priority = (int) $priority; - - if (!$helper instanceof Zend_Controller_Action_Helper_Abstract) { - #require_once 'Zend/Controller/Action/Exception.php'; - throw new Zend_Controller_Action_Exception('$helper must extend Zend_Controller_Action_Helper_Abstract.'); - } - - if (array_key_exists($helper->getName(), $this->_helpersByNameRef)) { - // remove any object with the same name to retain BC compailitbility - // @todo At ZF 2.0 time throw an exception here. - $this->offsetUnset($helper->getName()); - } - - if (array_key_exists($priority, $this->_helpersByPriority)) { - $priority = $this->getNextFreeHigherPriority($priority); // ensures LIFO - trigger_error("A helper with the same priority already exists, reassigning to $priority", E_USER_WARNING); - } - - $this->_helpersByPriority[$priority] = $helper; - $this->_helpersByNameRef[$helper->getName()] = $helper; - - if ($priority == ($nextFreeDefault = $this->getNextFreeHigherPriority($this->_nextDefaultPriority))) { - $this->_nextDefaultPriority = $nextFreeDefault; - } - - krsort($this->_helpersByPriority); // always make sure priority and LIFO are both enforced - return $this; - } - - /** - * offsetUnset() - * - * @param int|string $priorityOrHelperName Priority integer or the helper name - * @return Zend_Controller_Action_HelperBroker_PriorityStack - */ - public function offsetUnset($priorityOrHelperName) - { - if (!$this->offsetExists($priorityOrHelperName)) { - #require_once 'Zend/Controller/Action/Exception.php'; - throw new Zend_Controller_Action_Exception('A helper with priority or name ' . $priorityOrHelperName . ' does not exist.'); - } - - if (is_string($priorityOrHelperName)) { - $helperName = $priorityOrHelperName; - $helper = $this->_helpersByNameRef[$helperName]; - $priority = array_search($helper, $this->_helpersByPriority, true); - } else { - $priority = $priorityOrHelperName; - $helperName = $this->_helpersByPriority[$priorityOrHelperName]->getName(); - } - - unset($this->_helpersByNameRef[$helperName]); - unset($this->_helpersByPriority[$priority]); - return $this; - } - - /** - * return the count of helpers - * - * @return int - */ - public function count() - { - return count($this->_helpersByPriority); - } - - /** - * Find the next free higher priority. If an index is given, it will - * find the next free highest priority after it. - * - * @param int $indexPriority OPTIONAL - * @return int - */ - public function getNextFreeHigherPriority($indexPriority = null) - { - if ($indexPriority == null) { - $indexPriority = $this->_nextDefaultPriority; - } - - $priorities = array_keys($this->_helpersByPriority); - - while (in_array($indexPriority, $priorities)) { - $indexPriority++; - } - - return $indexPriority; - } - - /** - * Find the next free lower priority. If an index is given, it will - * find the next free lower priority before it. - * - * @param int $indexPriority - * @return int - */ - public function getNextFreeLowerPriority($indexPriority = null) - { - if ($indexPriority == null) { - $indexPriority = $this->_nextDefaultPriority; - } - - $priorities = array_keys($this->_helpersByPriority); - - while (in_array($indexPriority, $priorities)) { - $indexPriority--; - } - - return $indexPriority; - } - - /** - * return the highest priority - * - * @return int - */ - public function getHighestPriority() - { - return max(array_keys($this->_helpersByPriority)); - } - - /** - * return the lowest priority - * - * @return int - */ - public function getLowestPriority() - { - return min(array_keys($this->_helpersByPriority)); - } - - /** - * return the helpers referenced by name - * - * @return array - */ - public function getHelpersByName() - { - return $this->_helpersByNameRef; - } - -} diff --git a/library/Zend/Controller/Action/Interface.php b/library/Zend/Controller/Action/Interface.php deleted file mode 100644 index db354637a1..0000000000 --- a/library/Zend/Controller/Action/Interface.php +++ /dev/null @@ -1,69 +0,0 @@ -setParams($params); - } - - /** - * Formats a string into a controller name. This is used to take a raw - * controller name, such as one stored inside a Zend_Controller_Request_Abstract - * object, and reformat it to a proper class name that a class extending - * Zend_Controller_Action would use. - * - * @param string $unformatted - * @return string - */ - public function formatControllerName($unformatted) - { - return ucfirst($this->_formatName($unformatted)) . 'Controller'; - } - - /** - * Formats a string into an action name. This is used to take a raw - * action name, such as one that would be stored inside a Zend_Controller_Request_Abstract - * object, and reformat into a proper method name that would be found - * inside a class extending Zend_Controller_Action. - * - * @param string $unformatted - * @return string - */ - public function formatActionName($unformatted) - { - $formatted = $this->_formatName($unformatted, true); - return strtolower(substr($formatted, 0, 1)) . substr($formatted, 1) . 'Action'; - } - - /** - * Verify delimiter - * - * Verify a delimiter to use in controllers or actions. May be a single - * string or an array of strings. - * - * @param string|array $spec - * @return array - * @throws Zend_Controller_Dispatcher_Exception with invalid delimiters - */ - public function _verifyDelimiter($spec) - { - if (is_string($spec)) { - return (array) $spec; - } elseif (is_array($spec)) { - $allStrings = true; - foreach ($spec as $delim) { - if (!is_string($delim)) { - $allStrings = false; - break; - } - } - - if (!$allStrings) { - #require_once 'Zend/Controller/Dispatcher/Exception.php'; - throw new Zend_Controller_Dispatcher_Exception('Word delimiter array must contain only strings'); - } - - return $spec; - } - - #require_once 'Zend/Controller/Dispatcher/Exception.php'; - throw new Zend_Controller_Dispatcher_Exception('Invalid word delimiter'); - } - - /** - * Retrieve the word delimiter character(s) used in - * controller or action names - * - * @return array - */ - public function getWordDelimiter() - { - return $this->_wordDelimiter; - } - - /** - * Set word delimiter - * - * Set the word delimiter to use in controllers and actions. May be a - * single string or an array of strings. - * - * @param string|array $spec - * @return Zend_Controller_Dispatcher_Abstract - */ - public function setWordDelimiter($spec) - { - $spec = $this->_verifyDelimiter($spec); - $this->_wordDelimiter = $spec; - - return $this; - } - - /** - * Retrieve the path delimiter character(s) used in - * controller names - * - * @return array - */ - public function getPathDelimiter() - { - return $this->_pathDelimiter; - } - - /** - * Set path delimiter - * - * Set the path delimiter to use in controllers. May be a single string or - * an array of strings. - * - * @param string $spec - * @return Zend_Controller_Dispatcher_Abstract - */ - public function setPathDelimiter($spec) - { - if (!is_string($spec)) { - #require_once 'Zend/Controller/Dispatcher/Exception.php'; - throw new Zend_Controller_Dispatcher_Exception('Invalid path delimiter'); - } - $this->_pathDelimiter = $spec; - - return $this; - } - - /** - * Formats a string from a URI into a PHP-friendly name. - * - * By default, replaces words separated by the word separator character(s) - * with camelCaps. If $isAction is false, it also preserves replaces words - * separated by the path separation character with an underscore, making - * the following word Title cased. All non-alphanumeric characters are - * removed. - * - * @param string $unformatted - * @param boolean $isAction Defaults to false - * @return string - */ - protected function _formatName($unformatted, $isAction = false) - { - // preserve directories - if (!$isAction) { - $segments = explode($this->getPathDelimiter(), $unformatted); - } else { - $segments = (array) $unformatted; - } - - foreach ($segments as $key => $segment) { - $segment = str_replace($this->getWordDelimiter(), ' ', strtolower($segment)); - $segment = preg_replace('/[^a-z0-9 ]/', '', $segment); - $segments[$key] = str_replace(' ', '', ucwords($segment)); - } - - return implode('_', $segments); - } - - /** - * Retrieve front controller instance - * - * @return Zend_Controller_Front - */ - public function getFrontController() - { - if (null === $this->_frontController) { - #require_once 'Zend/Controller/Front.php'; - $this->_frontController = Zend_Controller_Front::getInstance(); - } - - return $this->_frontController; - } - - /** - * Set front controller instance - * - * @param Zend_Controller_Front $controller - * @return Zend_Controller_Dispatcher_Abstract - */ - public function setFrontController(Zend_Controller_Front $controller) - { - $this->_frontController = $controller; - return $this; - } - - /** - * Add or modify a parameter to use when instantiating an action controller - * - * @param string $name - * @param mixed $value - * @return Zend_Controller_Dispatcher_Abstract - */ - public function setParam($name, $value) - { - $name = (string) $name; - $this->_invokeParams[$name] = $value; - return $this; - } - - /** - * Set parameters to pass to action controller constructors - * - * @param array $params - * @return Zend_Controller_Dispatcher_Abstract - */ - public function setParams(array $params) - { - $this->_invokeParams = array_merge($this->_invokeParams, $params); - return $this; - } - - /** - * Retrieve a single parameter from the controller parameter stack - * - * @param string $name - * @return mixed - */ - public function getParam($name) - { - if(isset($this->_invokeParams[$name])) { - return $this->_invokeParams[$name]; - } - - return null; - } - - /** - * Retrieve action controller instantiation parameters - * - * @return array - */ - public function getParams() - { - return $this->_invokeParams; - } - - /** - * Clear the controller parameter stack - * - * By default, clears all parameters. If a parameter name is given, clears - * only that parameter; if an array of parameter names is provided, clears - * each. - * - * @param null|string|array single key or array of keys for params to clear - * @return Zend_Controller_Dispatcher_Abstract - */ - public function clearParams($name = null) - { - if (null === $name) { - $this->_invokeParams = array(); - } elseif (is_string($name) && isset($this->_invokeParams[$name])) { - unset($this->_invokeParams[$name]); - } elseif (is_array($name)) { - foreach ($name as $key) { - if (is_string($key) && isset($this->_invokeParams[$key])) { - unset($this->_invokeParams[$key]); - } - } - } - - return $this; - } - - /** - * Set response object to pass to action controllers - * - * @param Zend_Controller_Response_Abstract|null $response - * @return Zend_Controller_Dispatcher_Abstract - */ - public function setResponse(Zend_Controller_Response_Abstract $response = null) - { - $this->_response = $response; - return $this; - } - - /** - * Return the registered response object - * - * @return Zend_Controller_Response_Abstract|null - */ - public function getResponse() - { - return $this->_response; - } - - /** - * Set the default controller (minus any formatting) - * - * @param string $controller - * @return Zend_Controller_Dispatcher_Abstract - */ - public function setDefaultControllerName($controller) - { - $this->_defaultController = (string) $controller; - return $this; - } - - /** - * Retrieve the default controller name (minus formatting) - * - * @return string - */ - public function getDefaultControllerName() - { - return $this->_defaultController; - } - - /** - * Set the default action (minus any formatting) - * - * @param string $action - * @return Zend_Controller_Dispatcher_Abstract - */ - public function setDefaultAction($action) - { - $this->_defaultAction = (string) $action; - return $this; - } - - /** - * Retrieve the default action name (minus formatting) - * - * @return string - */ - public function getDefaultAction() - { - return $this->_defaultAction; - } - - /** - * Set the default module - * - * @param string $module - * @return Zend_Controller_Dispatcher_Abstract - */ - public function setDefaultModule($module) - { - $this->_defaultModule = (string) $module; - return $this; - } - - /** - * Retrieve the default module - * - * @return string - */ - public function getDefaultModule() - { - return $this->_defaultModule; - } -} diff --git a/library/Zend/Controller/Dispatcher/Exception.php b/library/Zend/Controller/Dispatcher/Exception.php deleted file mode 100644 index 7a295dc447..0000000000 --- a/library/Zend/Controller/Dispatcher/Exception.php +++ /dev/null @@ -1,37 +0,0 @@ -_curModule = $this->getDefaultModule(); - } - - /** - * Add a single path to the controller directory stack - * - * @param string $path - * @param string $module - * @return Zend_Controller_Dispatcher_Standard - */ - public function addControllerDirectory($path, $module = null) - { - if (null === $module) { - $module = $this->_defaultModule; - } - - $module = (string) $module; - $path = rtrim((string) $path, '/\\'); - - $this->_controllerDirectory[$module] = $path; - return $this; - } - - /** - * Set controller directory - * - * @param array|string $directory - * @return Zend_Controller_Dispatcher_Standard - */ - public function setControllerDirectory($directory, $module = null) - { - $this->_controllerDirectory = array(); - - if (is_string($directory)) { - $this->addControllerDirectory($directory, $module); - } elseif (is_array($directory)) { - foreach ((array) $directory as $module => $path) { - $this->addControllerDirectory($path, $module); - } - } else { - #require_once 'Zend/Controller/Exception.php'; - throw new Zend_Controller_Exception('Controller directory spec must be either a string or an array'); - } - - return $this; - } - - /** - * Return the currently set directories for Zend_Controller_Action class - * lookup - * - * If a module is specified, returns just that directory. - * - * @param string $module Module name - * @return array|string Returns array of all directories by default, single - * module directory if module argument provided - */ - public function getControllerDirectory($module = null) - { - if (null === $module) { - return $this->_controllerDirectory; - } - - $module = (string) $module; - if (array_key_exists($module, $this->_controllerDirectory)) { - return $this->_controllerDirectory[$module]; - } - - return null; - } - - /** - * Remove a controller directory by module name - * - * @param string $module - * @return bool - */ - public function removeControllerDirectory($module) - { - $module = (string) $module; - if (array_key_exists($module, $this->_controllerDirectory)) { - unset($this->_controllerDirectory[$module]); - return true; - } - return false; - } - - /** - * Format the module name. - * - * @param string $unformatted - * @return string - */ - public function formatModuleName($unformatted) - { - if (($this->_defaultModule == $unformatted) && !$this->getParam('prefixDefaultModule')) { - return $unformatted; - } - - return ucfirst($this->_formatName($unformatted)); - } - - /** - * Format action class name - * - * @param string $moduleName Name of the current module - * @param string $className Name of the action class - * @return string Formatted class name - */ - public function formatClassName($moduleName, $className) - { - return $this->formatModuleName($moduleName) . '_' . $className; - } - - /** - * Convert a class name to a filename - * - * @param string $class - * @return string - */ - public function classToFilename($class) - { - return str_replace('_', DIRECTORY_SEPARATOR, $class) . '.php'; - } - - /** - * Returns TRUE if the Zend_Controller_Request_Abstract object can be - * dispatched to a controller. - * - * Use this method wisely. By default, the dispatcher will fall back to the - * default controller (either in the module specified or the global default) - * if a given controller does not exist. This method returning false does - * not necessarily indicate the dispatcher will not still dispatch the call. - * - * @param Zend_Controller_Request_Abstract $action - * @return boolean - */ - public function isDispatchable(Zend_Controller_Request_Abstract $request) - { - $className = $this->getControllerClass($request); - if (!$className) { - return false; - } - - $finalClass = $className; - if (($this->_defaultModule != $this->_curModule) - || $this->getParam('prefixDefaultModule')) - { - $finalClass = $this->formatClassName($this->_curModule, $className); - } - if (class_exists($finalClass, false)) { - return true; - } - - $fileSpec = $this->classToFilename($className); - $dispatchDir = $this->getDispatchDirectory(); - $test = $dispatchDir . DIRECTORY_SEPARATOR . $fileSpec; - return Zend_Loader::isReadable($test); - } - - /** - * Dispatch to a controller/action - * - * By default, if a controller is not dispatchable, dispatch() will throw - * an exception. If you wish to use the default controller instead, set the - * param 'useDefaultControllerAlways' via {@link setParam()}. - * - * @param Zend_Controller_Request_Abstract $request - * @param Zend_Controller_Response_Abstract $response - * @return void - * @throws Zend_Controller_Dispatcher_Exception - */ - public function dispatch(Zend_Controller_Request_Abstract $request, Zend_Controller_Response_Abstract $response) - { - $this->setResponse($response); - - /** - * Get controller class - */ - if (!$this->isDispatchable($request)) { - $controller = $request->getControllerName(); - if (!$this->getParam('useDefaultControllerAlways') && !empty($controller)) { - #require_once 'Zend/Controller/Dispatcher/Exception.php'; - throw new Zend_Controller_Dispatcher_Exception('Invalid controller specified (' . $request->getControllerName() . ')'); - } - - $className = $this->getDefaultControllerClass($request); - } else { - $className = $this->getControllerClass($request); - if (!$className) { - $className = $this->getDefaultControllerClass($request); - } - } - - /** - * If we're in a module or prefixDefaultModule is on, we must add the module name - * prefix to the contents of $className, as getControllerClass does not do that automatically. - * We must keep a separate variable because modules are not strictly PSR-0: We need the no-module-prefix - * class name to do the class->file mapping, but the full class name to insantiate the controller - */ - $moduleClassName = $className; - if (($this->_defaultModule != $this->_curModule) - || $this->getParam('prefixDefaultModule')) - { - $moduleClassName = $this->formatClassName($this->_curModule, $className); - } - - /** - * Load the controller class file - */ - $className = $this->loadClass($className); - - /** - * Instantiate controller with request, response, and invocation - * arguments; throw exception if it's not an action controller - */ - $controller = new $moduleClassName($request, $this->getResponse(), $this->getParams()); - if (!($controller instanceof Zend_Controller_Action_Interface) && - !($controller instanceof Zend_Controller_Action)) { - #require_once 'Zend/Controller/Dispatcher/Exception.php'; - throw new Zend_Controller_Dispatcher_Exception( - 'Controller "' . $moduleClassName . '" is not an instance of Zend_Controller_Action_Interface' - ); - } - - /** - * Retrieve the action name - */ - $action = $this->getActionMethod($request); - - /** - * Dispatch the method call - */ - $request->setDispatched(true); - - // by default, buffer output - $disableOb = $this->getParam('disableOutputBuffering'); - $obLevel = ob_get_level(); - if (empty($disableOb)) { - ob_start(); - } - - try { - $controller->dispatch($action); - } catch (Exception $e) { - // Clean output buffer on error - $curObLevel = ob_get_level(); - if ($curObLevel > $obLevel) { - do { - ob_get_clean(); - $curObLevel = ob_get_level(); - } while ($curObLevel > $obLevel); - } - throw $e; - } - - if (empty($disableOb)) { - $content = ob_get_clean(); - $response->appendBody($content); - } - - // Destroy the page controller instance and reflection objects - $controller = null; - } - - /** - * Load a controller class - * - * Attempts to load the controller class file from - * {@link getControllerDirectory()}. If the controller belongs to a - * module, looks for the module prefix to the controller class. - * - * @param string $className - * @return string Class name loaded - * @throws Zend_Controller_Dispatcher_Exception if class not loaded - */ - public function loadClass($className) - { - $finalClass = $className; - if (($this->_defaultModule != $this->_curModule) - || $this->getParam('prefixDefaultModule')) - { - $finalClass = $this->formatClassName($this->_curModule, $className); - } - if (class_exists($finalClass, false)) { - return $finalClass; - } - - $dispatchDir = $this->getDispatchDirectory(); - $loadFile = $dispatchDir . DIRECTORY_SEPARATOR . $this->classToFilename($className); - - if (Zend_Loader::isReadable($loadFile)) { - include_once $loadFile; - } else { - #require_once 'Zend/Controller/Dispatcher/Exception.php'; - throw new Zend_Controller_Dispatcher_Exception('Cannot load controller class "' . $className . '" from file "' . $loadFile . "'"); - } - - if (!class_exists($finalClass, false)) { - #require_once 'Zend/Controller/Dispatcher/Exception.php'; - throw new Zend_Controller_Dispatcher_Exception('Invalid controller class ("' . $finalClass . '")'); - } - - return $finalClass; - } - - /** - * Get controller class name - * - * Try request first; if not found, try pulling from request parameter; - * if still not found, fallback to default - * - * @param Zend_Controller_Request_Abstract $request - * @return string|false Returns class name on success - */ - public function getControllerClass(Zend_Controller_Request_Abstract $request) - { - $controllerName = $request->getControllerName(); - if (empty($controllerName)) { - if (!$this->getParam('useDefaultControllerAlways')) { - return false; - } - $controllerName = $this->getDefaultControllerName(); - $request->setControllerName($controllerName); - } - - $className = $this->formatControllerName($controllerName); - - $controllerDirs = $this->getControllerDirectory(); - $module = $request->getModuleName(); - if ($this->isValidModule($module)) { - $this->_curModule = $module; - $this->_curDirectory = $controllerDirs[$module]; - } elseif ($this->isValidModule($this->_defaultModule)) { - $request->setModuleName($this->_defaultModule); - $this->_curModule = $this->_defaultModule; - $this->_curDirectory = $controllerDirs[$this->_defaultModule]; - } else { - #require_once 'Zend/Controller/Exception.php'; - throw new Zend_Controller_Exception('No default module defined for this application'); - } - - return $className; - } - - /** - * Determine if a given module is valid - * - * @param string $module - * @return bool - */ - public function isValidModule($module) - { - if (!is_string($module)) { - return false; - } - - $module = strtolower($module); - $controllerDir = $this->getControllerDirectory(); - foreach (array_keys($controllerDir) as $moduleName) { - if ($module == strtolower($moduleName)) { - return true; - } - } - - return false; - } - - /** - * Retrieve default controller class - * - * Determines whether the default controller to use lies within the - * requested module, or if the global default should be used. - * - * By default, will only use the module default unless that controller does - * not exist; if this is the case, it falls back to the default controller - * in the default module. - * - * @param Zend_Controller_Request_Abstract $request - * @return string - */ - public function getDefaultControllerClass(Zend_Controller_Request_Abstract $request) - { - $controller = $this->getDefaultControllerName(); - $default = $this->formatControllerName($controller); - $request->setControllerName($controller) - ->setActionName(null); - - $module = $request->getModuleName(); - $controllerDirs = $this->getControllerDirectory(); - $this->_curModule = $this->_defaultModule; - $this->_curDirectory = $controllerDirs[$this->_defaultModule]; - if ($this->isValidModule($module)) { - $found = false; - if (class_exists($default, false)) { - $found = true; - } else { - $moduleDir = $controllerDirs[$module]; - $fileSpec = $moduleDir . DIRECTORY_SEPARATOR . $this->classToFilename($default); - if (Zend_Loader::isReadable($fileSpec)) { - $found = true; - $this->_curDirectory = $moduleDir; - } - } - if ($found) { - $request->setModuleName($module); - $this->_curModule = $this->formatModuleName($module); - } - } else { - $request->setModuleName($this->_defaultModule); - } - - return $default; - } - - /** - * Return the value of the currently selected dispatch directory (as set by - * {@link getController()}) - * - * @return string - */ - public function getDispatchDirectory() - { - return $this->_curDirectory; - } - - /** - * Determine the action name - * - * First attempt to retrieve from request; then from request params - * using action key; default to default action - * - * Returns formatted action name - * - * @param Zend_Controller_Request_Abstract $request - * @return string - */ - public function getActionMethod(Zend_Controller_Request_Abstract $request) - { - $action = $request->getActionName(); - if (empty($action)) { - $action = $this->getDefaultAction(); - $request->setActionName($action); - } - - return $this->formatActionName($action); - } -} diff --git a/library/Zend/Controller/Exception.php b/library/Zend/Controller/Exception.php deleted file mode 100644 index f9f04819f5..0000000000 --- a/library/Zend/Controller/Exception.php +++ /dev/null @@ -1,35 +0,0 @@ -_plugins = new Zend_Controller_Plugin_Broker(); - } - - /** - * Enforce singleton; disallow cloning - * - * @return void - */ - private function __clone() - { - } - - /** - * Singleton instance - * - * @return Zend_Controller_Front - */ - public static function getInstance() - { - if (null === self::$_instance) { - self::$_instance = new self(); - } - - return self::$_instance; - } - - /** - * Resets all object properties of the singleton instance - * - * Primarily used for testing; could be used to chain front controllers. - * - * Also resets action helper broker, clearing all registered helpers. - * - * @return void - */ - public function resetInstance() - { - $reflection = new ReflectionObject($this); - foreach ($reflection->getProperties() as $property) { - $name = $property->getName(); - switch ($name) { - case '_instance': - break; - case '_controllerDir': - case '_invokeParams': - $this->{$name} = array(); - break; - case '_plugins': - $this->{$name} = new Zend_Controller_Plugin_Broker(); - break; - case '_throwExceptions': - case '_returnResponse': - $this->{$name} = false; - break; - case '_moduleControllerDirectoryName': - $this->{$name} = 'controllers'; - break; - default: - $this->{$name} = null; - break; - } - } - Zend_Controller_Action_HelperBroker::resetHelpers(); - } - - /** - * Convenience feature, calls setControllerDirectory()->setRouter()->dispatch() - * - * In PHP 5.1.x, a call to a static method never populates $this -- so run() - * may actually be called after setting up your front controller. - * - * @param string|array $controllerDirectory Path to Zend_Controller_Action - * controller classes or array of such paths - * @return void - * @throws Zend_Controller_Exception if called from an object instance - */ - public static function run($controllerDirectory) - { - self::getInstance() - ->setControllerDirectory($controllerDirectory) - ->dispatch(); - } - - /** - * Add a controller directory to the controller directory stack - * - * If $args is presented and is a string, uses it for the array key mapping - * to the directory specified. - * - * @param string $directory - * @param string $module Optional argument; module with which to associate directory. If none provided, assumes 'default' - * @return Zend_Controller_Front - * @throws Zend_Controller_Exception if directory not found or readable - */ - public function addControllerDirectory($directory, $module = null) - { - $this->getDispatcher()->addControllerDirectory($directory, $module); - return $this; - } - - /** - * Set controller directory - * - * Stores controller directory(ies) in dispatcher. May be an array of - * directories or a string containing a single directory. - * - * @param string|array $directory Path to Zend_Controller_Action controller - * classes or array of such paths - * @param string $module Optional module name to use with string $directory - * @return Zend_Controller_Front - */ - public function setControllerDirectory($directory, $module = null) - { - $this->getDispatcher()->setControllerDirectory($directory, $module); - return $this; - } - - /** - * Retrieve controller directory - * - * Retrieves: - * - Array of all controller directories if no $name passed - * - String path if $name passed and exists as a key in controller directory array - * - null if $name passed but does not exist in controller directory keys - * - * @param string $name Default null - * @return array|string|null - */ - public function getControllerDirectory($name = null) - { - return $this->getDispatcher()->getControllerDirectory($name); - } - - /** - * Remove a controller directory by module name - * - * @param string $module - * @return bool - */ - public function removeControllerDirectory($module) - { - return $this->getDispatcher()->removeControllerDirectory($module); - } - - /** - * Specify a directory as containing modules - * - * Iterates through the directory, adding any subdirectories as modules; - * the subdirectory within each module named after {@link $_moduleControllerDirectoryName} - * will be used as the controller directory path. - * - * @param string $path - * @return Zend_Controller_Front - */ - public function addModuleDirectory($path) - { - try{ - $dir = new DirectoryIterator($path); - } catch(Exception $e) { - #require_once 'Zend/Controller/Exception.php'; - throw new Zend_Controller_Exception("Directory $path not readable", 0, $e); - } - foreach ($dir as $file) { - if ($file->isDot() || !$file->isDir()) { - continue; - } - - $module = $file->getFilename(); - - // Don't use SCCS directories as modules - if (preg_match('/^[^a-z]/i', $module) || ('CVS' == $module)) { - continue; - } - - $moduleDir = $file->getPathname() . DIRECTORY_SEPARATOR . $this->getModuleControllerDirectoryName(); - $this->addControllerDirectory($moduleDir, $module); - } - - return $this; - } - - /** - * Return the path to a module directory (but not the controllers directory within) - * - * @param string $module - * @return string|null - */ - public function getModuleDirectory($module = null) - { - if (null === $module) { - $request = $this->getRequest(); - if (null !== $request) { - $module = $this->getRequest()->getModuleName(); - } - if (empty($module)) { - $module = $this->getDispatcher()->getDefaultModule(); - } - } - - $controllerDir = $this->getControllerDirectory($module); - - if ((null === $controllerDir) || !is_string($controllerDir)) { - return null; - } - - return dirname($controllerDir); - } - - /** - * Set the directory name within a module containing controllers - * - * @param string $name - * @return Zend_Controller_Front - */ - public function setModuleControllerDirectoryName($name = 'controllers') - { - $this->_moduleControllerDirectoryName = (string) $name; - - return $this; - } - - /** - * Return the directory name within a module containing controllers - * - * @return string - */ - public function getModuleControllerDirectoryName() - { - return $this->_moduleControllerDirectoryName; - } - - /** - * Set the default controller (unformatted string) - * - * @param string $controller - * @return Zend_Controller_Front - */ - public function setDefaultControllerName($controller) - { - $dispatcher = $this->getDispatcher(); - $dispatcher->setDefaultControllerName($controller); - return $this; - } - - /** - * Retrieve the default controller (unformatted string) - * - * @return string - */ - public function getDefaultControllerName() - { - return $this->getDispatcher()->getDefaultControllerName(); - } - - /** - * Set the default action (unformatted string) - * - * @param string $action - * @return Zend_Controller_Front - */ - public function setDefaultAction($action) - { - $dispatcher = $this->getDispatcher(); - $dispatcher->setDefaultAction($action); - return $this; - } - - /** - * Retrieve the default action (unformatted string) - * - * @return string - */ - public function getDefaultAction() - { - return $this->getDispatcher()->getDefaultAction(); - } - - /** - * Set the default module name - * - * @param string $module - * @return Zend_Controller_Front - */ - public function setDefaultModule($module) - { - $dispatcher = $this->getDispatcher(); - $dispatcher->setDefaultModule($module); - return $this; - } - - /** - * Retrieve the default module - * - * @return string - */ - public function getDefaultModule() - { - return $this->getDispatcher()->getDefaultModule(); - } - - /** - * Set request class/object - * - * Set the request object. The request holds the request environment. - * - * If a class name is provided, it will instantiate it - * - * @param string|Zend_Controller_Request_Abstract $request - * @throws Zend_Controller_Exception if invalid request class - * @return Zend_Controller_Front - */ - public function setRequest($request) - { - if (is_string($request)) { - if (!class_exists($request)) { - #require_once 'Zend/Loader.php'; - Zend_Loader::loadClass($request); - } - $request = new $request(); - } - if (!$request instanceof Zend_Controller_Request_Abstract) { - #require_once 'Zend/Controller/Exception.php'; - throw new Zend_Controller_Exception('Invalid request class'); - } - - $this->_request = $request; - - return $this; - } - - /** - * Return the request object. - * - * @return null|Zend_Controller_Request_Abstract - */ - public function getRequest() - { - return $this->_request; - } - - /** - * Set router class/object - * - * Set the router object. The router is responsible for mapping - * the request to a controller and action. - * - * If a class name is provided, instantiates router with any parameters - * registered via {@link setParam()} or {@link setParams()}. - * - * @param string|Zend_Controller_Router_Interface $router - * @throws Zend_Controller_Exception if invalid router class - * @return Zend_Controller_Front - */ - public function setRouter($router) - { - if (is_string($router)) { - if (!class_exists($router)) { - #require_once 'Zend/Loader.php'; - Zend_Loader::loadClass($router); - } - $router = new $router(); - } - - if (!$router instanceof Zend_Controller_Router_Interface) { - #require_once 'Zend/Controller/Exception.php'; - throw new Zend_Controller_Exception('Invalid router class'); - } - - $router->setFrontController($this); - $this->_router = $router; - - return $this; - } - - /** - * Return the router object. - * - * Instantiates a Zend_Controller_Router_Rewrite object if no router currently set. - * - * @return Zend_Controller_Router_Interface - */ - public function getRouter() - { - if (null == $this->_router) { - #require_once 'Zend/Controller/Router/Rewrite.php'; - $this->setRouter(new Zend_Controller_Router_Rewrite()); - } - - return $this->_router; - } - - /** - * Set the base URL used for requests - * - * Use to set the base URL segment of the REQUEST_URI to use when - * determining PATH_INFO, etc. Examples: - * - /admin - * - /myapp - * - /subdir/index.php - * - * Note that the URL should not include the full URI. Do not use: - * - http://example.com/admin - * - http://example.com/myapp - * - http://example.com/subdir/index.php - * - * If a null value is passed, this can be used as well for autodiscovery (default). - * - * @param string $base - * @return Zend_Controller_Front - * @throws Zend_Controller_Exception for non-string $base - */ - public function setBaseUrl($base = null) - { - if (!is_string($base) && (null !== $base)) { - #require_once 'Zend/Controller/Exception.php'; - throw new Zend_Controller_Exception('Rewrite base must be a string'); - } - - $this->_baseUrl = $base; - - if ((null !== ($request = $this->getRequest())) && (method_exists($request, 'setBaseUrl'))) { - $request->setBaseUrl($base); - } - - return $this; - } - - /** - * Retrieve the currently set base URL - * - * @return string - */ - public function getBaseUrl() - { - $request = $this->getRequest(); - if ((null !== $request) && method_exists($request, 'getBaseUrl')) { - return $request->getBaseUrl(); - } - - return $this->_baseUrl; - } - - /** - * Set the dispatcher object. The dispatcher is responsible for - * taking a Zend_Controller_Dispatcher_Token object, instantiating the controller, and - * call the action method of the controller. - * - * @param Zend_Controller_Dispatcher_Interface $dispatcher - * @return Zend_Controller_Front - */ - public function setDispatcher(Zend_Controller_Dispatcher_Interface $dispatcher) - { - $this->_dispatcher = $dispatcher; - return $this; - } - - /** - * Return the dispatcher object. - * - * @return Zend_Controller_Dispatcher_Interface - */ - public function getDispatcher() - { - /** - * Instantiate the default dispatcher if one was not set. - */ - if (!$this->_dispatcher instanceof Zend_Controller_Dispatcher_Interface) { - #require_once 'Zend/Controller/Dispatcher/Standard.php'; - $this->_dispatcher = new Zend_Controller_Dispatcher_Standard(); - } - return $this->_dispatcher; - } - - /** - * Set response class/object - * - * Set the response object. The response is a container for action - * responses and headers. Usage is optional. - * - * If a class name is provided, instantiates a response object. - * - * @param string|Zend_Controller_Response_Abstract $response - * @throws Zend_Controller_Exception if invalid response class - * @return Zend_Controller_Front - */ - public function setResponse($response) - { - if (is_string($response)) { - if (!class_exists($response)) { - #require_once 'Zend/Loader.php'; - Zend_Loader::loadClass($response); - } - $response = new $response(); - } - if (!$response instanceof Zend_Controller_Response_Abstract) { - #require_once 'Zend/Controller/Exception.php'; - throw new Zend_Controller_Exception('Invalid response class'); - } - - $this->_response = $response; - - return $this; - } - - /** - * Return the response object. - * - * @return null|Zend_Controller_Response_Abstract - */ - public function getResponse() - { - return $this->_response; - } - - /** - * Add or modify a parameter to use when instantiating an action controller - * - * @param string $name - * @param mixed $value - * @return Zend_Controller_Front - */ - public function setParam($name, $value) - { - $name = (string) $name; - $this->_invokeParams[$name] = $value; - return $this; - } - - /** - * Set parameters to pass to action controller constructors - * - * @param array $params - * @return Zend_Controller_Front - */ - public function setParams(array $params) - { - $this->_invokeParams = array_merge($this->_invokeParams, $params); - return $this; - } - - /** - * Retrieve a single parameter from the controller parameter stack - * - * @param string $name - * @return mixed - */ - public function getParam($name) - { - if(isset($this->_invokeParams[$name])) { - return $this->_invokeParams[$name]; - } - - return null; - } - - /** - * Retrieve action controller instantiation parameters - * - * @return array - */ - public function getParams() - { - return $this->_invokeParams; - } - - /** - * Clear the controller parameter stack - * - * By default, clears all parameters. If a parameter name is given, clears - * only that parameter; if an array of parameter names is provided, clears - * each. - * - * @param null|string|array single key or array of keys for params to clear - * @return Zend_Controller_Front - */ - public function clearParams($name = null) - { - if (null === $name) { - $this->_invokeParams = array(); - } elseif (is_string($name) && isset($this->_invokeParams[$name])) { - unset($this->_invokeParams[$name]); - } elseif (is_array($name)) { - foreach ($name as $key) { - if (is_string($key) && isset($this->_invokeParams[$key])) { - unset($this->_invokeParams[$key]); - } - } - } - - return $this; - } - - /** - * Register a plugin. - * - * @param Zend_Controller_Plugin_Abstract $plugin - * @param int $stackIndex Optional; stack index for plugin - * @return Zend_Controller_Front - */ - public function registerPlugin(Zend_Controller_Plugin_Abstract $plugin, $stackIndex = null) - { - $this->_plugins->registerPlugin($plugin, $stackIndex); - return $this; - } - - /** - * Unregister a plugin. - * - * @param string|Zend_Controller_Plugin_Abstract $plugin Plugin class or object to unregister - * @return Zend_Controller_Front - */ - public function unregisterPlugin($plugin) - { - $this->_plugins->unregisterPlugin($plugin); - return $this; - } - - /** - * Is a particular plugin registered? - * - * @param string $class - * @return bool - */ - public function hasPlugin($class) - { - return $this->_plugins->hasPlugin($class); - } - - /** - * Retrieve a plugin or plugins by class - * - * @param string $class - * @return false|Zend_Controller_Plugin_Abstract|array - */ - public function getPlugin($class) - { - return $this->_plugins->getPlugin($class); - } - - /** - * Retrieve all plugins - * - * @return array - */ - public function getPlugins() - { - return $this->_plugins->getPlugins(); - } - - /** - * Set the throwExceptions flag and retrieve current status - * - * Set whether exceptions encounted in the dispatch loop should be thrown - * or caught and trapped in the response object. - * - * Default behaviour is to trap them in the response object; call this - * method to have them thrown. - * - * Passing no value will return the current value of the flag; passing a - * boolean true or false value will set the flag and return the current - * object instance. - * - * @param boolean $flag Defaults to null (return flag state) - * @return boolean|Zend_Controller_Front Used as a setter, returns object; as a getter, returns boolean - */ - public function throwExceptions($flag = null) - { - if ($flag !== null) { - $this->_throwExceptions = (bool) $flag; - return $this; - } - - return $this->_throwExceptions; - } - - /** - * Set whether {@link dispatch()} should return the response without first - * rendering output. By default, output is rendered and dispatch() returns - * nothing. - * - * @param boolean $flag - * @return boolean|Zend_Controller_Front Used as a setter, returns object; as a getter, returns boolean - */ - public function returnResponse($flag = null) - { - if (true === $flag) { - $this->_returnResponse = true; - return $this; - } elseif (false === $flag) { - $this->_returnResponse = false; - return $this; - } - - return $this->_returnResponse; - } - - /** - * Dispatch an HTTP request to a controller/action. - * - * @param Zend_Controller_Request_Abstract|null $request - * @param Zend_Controller_Response_Abstract|null $response - * @return void|Zend_Controller_Response_Abstract Returns response object if returnResponse() is true - */ - public function dispatch(Zend_Controller_Request_Abstract $request = null, Zend_Controller_Response_Abstract $response = null) - { - if (!$this->getParam('noErrorHandler') && !$this->_plugins->hasPlugin('Zend_Controller_Plugin_ErrorHandler')) { - // Register with stack index of 100 - #require_once 'Zend/Controller/Plugin/ErrorHandler.php'; - $this->_plugins->registerPlugin(new Zend_Controller_Plugin_ErrorHandler(), 100); - } - - if (!$this->getParam('noViewRenderer') && !Zend_Controller_Action_HelperBroker::hasHelper('viewRenderer')) { - #require_once 'Zend/Controller/Action/Helper/ViewRenderer.php'; - Zend_Controller_Action_HelperBroker::getStack()->offsetSet(-80, new Zend_Controller_Action_Helper_ViewRenderer()); - } - - /** - * Instantiate default request object (HTTP version) if none provided - */ - if (null !== $request) { - $this->setRequest($request); - } elseif ((null === $request) && (null === ($request = $this->getRequest()))) { - #require_once 'Zend/Controller/Request/Http.php'; - $request = new Zend_Controller_Request_Http(); - $this->setRequest($request); - } - - /** - * Set base URL of request object, if available - */ - if (is_callable(array($this->_request, 'setBaseUrl'))) { - if (null !== $this->_baseUrl) { - $this->_request->setBaseUrl($this->_baseUrl); - } - } - - /** - * Instantiate default response object (HTTP version) if none provided - */ - if (null !== $response) { - $this->setResponse($response); - } elseif ((null === $this->_response) && (null === ($this->_response = $this->getResponse()))) { - #require_once 'Zend/Controller/Response/Http.php'; - $response = new Zend_Controller_Response_Http(); - $this->setResponse($response); - } - - /** - * Register request and response objects with plugin broker - */ - $this->_plugins - ->setRequest($this->_request) - ->setResponse($this->_response); - - /** - * Initialize router - */ - $router = $this->getRouter(); - $router->setParams($this->getParams()); - - /** - * Initialize dispatcher - */ - $dispatcher = $this->getDispatcher(); - $dispatcher->setParams($this->getParams()) - ->setResponse($this->_response); - - // Begin dispatch - try { - /** - * Route request to controller/action, if a router is provided - */ - - /** - * Notify plugins of router startup - */ - $this->_plugins->routeStartup($this->_request); - - try { - $router->route($this->_request); - } catch (Exception $e) { - if ($this->throwExceptions()) { - throw $e; - } - - $this->_response->setException($e); - } - - /** - * Notify plugins of router completion - */ - $this->_plugins->routeShutdown($this->_request); - - /** - * Notify plugins of dispatch loop startup - */ - $this->_plugins->dispatchLoopStartup($this->_request); - - /** - * Attempt to dispatch the controller/action. If the $this->_request - * indicates that it needs to be dispatched, move to the next - * action in the request. - */ - do { - $this->_request->setDispatched(true); - - /** - * Notify plugins of dispatch startup - */ - $this->_plugins->preDispatch($this->_request); - - /** - * Skip requested action if preDispatch() has reset it - */ - if (!$this->_request->isDispatched()) { - continue; - } - - /** - * Dispatch request - */ - try { - $dispatcher->dispatch($this->_request, $this->_response); - } catch (Exception $e) { - if ($this->throwExceptions()) { - throw $e; - } - $this->_response->setException($e); - } - - /** - * Notify plugins of dispatch completion - */ - $this->_plugins->postDispatch($this->_request); - } while (!$this->_request->isDispatched()); - } catch (Exception $e) { - if ($this->throwExceptions()) { - throw $e; - } - - $this->_response->setException($e); - } - - /** - * Notify plugins of dispatch loop completion - */ - try { - $this->_plugins->dispatchLoopShutdown(); - } catch (Exception $e) { - if ($this->throwExceptions()) { - throw $e; - } - - $this->_response->setException($e); - } - - if ($this->returnResponse()) { - return $this->_response; - } - - $this->_response->sendResponse(); - } -} diff --git a/library/Zend/Controller/Plugin/Abstract.php b/library/Zend/Controller/Plugin/Abstract.php deleted file mode 100644 index 7e590b7eef..0000000000 --- a/library/Zend/Controller/Plugin/Abstract.php +++ /dev/null @@ -1,151 +0,0 @@ -_request = $request; - return $this; - } - - /** - * Get request object - * - * @return Zend_Controller_Request_Abstract $request - */ - public function getRequest() - { - return $this->_request; - } - - /** - * Set response object - * - * @param Zend_Controller_Response_Abstract $response - * @return Zend_Controller_Plugin_Abstract - */ - public function setResponse(Zend_Controller_Response_Abstract $response) - { - $this->_response = $response; - return $this; - } - - /** - * Get response object - * - * @return Zend_Controller_Response_Abstract $response - */ - public function getResponse() - { - return $this->_response; - } - - /** - * Called before Zend_Controller_Front begins evaluating the - * request against its routes. - * - * @param Zend_Controller_Request_Abstract $request - * @return void - */ - public function routeStartup(Zend_Controller_Request_Abstract $request) - {} - - /** - * Called after Zend_Controller_Router exits. - * - * Called after Zend_Controller_Front exits from the router. - * - * @param Zend_Controller_Request_Abstract $request - * @return void - */ - public function routeShutdown(Zend_Controller_Request_Abstract $request) - {} - - /** - * Called before Zend_Controller_Front enters its dispatch loop. - * - * @param Zend_Controller_Request_Abstract $request - * @return void - */ - public function dispatchLoopStartup(Zend_Controller_Request_Abstract $request) - {} - - /** - * Called before an action is dispatched by Zend_Controller_Dispatcher. - * - * This callback allows for proxy or filter behavior. By altering the - * request and resetting its dispatched flag (via - * {@link Zend_Controller_Request_Abstract::setDispatched() setDispatched(false)}), - * the current action may be skipped. - * - * @param Zend_Controller_Request_Abstract $request - * @return void - */ - public function preDispatch(Zend_Controller_Request_Abstract $request) - {} - - /** - * Called after an action is dispatched by Zend_Controller_Dispatcher. - * - * This callback allows for proxy or filter behavior. By altering the - * request and resetting its dispatched flag (via - * {@link Zend_Controller_Request_Abstract::setDispatched() setDispatched(false)}), - * a new action may be specified for dispatching. - * - * @param Zend_Controller_Request_Abstract $request - * @return void - */ - public function postDispatch(Zend_Controller_Request_Abstract $request) - {} - - /** - * Called before Zend_Controller_Front exits its dispatch loop. - * - * @return void - */ - public function dispatchLoopShutdown() - {} -} diff --git a/library/Zend/Controller/Plugin/ActionStack.php b/library/Zend/Controller/Plugin/ActionStack.php deleted file mode 100644 index c3d2cb5eea..0000000000 --- a/library/Zend/Controller/Plugin/ActionStack.php +++ /dev/null @@ -1,280 +0,0 @@ -setRegistry($registry); - - if (null !== $key) { - $this->setRegistryKey($key); - } else { - $key = $this->getRegistryKey(); - } - - $registry[$key] = array(); - } - - /** - * Set registry object - * - * @param Zend_Registry $registry - * @return Zend_Controller_Plugin_ActionStack - */ - public function setRegistry(Zend_Registry $registry) - { - $this->_registry = $registry; - return $this; - } - - /** - * Retrieve registry object - * - * @return Zend_Registry - */ - public function getRegistry() - { - return $this->_registry; - } - - /** - * Retrieve registry key - * - * @return string - */ - public function getRegistryKey() - { - return $this->_registryKey; - } - - /** - * Set registry key - * - * @param string $key - * @return Zend_Controller_Plugin_ActionStack - */ - public function setRegistryKey($key) - { - $this->_registryKey = (string) $key; - return $this; - } - - /** - * Set clearRequestParams flag - * - * @param bool $clearRequestParams - * @return Zend_Controller_Plugin_ActionStack - */ - public function setClearRequestParams($clearRequestParams) - { - $this->_clearRequestParams = (bool) $clearRequestParams; - return $this; - } - - /** - * Retrieve clearRequestParams flag - * - * @return bool - */ - public function getClearRequestParams() - { - return $this->_clearRequestParams; - } - - /** - * Retrieve action stack - * - * @return array - */ - public function getStack() - { - $registry = $this->getRegistry(); - $stack = $registry[$this->getRegistryKey()]; - return $stack; - } - - /** - * Save stack to registry - * - * @param array $stack - * @return Zend_Controller_Plugin_ActionStack - */ - protected function _saveStack(array $stack) - { - $registry = $this->getRegistry(); - $registry[$this->getRegistryKey()] = $stack; - return $this; - } - - /** - * Push an item onto the stack - * - * @param Zend_Controller_Request_Abstract $next - * @return Zend_Controller_Plugin_ActionStack - */ - public function pushStack(Zend_Controller_Request_Abstract $next) - { - $stack = $this->getStack(); - array_push($stack, $next); - return $this->_saveStack($stack); - } - - /** - * Pop an item off the action stack - * - * @return false|Zend_Controller_Request_Abstract - */ - public function popStack() - { - $stack = $this->getStack(); - if (0 == count($stack)) { - return false; - } - - $next = array_pop($stack); - $this->_saveStack($stack); - - if (!$next instanceof Zend_Controller_Request_Abstract) { - #require_once 'Zend/Controller/Exception.php'; - throw new Zend_Controller_Exception('ArrayStack should only contain request objects'); - } - $action = $next->getActionName(); - if (empty($action)) { - return $this->popStack($stack); - } - - $request = $this->getRequest(); - $controller = $next->getControllerName(); - if (empty($controller)) { - $next->setControllerName($request->getControllerName()); - } - - $module = $next->getModuleName(); - if (empty($module)) { - $next->setModuleName($request->getModuleName()); - } - - return $next; - } - - /** - * postDispatch() plugin hook -- check for actions in stack, and dispatch if any found - * - * @param Zend_Controller_Request_Abstract $request - * @return void - */ - public function postDispatch(Zend_Controller_Request_Abstract $request) - { - // Don't move on to next request if this is already an attempt to - // forward - if (!$request->isDispatched()) { - return; - } - - $this->setRequest($request); - $stack = $this->getStack(); - if (empty($stack)) { - return; - } - $next = $this->popStack(); - if (!$next) { - return; - } - - $this->forward($next); - } - - /** - * Forward request with next action - * - * @param array $next - * @return void - */ - public function forward(Zend_Controller_Request_Abstract $next) - { - $request = $this->getRequest(); - if ($this->getClearRequestParams()) { - $request->clearParams(); - } - - $request->setModuleName($next->getModuleName()) - ->setControllerName($next->getControllerName()) - ->setActionName($next->getActionName()) - ->setParams($next->getParams()) - ->setDispatched(false); - } -} diff --git a/library/Zend/Controller/Plugin/Broker.php b/library/Zend/Controller/Plugin/Broker.php deleted file mode 100644 index 3e1c87f3e1..0000000000 --- a/library/Zend/Controller/Plugin/Broker.php +++ /dev/null @@ -1,365 +0,0 @@ -_plugins, true)) { - #require_once 'Zend/Controller/Exception.php'; - throw new Zend_Controller_Exception('Plugin already registered'); - } - - $stackIndex = (int) $stackIndex; - - if ($stackIndex) { - if (isset($this->_plugins[$stackIndex])) { - #require_once 'Zend/Controller/Exception.php'; - throw new Zend_Controller_Exception('Plugin with stackIndex "' . $stackIndex . '" already registered'); - } - $this->_plugins[$stackIndex] = $plugin; - } else { - $stackIndex = count($this->_plugins); - while (isset($this->_plugins[$stackIndex])) { - ++$stackIndex; - } - $this->_plugins[$stackIndex] = $plugin; - } - - $request = $this->getRequest(); - if ($request) { - $this->_plugins[$stackIndex]->setRequest($request); - } - $response = $this->getResponse(); - if ($response) { - $this->_plugins[$stackIndex]->setResponse($response); - } - - ksort($this->_plugins); - - return $this; - } - - /** - * Unregister a plugin. - * - * @param string|Zend_Controller_Plugin_Abstract $plugin Plugin object or class name - * @return Zend_Controller_Plugin_Broker - */ - public function unregisterPlugin($plugin) - { - if ($plugin instanceof Zend_Controller_Plugin_Abstract) { - // Given a plugin object, find it in the array - $key = array_search($plugin, $this->_plugins, true); - if (false === $key) { - #require_once 'Zend/Controller/Exception.php'; - throw new Zend_Controller_Exception('Plugin never registered.'); - } - unset($this->_plugins[$key]); - } elseif (is_string($plugin)) { - // Given a plugin class, find all plugins of that class and unset them - foreach ($this->_plugins as $key => $_plugin) { - $type = get_class($_plugin); - if ($plugin == $type) { - unset($this->_plugins[$key]); - } - } - } - return $this; - } - - /** - * Is a plugin of a particular class registered? - * - * @param string $class - * @return bool - */ - public function hasPlugin($class) - { - foreach ($this->_plugins as $plugin) { - $type = get_class($plugin); - if ($class == $type) { - return true; - } - } - - return false; - } - - /** - * Retrieve a plugin or plugins by class - * - * @param string $class Class name of plugin(s) desired - * @return false|Zend_Controller_Plugin_Abstract|array Returns false if none found, plugin if only one found, and array of plugins if multiple plugins of same class found - */ - public function getPlugin($class) - { - $found = array(); - foreach ($this->_plugins as $plugin) { - $type = get_class($plugin); - if ($class == $type) { - $found[] = $plugin; - } - } - - switch (count($found)) { - case 0: - return false; - case 1: - return $found[0]; - default: - return $found; - } - } - - /** - * Retrieve all plugins - * - * @return array - */ - public function getPlugins() - { - return $this->_plugins; - } - - /** - * Set request object, and register with each plugin - * - * @param Zend_Controller_Request_Abstract $request - * @return Zend_Controller_Plugin_Broker - */ - public function setRequest(Zend_Controller_Request_Abstract $request) - { - $this->_request = $request; - - foreach ($this->_plugins as $plugin) { - $plugin->setRequest($request); - } - - return $this; - } - - /** - * Get request object - * - * @return Zend_Controller_Request_Abstract $request - */ - public function getRequest() - { - return $this->_request; - } - - /** - * Set response object - * - * @param Zend_Controller_Response_Abstract $response - * @return Zend_Controller_Plugin_Broker - */ - public function setResponse(Zend_Controller_Response_Abstract $response) - { - $this->_response = $response; - - foreach ($this->_plugins as $plugin) { - $plugin->setResponse($response); - } - - - return $this; - } - - /** - * Get response object - * - * @return Zend_Controller_Response_Abstract $response - */ - public function getResponse() - { - return $this->_response; - } - - - /** - * Called before Zend_Controller_Front begins evaluating the - * request against its routes. - * - * @param Zend_Controller_Request_Abstract $request - * @return void - */ - public function routeStartup(Zend_Controller_Request_Abstract $request) - { - foreach ($this->_plugins as $plugin) { - try { - $plugin->routeStartup($request); - } catch (Exception $e) { - if (Zend_Controller_Front::getInstance()->throwExceptions()) { - throw new Zend_Controller_Exception($e->getMessage() . $e->getTraceAsString(), $e->getCode(), $e); - } else { - $this->getResponse()->setException($e); - } - } - } - } - - - /** - * Called before Zend_Controller_Front exits its iterations over - * the route set. - * - * @param Zend_Controller_Request_Abstract $request - * @return void - */ - public function routeShutdown(Zend_Controller_Request_Abstract $request) - { - foreach ($this->_plugins as $plugin) { - try { - $plugin->routeShutdown($request); - } catch (Exception $e) { - if (Zend_Controller_Front::getInstance()->throwExceptions()) { - throw new Zend_Controller_Exception($e->getMessage() . $e->getTraceAsString(), $e->getCode(), $e); - } else { - $this->getResponse()->setException($e); - } - } - } - } - - - /** - * Called before Zend_Controller_Front enters its dispatch loop. - * - * During the dispatch loop, Zend_Controller_Front keeps a - * Zend_Controller_Request_Abstract object, and uses - * Zend_Controller_Dispatcher to dispatch the - * Zend_Controller_Request_Abstract object to controllers/actions. - * - * @param Zend_Controller_Request_Abstract $request - * @return void - */ - public function dispatchLoopStartup(Zend_Controller_Request_Abstract $request) - { - foreach ($this->_plugins as $plugin) { - try { - $plugin->dispatchLoopStartup($request); - } catch (Exception $e) { - if (Zend_Controller_Front::getInstance()->throwExceptions()) { - throw new Zend_Controller_Exception($e->getMessage() . $e->getTraceAsString(), $e->getCode(), $e); - } else { - $this->getResponse()->setException($e); - } - } - } - } - - - /** - * Called before an action is dispatched by Zend_Controller_Dispatcher. - * - * @param Zend_Controller_Request_Abstract $request - * @return void - */ - public function preDispatch(Zend_Controller_Request_Abstract $request) - { - foreach ($this->_plugins as $plugin) { - try { - $plugin->preDispatch($request); - } catch (Exception $e) { - if (Zend_Controller_Front::getInstance()->throwExceptions()) { - throw new Zend_Controller_Exception($e->getMessage() . $e->getTraceAsString(), $e->getCode(), $e); - } else { - $this->getResponse()->setException($e); - // skip rendering of normal dispatch give the error handler a try - $this->getRequest()->setDispatched(false); - } - } - } - } - - - /** - * Called after an action is dispatched by Zend_Controller_Dispatcher. - * - * @param Zend_Controller_Request_Abstract $request - * @return void - */ - public function postDispatch(Zend_Controller_Request_Abstract $request) - { - foreach ($this->_plugins as $plugin) { - try { - $plugin->postDispatch($request); - } catch (Exception $e) { - if (Zend_Controller_Front::getInstance()->throwExceptions()) { - throw new Zend_Controller_Exception($e->getMessage() . $e->getTraceAsString(), $e->getCode(), $e); - } else { - $this->getResponse()->setException($e); - } - } - } - } - - - /** - * Called before Zend_Controller_Front exits its dispatch loop. - * - * @param Zend_Controller_Request_Abstract $request - * @return void - */ - public function dispatchLoopShutdown() - { - foreach ($this->_plugins as $plugin) { - try { - $plugin->dispatchLoopShutdown(); - } catch (Exception $e) { - if (Zend_Controller_Front::getInstance()->throwExceptions()) { - throw new Zend_Controller_Exception($e->getMessage() . $e->getTraceAsString(), $e->getCode(), $e); - } else { - $this->getResponse()->setException($e); - } - } - } - } -} diff --git a/library/Zend/Controller/Plugin/ErrorHandler.php b/library/Zend/Controller/Plugin/ErrorHandler.php deleted file mode 100644 index 4185962091..0000000000 --- a/library/Zend/Controller/Plugin/ErrorHandler.php +++ /dev/null @@ -1,300 +0,0 @@ -setErrorHandler($options); - } - - /** - * setErrorHandler() - setup the error handling options - * - * @param array $options - * @return Zend_Controller_Plugin_ErrorHandler - */ - public function setErrorHandler(Array $options = array()) - { - if (isset($options['module'])) { - $this->setErrorHandlerModule($options['module']); - } - if (isset($options['controller'])) { - $this->setErrorHandlerController($options['controller']); - } - if (isset($options['action'])) { - $this->setErrorHandlerAction($options['action']); - } - return $this; - } - - /** - * Set the module name for the error handler - * - * @param string $module - * @return Zend_Controller_Plugin_ErrorHandler - */ - public function setErrorHandlerModule($module) - { - $this->_errorModule = (string) $module; - return $this; - } - - /** - * Retrieve the current error handler module - * - * @return string - */ - public function getErrorHandlerModule() - { - if (null === $this->_errorModule) { - $this->_errorModule = Zend_Controller_Front::getInstance()->getDispatcher()->getDefaultModule(); - } - return $this->_errorModule; - } - - /** - * Set the controller name for the error handler - * - * @param string $controller - * @return Zend_Controller_Plugin_ErrorHandler - */ - public function setErrorHandlerController($controller) - { - $this->_errorController = (string) $controller; - return $this; - } - - /** - * Retrieve the current error handler controller - * - * @return string - */ - public function getErrorHandlerController() - { - return $this->_errorController; - } - - /** - * Set the action name for the error handler - * - * @param string $action - * @return Zend_Controller_Plugin_ErrorHandler - */ - public function setErrorHandlerAction($action) - { - $this->_errorAction = (string) $action; - return $this; - } - - /** - * Retrieve the current error handler action - * - * @return string - */ - public function getErrorHandlerAction() - { - return $this->_errorAction; - } - - /** - * Route shutdown hook -- Ccheck for router exceptions - * - * @param Zend_Controller_Request_Abstract $request - */ - public function routeShutdown(Zend_Controller_Request_Abstract $request) - { - $this->_handleError($request); - } - - /** - * Pre dispatch hook -- check for exceptions and dispatch error handler if - * necessary - * - * @param Zend_Controller_Request_Abstract $request - */ - public function preDispatch(Zend_Controller_Request_Abstract $request) - { - $this->_handleError($request); - } - - /** - * Post dispatch hook -- check for exceptions and dispatch error handler if - * necessary - * - * @param Zend_Controller_Request_Abstract $request - */ - public function postDispatch(Zend_Controller_Request_Abstract $request) - { - $this->_handleError($request); - } - - /** - * Handle errors and exceptions - * - * If the 'noErrorHandler' front controller flag has been set, - * returns early. - * - * @param Zend_Controller_Request_Abstract $request - * @return void - */ - protected function _handleError(Zend_Controller_Request_Abstract $request) - { - $frontController = Zend_Controller_Front::getInstance(); - if ($frontController->getParam('noErrorHandler')) { - return; - } - - $response = $this->getResponse(); - - if ($this->_isInsideErrorHandlerLoop) { - $exceptions = $response->getException(); - if (count($exceptions) > $this->_exceptionCountAtFirstEncounter) { - // Exception thrown by error handler; tell the front controller to throw it - $frontController->throwExceptions(true); - throw array_pop($exceptions); - } - } - - // check for an exception AND allow the error handler controller the option to forward - if (($response->isException()) && (!$this->_isInsideErrorHandlerLoop)) { - $this->_isInsideErrorHandlerLoop = true; - - // Get exception information - $error = new ArrayObject(array(), ArrayObject::ARRAY_AS_PROPS); - $exceptions = $response->getException(); - $exception = $exceptions[0]; - $exceptionType = get_class($exception); - $error->exception = $exception; - switch ($exceptionType) { - case 'Zend_Controller_Router_Exception': - if (404 == $exception->getCode()) { - $error->type = self::EXCEPTION_NO_ROUTE; - } else { - $error->type = self::EXCEPTION_OTHER; - } - break; - case 'Zend_Controller_Dispatcher_Exception': - $error->type = self::EXCEPTION_NO_CONTROLLER; - break; - case 'Zend_Controller_Action_Exception': - if (404 == $exception->getCode()) { - $error->type = self::EXCEPTION_NO_ACTION; - } else { - $error->type = self::EXCEPTION_OTHER; - } - break; - default: - $error->type = self::EXCEPTION_OTHER; - break; - } - - // Keep a copy of the original request - $error->request = clone $request; - - // get a count of the number of exceptions encountered - $this->_exceptionCountAtFirstEncounter = count($exceptions); - - // Forward to the error handler - $request->setParam('error_handler', $error) - ->setModuleName($this->getErrorHandlerModule()) - ->setControllerName($this->getErrorHandlerController()) - ->setActionName($this->getErrorHandlerAction()) - ->setDispatched(false); - } - } -} diff --git a/library/Zend/Controller/Plugin/PutHandler.php b/library/Zend/Controller/Plugin/PutHandler.php deleted file mode 100644 index c1ba035880..0000000000 --- a/library/Zend/Controller/Plugin/PutHandler.php +++ /dev/null @@ -1,60 +0,0 @@ -_request->isPut()) { - $putParams = array(); - parse_str($this->_request->getRawBody(), $putParams); - $request->setParams($putParams); - } - } -} diff --git a/library/Zend/Controller/Request/Abstract.php b/library/Zend/Controller/Request/Abstract.php deleted file mode 100644 index d57238f46b..0000000000 --- a/library/Zend/Controller/Request/Abstract.php +++ /dev/null @@ -1,356 +0,0 @@ -_module) { - $this->_module = $this->getParam($this->getModuleKey()); - } - - return $this->_module; - } - - /** - * Set the module name to use - * - * @param string $value - * @return Zend_Controller_Request_Abstract - */ - public function setModuleName($value) - { - $this->_module = $value; - return $this; - } - - /** - * Retrieve the controller name - * - * @return string - */ - public function getControllerName() - { - if (null === $this->_controller) { - $this->_controller = $this->getParam($this->getControllerKey()); - } - - return $this->_controller; - } - - /** - * Set the controller name to use - * - * @param string $value - * @return Zend_Controller_Request_Abstract - */ - public function setControllerName($value) - { - $this->_controller = $value; - return $this; - } - - /** - * Retrieve the action name - * - * @return string - */ - public function getActionName() - { - if (null === $this->_action) { - $this->_action = $this->getParam($this->getActionKey()); - } - - return $this->_action; - } - - /** - * Set the action name - * - * @param string $value - * @return Zend_Controller_Request_Abstract - */ - public function setActionName($value) - { - $this->_action = $value; - /** - * @see ZF-3465 - */ - if (null === $value) { - $this->setParam($this->getActionKey(), $value); - } - return $this; - } - - /** - * Retrieve the module key - * - * @return string - */ - public function getModuleKey() - { - return $this->_moduleKey; - } - - /** - * Set the module key - * - * @param string $key - * @return Zend_Controller_Request_Abstract - */ - public function setModuleKey($key) - { - $this->_moduleKey = (string) $key; - return $this; - } - - /** - * Retrieve the controller key - * - * @return string - */ - public function getControllerKey() - { - return $this->_controllerKey; - } - - /** - * Set the controller key - * - * @param string $key - * @return Zend_Controller_Request_Abstract - */ - public function setControllerKey($key) - { - $this->_controllerKey = (string) $key; - return $this; - } - - /** - * Retrieve the action key - * - * @return string - */ - public function getActionKey() - { - return $this->_actionKey; - } - - /** - * Set the action key - * - * @param string $key - * @return Zend_Controller_Request_Abstract - */ - public function setActionKey($key) - { - $this->_actionKey = (string) $key; - return $this; - } - - /** - * Get an action parameter - * - * @param string $key - * @param mixed $default Default value to use if key not found - * @return mixed - */ - public function getParam($key, $default = null) - { - $key = (string) $key; - if (isset($this->_params[$key])) { - return $this->_params[$key]; - } - - return $default; - } - - /** - * Retrieve only user params (i.e, any param specific to the object and not the environment) - * - * @return array - */ - public function getUserParams() - { - return $this->_params; - } - - /** - * Retrieve a single user param (i.e, a param specific to the object and not the environment) - * - * @param string $key - * @param string $default Default value to use if key not found - * @return mixed - */ - public function getUserParam($key, $default = null) - { - if (isset($this->_params[$key])) { - return $this->_params[$key]; - } - - return $default; - } - - /** - * Set an action parameter - * - * A $value of null will unset the $key if it exists - * - * @param string $key - * @param mixed $value - * @return Zend_Controller_Request_Abstract - */ - public function setParam($key, $value) - { - $key = (string) $key; - - if ((null === $value) && isset($this->_params[$key])) { - unset($this->_params[$key]); - } elseif (null !== $value) { - $this->_params[$key] = $value; - } - - return $this; - } - - /** - * Get all action parameters - * - * @return array - */ - public function getParams() - { - return $this->_params; - } - - /** - * Set action parameters en masse; does not overwrite - * - * Null values will unset the associated key. - * - * @param array $array - * @return Zend_Controller_Request_Abstract - */ - public function setParams(array $array) - { - $this->_params = $this->_params + (array) $array; - - foreach ($array as $key => $value) { - if (null === $value) { - unset($this->_params[$key]); - } - } - - return $this; - } - - /** - * Unset all user parameters - * - * @return Zend_Controller_Request_Abstract - */ - public function clearParams() - { - $this->_params = array(); - return $this; - } - - /** - * Set flag indicating whether or not request has been dispatched - * - * @param boolean $flag - * @return Zend_Controller_Request_Abstract - */ - public function setDispatched($flag = true) - { - $this->_dispatched = $flag ? true : false; - return $this; - } - - /** - * Determine if the request has been dispatched - * - * @return boolean - */ - public function isDispatched() - { - return $this->_dispatched; - } -} diff --git a/library/Zend/Controller/Request/Apache404.php b/library/Zend/Controller/Request/Apache404.php deleted file mode 100644 index 22a6527201..0000000000 --- a/library/Zend/Controller/Request/Apache404.php +++ /dev/null @@ -1,82 +0,0 @@ -_requestUri = $requestUri; - return $this; - } -} diff --git a/library/Zend/Controller/Request/Exception.php b/library/Zend/Controller/Request/Exception.php deleted file mode 100644 index 9e4e17ce7d..0000000000 --- a/library/Zend/Controller/Request/Exception.php +++ /dev/null @@ -1,37 +0,0 @@ -valid()) { - $path = $uri->getPath(); - $query = $uri->getQuery(); - if (!empty($query)) { - $path .= '?' . $query; - } - - $this->setRequestUri($path); - } else { - #require_once 'Zend/Controller/Request/Exception.php'; - throw new Zend_Controller_Request_Exception('Invalid URI provided to constructor'); - } - } else { - $this->setRequestUri(); - } - } - - /** - * Access values contained in the superglobals as public members - * Order of precedence: 1. GET, 2. POST, 3. COOKIE, 4. SERVER, 5. ENV - * - * @see http://msdn.microsoft.com/en-us/library/system.web.httprequest.item.aspx - * @param string $key - * @return mixed - */ - public function __get($key) - { - switch (true) { - case isset($this->_params[$key]): - return $this->_params[$key]; - case isset($_GET[$key]): - return $_GET[$key]; - case isset($_POST[$key]): - return $_POST[$key]; - case isset($_COOKIE[$key]): - return $_COOKIE[$key]; - case ($key == 'REQUEST_URI'): - return $this->getRequestUri(); - case ($key == 'PATH_INFO'): - return $this->getPathInfo(); - case isset($_SERVER[$key]): - return $_SERVER[$key]; - case isset($_ENV[$key]): - return $_ENV[$key]; - default: - return null; - } - } - - /** - * Alias to __get - * - * @param string $key - * @return mixed - */ - public function get($key) - { - return $this->__get($key); - } - - /** - * Set values - * - * In order to follow {@link __get()}, which operates on a number of - * superglobals, setting values through overloading is not allowed and will - * raise an exception. Use setParam() instead. - * - * @param string $key - * @param mixed $value - * @return void - * @throws Zend_Controller_Request_Exception - */ - public function __set($key, $value) - { - #require_once 'Zend/Controller/Request/Exception.php'; - throw new Zend_Controller_Request_Exception('Setting values in superglobals not allowed; please use setParam()'); - } - - /** - * Alias to __set() - * - * @param string $key - * @param mixed $value - * @return void - */ - public function set($key, $value) - { - return $this->__set($key, $value); - } - - /** - * Check to see if a property is set - * - * @param string $key - * @return boolean - */ - public function __isset($key) - { - switch (true) { - case isset($this->_params[$key]): - return true; - case isset($_GET[$key]): - return true; - case isset($_POST[$key]): - return true; - case isset($_COOKIE[$key]): - return true; - case isset($_SERVER[$key]): - return true; - case isset($_ENV[$key]): - return true; - default: - return false; - } - } - - /** - * Alias to __isset() - * - * @param string $key - * @return boolean - */ - public function has($key) - { - return $this->__isset($key); - } - - /** - * Set GET values - * - * @param string|array $spec - * @param null|mixed $value - * @return Zend_Controller_Request_Http - */ - public function setQuery($spec, $value = null) - { - if ((null === $value) && !is_array($spec)) { - #require_once 'Zend/Controller/Exception.php'; - throw new Zend_Controller_Exception('Invalid value passed to setQuery(); must be either array of values or key/value pair'); - } - if ((null === $value) && is_array($spec)) { - foreach ($spec as $key => $value) { - $this->setQuery($key, $value); - } - return $this; - } - $_GET[(string) $spec] = $value; - return $this; - } - - /** - * Retrieve a member of the $_GET superglobal - * - * If no $key is passed, returns the entire $_GET array. - * - * @todo How to retrieve from nested arrays - * @param string $key - * @param mixed $default Default value to use if key not found - * @return mixed Returns null if key does not exist - */ - public function getQuery($key = null, $default = null) - { - if (null === $key) { - return $_GET; - } - - return (isset($_GET[$key])) ? $_GET[$key] : $default; - } - - /** - * Set POST values - * - * @param string|array $spec - * @param null|mixed $value - * @return Zend_Controller_Request_Http - */ - public function setPost($spec, $value = null) - { - if ((null === $value) && !is_array($spec)) { - #require_once 'Zend/Controller/Exception.php'; - throw new Zend_Controller_Exception('Invalid value passed to setPost(); must be either array of values or key/value pair'); - } - if ((null === $value) && is_array($spec)) { - foreach ($spec as $key => $value) { - $this->setPost($key, $value); - } - return $this; - } - $_POST[(string) $spec] = $value; - return $this; - } - - /** - * Retrieve a member of the $_POST superglobal - * - * If no $key is passed, returns the entire $_POST array. - * - * @todo How to retrieve from nested arrays - * @param string $key - * @param mixed $default Default value to use if key not found - * @return mixed Returns null if key does not exist - */ - public function getPost($key = null, $default = null) - { - if (null === $key) { - return $_POST; - } - - return (isset($_POST[$key])) ? $_POST[$key] : $default; - } - - /** - * Retrieve a member of the $_COOKIE superglobal - * - * If no $key is passed, returns the entire $_COOKIE array. - * - * @todo How to retrieve from nested arrays - * @param string $key - * @param mixed $default Default value to use if key not found - * @return mixed Returns null if key does not exist - */ - public function getCookie($key = null, $default = null) - { - if (null === $key) { - return $_COOKIE; - } - - return (isset($_COOKIE[$key])) ? $_COOKIE[$key] : $default; - } - - /** - * Retrieve a member of the $_SERVER superglobal - * - * If no $key is passed, returns the entire $_SERVER array. - * - * @param string $key - * @param mixed $default Default value to use if key not found - * @return mixed Returns null if key does not exist - */ - public function getServer($key = null, $default = null) - { - if (null === $key) { - return $_SERVER; - } - - return (isset($_SERVER[$key])) ? $_SERVER[$key] : $default; - } - - /** - * Retrieve a member of the $_ENV superglobal - * - * If no $key is passed, returns the entire $_ENV array. - * - * @param string $key - * @param mixed $default Default value to use if key not found - * @return mixed Returns null if key does not exist - */ - public function getEnv($key = null, $default = null) - { - if (null === $key) { - return $_ENV; - } - - return (isset($_ENV[$key])) ? $_ENV[$key] : $default; - } - - /** - * Set the REQUEST_URI on which the instance operates - * - * If no request URI is passed, uses the value in $_SERVER['REQUEST_URI'], - * $_SERVER['HTTP_X_REWRITE_URL'], or $_SERVER['ORIG_PATH_INFO'] + $_SERVER['QUERY_STRING']. - * - * @param string $requestUri - * @return Zend_Controller_Request_Http - */ - public function setRequestUri($requestUri = null) - { - if ($requestUri === null) { - if (isset($_SERVER['HTTP_X_ORIGINAL_URL'])) { - // IIS with Microsoft Rewrite Module - $requestUri = $_SERVER['HTTP_X_ORIGINAL_URL']; - } elseif (isset($_SERVER['HTTP_X_REWRITE_URL'])) { - // IIS with ISAPI_Rewrite - $requestUri = $_SERVER['HTTP_X_REWRITE_URL']; - } elseif ( - // IIS7 with URL Rewrite: make sure we get the unencoded url (double slash problem) - isset($_SERVER['IIS_WasUrlRewritten']) - && $_SERVER['IIS_WasUrlRewritten'] == '1' - && isset($_SERVER['UNENCODED_URL']) - && $_SERVER['UNENCODED_URL'] != '' - ) { - $requestUri = $_SERVER['UNENCODED_URL']; - } elseif (isset($_SERVER['REQUEST_URI'])) { - $requestUri = $_SERVER['REQUEST_URI']; - // Http proxy reqs setup request uri with scheme and host [and port] + the url path, only use url path - $schemeAndHttpHost = $this->getScheme() . '://' . $this->getHttpHost(); - if (strpos($requestUri, $schemeAndHttpHost) === 0) { - $requestUri = substr($requestUri, strlen($schemeAndHttpHost)); - } - } elseif (isset($_SERVER['ORIG_PATH_INFO'])) { // IIS 5.0, PHP as CGI - $requestUri = $_SERVER['ORIG_PATH_INFO']; - if (!empty($_SERVER['QUERY_STRING'])) { - $requestUri .= '?' . $_SERVER['QUERY_STRING']; - } - } else { - return $this; - } - } elseif (!is_string($requestUri)) { - return $this; - } else { - // Set GET items, if available - if (false !== ($pos = strpos($requestUri, '?'))) { - // Get key => value pairs and set $_GET - $query = substr($requestUri, $pos + 1); - parse_str($query, $vars); - $this->setQuery($vars); - } - } - - $this->_requestUri = $requestUri; - return $this; - } - - /** - * Returns the REQUEST_URI taking into account - * platform differences between Apache and IIS - * - * @return string - */ - public function getRequestUri() - { - if (empty($this->_requestUri)) { - $this->setRequestUri(); - } - - return $this->_requestUri; - } - - /** - * Set the base URL of the request; i.e., the segment leading to the script name - * - * E.g.: - * - /admin - * - /myapp - * - /subdir/index.php - * - * Do not use the full URI when providing the base. The following are - * examples of what not to use: - * - http://example.com/admin (should be just /admin) - * - http://example.com/subdir/index.php (should be just /subdir/index.php) - * - * If no $baseUrl is provided, attempts to determine the base URL from the - * environment, using SCRIPT_FILENAME, SCRIPT_NAME, PHP_SELF, and - * ORIG_SCRIPT_NAME in its determination. - * - * @param mixed $baseUrl - * @return Zend_Controller_Request_Http - */ - public function setBaseUrl($baseUrl = null) - { - if ((null !== $baseUrl) && !is_string($baseUrl)) { - return $this; - } - - if ($baseUrl === null) { - $filename = (isset($_SERVER['SCRIPT_FILENAME'])) ? basename($_SERVER['SCRIPT_FILENAME']) : ''; - - if (isset($_SERVER['SCRIPT_NAME']) && basename($_SERVER['SCRIPT_NAME']) === $filename) { - $baseUrl = $_SERVER['SCRIPT_NAME']; - } elseif (isset($_SERVER['PHP_SELF']) && basename($_SERVER['PHP_SELF']) === $filename) { - $baseUrl = $_SERVER['PHP_SELF']; - } elseif (isset($_SERVER['ORIG_SCRIPT_NAME']) && basename($_SERVER['ORIG_SCRIPT_NAME']) === $filename) { - $baseUrl = $_SERVER['ORIG_SCRIPT_NAME']; // 1and1 shared hosting compatibility - } else { - // Backtrack up the script_filename to find the portion matching - // php_self - $path = isset($_SERVER['PHP_SELF']) ? $_SERVER['PHP_SELF'] : ''; - $file = isset($_SERVER['SCRIPT_FILENAME']) ? $_SERVER['SCRIPT_FILENAME'] : ''; - $segs = explode('/', trim($file, '/')); - $segs = array_reverse($segs); - $index = 0; - $last = count($segs); - $baseUrl = ''; - do { - $seg = $segs[$index]; - $baseUrl = '/' . $seg . $baseUrl; - ++$index; - } while (($last > $index) && (false !== ($pos = strpos($path, $baseUrl))) && (0 != $pos)); - } - - // Does the baseUrl have anything in common with the request_uri? - $requestUri = $this->getRequestUri(); - - if (0 === strpos($requestUri, $baseUrl)) { - // full $baseUrl matches - $this->_baseUrl = $baseUrl; - return $this; - } - - if (0 === strpos($requestUri, dirname($baseUrl))) { - // directory portion of $baseUrl matches - $this->_baseUrl = rtrim(dirname($baseUrl), '/'); - return $this; - } - - $truncatedRequestUri = $requestUri; - if (($pos = strpos($requestUri, '?')) !== false) { - $truncatedRequestUri = substr($requestUri, 0, $pos); - } - - $basename = basename($baseUrl); - if (empty($basename) || !strpos($truncatedRequestUri, $basename)) { - // no match whatsoever; set it blank - $this->_baseUrl = ''; - return $this; - } - - // If using mod_rewrite or ISAPI_Rewrite strip the script filename - // out of baseUrl. $pos !== 0 makes sure it is not matching a value - // from PATH_INFO or QUERY_STRING - if ((strlen($requestUri) >= strlen($baseUrl)) - && ((false !== ($pos = strpos($requestUri, $baseUrl))) && ($pos !== 0))) - { - $baseUrl = substr($requestUri, 0, $pos + strlen($baseUrl)); - } - } - - $this->_baseUrl = rtrim($baseUrl, '/'); - return $this; - } - - /** - * Everything in REQUEST_URI before PATH_INFO - *
- * - * @return string - */ - public function getBaseUrl($raw = false) - { - if (null === $this->_baseUrl) { - $this->setBaseUrl(); - } - - return (($raw == false) ? urldecode($this->_baseUrl) : $this->_baseUrl); - } - - /** - * Set the base path for the URL - * - * @param string|null $basePath - * @return Zend_Controller_Request_Http - */ - public function setBasePath($basePath = null) - { - if ($basePath === null) { - $filename = (isset($_SERVER['SCRIPT_FILENAME'])) - ? basename($_SERVER['SCRIPT_FILENAME']) - : ''; - - $baseUrl = $this->getBaseUrl(); - if (empty($baseUrl)) { - $this->_basePath = ''; - return $this; - } - - if (basename($baseUrl) === $filename) { - $basePath = dirname($baseUrl); - } else { - $basePath = $baseUrl; - } - } - - if (substr(PHP_OS, 0, 3) === 'WIN') { - $basePath = str_replace('\\', '/', $basePath); - } - - $this->_basePath = rtrim($basePath, '/'); - return $this; - } - - /** - * Everything in REQUEST_URI before PATH_INFO not including the filename - * - * - * @return string - */ - public function getBasePath() - { - if (null === $this->_basePath) { - $this->setBasePath(); - } - - return $this->_basePath; - } - - /** - * Set the PATH_INFO string - * - * @param string|null $pathInfo - * @return Zend_Controller_Request_Http - */ - public function setPathInfo($pathInfo = null) - { - if ($pathInfo === null) { - $baseUrl = $this->getBaseUrl(); // this actually calls setBaseUrl() & setRequestUri() - $baseUrlRaw = $this->getBaseUrl(false); - $baseUrlEncoded = urlencode($baseUrlRaw); - - if (null === ($requestUri = $this->getRequestUri())) { - return $this; - } - - // Remove the query string from REQUEST_URI - if ($pos = strpos($requestUri, '?')) { - $requestUri = substr($requestUri, 0, $pos); - } - - if (!empty($baseUrl) || !empty($baseUrlRaw)) { - if (strpos($requestUri, $baseUrl) === 0) { - $pathInfo = substr($requestUri, strlen($baseUrl)); - } elseif (strpos($requestUri, $baseUrlRaw) === 0) { - $pathInfo = substr($requestUri, strlen($baseUrlRaw)); - } elseif (strpos($requestUri, $baseUrlEncoded) === 0) { - $pathInfo = substr($requestUri, strlen($baseUrlEncoded)); - } else { - $pathInfo = $requestUri; - } - } else { - $pathInfo = $requestUri; - } - - } - - $this->_pathInfo = (string) $pathInfo; - return $this; - } - - /** - * Returns everything between the BaseUrl and QueryString. - * This value is calculated instead of reading PATH_INFO - * directly from $_SERVER due to cross-platform differences. - * - * @return string - */ - public function getPathInfo() - { - if (empty($this->_pathInfo)) { - $this->setPathInfo(); - } - - return $this->_pathInfo; - } - - /** - * Set allowed parameter sources - * - * Can be empty array, or contain one or more of '_GET' or '_POST'. - * - * @param array $paramSoures - * @return Zend_Controller_Request_Http - */ - public function setParamSources(array $paramSources = array()) - { - $this->_paramSources = $paramSources; - return $this; - } - - /** - * Get list of allowed parameter sources - * - * @return array - */ - public function getParamSources() - { - return $this->_paramSources; - } - - /** - * Set a userland parameter - * - * Uses $key to set a userland parameter. If $key is an alias, the actual - * key will be retrieved and used to set the parameter. - * - * @param mixed $key - * @param mixed $value - * @return Zend_Controller_Request_Http - */ - public function setParam($key, $value) - { - $key = (null !== ($alias = $this->getAlias($key))) ? $alias : $key; - parent::setParam($key, $value); - return $this; - } - - /** - * Retrieve a parameter - * - * Retrieves a parameter from the instance. Priority is in the order of - * userland parameters (see {@link setParam()}), $_GET, $_POST. If a - * parameter matching the $key is not found, null is returned. - * - * If the $key is an alias, the actual key aliased will be used. - * - * @param mixed $key - * @param mixed $default Default value to use if key not found - * @return mixed - */ - public function getParam($key, $default = null) - { - $keyName = (null !== ($alias = $this->getAlias($key))) ? $alias : $key; - - $paramSources = $this->getParamSources(); - if (isset($this->_params[$keyName])) { - return $this->_params[$keyName]; - } elseif (in_array('_GET', $paramSources) && (isset($_GET[$keyName]))) { - return $_GET[$keyName]; - } elseif (in_array('_POST', $paramSources) && (isset($_POST[$keyName]))) { - return $_POST[$keyName]; - } - - return $default; - } - - /** - * Retrieve an array of parameters - * - * Retrieves a merged array of parameters, with precedence of userland - * params (see {@link setParam()}), $_GET, $_POST (i.e., values in the - * userland params will take precedence over all others). - * - * @return array - */ - public function getParams() - { - $return = $this->_params; - $paramSources = $this->getParamSources(); - if (in_array('_GET', $paramSources) - && isset($_GET) - && is_array($_GET) - ) { - $return += $_GET; - } - if (in_array('_POST', $paramSources) - && isset($_POST) - && is_array($_POST) - ) { - $return += $_POST; - } - return $return; - } - - /** - * Set parameters - * - * Set one or more parameters. Parameters are set as userland parameters, - * using the keys specified in the array. - * - * @param array $params - * @return Zend_Controller_Request_Http - */ - public function setParams(array $params) - { - foreach ($params as $key => $value) { - $this->setParam($key, $value); - } - return $this; - } - - /** - * Set a key alias - * - * Set an alias used for key lookups. $name specifies the alias, $target - * specifies the actual key to use. - * - * @param string $name - * @param string $target - * @return Zend_Controller_Request_Http - */ - public function setAlias($name, $target) - { - $this->_aliases[$name] = $target; - return $this; - } - - /** - * Retrieve an alias - * - * Retrieve the actual key represented by the alias $name. - * - * @param string $name - * @return string|null Returns null when no alias exists - */ - public function getAlias($name) - { - if (isset($this->_aliases[$name])) { - return $this->_aliases[$name]; - } - - return null; - } - - /** - * Retrieve the list of all aliases - * - * @return array - */ - public function getAliases() - { - return $this->_aliases; - } - - /** - * Return the method by which the request was made - * - * @return string - */ - public function getMethod() - { - return $this->getServer('REQUEST_METHOD'); - } - - /** - * Was the request made by POST? - * - * @return boolean - */ - public function isPost() - { - if ('POST' == $this->getMethod()) { - return true; - } - - return false; - } - - /** - * Was the request made by GET? - * - * @return boolean - */ - public function isGet() - { - if ('GET' == $this->getMethod()) { - return true; - } - - return false; - } - - /** - * Was the request made by PUT? - * - * @return boolean - */ - public function isPut() - { - if ('PUT' == $this->getMethod()) { - return true; - } - - return false; - } - - /** - * Was the request made by DELETE? - * - * @return boolean - */ - public function isDelete() - { - if ('DELETE' == $this->getMethod()) { - return true; - } - - return false; - } - - /** - * Was the request made by HEAD? - * - * @return boolean - */ - public function isHead() - { - if ('HEAD' == $this->getMethod()) { - return true; - } - - return false; - } - - /** - * Was the request made by OPTIONS? - * - * @return boolean - */ - public function isOptions() - { - if ('OPTIONS' == $this->getMethod()) { - return true; - } - - return false; - } - - /** - * Was the request made by PATCH? - * - * @return boolean - */ - public function isPatch() - { - if ('PATCH' == $this->getMethod()) { - return true; - } - - return false; - } - - /** - * Is the request a Javascript XMLHttpRequest? - * - * Should work with Prototype/Script.aculo.us, possibly others. - * - * @return boolean - */ - public function isXmlHttpRequest() - { - return ($this->getHeader('X_REQUESTED_WITH') == 'XMLHttpRequest'); - } - - /** - * Is this a Flash request? - * - * @return boolean - */ - public function isFlashRequest() - { - $header = strtolower($this->getHeader('USER_AGENT')); - return (strstr($header, ' flash')) ? true : false; - } - - /** - * Is https secure request - * - * @return boolean - */ - public function isSecure() - { - return ($this->getScheme() === self::SCHEME_HTTPS); - } - - /** - * Return the raw body of the request, if present - * - * @return string|false Raw body, or false if not present - */ - public function getRawBody() - { - if (null === $this->_rawBody) { - $body = file_get_contents('php://input'); - - if (strlen(trim($body)) > 0) { - $this->_rawBody = $body; - } else { - $this->_rawBody = false; - } - } - return $this->_rawBody; - } - - /** - * Return the value of the given HTTP header. Pass the header name as the - * plain, HTTP-specified header name. Ex.: Ask for 'Accept' to get the - * Accept header, 'Accept-Encoding' to get the Accept-Encoding header. - * - * @param string $header HTTP header name - * @return string|false HTTP header value, or false if not found - * @throws Zend_Controller_Request_Exception - */ - public function getHeader($header) - { - if (empty($header)) { - #require_once 'Zend/Controller/Request/Exception.php'; - throw new Zend_Controller_Request_Exception('An HTTP header name is required'); - } - - // Try to get it from the $_SERVER array first - $temp = strtoupper(str_replace('-', '_', $header)); - if (isset($_SERVER['HTTP_' . $temp])) { - return $_SERVER['HTTP_' . $temp]; - } - - /* - * Try to get it from the $_SERVER array on POST request or CGI environment - * @see https://www.ietf.org/rfc/rfc3875 (4.1.2. and 4.1.3.) - */ - if (isset($_SERVER[$temp]) - && in_array($temp, array('CONTENT_TYPE', 'CONTENT_LENGTH')) - ) { - return $_SERVER[$temp]; - } - - // This seems to be the only way to get the Authorization header on - // Apache - if (function_exists('apache_request_headers')) { - $headers = apache_request_headers(); - if (isset($headers[$header])) { - return $headers[$header]; - } - $header = strtolower($header); - foreach ($headers as $key => $value) { - if (strtolower($key) == $header) { - return $value; - } - } - } - - return false; - } - - /** - * Get the request URI scheme - * - * @return string - */ - public function getScheme() - { - return ($this->getServer('HTTPS') == 'on') ? self::SCHEME_HTTPS : self::SCHEME_HTTP; - } - - /** - * Get the HTTP host. - * - * "Host" ":" host [ ":" port ] ; Section 3.2.2 - * Note the HTTP Host header is not the same as the URI host. - * It includes the port while the URI host doesn't. - * - * @return string - */ - public function getHttpHost() - { - $host = $this->getServer('HTTP_HOST'); - if (!empty($host)) { - return $host; - } - - $scheme = $this->getScheme(); - $name = $this->getServer('SERVER_NAME'); - $port = $this->getServer('SERVER_PORT'); - - if(null === $name) { - return ''; - } - elseif (($scheme == self::SCHEME_HTTP && $port == 80) || ($scheme == self::SCHEME_HTTPS && $port == 443)) { - return $name; - } else { - return $name . ':' . $port; - } - } - - /** - * Get the client's IP addres - * - * @param boolean $checkProxy - * @return string - */ - public function getClientIp($checkProxy = true) - { - if ($checkProxy && $this->getServer('HTTP_CLIENT_IP') != null) { - $ip = $this->getServer('HTTP_CLIENT_IP'); - } else if ($checkProxy && $this->getServer('HTTP_X_FORWARDED_FOR') != null) { - $ip = $this->getServer('HTTP_X_FORWARDED_FOR'); - } else { - $ip = $this->getServer('REMOTE_ADDR'); - } - - return $ip; - } -} diff --git a/library/Zend/Controller/Request/HttpTestCase.php b/library/Zend/Controller/Request/HttpTestCase.php deleted file mode 100644 index 33824d0e49..0000000000 --- a/library/Zend/Controller/Request/HttpTestCase.php +++ /dev/null @@ -1,277 +0,0 @@ -_rawBody = (string) $content; - return $this; - } - - /** - * Get RAW POST body - * - * @return string|null - */ - public function getRawBody() - { - return $this->_rawBody; - } - - /** - * Clear raw POST body - * - * @return Zend_Controller_Request_HttpTestCase - */ - public function clearRawBody() - { - $this->_rawBody = null; - return $this; - } - - /** - * Set a cookie - * - * @param string $key - * @param mixed $value - * @return Zend_Controller_Request_HttpTestCase - */ - public function setCookie($key, $value) - { - $_COOKIE[(string) $key] = $value; - return $this; - } - - /** - * Set multiple cookies at once - * - * @param array $cookies - * @return void - */ - public function setCookies(array $cookies) - { - foreach ($cookies as $key => $value) { - $_COOKIE[$key] = $value; - } - return $this; - } - - /** - * Clear all cookies - * - * @return Zend_Controller_Request_HttpTestCase - */ - public function clearCookies() - { - $_COOKIE = array(); - return $this; - } - - /** - * Set request method - * - * @param string $type - * @return Zend_Controller_Request_HttpTestCase - */ - public function setMethod($type) - { - $type = strtoupper(trim((string) $type)); - if (!in_array($type, $this->_validMethodTypes)) { - #require_once 'Zend/Controller/Exception.php'; - throw new Zend_Controller_Exception('Invalid request method specified'); - } - $this->_method = $type; - return $this; - } - - /** - * Get request method - * - * @return string|null - */ - public function getMethod() - { - return $this->_method; - } - - /** - * Set a request header - * - * @param string $key - * @param string $value - * @return Zend_Controller_Request_HttpTestCase - */ - public function setHeader($key, $value) - { - $key = $this->_normalizeHeaderName($key); - $this->_headers[$key] = (string) $value; - return $this; - } - - /** - * Set request headers - * - * @param array $headers - * @return Zend_Controller_Request_HttpTestCase - */ - public function setHeaders(array $headers) - { - foreach ($headers as $key => $value) { - $this->setHeader($key, $value); - } - return $this; - } - - /** - * Get request header - * - * @param string $header - * @param mixed $default - * @return string|null - */ - public function getHeader($header, $default = null) - { - $header = $this->_normalizeHeaderName($header); - if (array_key_exists($header, $this->_headers)) { - return $this->_headers[$header]; - } - return $default; - } - - /** - * Get all request headers - * - * @return array - */ - public function getHeaders() - { - return $this->_headers; - } - - /** - * Clear request headers - * - * @return Zend_Controller_Request_HttpTestCase - */ - public function clearHeaders() - { - $this->_headers = array(); - return $this; - } - - /** - * Get REQUEST_URI - * - * @return null|string - */ - public function getRequestUri() - { - return $this->_requestUri; - } - - /** - * Normalize a header name for setting and retrieval - * - * @param string $name - * @return string - */ - protected function _normalizeHeaderName($name) - { - $name = strtoupper((string) $name); - $name = str_replace('-', '_', $name); - return $name; - } -} diff --git a/library/Zend/Controller/Request/Simple.php b/library/Zend/Controller/Request/Simple.php deleted file mode 100644 index 492db7d56a..0000000000 --- a/library/Zend/Controller/Request/Simple.php +++ /dev/null @@ -1,55 +0,0 @@ -setActionName($action); - } - - if ($controller) { - $this->setControllerName($controller); - } - - if ($module) { - $this->setModuleName($module); - } - - if ($params) { - $this->setParams($params); - } - } - -} diff --git a/library/Zend/Controller/Response/Abstract.php b/library/Zend/Controller/Response/Abstract.php deleted file mode 100644 index dd3127e2ad..0000000000 --- a/library/Zend/Controller/Response/Abstract.php +++ /dev/null @@ -1,796 +0,0 @@ -canSendHeaders(true); - $name = $this->_normalizeHeader($name); - $value = (string) $value; - - if ($replace) { - foreach ($this->_headers as $key => $header) { - if ($name == $header['name']) { - unset($this->_headers[$key]); - } - } - } - - $this->_headers[] = array( - 'name' => $name, - 'value' => $value, - 'replace' => $replace - ); - - return $this; - } - - /** - * Set redirect URL - * - * Sets Location header and response code. Forces replacement of any prior - * redirects. - * - * @param string $url - * @param int $code - * @return Zend_Controller_Response_Abstract - */ - public function setRedirect($url, $code = 302) - { - $this->canSendHeaders(true); - $this->setHeader('Location', $url, true) - ->setHttpResponseCode($code); - - return $this; - } - - /** - * Is this a redirect? - * - * @return boolean - */ - public function isRedirect() - { - return $this->_isRedirect; - } - - /** - * Return array of headers; see {@link $_headers} for format - * - * @return array - */ - public function getHeaders() - { - return $this->_headers; - } - - /** - * Clear headers - * - * @return Zend_Controller_Response_Abstract - */ - public function clearHeaders() - { - $this->_headers = array(); - - return $this; - } - - /** - * Clears the specified HTTP header - * - * @param string $name - * @return Zend_Controller_Response_Abstract - */ - public function clearHeader($name) - { - if (! count($this->_headers)) { - return $this; - } - - foreach ($this->_headers as $index => $header) { - if ($name == $header['name']) { - unset($this->_headers[$index]); - } - } - - return $this; - } - - /** - * Set raw HTTP header - * - * Allows setting non key => value headers, such as status codes - * - * @param string $value - * @return Zend_Controller_Response_Abstract - */ - public function setRawHeader($value) - { - $this->canSendHeaders(true); - if ('Location' == substr($value, 0, 8)) { - $this->_isRedirect = true; - } - $this->_headersRaw[] = (string) $value; - return $this; - } - - /** - * Retrieve all {@link setRawHeader() raw HTTP headers} - * - * @return array - */ - public function getRawHeaders() - { - return $this->_headersRaw; - } - - /** - * Clear all {@link setRawHeader() raw HTTP headers} - * - * @return Zend_Controller_Response_Abstract - */ - public function clearRawHeaders() - { - $this->_headersRaw = array(); - return $this; - } - - /** - * Clears the specified raw HTTP header - * - * @param string $headerRaw - * @return Zend_Controller_Response_Abstract - */ - public function clearRawHeader($headerRaw) - { - if (! count($this->_headersRaw)) { - return $this; - } - - $key = array_search($headerRaw, $this->_headersRaw); - if ($key !== false) { - unset($this->_headersRaw[$key]); - } - - return $this; - } - - /** - * Clear all headers, normal and raw - * - * @return Zend_Controller_Response_Abstract - */ - public function clearAllHeaders() - { - return $this->clearHeaders() - ->clearRawHeaders(); - } - - /** - * Set HTTP response code to use with headers - * - * @param int $code - * @return Zend_Controller_Response_Abstract - */ - public function setHttpResponseCode($code) - { - if (!is_int($code) || (100 > $code) || (599 < $code)) { - #require_once 'Zend/Controller/Response/Exception.php'; - throw new Zend_Controller_Response_Exception('Invalid HTTP response code'); - } - - if ((300 <= $code) && (307 >= $code)) { - $this->_isRedirect = true; - } else { - $this->_isRedirect = false; - } - - $this->_httpResponseCode = $code; - return $this; - } - - /** - * Retrieve HTTP response code - * - * @return int - */ - public function getHttpResponseCode() - { - return $this->_httpResponseCode; - } - - /** - * Can we send headers? - * - * @param boolean $throw Whether or not to throw an exception if headers have been sent; defaults to false - * @return boolean - * @throws Zend_Controller_Response_Exception - */ - public function canSendHeaders($throw = false) - { - $ok = headers_sent($file, $line); - if ($ok && $throw && $this->headersSentThrowsException) { - #require_once 'Zend/Controller/Response/Exception.php'; - throw new Zend_Controller_Response_Exception('Cannot send headers; headers already sent in ' . $file . ', line ' . $line); - } - - return !$ok; - } - - /** - * Send all headers - * - * Sends any headers specified. If an {@link setHttpResponseCode() HTTP response code} - * has been specified, it is sent with the first header. - * - * @return Zend_Controller_Response_Abstract - */ - public function sendHeaders() - { - // Only check if we can send headers if we have headers to send - if (count($this->_headersRaw) || count($this->_headers) || (200 != $this->_httpResponseCode)) { - $this->canSendHeaders(true); - } elseif (200 == $this->_httpResponseCode) { - // Haven't changed the response code, and we have no headers - return $this; - } - - $httpCodeSent = false; - - foreach ($this->_headersRaw as $header) { - if (!$httpCodeSent && $this->_httpResponseCode) { - header($header, true, $this->_httpResponseCode); - $httpCodeSent = true; - } else { - header($header); - } - } - - foreach ($this->_headers as $header) { - if (!$httpCodeSent && $this->_httpResponseCode) { - header($header['name'] . ': ' . $header['value'], $header['replace'], $this->_httpResponseCode); - $httpCodeSent = true; - } else { - header($header['name'] . ': ' . $header['value'], $header['replace']); - } - } - - if (!$httpCodeSent) { - header('HTTP/1.1 ' . $this->_httpResponseCode); - $httpCodeSent = true; - } - - return $this; - } - - /** - * Set body content - * - * If $name is not passed, or is not a string, resets the entire body and - * sets the 'default' key to $content. - * - * If $name is a string, sets the named segment in the body array to - * $content. - * - * @param string $content - * @param null|string $name - * @return Zend_Controller_Response_Abstract - */ - public function setBody($content, $name = null) - { - if ((null === $name) || !is_string($name)) { - $this->_body = array('default' => (string) $content); - } else { - $this->_body[$name] = (string) $content; - } - - return $this; - } - - /** - * Append content to the body content - * - * @param string $content - * @param null|string $name - * @return Zend_Controller_Response_Abstract - */ - public function appendBody($content, $name = null) - { - if ((null === $name) || !is_string($name)) { - if (isset($this->_body['default'])) { - $this->_body['default'] .= (string) $content; - } else { - return $this->append('default', $content); - } - } elseif (isset($this->_body[$name])) { - $this->_body[$name] .= (string) $content; - } else { - return $this->append($name, $content); - } - - return $this; - } - - /** - * Clear body array - * - * With no arguments, clears the entire body array. Given a $name, clears - * just that named segment; if no segment matching $name exists, returns - * false to indicate an error. - * - * @param string $name Named segment to clear - * @return boolean - */ - public function clearBody($name = null) - { - if (null !== $name) { - $name = (string) $name; - if (isset($this->_body[$name])) { - unset($this->_body[$name]); - return true; - } - - return false; - } - - $this->_body = array(); - return true; - } - - /** - * Return the body content - * - * If $spec is false, returns the concatenated values of the body content - * array. If $spec is boolean true, returns the body content array. If - * $spec is a string and matches a named segment, returns the contents of - * that segment; otherwise, returns null. - * - * @param boolean $spec - * @return string|array|null - */ - public function getBody($spec = false) - { - if (false === $spec) { - ob_start(); - $this->outputBody(); - return ob_get_clean(); - } elseif (true === $spec) { - return $this->_body; - } elseif (is_string($spec) && isset($this->_body[$spec])) { - return $this->_body[$spec]; - } - - return null; - } - - /** - * Append a named body segment to the body content array - * - * If segment already exists, replaces with $content and places at end of - * array. - * - * @param string $name - * @param string $content - * @return Zend_Controller_Response_Abstract - */ - public function append($name, $content) - { - if (!is_string($name)) { - #require_once 'Zend/Controller/Response/Exception.php'; - throw new Zend_Controller_Response_Exception('Invalid body segment key ("' . gettype($name) . '")'); - } - - if (isset($this->_body[$name])) { - unset($this->_body[$name]); - } - $this->_body[$name] = (string) $content; - return $this; - } - - /** - * Prepend a named body segment to the body content array - * - * If segment already exists, replaces with $content and places at top of - * array. - * - * @param string $name - * @param string $content - * @return void - */ - public function prepend($name, $content) - { - if (!is_string($name)) { - #require_once 'Zend/Controller/Response/Exception.php'; - throw new Zend_Controller_Response_Exception('Invalid body segment key ("' . gettype($name) . '")'); - } - - if (isset($this->_body[$name])) { - unset($this->_body[$name]); - } - - $new = array($name => (string) $content); - $this->_body = $new + $this->_body; - - return $this; - } - - /** - * Insert a named segment into the body content array - * - * @param string $name - * @param string $content - * @param string $parent - * @param boolean $before Whether to insert the new segment before or - * after the parent. Defaults to false (after) - * @return Zend_Controller_Response_Abstract - */ - public function insert($name, $content, $parent = null, $before = false) - { - if (!is_string($name)) { - #require_once 'Zend/Controller/Response/Exception.php'; - throw new Zend_Controller_Response_Exception('Invalid body segment key ("' . gettype($name) . '")'); - } - - if ((null !== $parent) && !is_string($parent)) { - #require_once 'Zend/Controller/Response/Exception.php'; - throw new Zend_Controller_Response_Exception('Invalid body segment parent key ("' . gettype($parent) . '")'); - } - - if (isset($this->_body[$name])) { - unset($this->_body[$name]); - } - - if ((null === $parent) || !isset($this->_body[$parent])) { - return $this->append($name, $content); - } - - $ins = array($name => (string) $content); - $keys = array_keys($this->_body); - $loc = array_search($parent, $keys); - if (!$before) { - // Increment location if not inserting before - ++$loc; - } - - if (0 === $loc) { - // If location of key is 0, we're prepending - $this->_body = $ins + $this->_body; - } elseif ($loc >= (count($this->_body))) { - // If location of key is maximal, we're appending - $this->_body = $this->_body + $ins; - } else { - // Otherwise, insert at location specified - $pre = array_slice($this->_body, 0, $loc); - $post = array_slice($this->_body, $loc); - $this->_body = $pre + $ins + $post; - } - - return $this; - } - - /** - * Echo the body segments - * - * @return void - */ - public function outputBody() - { - $body = implode('', $this->_body); - echo $body; - } - - /** - * Register an exception with the response - * - * @param Exception $e - * @return Zend_Controller_Response_Abstract - */ - public function setException(Exception $e) - { - $this->_exceptions[] = $e; - return $this; - } - - /** - * Retrieve the exception stack - * - * @return array - */ - public function getException() - { - return $this->_exceptions; - } - - /** - * Has an exception been registered with the response? - * - * @return boolean - */ - public function isException() - { - return !empty($this->_exceptions); - } - - /** - * Does the response object contain an exception of a given type? - * - * @param string $type - * @return boolean - */ - public function hasExceptionOfType($type) - { - foreach ($this->_exceptions as $e) { - if ($e instanceof $type) { - return true; - } - } - - return false; - } - - /** - * Does the response object contain an exception with a given message? - * - * @param string $message - * @return boolean - */ - public function hasExceptionOfMessage($message) - { - foreach ($this->_exceptions as $e) { - if ($message == $e->getMessage()) { - return true; - } - } - - return false; - } - - /** - * Does the response object contain an exception with a given code? - * - * @param int $code - * @return boolean - */ - public function hasExceptionOfCode($code) - { - $code = (int) $code; - foreach ($this->_exceptions as $e) { - if ($code == $e->getCode()) { - return true; - } - } - - return false; - } - - /** - * Retrieve all exceptions of a given type - * - * @param string $type - * @return false|array - */ - public function getExceptionByType($type) - { - $exceptions = array(); - foreach ($this->_exceptions as $e) { - if ($e instanceof $type) { - $exceptions[] = $e; - } - } - - if (empty($exceptions)) { - $exceptions = false; - } - - return $exceptions; - } - - /** - * Retrieve all exceptions of a given message - * - * @param string $message - * @return false|array - */ - public function getExceptionByMessage($message) - { - $exceptions = array(); - foreach ($this->_exceptions as $e) { - if ($message == $e->getMessage()) { - $exceptions[] = $e; - } - } - - if (empty($exceptions)) { - $exceptions = false; - } - - return $exceptions; - } - - /** - * Retrieve all exceptions of a given code - * - * @param mixed $code - * @return void - */ - public function getExceptionByCode($code) - { - $code = (int) $code; - $exceptions = array(); - foreach ($this->_exceptions as $e) { - if ($code == $e->getCode()) { - $exceptions[] = $e; - } - } - - if (empty($exceptions)) { - $exceptions = false; - } - - return $exceptions; - } - - /** - * Whether or not to render exceptions (off by default) - * - * If called with no arguments or a null argument, returns the value of the - * flag; otherwise, sets it and returns the current value. - * - * @param boolean $flag Optional - * @return boolean - */ - public function renderExceptions($flag = null) - { - if (null !== $flag) { - $this->_renderExceptions = $flag ? true : false; - } - - return $this->_renderExceptions; - } - - /** - * Send the response, including all headers, rendering exceptions if so - * requested. - * - * @return void - */ - public function sendResponse() - { - $this->sendHeaders(); - - if ($this->isException() && $this->renderExceptions()) { - $exceptions = ''; - foreach ($this->getException() as $e) { - $exceptions .= $e->__toString() . "\n"; - } - echo $exceptions; - return; - } - - $this->outputBody(); - } - - /** - * Magic __toString functionality - * - * Proxies to {@link sendResponse()} and returns response value as string - * using output buffering. - * - * @return string - */ - public function __toString() - { - ob_start(); - $this->sendResponse(); - return ob_get_clean(); - } -} diff --git a/library/Zend/Controller/Response/Cli.php b/library/Zend/Controller/Response/Cli.php deleted file mode 100644 index 5d9ce9b239..0000000000 --- a/library/Zend/Controller/Response/Cli.php +++ /dev/null @@ -1,68 +0,0 @@ -isException() && $this->renderExceptions()) { - $exceptions = ''; - foreach ($this->getException() as $e) { - $exceptions .= $e->__toString() . "\n"; - } - return $exceptions; - } - - return $this->_body; - } -} diff --git a/library/Zend/Controller/Response/Exception.php b/library/Zend/Controller/Response/Exception.php deleted file mode 100644 index 842c0e357c..0000000000 --- a/library/Zend/Controller/Response/Exception.php +++ /dev/null @@ -1,36 +0,0 @@ -_headersRaw as $header) { - $headers[] = $header; - } - foreach ($this->_headers as $header) { - $name = $header['name']; - $key = strtolower($name); - if (array_key_exists($name, $headers)) { - if ($header['replace']) { - $headers[$key] = $header['name'] . ': ' . $header['value']; - } - } else { - $headers[$key] = $header['name'] . ': ' . $header['value']; - } - } - return $headers; - } - - /** - * Can we send headers? - * - * @param bool $throw - * @return void - */ - public function canSendHeaders($throw = false) - { - return true; - } - - /** - * Return the concatenated body segments - * - * @return string - */ - public function outputBody() - { - $fullContent = ''; - foreach ($this->_body as $content) { - $fullContent .= $content; - } - return $fullContent; - } - - /** - * Get body and/or body segments - * - * @param bool|string $spec - * @return string|array|null - */ - public function getBody($spec = false) - { - if (false === $spec) { - return $this->outputBody(); - } elseif (true === $spec) { - return $this->_body; - } elseif (is_string($spec) && isset($this->_body[$spec])) { - return $this->_body[$spec]; - } - - return null; - } - - /** - * "send" Response - * - * Concats all response headers, and then final body (separated by two - * newlines) - * - * @return string - */ - public function sendResponse() - { - $headers = $this->sendHeaders(); - $content = implode("\n", $headers) . "\n\n"; - - if ($this->isException() && $this->renderExceptions()) { - $exceptions = ''; - foreach ($this->getException() as $e) { - $exceptions .= $e->__toString() . "\n"; - } - $content .= $exceptions; - } else { - $content .= $this->outputBody(); - } - - return $content; - } -} diff --git a/library/Zend/Controller/Router/Abstract.php b/library/Zend/Controller/Router/Abstract.php deleted file mode 100644 index bd80babc1f..0000000000 --- a/library/Zend/Controller/Router/Abstract.php +++ /dev/null @@ -1,178 +0,0 @@ -setParams($params); - } - - /** - * Add or modify a parameter to use when instantiating an action controller - * - * @param string $name - * @param mixed $value - * @return Zend_Controller_Router_Abstract - */ - public function setParam($name, $value) - { - $name = (string)$name; - $this->_invokeParams[$name] = $value; - - return $this; - } - - /** - * Set parameters to pass to action controller constructors - * - * @param array $params - * @return Zend_Controller_Router_Abstract - */ - public function setParams(array $params) - { - $this->_invokeParams = array_merge($this->_invokeParams, $params); - - return $this; - } - - /** - * Retrieve a single parameter from the controller parameter stack - * - * @param string $name - * @return mixed - */ - public function getParam($name) - { - if (isset($this->_invokeParams[$name])) { - return $this->_invokeParams[$name]; - } - - return null; - } - - /** - * Retrieve action controller instantiation parameters - * - * @return array - */ - public function getParams() - { - return $this->_invokeParams; - } - - /** - * Clear the controller parameter stack - * - * By default, clears all parameters. If a parameter name is given, clears - * only that parameter; if an array of parameter names is provided, clears - * each. - * - * @param null|string|array single key or array of keys for params to clear - * @return Zend_Controller_Router_Abstract - */ - public function clearParams($name = null) - { - if (null === $name) { - $this->_invokeParams = array(); - } elseif (is_string($name) && isset($this->_invokeParams[$name])) { - unset($this->_invokeParams[$name]); - } elseif (is_array($name)) { - foreach ($name as $key) { - if (is_string($key) && isset($this->_invokeParams[$key])) { - unset($this->_invokeParams[$key]); - } - } - } - - return $this; - } - - /** - * Retrieve Front Controller - * - * @return Zend_Controller_Front - */ - public function getFrontController() - { - // Used cache version if found - if (null !== $this->_frontController) { - return $this->_frontController; - } - - #require_once 'Zend/Controller/Front.php'; - $this->_frontController = Zend_Controller_Front::getInstance(); - - return $this->_frontController; - } - - /** - * Set Front Controller - * - * @param Zend_Controller_Front $controller - * @return Zend_Controller_Router_Interface - */ - public function setFrontController(Zend_Controller_Front $controller) - { - $this->_frontController = $controller; - - return $this; - } -} diff --git a/library/Zend/Controller/Router/Exception.php b/library/Zend/Controller/Router/Exception.php deleted file mode 100644 index 40bfd68558..0000000000 --- a/library/Zend/Controller/Router/Exception.php +++ /dev/null @@ -1,35 +0,0 @@ -hasRoute('default')) { - $dispatcher = $this->getFrontController()->getDispatcher(); - $request = $this->getFrontController()->getRequest(); - - #require_once 'Zend/Controller/Router/Route/Module.php'; - $compat = new Zend_Controller_Router_Route_Module(array(), $dispatcher, $request); - - $this->_routes = array('default' => $compat) + $this->_routes; - } - - return $this; - } - - /** - * Add route to the route chain - * - * If route contains method setRequest(), it is initialized with a request object - * - * @param string $name Name of the route - * @param Zend_Controller_Router_Route_Interface $route Instance of the route - * @return Zend_Controller_Router_Rewrite - */ - public function addRoute($name, Zend_Controller_Router_Route_Interface $route) - { - if (method_exists($route, 'setRequest')) { - $route->setRequest($this->getFrontController()->getRequest()); - } - - $this->_routes[$name] = $route; - - return $this; - } - - /** - * Add routes to the route chain - * - * @param array $routes Array of routes with names as keys and routes as values - * @return Zend_Controller_Router_Rewrite - */ - public function addRoutes($routes) - { - foreach ($routes as $name => $route) { - $this->addRoute($name, $route); - } - - return $this; - } - - /** - * Create routes out of Zend_Config configuration - * - * Example INI: - * routes.archive.route = "archive/:year/*" - * routes.archive.defaults.controller = archive - * routes.archive.defaults.action = show - * routes.archive.defaults.year = 2000 - * routes.archive.reqs.year = "\d+" - * - * routes.news.type = "Zend_Controller_Router_Route_Static" - * routes.news.route = "news" - * routes.news.defaults.controller = "news" - * routes.news.defaults.action = "list" - * - * And finally after you have created a Zend_Config with above ini: - * $router = new Zend_Controller_Router_Rewrite(); - * $router->addConfig($config, 'routes'); - * - * @param Zend_Config $config Configuration object - * @param string $section Name of the config section containing route's definitions - * @throws Zend_Controller_Router_Exception - * @return Zend_Controller_Router_Rewrite - */ - public function addConfig(Zend_Config $config, $section = null) - { - if ($section !== null) { - if ($config->{$section} === null) { - #require_once 'Zend/Controller/Router/Exception.php'; - throw new Zend_Controller_Router_Exception("No route configuration in section '{$section}'"); - } - - $config = $config->{$section}; - } - - foreach ($config as $name => $info) { - $route = $this->_getRouteFromConfig($info); - - if ($route instanceof Zend_Controller_Router_Route_Chain) { - if (!isset($info->chain)) { - #require_once 'Zend/Controller/Router/Exception.php'; - throw new Zend_Controller_Router_Exception("No chain defined"); - } - - if ($info->chain instanceof Zend_Config) { - $childRouteNames = $info->chain; - } else { - $childRouteNames = explode(',', $info->chain); - } - - foreach ($childRouteNames as $childRouteName) { - $childRoute = $this->getRoute(trim($childRouteName)); - $route->chain($childRoute); - } - - $this->addRoute($name, $route); - } elseif (isset($info->chains) && $info->chains instanceof Zend_Config) { - $this->_addChainRoutesFromConfig($name, $route, $info->chains); - } else { - $this->addRoute($name, $route); - } - } - - return $this; - } - - /** - * Get a route frm a config instance - * - * @param Zend_Config $info - * @return Zend_Controller_Router_Route_Interface - */ - protected function _getRouteFromConfig(Zend_Config $info) - { - $class = (isset($info->type)) ? $info->type : 'Zend_Controller_Router_Route'; - if (!class_exists($class)) { - #require_once 'Zend/Loader.php'; - Zend_Loader::loadClass($class); - } - - $route = call_user_func( - array( - $class, - 'getInstance' - ), $info - ); - - if (isset($info->abstract) && $info->abstract && method_exists($route, 'isAbstract')) { - $route->isAbstract(true); - } - - return $route; - } - - /** - * Add chain routes from a config route - * - * @param string $name - * @param Zend_Controller_Router_Route_Interface $route - * @param Zend_Config $childRoutesInfo - * @return void - */ - protected function _addChainRoutesFromConfig( - $name, - Zend_Controller_Router_Route_Interface $route, - Zend_Config $childRoutesInfo - ) - { - foreach ($childRoutesInfo as $childRouteName => $childRouteInfo) { - if (is_string($childRouteInfo)) { - $childRouteName = $childRouteInfo; - $childRoute = $this->getRoute($childRouteName); - } else { - $childRoute = $this->_getRouteFromConfig($childRouteInfo); - } - - if ($route instanceof Zend_Controller_Router_Route_Chain) { - $chainRoute = clone $route; - $chainRoute->chain($childRoute); - } else { - $chainRoute = $route->chain($childRoute); - } - - $chainName = $name . $this->_chainNameSeparator . $childRouteName; - - if (isset($childRouteInfo->chains)) { - $this->_addChainRoutesFromConfig($chainName, $chainRoute, $childRouteInfo->chains); - } else { - $this->addRoute($chainName, $chainRoute); - } - } - } - - /** - * Remove a route from the route chain - * - * @param string $name Name of the route - * @throws Zend_Controller_Router_Exception - * @return Zend_Controller_Router_Rewrite - */ - public function removeRoute($name) - { - if (!isset($this->_routes[$name])) { - #require_once 'Zend/Controller/Router/Exception.php'; - throw new Zend_Controller_Router_Exception("Route $name is not defined"); - } - - unset($this->_routes[$name]); - - return $this; - } - - /** - * Remove all standard default routes - * - * @return Zend_Controller_Router_Rewrite - */ - public function removeDefaultRoutes() - { - $this->_useDefaultRoutes = false; - - return $this; - } - - /** - * Check if named route exists - * - * @param string $name Name of the route - * @return boolean - */ - public function hasRoute($name) - { - return isset($this->_routes[$name]); - } - - /** - * Retrieve a named route - * - * @param string $name Name of the route - * @throws Zend_Controller_Router_Exception - * @return Zend_Controller_Router_Route_Interface Route object - */ - public function getRoute($name) - { - if (!isset($this->_routes[$name])) { - #require_once 'Zend/Controller/Router/Exception.php'; - throw new Zend_Controller_Router_Exception("Route $name is not defined"); - } - - return $this->_routes[$name]; - } - - /** - * Retrieve a currently matched route - * - * @throws Zend_Controller_Router_Exception - * @return Zend_Controller_Router_Route_Interface Route object - */ - public function getCurrentRoute() - { - if (!isset($this->_currentRoute)) { - #require_once 'Zend/Controller/Router/Exception.php'; - throw new Zend_Controller_Router_Exception("Current route is not defined"); - } - - return $this->getRoute($this->_currentRoute); - } - - /** - * Retrieve a name of currently matched route - * - * @throws Zend_Controller_Router_Exception - * @return string Route name - */ - public function getCurrentRouteName() - { - if (!isset($this->_currentRoute)) { - #require_once 'Zend/Controller/Router/Exception.php'; - throw new Zend_Controller_Router_Exception("Current route is not defined"); - } - - return $this->_currentRoute; - } - - /** - * Retrieve an array of routes added to the route chain - * - * @return array All of the defined routes - */ - public function getRoutes() - { - return $this->_routes; - } - - /** - * Find a matching route to the current PATH_INFO and inject - * returning values to the Request object. - * - * @param Zend_Controller_Request_Abstract $request - * @throws Zend_Controller_Router_Exception - * @return Zend_Controller_Request_Abstract Request object - */ - public function route(Zend_Controller_Request_Abstract $request) - { - if (!$request instanceof Zend_Controller_Request_Http) { - #require_once 'Zend/Controller/Router/Exception.php'; - throw new Zend_Controller_Router_Exception( - 'Zend_Controller_Router_Rewrite requires a Zend_Controller_Request_Http-based request object' - ); - } - - if ($this->_useDefaultRoutes) { - $this->addDefaultRoutes(); - } - - // Find the matching route - $routeMatched = false; - - foreach (array_reverse($this->_routes, true) as $name => $route) { - // TODO: Should be an interface method. Hack for 1.0 BC - if (method_exists($route, 'isAbstract') && $route->isAbstract()) { - continue; - } - - // TODO: Should be an interface method. Hack for 1.0 BC - if (!method_exists($route, 'getVersion') || $route->getVersion() == 1) { - $match = $request->getPathInfo(); - } else { - $match = $request; - } - - if ($params = $route->match($match)) { - $this->_setRequestParams($request, $params); - $this->_currentRoute = $name; - $routeMatched = true; - break; - } - } - - if (!$routeMatched) { - #require_once 'Zend/Controller/Router/Exception.php'; - throw new Zend_Controller_Router_Exception('No route matched the request', 404); - } - - if ($this->_useCurrentParamsAsGlobal) { - $params = $request->getParams(); - foreach ($params as $param => $value) { - $this->setGlobalParam($param, $value); - } - } - - return $request; - } - - /** - * Sets parameters for request object - * - * Module name, controller name and action name - * - * @param Zend_Controller_Request_Abstract $request - * @param array $params - */ - protected function _setRequestParams($request, $params) - { - foreach ($params as $param => $value) { - - $request->setParam($param, $value); - - if ($param === $request->getModuleKey()) { - $request->setModuleName($value); - } - if ($param === $request->getControllerKey()) { - $request->setControllerName($value); - } - if ($param === $request->getActionKey()) { - $request->setActionName($value); - } - } - } - - /** - * Generates a URL path that can be used in URL creation, redirection, etc. - * - * @param array $userParams Options passed by a user used to override parameters - * @param mixed $name The name of a Route to use - * @param bool $reset Whether to reset to the route defaults ignoring URL params - * @param bool $encode Tells to encode URL parts on output - * @throws Zend_Controller_Router_Exception - * @return string Resulting absolute URL path - */ - public function assemble($userParams, $name = null, $reset = false, $encode = true) - { - if (!is_array($userParams)) { - #require_once 'Zend/Controller/Router/Exception.php'; - throw new Zend_Controller_Router_Exception('userParams must be an array'); - } - - if ($name == null) { - try { - $name = $this->getCurrentRouteName(); - } catch (Zend_Controller_Router_Exception $e) { - $name = 'default'; - } - } - - // Use UNION (+) in order to preserve numeric keys - $params = $userParams + $this->_globalParams; - - $route = $this->getRoute($name); - $url = $route->assemble($params, $reset, $encode); - - if (!preg_match('|^[a-z]+://|', $url)) { - $url = rtrim($this->getFrontController()->getBaseUrl(), self::URI_DELIMITER) . self::URI_DELIMITER . $url; - } - - return $url; - } - - /** - * Set a global parameter - * - * @param string $name - * @param mixed $value - * @return Zend_Controller_Router_Rewrite - */ - public function setGlobalParam($name, $value) - { - $this->_globalParams[$name] = $value; - - return $this; - } - - /** - * Set the separator to use with chain names - * - * @param string $separator The separator to use - * @return Zend_Controller_Router_Rewrite - */ - public function setChainNameSeparator($separator) - { - $this->_chainNameSeparator = $separator; - - return $this; - } - - /** - * Get the separator to use for chain names - * - * @return string - */ - public function getChainNameSeparator() - { - return $this->_chainNameSeparator; - } - - /** - * Determines/returns whether to use the request parameters as global parameters. - * - * @param boolean|null $use - * Null/unset when you want to retrieve the current state. - * True when request parameters should be global, false otherwise - * @return boolean|Zend_Controller_Router_Rewrite - * Returns a boolean if first param isn't set, returns an - * instance of Zend_Controller_Router_Rewrite otherwise. - * - */ - public function useRequestParametersAsGlobal($use = null) - { - if ($use === null) { - return $this->_useCurrentParamsAsGlobal; - } - - $this->_useCurrentParamsAsGlobal = (bool)$use; - - return $this; - } -} diff --git a/library/Zend/Controller/Router/Route.php b/library/Zend/Controller/Router/Route.php deleted file mode 100644 index 2eda8af42f..0000000000 --- a/library/Zend/Controller/Router/Route.php +++ /dev/null @@ -1,602 +0,0 @@ -reqs instanceof Zend_Config) ? $config->reqs->toArray() : array(); - $defs = ($config->defaults instanceof Zend_Config) ? $config->defaults->toArray() : array(); - - return new self($config->route, $defs, $reqs); - } - - /** - * Prepares the route for mapping by splitting (exploding) it - * to a corresponding atomic parts. These parts are assigned - * a position which is later used for matching and preparing values. - * - * @param string $route Map used to match with later submitted URL path - * @param array $defaults Defaults for map variables with keys as variable names - * @param array $reqs Regular expression requirements for variables (keys as variable names) - * @param Zend_Translate $translator Translator to use for this instance - * @param mixed|null $locale - */ - public function __construct( - $route, $defaults = array(), $reqs = array(), Zend_Translate $translator = null, $locale = null - ) - { - $route = trim($route, $this->_urlDelimiter); - $this->_defaults = (array)$defaults; - $this->_requirements = (array)$reqs; - $this->_translator = $translator; - $this->_locale = $locale; - - if ($route !== '') { - foreach (explode($this->_urlDelimiter, $route) as $pos => $part) { - if (substr($part, 0, 1) == $this->_urlVariable && substr($part, 1, 1) != $this->_urlVariable) { - $name = substr($part, 1); - - if (substr($name, 0, 1) === '@' && substr($name, 1, 1) !== '@') { - $name = substr($name, 1); - $this->_translatable[] = $name; - $this->_isTranslated = true; - } - - $this->_parts[$pos] = (isset($reqs[$name]) ? $reqs[$name] : $this->_defaultRegex); - $this->_variables[$pos] = $name; - } else { - if (substr($part, 0, 1) == $this->_urlVariable) { - $part = substr($part, 1); - } - - if (substr($part, 0, 1) === '@' && substr($part, 1, 1) !== '@') { - $this->_isTranslated = true; - } - - $this->_parts[$pos] = $part; - - if ($part !== '*') { - $this->_staticCount++; - } - } - } - } - } - - /** - * Matches a user submitted path with parts defined by a map. Assigns and - * returns an array of variables on a successful match. - * - * @param string $path Path used to match against this routing map - * @param boolean $partial - * @throws Zend_Controller_Router_Exception - * @return array|false An array of assigned values or a false on a mismatch - */ - public function match($path, $partial = false) - { - if ($this->_isTranslated) { - $translateMessages = $this->getTranslator()->getMessages(); - } - - $pathStaticCount = 0; - $values = array(); - $matchedPath = ''; - - if (!$partial) { - $path = trim($path, $this->_urlDelimiter); - } - - if ($path !== '') { - $path = explode($this->_urlDelimiter, $path); - - foreach ($path as $pos => $pathPart) { - // Path is longer than a route, it's not a match - if (!array_key_exists($pos, $this->_parts)) { - if ($partial) { - break; - } else { - return false; - } - } - - $matchedPath .= $pathPart . $this->_urlDelimiter; - - // If it's a wildcard, get the rest of URL as wildcard data and stop matching - if ($this->_parts[$pos] == '*') { - $count = count($path); - for ($i = $pos; $i < $count; $i += 2) { - $var = urldecode($path[$i]); - if (!isset($this->_wildcardData[$var]) && !isset($this->_defaults[$var]) - && !isset($values[$var]) - ) { - $this->_wildcardData[$var] = (isset($path[$i + 1])) ? urldecode($path[$i + 1]) : null; - } - } - - $matchedPath = implode($this->_urlDelimiter, $path); - break; - } - - $name = isset($this->_variables[$pos]) ? $this->_variables[$pos] : null; - $pathPart = urldecode($pathPart); - - // Translate value if required - $part = $this->_parts[$pos]; - if ($this->_isTranslated - && (substr($part, 0, 1) === '@' && substr($part, 1, 1) !== '@' - && $name === null) - || $name !== null && in_array($name, $this->_translatable) - ) { - if (substr($part, 0, 1) === '@') { - $part = substr($part, 1); - } - - if (($originalPathPart = array_search($pathPart, $translateMessages)) !== false) { - $pathPart = $originalPathPart; - } - } - - if (substr($part, 0, 2) === '@@') { - $part = substr($part, 1); - } - - // If it's a static part, match directly - if ($name === null && $part != $pathPart) { - return false; - } - - // If it's a variable with requirement, match a regex. If not - everything matches - if ($part !== null - && !preg_match( - $this->_regexDelimiter . '^' . $part . '$' . $this->_regexDelimiter . 'iu', $pathPart - ) - ) { - return false; - } - - // If it's a variable store it's value for later - if ($name !== null) { - $values[$name] = $pathPart; - } else { - $pathStaticCount++; - } - } - } - - // Check if all static mappings have been matched - if ($this->_staticCount != $pathStaticCount) { - return false; - } - - $return = $values + $this->_wildcardData + $this->_defaults; - - // Check if all map variables have been initialized - foreach ($this->_variables as $var) { - if (!array_key_exists($var, $return)) { - return false; - } - } - - $this->setMatchedPath(rtrim($matchedPath, $this->_urlDelimiter)); - - $this->_values = $values; - - return $return; - } - - /** - * Assembles user submitted parameters forming a URL path defined by this route - * - * @param array $data An array of variable and value pairs used as parameters - * @param boolean $reset Whether or not to set route defaults with those provided in $data - * @param boolean $encode - * @param boolean $partial - * @throws Zend_Controller_Router_Exception - * @return string Route path with user submitted parameters - */ - public function assemble($data = array(), $reset = false, $encode = false, $partial = false) - { - if ($this->_isTranslated) { - $translator = $this->getTranslator(); - - if (isset($data['@locale'])) { - $locale = $data['@locale']; - unset($data['@locale']); - } else { - $locale = $this->getLocale(); - } - } - - $url = array(); - $flag = false; - - foreach ($this->_parts as $key => $part) { - $name = isset($this->_variables[$key]) ? $this->_variables[$key] : null; - - $useDefault = false; - if (isset($name) && array_key_exists($name, $data) && $data[$name] === null) { - $useDefault = true; - } - - if (isset($name)) { - if (isset($data[$name]) && !$useDefault) { - $value = $data[$name]; - unset($data[$name]); - } elseif (!$reset && !$useDefault && isset($this->_values[$name])) { - $value = $this->_values[$name]; - } elseif (!$reset && !$useDefault && isset($this->_wildcardData[$name])) { - $value = $this->_wildcardData[$name]; - } elseif (array_key_exists($name, $this->_defaults)) { - $value = $this->_defaults[$name]; - } else { - #require_once 'Zend/Controller/Router/Exception.php'; - throw new Zend_Controller_Router_Exception($name . ' is not specified'); - } - - if ($this->_isTranslated && in_array($name, $this->_translatable)) { - $url[$key] = $translator->translate($value, $locale); - } else { - $url[$key] = $value; - } - } elseif ($part != '*') { - if ($this->_isTranslated && substr($part, 0, 1) === '@') { - if (substr($part, 1, 1) !== '@') { - $url[$key] = $translator->translate(substr($part, 1), $locale); - } else { - $url[$key] = substr($part, 1); - } - } else { - if (substr($part, 0, 2) === '@@') { - $part = substr($part, 1); - } - - $url[$key] = $part; - } - } else { - if (!$reset) { - $data += $this->_wildcardData; - } - $defaults = $this->getDefaults(); - foreach ($data as $var => $value) { - if ($value !== null && (!isset($defaults[$var]) || $value != $defaults[$var])) { - $url[$key++] = $var; - $url[$key++] = $value; - $flag = true; - } - } - } - } - - $return = ''; - - foreach (array_reverse($url, true) as $key => $value) { - $defaultValue = null; - - if (isset($this->_variables[$key])) { - $defaultValue = $this->getDefault($this->_variables[$key]); - - if ($this->_isTranslated && $defaultValue !== null - && isset($this->_translatable[$this->_variables[$key]]) - ) { - $defaultValue = $translator->translate($defaultValue, $locale); - } - } - - if ($flag || $value !== $defaultValue || $partial) { - if ($encode) { - $value = urlencode($value); - } - $return = $this->_urlDelimiter . $value . $return; - $flag = true; - } - } - - return trim($return, $this->_urlDelimiter); - } - - /** - * Return a single parameter of route's defaults - * - * @param string $name Array key of the parameter - * @return string Previously set default - */ - public function getDefault($name) - { - if (isset($this->_defaults[$name])) { - return $this->_defaults[$name]; - } - - return null; - } - - /** - * Return an array of defaults - * - * @return array Route defaults - */ - public function getDefaults() - { - return $this->_defaults; - } - - /** - * Get all variables which are used by the route - * - * @return array - */ - public function getVariables() - { - return $this->_variables; - } - - /** - * Set a default translator - * - * @param Zend_Translate $translator - * @return void - */ - public static function setDefaultTranslator(Zend_Translate $translator = null) - { - self::$_defaultTranslator = $translator; - } - - /** - * Get the default translator - * - * @return Zend_Translate - */ - public static function getDefaultTranslator() - { - return self::$_defaultTranslator; - } - - /** - * Set a translator - * - * @param Zend_Translate $translator - * @return void - */ - public function setTranslator(Zend_Translate $translator) - { - $this->_translator = $translator; - } - - /** - * Get the translator - * - * @throws Zend_Controller_Router_Exception When no translator can be found - * @return Zend_Translate - */ - public function getTranslator() - { - if ($this->_translator !== null) { - return $this->_translator; - } else { - if (($translator = self::getDefaultTranslator()) !== null) { - return $translator; - } else { - try { - $translator = Zend_Registry::get('Zend_Translate'); - } catch (Zend_Exception $e) { - $translator = null; - } - - if ($translator instanceof Zend_Translate) { - return $translator; - } - } - } - - #require_once 'Zend/Controller/Router/Exception.php'; - throw new Zend_Controller_Router_Exception('Could not find a translator'); - } - - /** - * Set a default locale - * - * @param mixed $locale - * @return void - */ - public static function setDefaultLocale($locale = null) - { - self::$_defaultLocale = $locale; - } - - /** - * Get the default locale - * - * @return mixed - */ - public static function getDefaultLocale() - { - return self::$_defaultLocale; - } - - /** - * Set a locale - * - * @param mixed $locale - * @return void - */ - public function setLocale($locale) - { - $this->_locale = $locale; - } - - /** - * Get the locale - * - * @return mixed - */ - public function getLocale() - { - if ($this->_locale !== null) { - return $this->_locale; - } else { - if (($locale = self::getDefaultLocale()) !== null) { - return $locale; - } else { - try { - $locale = Zend_Registry::get('Zend_Locale'); - } catch (Zend_Exception $e) { - $locale = null; - } - - if ($locale !== null) { - return $locale; - } - } - } - - return null; - } -} diff --git a/library/Zend/Controller/Router/Route/Abstract.php b/library/Zend/Controller/Router/Route/Abstract.php deleted file mode 100644 index b549c0a1de..0000000000 --- a/library/Zend/Controller/Router/Route/Abstract.php +++ /dev/null @@ -1,121 +0,0 @@ -_matchedPath = $path; - } - - /** - * Get partially matched path - * - * @return string - */ - public function getMatchedPath() - { - return $this->_matchedPath; - } - - /** - * Check or set wether this is an abstract route or not - * - * @param boolean $flag - * @return boolean - */ - public function isAbstract($flag = null) - { - if ($flag !== null) { - $this->_isAbstract = $flag; - } - - return $this->_isAbstract; - } - - /** - * Create a new chain - * - * @param Zend_Controller_Router_Route_Abstract $route - * @param string $separator - * @return Zend_Controller_Router_Route_Chain - */ - public function chain(Zend_Controller_Router_Route_Abstract $route, $separator = '/') - { - #require_once 'Zend/Controller/Router/Route/Chain.php'; - - $chain = new Zend_Controller_Router_Route_Chain(); - $chain->chain($this)->chain($route, $separator); - - return $chain; - } -} diff --git a/library/Zend/Controller/Router/Route/Chain.php b/library/Zend/Controller/Router/Route/Chain.php deleted file mode 100644 index 19bf9f6065..0000000000 --- a/library/Zend/Controller/Router/Route/Chain.php +++ /dev/null @@ -1,229 +0,0 @@ -defaults instanceof Zend_Config) ? $config->defaults->toArray() : array(); - - return new self($config->route, $defs); - } - - /** - * Add a route to this chain - * - * @param Zend_Controller_Router_Route_Abstract $route - * @param string $separator - * @return Zend_Controller_Router_Route_Chain - */ - public function chain(Zend_Controller_Router_Route_Abstract $route, $separator = self::URI_DELIMITER) - { - $this->_routes[] = $route; - $this->_separators[] = $separator; - - return $this; - } - - /** - * Matches a user submitted path with a previously defined route. - * Assigns and returns an array of defaults on a successful match. - * - * @param Zend_Controller_Request_Http $request Request to get the path info from - * @param null $partial - * @return array|false An array of assigned values or a false on a mismatch - */ - public function match($request, $partial = null) - { - $rawPath = $request->getPathInfo(); - $path = trim($request->getPathInfo(), self::URI_DELIMITER); - $subPath = $path; - $values = array(); - $matchedPath = null; - - foreach ($this->_routes as $key => $route) { - if ($key > 0 - && $matchedPath !== null - && $subPath !== '' - && $subPath !== false - ) { - $separator = substr($subPath, 0, strlen($this->_separators[$key])); - - if ($separator !== $this->_separators[$key]) { - $request->setPathInfo($rawPath); - return false; - } - - $subPath = substr($subPath, strlen($separator)); - } - // TODO: Should be an interface method. Hack for 1.0 BC - if (!method_exists($route, 'getVersion') || $route->getVersion() == 1) { - $match = $subPath; - } else { - $request->setPathInfo($subPath); - $match = $request; - } - - $res = $route->match($match, true); - - if ($res === false) { - $request->setPathInfo($rawPath); - return false; - } - - $matchedPath = $route->getMatchedPath(); - - if ($matchedPath !== null) { - $subPath = substr($subPath, strlen($matchedPath)); - } - - $values = $res + $values; - } - - $request->setPathInfo($path); - - if ($subPath !== '' && $subPath !== false) { - return false; - } - - return $values; - } - - /** - * Assembles a URL path defined by this route - * - * @param array $data An array of variable and value pairs used as parameters - * @param bool $reset - * @param bool $encode - * @return string Route path with user submitted parameters - */ - public function assemble($data = array(), $reset = false, $encode = false) - { - $value = ''; - $numRoutes = count($this->_routes); - - foreach ($this->_routes as $key => $route) { - if ($key > 0) { - $value .= $this->_separators[$key]; - } - - $value .= $route->assemble($data, $reset, $encode, (($numRoutes - 1) > $key)); - - if (method_exists($route, 'getVariables')) { - $variables = $route->getVariables(); - - foreach ($variables as $variable) { - $data[$variable] = null; - } - } - } - - return $value; - } - - /** - * Set the request object for this and the child routes - * - * @param Zend_Controller_Request_Abstract|null $request - * @return void - */ - public function setRequest(Zend_Controller_Request_Abstract $request = null) - { - $this->_request = $request; - - foreach ($this->_routes as $route) { - if (method_exists($route, 'setRequest')) { - $route->setRequest($request); - } - } - } - - /** - * Return a single parameter of route's defaults - * - * @param string $name Array key of the parameter - * @return string Previously set default - */ - public function getDefault($name) - { - $default = null; - foreach ($this->_routes as $route) { - if (method_exists($route, 'getDefault')) { - $current = $route->getDefault($name); - if (null !== $current) { - $default = $current; - } - } - } - - return $default; - } - - /** - * Return an array of defaults - * - * @return array Route defaults - */ - public function getDefaults() - { - $defaults = array(); - foreach ($this->_routes as $route) { - if (method_exists($route, 'getDefaults')) { - $defaults = array_merge($defaults, $route->getDefaults()); - } - } - - return $defaults; - } -} diff --git a/library/Zend/Controller/Router/Route/Hostname.php b/library/Zend/Controller/Router/Route/Hostname.php deleted file mode 100644 index 214d19f3eb..0000000000 --- a/library/Zend/Controller/Router/Route/Hostname.php +++ /dev/null @@ -1,380 +0,0 @@ -_request = $request; - } - - /** - * Get the request object - * - * @return Zend_Controller_Request_Abstract $request - */ - public function getRequest() - { - if ($this->_request === null) { - #require_once 'Zend/Controller/Front.php'; - $this->_request = Zend_Controller_Front::getInstance()->getRequest(); - } - - return $this->_request; - } - - /** - * Instantiates route based on passed Zend_Config structure - * - * @param Zend_Config $config Configuration object - * @return Zend_Controller_Router_Route_Hostname - */ - public static function getInstance(Zend_Config $config) - { - $reqs = ($config->reqs instanceof Zend_Config) ? $config->reqs->toArray() : array(); - $defs = ($config->defaults instanceof Zend_Config) ? $config->defaults->toArray() : array(); - $scheme = (isset($config->scheme)) ? $config->scheme : null; - - return new self($config->route, $defs, $reqs, $scheme); - } - - /** - * Prepares the route for mapping by splitting (exploding) it - * to a corresponding atomic parts. These parts are assigned - * a position which is later used for matching and preparing values. - * - * @param string $route Map used to match with later submitted hostname - * @param array $defaults Defaults for map variables with keys as variable names - * @param array $reqs Regular expression requirements for variables (keys as variable names) - * @param string $scheme - */ - public function __construct($route, $defaults = array(), $reqs = array(), $scheme = null) - { - $route = trim($route, '.'); - $this->_defaults = (array) $defaults; - $this->_requirements = (array) $reqs; - $this->_scheme = $scheme; - - if ($route != '') { - foreach (explode('.', $route) as $pos => $part) { - if (substr($part, 0, 1) == $this->_hostVariable) { - $name = substr($part, 1); - $this->_parts[$pos] = (isset($reqs[$name]) ? $reqs[$name] : $this->_defaultRegex); - $this->_variables[$pos] = $name; - } else { - $this->_parts[$pos] = $part; - $this->_staticCount++; - } - } - } - } - - /** - * Matches a user submitted path with parts defined by a map. Assigns and - * returns an array of variables on a successful match. - * - * @param Zend_Controller_Request_Http $request Request to get the host from - * @return array|false An array of assigned values or a false on a mismatch - */ - public function match($request) - { - // Check the scheme if required - if ($this->_scheme !== null) { - $scheme = $request->getScheme(); - - if ($scheme !== $this->_scheme) { - return false; - } - } - - // Get the host and remove unnecessary port information - $host = $request->getHttpHost(); - if (preg_match('#:\d+$#', $host, $result) === 1) { - $host = substr($host, 0, -strlen($result[0])); - } - - $hostStaticCount = 0; - $values = array(); - - $host = trim($host, '.'); - - if ($host != '') { - $host = explode('.', $host); - - foreach ($host as $pos => $hostPart) { - // Host is longer than a route, it's not a match - if (!array_key_exists($pos, $this->_parts)) { - return false; - } - - $name = isset($this->_variables[$pos]) ? $this->_variables[$pos] : null; - $hostPart = urldecode($hostPart); - - // If it's a static part, match directly - if ($name === null && $this->_parts[$pos] != $hostPart) { - return false; - } - - // If it's a variable with requirement, match a regex. If not - everything matches - if ($this->_parts[$pos] !== null - && !preg_match( - $this->_regexDelimiter . '^' . $this->_parts[$pos] . '$' . $this->_regexDelimiter . 'iu', - $hostPart - ) - ) { - return false; - } - - // If it's a variable store it's value for later - if ($name !== null) { - $values[$name] = $hostPart; - } else { - $hostStaticCount++; - } - } - } - - // Check if all static mappings have been matched - if ($this->_staticCount != $hostStaticCount) { - return false; - } - - $return = $values + $this->_defaults; - - // Check if all map variables have been initialized - foreach ($this->_variables as $var) { - if (!array_key_exists($var, $return)) { - return false; - } - } - - $this->_values = $values; - - return $return; - } - - /** - * Assembles user submitted parameters forming a hostname defined by this route - * - * @param array $data An array of variable and value pairs used as parameters - * @param boolean $reset Whether or not to set route defaults with those provided in $data - * @param boolean $encode - * @param boolean $partial - * @throws Zend_Controller_Router_Exception - * @return string Route path with user submitted parameters - */ - public function assemble($data = array(), $reset = false, $encode = false, $partial = false) - { - $host = array(); - $flag = false; - - foreach ($this->_parts as $key => $part) { - $name = isset($this->_variables[$key]) ? $this->_variables[$key] : null; - - $useDefault = false; - if (isset($name) && array_key_exists($name, $data) && $data[$name] === null) { - $useDefault = true; - } - - if (isset($name)) { - if (isset($data[$name]) && !$useDefault) { - $host[$key] = $data[$name]; - unset($data[$name]); - } elseif (!$reset && !$useDefault && isset($this->_values[$name])) { - $host[$key] = $this->_values[$name]; - } elseif (isset($this->_defaults[$name])) { - $host[$key] = $this->_defaults[$name]; - } else { - #require_once 'Zend/Controller/Router/Exception.php'; - throw new Zend_Controller_Router_Exception($name . ' is not specified'); - } - } else { - $host[$key] = $part; - } - } - - $return = ''; - - foreach (array_reverse($host, true) as $key => $value) { - if ($flag || !isset($this->_variables[$key]) || $value !== $this->getDefault($this->_variables[$key]) - || $partial - ) { - if ($encode) { - $value = urlencode($value); - } - $return = '.' . $value . $return; - $flag = true; - } - } - - $url = trim($return, '.'); - - if ($this->_scheme !== null) { - $scheme = $this->_scheme; - } else { - $request = $this->getRequest(); - if ($request instanceof Zend_Controller_Request_Http) { - $scheme = $request->getScheme(); - } else { - $scheme = 'http'; - } - } - - $url = $scheme . '://' . $url; - - return $url; - } - - /** - * Return a single parameter of route's defaults - * - * @param string $name Array key of the parameter - * @return string Previously set default - */ - public function getDefault($name) - { - if (isset($this->_defaults[$name])) { - return $this->_defaults[$name]; - } - - return null; - } - - /** - * Return an array of defaults - * - * @return array Route defaults - */ - public function getDefaults() - { - return $this->_defaults; - } - - /** - * Get all variables which are used by the route - * - * @return array - */ - public function getVariables() - { - return $this->_variables; - } -} diff --git a/library/Zend/Controller/Router/Route/Interface.php b/library/Zend/Controller/Router/Route/Interface.php deleted file mode 100644 index 5fcfa269de..0000000000 --- a/library/Zend/Controller/Router/Route/Interface.php +++ /dev/null @@ -1,39 +0,0 @@ -defaults instanceof Zend_Config) ? $config->defaults->toArray() : array(); - $dispatcher = $frontController->getDispatcher(); - $request = $frontController->getRequest(); - - return new self($defs, $dispatcher, $request); - } - - /** - * Constructor - * - * @param array $defaults Defaults for map variables with keys as variable names - * @param Zend_Controller_Dispatcher_Interface $dispatcher Dispatcher object - * @param Zend_Controller_Request_Abstract $request Request object - */ - public function __construct( - array $defaults = array(), - Zend_Controller_Dispatcher_Interface $dispatcher = null, - Zend_Controller_Request_Abstract $request = null - ) - { - $this->_defaults = $defaults; - - if (isset($request)) { - $this->_request = $request; - } - - if (isset($dispatcher)) { - $this->_dispatcher = $dispatcher; - } - } - - /** - * Set request keys based on values in request object - * - * @return void - */ - protected function _setRequestKeys() - { - if (null !== $this->_request) { - $this->_moduleKey = $this->_request->getModuleKey(); - $this->_controllerKey = $this->_request->getControllerKey(); - $this->_actionKey = $this->_request->getActionKey(); - } - - if (null !== $this->_dispatcher) { - $this->_defaults += array( - $this->_controllerKey => $this->_dispatcher->getDefaultControllerName(), - $this->_actionKey => $this->_dispatcher->getDefaultAction(), - $this->_moduleKey => $this->_dispatcher->getDefaultModule() - ); - } - - $this->_keysSet = true; - } - - /** - * Matches a user submitted path. Assigns and returns an array of variables - * on a successful match. - * - * If a request object is registered, it uses its setModuleName(), - * setControllerName(), and setActionName() accessors to set those values. - * Always returns the values as an array. - * - * @param string $path Path used to match against this routing map - * @param boolean $partial - * @return array An array of assigned values or a false on a mismatch - */ - public function match($path, $partial = false) - { - $this->_setRequestKeys(); - - $values = array(); - $params = array(); - - if (!$partial) { - $path = trim($path, self::URI_DELIMITER); - } else { - $matchedPath = $path; - } - - if ($path != '') { - $path = explode(self::URI_DELIMITER, $path); - - if ($this->_dispatcher && $this->_dispatcher->isValidModule($path[0])) { - $values[$this->_moduleKey] = array_shift($path); - $this->_moduleValid = true; - } - - if (count($path) && !empty($path[0])) { - $values[$this->_controllerKey] = array_shift($path); - } - - if (count($path) && !empty($path[0])) { - $values[$this->_actionKey] = array_shift($path); - } - - if ($numSegs = count($path)) { - for ($i = 0; $i < $numSegs; $i = $i + 2) { - $key = urldecode($path[$i]); - $val = isset($path[$i + 1]) ? urldecode($path[$i + 1]) : null; - $params[$key] = (isset($params[$key]) ? (array_merge((array)$params[$key], array($val))) : $val); - } - } - } - - if ($partial) { - $this->setMatchedPath($matchedPath); - } - - $this->_values = $values + $params; - - return $this->_values + $this->_defaults; - } - - /** - * Assembles user submitted parameters forming a URL path defined by this route - * - * @param array $data An array of variable and value pairs used as parameters - * @param boolean $reset Weither to reset the current params - * @param boolean $encode - * @param boolean $partial - * @return string Route path with user submitted parameters - */ - public function assemble($data = array(), $reset = false, $encode = true, $partial = false) - { - if (!$this->_keysSet) { - $this->_setRequestKeys(); - } - - $params = (!$reset) ? $this->_values : array(); - - foreach ($data as $key => $value) { - if ($value !== null) { - $params[$key] = $value; - } elseif (isset($params[$key])) { - unset($params[$key]); - } - } - - $params += $this->_defaults; - - $url = ''; - - if ($this->_moduleValid || array_key_exists($this->_moduleKey, $data)) { - if ($params[$this->_moduleKey] != $this->_defaults[$this->_moduleKey]) { - $module = $params[$this->_moduleKey]; - } - } - unset($params[$this->_moduleKey]); - - $controller = $params[$this->_controllerKey]; - unset($params[$this->_controllerKey]); - - $action = $params[$this->_actionKey]; - unset($params[$this->_actionKey]); - - foreach ($params as $key => $value) { - $key = ($encode) ? urlencode($key) : $key; - if (is_array($value)) { - foreach ($value as $arrayValue) { - $arrayValue = ($encode) ? urlencode($arrayValue) : $arrayValue; - $url .= self::URI_DELIMITER . $key; - $url .= self::URI_DELIMITER . $arrayValue; - } - } else { - if ($encode) { - $value = urlencode($value); - } - $url .= self::URI_DELIMITER . $key; - $url .= self::URI_DELIMITER . $value; - } - } - - if (!empty($url) || $action !== $this->_defaults[$this->_actionKey]) { - if ($encode) { - $action = urlencode($action); - } - $url = self::URI_DELIMITER . $action . $url; - } - - if (!empty($url) || $controller !== $this->_defaults[$this->_controllerKey]) { - if ($encode) { - $controller = urlencode($controller); - } - $url = self::URI_DELIMITER . $controller . $url; - } - - if (isset($module)) { - if ($encode) { - $module = urlencode($module); - } - $url = self::URI_DELIMITER . $module . $url; - } - - return ltrim($url, self::URI_DELIMITER); - } - - /** - * Return a single parameter of route's defaults - * - * @param string $name Array key of the parameter - * @return string Previously set default - */ - public function getDefault($name) - { - if (isset($this->_defaults[$name])) { - return $this->_defaults[$name]; - } - } - - /** - * Return an array of defaults - * - * @return array Route defaults - */ - public function getDefaults() - { - return $this->_defaults; - } -} diff --git a/library/Zend/Controller/Router/Route/Regex.php b/library/Zend/Controller/Router/Route/Regex.php deleted file mode 100644 index e328c7260b..0000000000 --- a/library/Zend/Controller/Router/Route/Regex.php +++ /dev/null @@ -1,319 +0,0 @@ -defaults instanceof Zend_Config) ? $config->defaults->toArray() : array(); - $map = ($config->map instanceof Zend_Config) ? $config->map->toArray() : array(); - $reverse = (isset($config->reverse)) ? $config->reverse : null; - - return new self($config->route, $defs, $map, $reverse); - } - - /** - * Constructor - * - * @param $route - * @param array $defaults - * @param array $map - * @param null $reverse - */ - public function __construct($route, $defaults = array(), $map = array(), $reverse = null) - { - $this->_regex = $route; - $this->_defaults = (array) $defaults; - $this->_map = (array) $map; - $this->_reverse = $reverse; - } - - /** - * Get the version of the route - * - * @return int - */ - public function getVersion() - { - return 1; - } - - /** - * Matches a user submitted path with a previously defined route. - * Assigns and returns an array of defaults on a successful match. - * - * @param string $path Path used to match against this routing map - * @return array|false An array of assigned values or a false on a mismatch - */ - public function match($path, $partial = false) - { - if (!$partial) { - $path = trim(urldecode($path), self::URI_DELIMITER); - $regex = '#^' . $this->_regex . '$#i'; - } else { - $regex = '#^' . $this->_regex . '#i'; - } - - $res = preg_match($regex, $path, $values); - - if ($res === 0) { - return false; - } - - if ($partial) { - $this->setMatchedPath($values[0]); - } - - // array_filter_key()? Why isn't this in a standard PHP function set yet? :) - foreach ($values as $i => $value) { - if (!is_int($i) || $i === 0) { - unset($values[$i]); - } - } - - $this->_values = $values; - - $values = $this->_getMappedValues($values); - $defaults = $this->_getMappedValues($this->_defaults, false, true); - $return = $values + $defaults; - - return $return; - } - - /** - * Maps numerically indexed array values to it's associative mapped counterpart. - * Or vice versa. Uses user provided map array which consists of index => name - * parameter mapping. If map is not found, it returns original array. - * - * Method strips destination type of keys form source array. Ie. if source array is - * indexed numerically then every associative key will be stripped. Vice versa if reversed - * is set to true. - * - * @param array $values Indexed or associative array of values to map - * @param boolean $reversed False means translation of index to association. True means reverse. - * @param boolean $preserve Should wrong type of keys be preserved or stripped. - * @return array An array of mapped values - */ - protected function _getMappedValues($values, $reversed = false, $preserve = false) - { - if (count($this->_map) == 0) { - return $values; - } - - $return = array(); - - foreach ($values as $key => $value) { - if (is_int($key) && !$reversed) { - if (array_key_exists($key, $this->_map)) { - $index = $this->_map[$key]; - } elseif (false === ($index = array_search($key, $this->_map))) { - $index = $key; - } - $return[$index] = $values[$key]; - } elseif ($reversed) { - $index = $key; - if (!is_int($key)) { - if (array_key_exists($key, $this->_map)) { - $index = $this->_map[$key]; - } else { - $index = array_search($key, $this->_map, true); - } - } - if (false !== $index) { - $return[$index] = $values[$key]; - } - } elseif ($preserve) { - $return[$key] = $value; - } - } - - return $return; - } - - /** - * Assembles a URL path defined by this route - * - * @param array $data An array of name (or index) and value pairs used as parameters - * @param boolean $reset - * @param boolean $encode - * @param boolean $partial - * @throws Zend_Controller_Router_Exception - * @return string Route path with user submitted parameters - */ - public function assemble($data = array(), $reset = false, $encode = false, $partial = false) - { - if ($this->_reverse === null) { - #require_once 'Zend/Controller/Router/Exception.php'; - throw new Zend_Controller_Router_Exception('Cannot assemble. Reversed route is not specified.'); - } - - $defaultValuesMapped = $this->_getMappedValues($this->_defaults, true, false); - $matchedValuesMapped = $this->_getMappedValues($this->_values, true, false); - $dataValuesMapped = $this->_getMappedValues($data, true, false); - - // handle resets, if so requested (By null value) to do so - if (($resetKeys = array_search(null, $dataValuesMapped, true)) !== false) { - foreach ((array)$resetKeys as $resetKey) { - if (isset($matchedValuesMapped[$resetKey])) { - unset($matchedValuesMapped[$resetKey]); - unset($dataValuesMapped[$resetKey]); - } - } - } - - // merge all the data together, first defaults, then values matched, then supplied - $mergedData = $defaultValuesMapped; - $mergedData = $this->_arrayMergeNumericKeys($mergedData, $matchedValuesMapped); - $mergedData = $this->_arrayMergeNumericKeys($mergedData, $dataValuesMapped); - - if ($encode) { - foreach ($mergedData as $key => &$value) { - $value = urlencode($value); - } - } - - ksort($mergedData); - - $return = @vsprintf($this->_reverse, $mergedData); - - if ($return === false) { - #require_once 'Zend/Controller/Router/Exception.php'; - throw new Zend_Controller_Router_Exception('Cannot assemble. Too few arguments?'); - } - - return $return; - } - - /** - * Return a single parameter of route's defaults - * - * @param string $name Array key of the parameter - * @return string Previously set default - */ - public function getDefault($name) - { - if (isset($this->_defaults[$name])) { - return $this->_defaults[$name]; - } - } - - /** - * Return an array of defaults - * - * @return array Route defaults - */ - public function getDefaults() - { - return $this->_defaults; - } - - /** - * Get all variables which are used by the route - * - * @return array - */ - public function getVariables() - { - $variables = array(); - - foreach ($this->_map as $key => $value) { - if (is_numeric($key)) { - $variables[] = $value; - } else { - $variables[] = $key; - } - } - - return $variables; - } - - /** - * _arrayMergeNumericKeys() - allows for a strict key (numeric's included) array_merge. - * php's array_merge() lacks the ability to merge with numeric keys. - * - * @param array $array1 - * @param array $array2 - * @return array - */ - protected function _arrayMergeNumericKeys(Array $array1, Array $array2) - { - $returnArray = $array1; - foreach ($array2 as $array2Index => $array2Value) { - $returnArray[$array2Index] = $array2Value; - } - - return $returnArray; - } -} diff --git a/library/Zend/Controller/Router/Route/Static.php b/library/Zend/Controller/Router/Route/Static.php deleted file mode 100644 index a544cceba3..0000000000 --- a/library/Zend/Controller/Router/Route/Static.php +++ /dev/null @@ -1,149 +0,0 @@ -defaults instanceof Zend_Config) ? $config->defaults->toArray() : array(); - - return new self($config->route, $defs); - } - - /** - * Prepares the route for mapping. - * - * @param string $route Map used to match with later submitted URL path - * @param array $defaults Defaults for map variables with keys as variable names - */ - public function __construct($route, $defaults = array()) - { - $this->_route = trim($route, self::URI_DELIMITER); - $this->_defaults = (array) $defaults; - } - - /** - * Matches a user submitted path with a previously defined route. - * Assigns and returns an array of defaults on a successful match. - * - * @param string $path Path used to match against this routing map - * @return array|false An array of assigned values or a false on a mismatch - */ - public function match($path, $partial = false) - { - if ($partial) { - if ((empty($path) && empty($this->_route)) - || (substr($path, 0, strlen($this->_route)) === $this->_route) - ) { - $this->setMatchedPath($this->_route); - - return $this->_defaults; - } - } else { - if (trim($path, self::URI_DELIMITER) == $this->_route) { - return $this->_defaults; - } - } - - return false; - } - - /** - * Assembles a URL path defined by this route - * - * @param array $data An array of variable and value pairs used as parameters - * @return string Route path with user submitted parameters - */ - public function assemble($data = array(), $reset = false, $encode = false, $partial = false) - { - return $this->_route; - } - - /** - * Return a single parameter of route's defaults - * - * @param string $name Array key of the parameter - * @return string Previously set default - */ - public function getDefault($name) - { - if (isset($this->_defaults[$name])) { - return $this->_defaults[$name]; - } - - return null; - } - - /** - * Return an array of defaults - * - * @return array Route defaults - */ - public function getDefaults() - { - return $this->_defaults; - } -} diff --git a/library/Zend/Dojo.php b/library/Zend/Dojo.php deleted file mode 100644 index 6035a65f33..0000000000 --- a/library/Zend/Dojo.php +++ /dev/null @@ -1,87 +0,0 @@ -addPrefixPath('Zend_Dojo_Form_Decorator', 'Zend/Dojo/Form/Decorator', 'decorator') - ->addPrefixPath('Zend_Dojo_Form_Element', 'Zend/Dojo/Form/Element', 'element') - ->addElementPrefixPath('Zend_Dojo_Form_Decorator', 'Zend/Dojo/Form/Decorator', 'decorator') - ->addDisplayGroupPrefixPath('Zend_Dojo_Form_Decorator', 'Zend/Dojo/Form/Decorator') - ->setDefaultDisplayGroupClass('Zend_Dojo_Form_DisplayGroup'); - - foreach ($form->getSubForms() as $subForm) { - self::enableForm($subForm); - } - - if (null !== ($view = $form->getView())) { - self::enableView($view); - } - } - - /** - * Dojo-enable a view instance - * - * @param Zend_View_Interface $view - * @return void - */ - public static function enableView(Zend_View_Interface $view) - { - if (false === $view->getPluginLoader('helper')->getPaths('Zend_Dojo_View_Helper')) { - $view->addHelperPath('Zend/Dojo/View/Helper', 'Zend_Dojo_View_Helper'); - } - } -} - diff --git a/library/Zend/Dojo/BuildLayer.php b/library/Zend/Dojo/BuildLayer.php deleted file mode 100644 index 8d3d08f737..0000000000 --- a/library/Zend/Dojo/BuildLayer.php +++ /dev/null @@ -1,536 +0,0 @@ - 'release', - 'optimize' => 'shrinksafe', - 'layerOptimize' => 'shrinksafe', - 'copyTests' => false, - 'loader' => 'default', - 'cssOptimize' => 'comments', - ); - - /** - * Associative array of module/path pairs for the build profile - * @var array - */ - protected $_profilePrefixes = array(); - - /** - * Zend_View reference - * @var Zend_View_Interface - */ - protected $_view; - - /** - * Constructor - * - * @param array|Zend_Config $options - * @return void - * @throws Zend_Dojo_Exception for invalid option argument - */ - public function __construct($options = null) - { - if (null !== $options) { - if ($options instanceof Zend_Config) { - $options = $options->toArray(); - } elseif (!is_array($options)) { - #require_once 'Zend/Dojo/Exception.php'; - throw new Zend_Dojo_Exception('Invalid options provided to constructor'); - } - $this->setOptions($options); - } - } - - /** - * Set options - * - * Proxies to any setter that matches an option key. - * - * @param array $options - * @return Zend_Dojo_BuildLayer - */ - public function setOptions(array $options) - { - $methods = get_class_methods($this); - foreach ($options as $key => $value) { - $method = 'set' . ucfirst($key); - if (in_array($method, $methods)) { - $this->$method($value); - } - } - return $this; - } - - /** - * Set View object - * - * @param Zend_View_Interface $view - * @return Zend_Dojo_BuildLayer - */ - public function setView(Zend_View_Interface $view) - { - $this->_view = $view; - return $this; - } - - /** - * Retrieve view object - * - * @return Zend_View_Interface|null - */ - public function getView() - { - return $this->_view; - } - - /** - * Set dojo() view helper instance - * - * @param Zend_Dojo_View_Helper_Dojo_Container $helper - * @return Zend_Dojo_BuildLayer - */ - public function setDojoHelper(Zend_Dojo_View_Helper_Dojo_Container $helper) - { - $this->_dojo = $helper; - return $this; - } - - /** - * Retrieve dojo() view helper instance - * - * Will retrieve it from the view object if not registered. - * - * @return Zend_Dojo_View_Helper_Dojo_Container - * @throws Zend_Dojo_Exception if not registered and no view object found - */ - public function getDojoHelper() - { - if (null === $this->_dojo) { - if (null === ($view = $this->getView())) { - #require_once 'Zend/Dojo/Exception.php'; - throw new Zend_Dojo_Exception('View object not registered; cannot retrieve dojo helper'); - } - $helper = $view->getHelper('dojo'); - $this->setDojoHelper($view->dojo()); - } - return $this->_dojo; - } - - /** - * Set custom layer name; e.g. "custom.main" - * - * @param string $name - * @return Zend_Dojo_BuildLayer - */ - public function setLayerName($name) - { - if (!preg_match('/^[a-z][a-z0-9_]*(\.[a-z][a-z0-9_]*)+$/i', $name)) { - #require_once 'Zend/Dojo/Exception.php'; - throw new Zend_Dojo_Exception('Invalid layer name provided; must be of form[a-z][a-z0-9_](\.[a-z][a-z0-9_])+'); - } - $this->_layerName = $name; - return $this; - } - - /** - * Retrieve custom layer name - * - * @return string|null - */ - public function getLayerName() - { - return $this->_layerName; - } - - /** - * Set the path to the custom layer script - * - * Should be a path relative to dojo.js - * - * @param string $path - * @return Zend_Dojo_BuildLayer - */ - public function setLayerScriptPath($path) - { - $this->_layerScriptPath = (string) $path; - return $this; - } - - /** - * Get custom layer script path - * - * @return string|null - */ - public function getLayerScriptPath() - { - return $this->_layerScriptPath; - } - - /** - * Set flag indicating whether or not to consume JS aggregated in dojo() - * view helper - * - * @param bool $flag - * @return Zend_Dojo_BuildLayer - */ - public function setConsumeJavascript($flag) - { - $this->_consumeJavascript = (bool) $flag; - return $this; - } - - /** - * Get flag indicating whether or not to consume JS aggregated in dojo() - * view helper - * - * @return bool - */ - public function consumeJavascript() - { - return $this->_consumeJavascript; - } - - /** - * Set flag indicating whether or not to consume dojo.addOnLoad events - * aggregated in dojo() view helper - * - * @param bool $flag - * @return Zend_Dojo_BuildLayer - */ - public function setConsumeOnLoad($flag) - { - $this->_consumeOnLoad = (bool) $flag; - return $this; - } - - /** - * Get flag indicating whether or not to consume dojo.addOnLoad events aggregated in dojo() view helper - * - * @return bool - */ - public function consumeOnLoad() - { - return $this->_consumeOnLoad; - } - - /** - * Set many build profile options at once - * - * @param array $options - * @return Zend_Dojo_BuildLayer - */ - public function setProfileOptions(array $options) - { - $this->_profileOptions += $options; - return $this; - } - - /** - * Add many build profile options at once - * - * @param array $options - * @return Zend_Dojo_BuildLayer - */ - public function addProfileOptions(array $options) - { - $this->_profileOptions = $this->_profileOptions + $options; - return $this; - } - - /** - * Add a single build profile option - * - * @param string $key - * @param value $value - * @return Zend_Dojo_BuildLayer - */ - public function addProfileOption($key, $value) - { - $this->_profileOptions[(string) $key] = $value; - return $this; - } - - /** - * Is a given build profile option set? - * - * @param string $key - * @return bool - */ - public function hasProfileOption($key) - { - return array_key_exists((string) $key, $this->_profileOptions); - } - - /** - * Retrieve a single build profile option - * - * Returns null if profile option does not exist. - * - * @param string $key - * @return mixed - */ - public function getProfileOption($key) - { - if ($this->hasProfileOption($key)) { - return $this->_profileOptions[(string) $key]; - } - return null; - } - - /** - * Get all build profile options - * - * @return array - */ - public function getProfileOptions() - { - return $this->_profileOptions; - } - - /** - * Remove a build profile option - * - * @param string $name - * @return Zend_Dojo_BuildLayer - */ - public function removeProfileOption($name) - { - if ($this->hasProfileOption($name)) { - unset($this->_profileOptions[(string) $name]); - } - return $this; - } - - /** - * Remove all build profile options - * - * @return Zend_Dojo_BuildLayer - */ - public function clearProfileOptions() - { - $this->_profileOptions = array(); - return $this; - } - - /** - * Add a build profile dependency prefix - * - * If just the prefix is passed, sets path to "../$prefix". - * - * @param string $prefix - * @param null|string $path - * @return Zend_Dojo_BuildLayer - */ - public function addProfilePrefix($prefix, $path = null) - { - if (null === $path) { - $path = '../' . $prefix; - } - $this->_profilePrefixes[$prefix] = array($prefix, $path); - return $this; - } - - /** - * Set multiple dependency prefixes for bulid profile - * - * @param array $prefixes - * @return Zend_Dojo_BuildLayer - */ - public function setProfilePrefixes(array $prefixes) - { - foreach ($prefixes as $prefix => $path) { - $this->addProfilePrefix($prefix, $path); - } - return $this; - } - - /** - * Get build profile dependency prefixes - * - * @return array - */ - public function getProfilePrefixes() - { - $layerName = $this->getLayerName(); - if (null !== $layerName) { - $prefix = $this->_getPrefix($layerName); - if (!array_key_exists($prefix, $this->_profilePrefixes)) { - $this->addProfilePrefix($prefix); - } - } - $view = $this->getView(); - if (!empty($view)) { - $helper = $this->getDojoHelper(); - if ($helper) { - $modules = $helper->getModules(); - foreach ($modules as $module) { - $prefix = $this->_getPrefix($module); - if (!array_key_exists($prefix, $this->_profilePrefixes)) { - $this->addProfilePrefix($prefix); - } - } - } - } - return $this->_profilePrefixes; - } - - /** - * Generate module layer script - * - * @return string - */ - public function generateLayerScript() - { - $helper = $this->getDojoHelper(); - $layerName = $this->getLayerName(); - $modulePaths = $helper->getModulePaths(); - $modules = $helper->getModules(); - $onLoadActions = $helper->getOnLoadActions(); - $javascript = $helper->getJavascript(); - - $content = 'dojo.provide("' . $layerName . '");' . "\n\n(function(){\n"; - - foreach ($modulePaths as $module => $path) { - $content .= sprintf("dojo.registerModulePath(\"%s\", \"%s\");\n", $module, $path); - } - foreach ($modules as $module) { - $content .= sprintf("dojo.require(\"%s\");\n", $module); - } - - if ($this->consumeOnLoad()) { - foreach ($helper->getOnLoadActions() as $callback) { - $content .= sprintf("dojo.addOnLoad(%s);\n", $callback); - } - } - if ($this->consumeJavascript()) { - $javascript = implode("\n", $helper->getJavascript()); - if (!empty($javascript)) { - $content .= "\n" . $javascript . "\n"; - } - } - - $content .= "})();"; - - return $content; - } - - /** - * Generate build profile - * - * @return string - */ - public function generateBuildProfile() - { - $profileOptions = $this->getProfileOptions(); - $layerName = $this->getLayerName(); - $layerScriptPath = $this->getLayerScriptPath(); - $profilePrefixes = $this->getProfilePrefixes(); - - if (!array_key_exists('releaseName', $profileOptions)) { - $profileOptions['releaseName'] = substr($layerName, 0, strpos($layerName, '.')); - } - - $profile = $profileOptions; - $profile['layers'] = array(array( - 'name' => $layerScriptPath, - 'layerDependencies' => array(), - 'dependencies' => array($layerName), - )); - $profile['prefixes'] = array_values($profilePrefixes); - - return 'dependencies = ' . $this->_filterJsonProfileToJavascript($profile) . ';'; - } - - /** - * Retrieve module prefix - * - * @param string $module - * @return void - */ - protected function _getPrefix($module) - { - $segments = explode('.', $module, 2); - return $segments[0]; - } - - /** - * Filter a JSON build profile to JavaScript - * - * @param string $profile - * @return string - */ - protected function _filterJsonProfileToJavascript($profile) - { - #require_once 'Zend/Json.php'; - $profile = Zend_Json::encode($profile); - $profile = trim($profile, '"'); - $profile = preg_replace('/' . preg_quote('\\') . '/', '', $profile); - return $profile; - } -} diff --git a/library/Zend/Dojo/Data.php b/library/Zend/Dojo/Data.php deleted file mode 100644 index d614d2e36a..0000000000 --- a/library/Zend/Dojo/Data.php +++ /dev/null @@ -1,563 +0,0 @@ -setIdentifier($identifier); - } - if (null !== $items) { - $this->setItems($items); - } - if (null !== $label) { - $this->setLabel($label); - } - } - - /** - * Set the items to collect - * - * @param array|Traversable $items - * @return Zend_Dojo_Data - */ - public function setItems($items) - { - $this->clearItems(); - return $this->addItems($items); - } - - /** - * Set an individual item, optionally by identifier (overwrites) - * - * @param array|object $item - * @param string|null $identifier - * @return Zend_Dojo_Data - */ - public function setItem($item, $id = null) - { - $item = $this->_normalizeItem($item, $id); - $this->_items[$item['id']] = $item['data']; - return $this; - } - - /** - * Add an individual item, optionally by identifier - * - * @param array|object $item - * @param string|null $id - * @return Zend_Dojo_Data - */ - public function addItem($item, $id = null) - { - $item = $this->_normalizeItem($item, $id); - - if ($this->hasItem($item['id'])) { - #require_once 'Zend/Dojo/Exception.php'; - throw new Zend_Dojo_Exception('Overwriting items using addItem() is not allowed'); - } - - $this->_items[$item['id']] = $item['data']; - - return $this; - } - - /** - * Add multiple items at once - * - * @param array|Traversable $items - * @return Zend_Dojo_Data - */ - public function addItems($items) - { - if (!is_array($items) && (!is_object($items) || !($items instanceof Traversable))) { - #require_once 'Zend/Dojo/Exception.php'; - throw new Zend_Dojo_Exception('Only arrays and Traversable objects may be added to ' . __CLASS__); - } - - foreach ($items as $item) { - $this->addItem($item); - } - - return $this; - } - - /** - * Get all items as an array - * - * Serializes items to arrays. - * - * @return array - */ - public function getItems() - { - return $this->_items; - } - - /** - * Does an item with the given identifier exist? - * - * @param string|int $id - * @return bool - */ - public function hasItem($id) - { - return array_key_exists($id, $this->_items); - } - - /** - * Retrieve an item by identifier - * - * Item retrieved will be flattened to an array. - * - * @param string $id - * @return array - */ - public function getItem($id) - { - if (!$this->hasItem($id)) { - return null; - } - - return $this->_items[$id]; - } - - /** - * Remove item by identifier - * - * @param string $id - * @return Zend_Dojo_Data - */ - public function removeItem($id) - { - if ($this->hasItem($id)) { - unset($this->_items[$id]); - } - - return $this; - } - - /** - * Remove all items at once - * - * @return Zend_Dojo_Data - */ - public function clearItems() - { - $this->_items = array(); - return $this; - } - - - /** - * Set identifier for item lookups - * - * @param string|int|null $identifier - * @return Zend_Dojo_Data - */ - public function setIdentifier($identifier) - { - if (null === $identifier) { - $this->_identifier = null; - } elseif (is_string($identifier)) { - $this->_identifier = $identifier; - } elseif (is_numeric($identifier)) { - $this->_identifier = (int) $identifier; - } else { - #require_once 'Zend/Dojo/Exception.php'; - throw new Zend_Dojo_Exception('Invalid identifier; please use a string or integer'); - } - - return $this; - } - - /** - * Retrieve current item identifier - * - * @return string|int|null - */ - public function getIdentifier() - { - return $this->_identifier; - } - - - /** - * Set label to use for displaying item associations - * - * @param string|null $label - * @return Zend_Dojo_Data - */ - public function setLabel($label) - { - if (null === $label) { - $this->_label = null; - } else { - $this->_label = (string) $label; - } - return $this; - } - - /** - * Retrieve item association label - * - * @return string|null - */ - public function getLabel() - { - return $this->_label; - } - - /** - * Set metadata by key or en masse - * - * @param string|array $spec - * @param mixed $value - * @return Zend_Dojo_Data - */ - public function setMetadata($spec, $value = null) - { - if (is_string($spec) && (null !== $value)) { - $this->_metadata[$spec] = $value; - } elseif (is_array($spec)) { - foreach ($spec as $key => $value) { - $this->setMetadata($key, $value); - } - } - return $this; - } - - /** - * Get metadata item or all metadata - * - * @param null|string $key Metadata key when pulling single metadata item - * @return mixed - */ - public function getMetadata($key = null) - { - if (null === $key) { - return $this->_metadata; - } - - if (array_key_exists($key, $this->_metadata)) { - return $this->_metadata[$key]; - } - - return null; - } - - /** - * Clear individual or all metadata item(s) - * - * @param null|string $key - * @return Zend_Dojo_Data - */ - public function clearMetadata($key = null) - { - if (null === $key) { - $this->_metadata = array(); - } elseif (array_key_exists($key, $this->_metadata)) { - unset($this->_metadata[$key]); - } - return $this; - } - - /** - * Load object from array - * - * @param array $data - * @return Zend_Dojo_Data - */ - public function fromArray(array $data) - { - if (array_key_exists('identifier', $data)) { - $this->setIdentifier($data['identifier']); - } - if (array_key_exists('label', $data)) { - $this->setLabel($data['label']); - } - if (array_key_exists('items', $data) && is_array($data['items'])) { - $this->setItems($data['items']); - } else { - $this->clearItems(); - } - return $this; - } - - /** - * Load object from JSON - * - * @param string $json - * @return Zend_Dojo_Data - */ - public function fromJson($json) - { - if (!is_string($json)) { - #require_once 'Zend/Dojo/Exception.php'; - throw new Zend_Dojo_Exception('fromJson() expects JSON input'); - } - #require_once 'Zend/Json.php'; - $data = Zend_Json::decode($json); - return $this->fromArray($data); - } - - /** - * Seralize entire data structure, including identifier and label, to array - * - * @return array - */ - public function toArray() - { - if (null === ($identifier = $this->getIdentifier())) { - #require_once 'Zend/Dojo/Exception.php'; - throw new Zend_Dojo_Exception('Serialization requires that an identifier be present in the object; first call setIdentifier()'); - } - - $array = array( - 'identifier' => $identifier, - 'items' => array_values($this->getItems()), - ); - - $metadata = $this->getMetadata(); - if (!empty($metadata)) { - foreach ($metadata as $key => $value) { - $array[$key] = $value; - } - } - - if (null !== ($label = $this->getLabel())) { - $array['label'] = $label; - } - - return $array; - } - - /** - * Serialize to JSON (dojo.data format) - * - * @return string - */ - public function toJson() - { - #require_once 'Zend/Json.php'; - return Zend_Json::encode($this->toArray()); - } - - /** - * Serialize to string (proxy to {@link toJson()}) - * - * @return string - */ - public function __toString() - { - return $this->toJson(); - } - - /** - * ArrayAccess: does offset exist? - * - * @param string|int $offset - * @return bool - */ - public function offsetExists($offset) - { - return (null !== $this->getItem($offset)); - } - - /** - * ArrayAccess: retrieve by offset - * - * @param string|int $offset - * @return array - */ - public function offsetGet($offset) - { - return $this->getItem($offset); - } - - /** - * ArrayAccess: set value by offset - * - * @param string $offset - * @param array|object|null $value - * @return void - */ - public function offsetSet($offset, $value) - { - $this->setItem($value, $offset); - } - - /** - * ArrayAccess: unset value by offset - * - * @param string $offset - * @return void - */ - public function offsetUnset($offset) - { - $this->removeItem($offset); - } - - /** - * Iterator: get current value - * - * @return array - */ - public function current() - { - return current($this->_items); - } - - /** - * Iterator: get current key - * - * @return string|int - */ - public function key() - { - return key($this->_items); - } - - /** - * Iterator: get next item - * - * @return void - */ - public function next() - { - return next($this->_items); - } - - /** - * Iterator: rewind to first value in collection - * - * @return void - */ - public function rewind() - { - return reset($this->_items); - } - - /** - * Iterator: is item valid? - * - * @return bool - */ - public function valid() - { - return (bool) $this->current(); - } - - /** - * Countable: how many items are present - * - * @return int - */ - public function count() - { - return count($this->_items); - } - - /** - * Normalize an item to attach to the collection - * - * @param array|object $item - * @param string|int|null $id - * @return array - */ - protected function _normalizeItem($item, $id) - { - if (null === ($identifier = $this->getIdentifier())) { - #require_once 'Zend/Dojo/Exception.php'; - throw new Zend_Dojo_Exception('You must set an identifier prior to adding items'); - } - - if (!is_object($item) && !is_array($item)) { - #require_once 'Zend/Dojo/Exception.php'; - throw new Zend_Dojo_Exception('Only arrays and objects may be attached'); - } - - if (is_object($item)) { - if (method_exists($item, 'toArray')) { - $item = $item->toArray(); - } else { - $item = get_object_vars($item); - } - } - - if ((null === $id) && !array_key_exists($identifier, $item)) { - #require_once 'Zend/Dojo/Exception.php'; - throw new Zend_Dojo_Exception('Item must contain a column matching the currently set identifier'); - } elseif (null === $id) { - $id = $item[$identifier]; - } else { - $item[$identifier] = $id; - } - - return array( - 'id' => $id, - 'data' => $item, - ); - } -} diff --git a/library/Zend/Dojo/Exception.php b/library/Zend/Dojo/Exception.php deleted file mode 100644 index ffdf377156..0000000000 --- a/library/Zend/Dojo/Exception.php +++ /dev/null @@ -1,35 +0,0 @@ -addPrefixPath('Zend_Dojo_Form_Decorator', 'Zend/Dojo/Form/Decorator', 'decorator') - ->addPrefixPath('Zend_Dojo_Form_Element', 'Zend/Dojo/Form/Element', 'element') - ->addElementPrefixPath('Zend_Dojo_Form_Decorator', 'Zend/Dojo/Form/Decorator', 'decorator') - ->addDisplayGroupPrefixPath('Zend_Dojo_Form_Decorator', 'Zend/Dojo/Form/Decorator') - ->setDefaultDisplayGroupClass('Zend_Dojo_Form_DisplayGroup'); - parent::__construct($options); - } - - /** - * Load the default decorators - * - * @return void - */ - public function loadDefaultDecorators() - { - if ($this->loadDefaultDecoratorsIsDisabled()) { - return; - } - - $decorators = $this->getDecorators(); - if (empty($decorators)) { - $this->addDecorator('FormElements') - ->addDecorator('HtmlTag', array('tag' => 'dl', 'class' => 'zend_form_dojo')) - ->addDecorator('DijitForm'); - } - } - - /** - * Set the view object - * - * Ensures that the view object has the dojo view helper path set. - * - * @param Zend_View_Interface $view - * @return Zend_Dojo_Form_Element_Dijit - */ - public function setView(Zend_View_Interface $view = null) - { - if (null !== $view) { - if (false === $view->getPluginLoader('helper')->getPaths('Zend_Dojo_View_Helper')) { - $view->addHelperPath('Zend/Dojo/View/Helper', 'Zend_Dojo_View_Helper'); - } - } - return parent::setView($view); - } -} diff --git a/library/Zend/Dojo/Form/Decorator/AccordionContainer.php b/library/Zend/Dojo/Form/Decorator/AccordionContainer.php deleted file mode 100644 index d247841af2..0000000000 --- a/library/Zend/Dojo/Form/Decorator/AccordionContainer.php +++ /dev/null @@ -1,43 +0,0 @@ -_helper) { - #require_once 'Zend/Form/Decorator/Exception.php'; - throw new Zend_Form_Decorator_Exception('No view helper specified fo DijitContainer decorator'); - } - return $this->_helper; - } - - /** - * Get element attributes - * - * @return array - */ - public function getAttribs() - { - if (null === $this->_attribs) { - $attribs = $this->getElement()->getAttribs(); - if (array_key_exists('dijitParams', $attribs)) { - unset($attribs['dijitParams']); - } - $this->_attribs = $attribs; - } - return $this->_attribs; - } - - /** - * Get dijit option parameters - * - * @return array - */ - public function getDijitParams() - { - if (null === $this->_dijitParams) { - $attribs = $this->getElement()->getAttribs(); - if (array_key_exists('dijitParams', $attribs)) { - $this->_dijitParams = $attribs['dijitParams']; - } else { - $this->_dijitParams = array(); - } - - $options = $this->getOptions(); - if (array_key_exists('dijitParams', $options)) { - $this->_dijitParams = array_merge($this->_dijitParams, $options['dijitParams']); - $this->removeOption('dijitParams'); - } - } - - // Ensure we have a title param - if (!array_key_exists('title', $this->_dijitParams)) { - $this->_dijitParams['title'] = $this->getTitle(); - } - - return $this->_dijitParams; - } - - /** - * Get title - * - * @return string - */ - public function getTitle() - { - if (null === $this->_title) { - $title = null; - if (null !== ($element = $this->getElement())) { - if (method_exists($element, 'getLegend')) { - $title = $element->getLegend(); - } - } - if (empty($title) && (null !== ($title = $this->getOption('legend')))) { - $this->removeOption('legend'); - } - if (empty($title) && (null !== ($title = $this->getOption('title')))) { - $this->removeOption('title'); - } - - if (!empty($title)) { - if (null !== ($translator = $element->getTranslator())) { - $title = $translator->translate($title); - } - $this->_title = $title; - } - } - - return (empty($this->_title) ? '' : $this->_title); - } - - /** - * Render a dijit layout container - * - * Replaces $content entirely from currently set element. - * - * @param string $content - * @return string - */ - public function render($content) - { - $element = $this->getElement(); - $view = $element->getView(); - if (null === $view) { - return $content; - } - - $dijitParams = $this->getDijitParams(); - $attribs = array_merge($this->getAttribs(), $this->getOptions()); - - if (array_key_exists('legend', $attribs)) { - if (!array_key_exists('title', $dijitParams) || empty($dijitParams['title'])) { - $dijitParams['title'] = $attribs['legend']; - } - unset($attribs['legend']); - } - - $helper = $this->getHelper(); - $id = $element->getId() . '-' . $helper; - - if ($view->dojo()->hasDijit($id)) { - trigger_error(sprintf('Duplicate dijit ID detected for id "%s; temporarily generating uniqid"', $id), E_USER_WARNING); - $base = $id; - do { - $id = $base . '-' . uniqid(); - } while ($view->dojo()->hasDijit($id)); - } - - return $view->$helper($id, $content, $dijitParams, $attribs); - } -} diff --git a/library/Zend/Dojo/Form/Decorator/DijitElement.php b/library/Zend/Dojo/Form/Decorator/DijitElement.php deleted file mode 100644 index a4c67b53f3..0000000000 --- a/library/Zend/Dojo/Form/Decorator/DijitElement.php +++ /dev/null @@ -1,193 +0,0 @@ -_attribs) { - $this->_attribs = parent::getElementAttribs(); - if (array_key_exists('dijitParams', $this->_attribs)) { - $this->setDijitParams($this->_attribs['dijitParams']); - unset($this->_attribs['dijitParams']); - } - } - - return $this->_attribs; - } - - /** - * Set a single dijit option parameter - * - * @param string $key - * @param mixed $value - * @return Zend_Dojo_Form_Decorator_DijitContainer - */ - public function setDijitParam($key, $value) - { - $this->_dijitParams[(string) $key] = $value; - return $this; - } - - /** - * Set dijit option parameters - * - * @param array $params - * @return Zend_Dojo_Form_Decorator_DijitContainer - */ - public function setDijitParams(array $params) - { - $this->_dijitParams = array_merge($this->_dijitParams, $params); - return $this; - } - - /** - * Retrieve a single dijit option parameter - * - * @param string $key - * @return mixed|null - */ - public function getDijitParam($key) - { - $this->getElementAttribs(); - $key = (string) $key; - if (array_key_exists($key, $this->_dijitParams)) { - return $this->_dijitParams[$key]; - } - - return null; - } - - /** - * Get dijit option parameters - * - * @return array - */ - public function getDijitParams() - { - $this->getElementAttribs(); - return $this->_dijitParams; - } - - /** - * Render an element using a view helper - * - * Determine view helper from 'helper' option, or, if none set, from - * the element type. Then call as - * helper($element->getName(), $element->getValue(), $element->getAttribs()) - * - * @param string $content - * @return string - * @throws Zend_Form_Decorator_Exception if element or view are not registered - */ - public function render($content) - { - $element = $this->getElement(); - $view = $element->getView(); - if (null === $view) { - #require_once 'Zend/Form/Decorator/Exception.php'; - throw new Zend_Form_Decorator_Exception('DijitElement decorator cannot render without a registered view object'); - } - - $options = null; - $helper = $this->getHelper(); - $separator = $this->getSeparator(); - $value = $this->getValue($element); - $attribs = $this->getElementAttribs(); - $name = $element->getFullyQualifiedName(); - - $dijitParams = $this->getDijitParams(); - $dijitParams['required'] = $element->isRequired(); - - $id = $element->getId(); - if ($view->dojo()->hasDijit($id)) { - trigger_error(sprintf('Duplicate dijit ID detected for id "%s; temporarily generating uniqid"', $id), E_USER_NOTICE); - $base = $id; - do { - $id = $base . '-' . uniqid(); - } while ($view->dojo()->hasDijit($id)); - } - $attribs['id'] = $id; - - if (array_key_exists('options', $attribs)) { - $options = $attribs['options']; - } - - $elementContent = $view->$helper($name, $value, $dijitParams, $attribs, $options); - switch ($this->getPlacement()) { - case self::APPEND: - return $content . $separator . $elementContent; - case self::PREPEND: - return $elementContent . $separator . $content; - default: - return $elementContent; - } - } -} diff --git a/library/Zend/Dojo/Form/Decorator/DijitForm.php b/library/Zend/Dojo/Form/Decorator/DijitForm.php deleted file mode 100644 index 19ecfdcce9..0000000000 --- a/library/Zend/Dojo/Form/Decorator/DijitForm.php +++ /dev/null @@ -1,66 +0,0 @@ -getElement(); - $view = $element->getView(); - if (null === $view) { - return $content; - } - - $dijitParams = $this->getDijitParams(); - $attribs = array_merge($this->getAttribs(), $this->getOptions()); - - // Enforce id attribute of form for dojo events - if (!isset($attribs['name']) || !$attribs['name']) { - $element->setName(get_class($element) . '_' . uniqid()); - } - - return $view->form($element->getName(), $attribs, $content); - } -} diff --git a/library/Zend/Dojo/Form/Decorator/SplitContainer.php b/library/Zend/Dojo/Form/Decorator/SplitContainer.php deleted file mode 100644 index 7d51ac81d5..0000000000 --- a/library/Zend/Dojo/Form/Decorator/SplitContainer.php +++ /dev/null @@ -1,43 +0,0 @@ -addPrefixPath('Zend_Dojo_Form_Decorator', 'Zend/Dojo/Form/Decorator'); - } - - /** - * Set the view object - * - * Ensures that the view object has the dojo view helper path set. - * - * @param Zend_View_Interface $view - * @return Zend_Dojo_Form_Element_Dijit - */ - public function setView(Zend_View_Interface $view = null) - { - if (null !== $view) { - if (false === $view->getPluginLoader('helper')->getPaths('Zend_Dojo_View_Helper')) { - $view->addHelperPath('Zend/Dojo/View/Helper', 'Zend_Dojo_View_Helper'); - } - } - return parent::setView($view); - } -} diff --git a/library/Zend/Dojo/Form/Element/Button.php b/library/Zend/Dojo/Form/Element/Button.php deleted file mode 100644 index c1864ebb6d..0000000000 --- a/library/Zend/Dojo/Form/Element/Button.php +++ /dev/null @@ -1,121 +0,0 @@ - $options); - } - - parent::__construct($spec, $options); - } - - /** - * Return label - * - * If no label is present, returns the currently set name. - * - * If a translator is present, returns the translated label. - * - * @return string - */ - public function getLabel() - { - $value = parent::getLabel(); - - if (null === $value) { - $value = $this->getName(); - } - - if (null !== ($translator = $this->getTranslator())) { - return $translator->translate($value); - } - - return $value; - } - - /** - * Has this submit button been selected? - * - * @return bool - */ - public function isChecked() - { - $value = $this->getValue(); - - if (empty($value)) { - return false; - } - if ($value != $this->getLabel()) { - return false; - } - - return true; - } - - /** - * Default decorators - * - * Uses only 'DijitElement' and 'DtDdWrapper' decorators by default. - * - * @return void - */ - public function loadDefaultDecorators() - { - if ($this->loadDefaultDecoratorsIsDisabled()) { - return; - } - - $decorators = $this->getDecorators(); - if (empty($decorators)) { - $this->addDecorator('DijitElement') - ->addDecorator('DtDdWrapper'); - } - } -} diff --git a/library/Zend/Dojo/Form/Element/CheckBox.php b/library/Zend/Dojo/Form/Element/CheckBox.php deleted file mode 100644 index 14278bab25..0000000000 --- a/library/Zend/Dojo/Form/Element/CheckBox.php +++ /dev/null @@ -1,206 +0,0 @@ - '1', - 'uncheckedValue' => '0', - ); - - /** - * Value when checked - * @var string - */ - protected $_checkedValue = '1'; - - /** - * Value when not checked - * @var string - */ - protected $_uncheckedValue = '0'; - - /** - * Current value - * @var string 0 or 1 - */ - protected $_value = '0'; - - /** - * Set options - * - * Intercept checked and unchecked values and set them early; test stored - * value against checked and unchecked values after configuration. - * - * @param array $options - * @return Zend_Form_Element_Checkbox - */ - public function setOptions(array $options) - { - if (array_key_exists('checkedValue', $options)) { - $this->setCheckedValue($options['checkedValue']); - unset($options['checkedValue']); - } - if (array_key_exists('uncheckedValue', $options)) { - $this->setUncheckedValue($options['uncheckedValue']); - unset($options['uncheckedValue']); - } - parent::setOptions($options); - - $curValue = $this->getValue(); - $test = array($this->getCheckedValue(), $this->getUncheckedValue()); - if (!in_array($curValue, $test)) { - $this->setValue($curValue); - } - - return $this; - } - - /** - * Set value - * - * If value matches checked value, sets to that value, and sets the checked - * flag to true. - * - * Any other value causes the unchecked value to be set as the current - * value, and the checked flag to be set as false. - * - * - * @param mixed $value - * @return Zend_Form_Element_Checkbox - */ - public function setValue($value) - { - if ($value == $this->getCheckedValue()) { - parent::setValue($value); - $this->checked = true; - } else { - parent::setValue($this->getUncheckedValue()); - $this->checked = false; - } - return $this; - } - - /** - * Set checked value - * - * @param string $value - * @return Zend_Form_Element_Checkbox - */ - public function setCheckedValue($value) - { - $this->_checkedValue = (string) $value; - $this->options['checkedValue'] = $value; - return $this; - } - - /** - * Get value when checked - * - * @return string - */ - public function getCheckedValue() - { - return $this->_checkedValue; - } - - /** - * Set unchecked value - * - * @param string $value - * @return Zend_Form_Element_Checkbox - */ - public function setUncheckedValue($value) - { - $this->_uncheckedValue = (string) $value; - $this->options['uncheckedValue'] = $value; - return $this; - } - - /** - * Get value when not checked - * - * @return string - */ - public function getUncheckedValue() - { - return $this->_uncheckedValue; - } - - /** - * Set checked flag - * - * @param bool $flag - * @return Zend_Form_Element_Checkbox - */ - public function setChecked($flag) - { - $this->checked = (bool) $flag; - if ($this->checked) { - $this->setValue($this->getCheckedValue()); - } else { - $this->setValue($this->getUncheckedValue()); - } - return $this; - } - - /** - * Get checked flag - * - * @return bool - */ - public function isChecked() - { - return $this->checked; - } -} - diff --git a/library/Zend/Dojo/Form/Element/ComboBox.php b/library/Zend/Dojo/Form/Element/ComboBox.php deleted file mode 100644 index 2e3bad4f8a..0000000000 --- a/library/Zend/Dojo/Form/Element/ComboBox.php +++ /dev/null @@ -1,186 +0,0 @@ -hasDijitParam('store')) { - $this->dijitParams['store'] = array(); - } - return $this->dijitParams['store']; - } - - /** - * Set datastore identifier - * - * @param string $identifier - * @return Zend_Dojo_Form_Element_ComboBox - */ - public function setStoreId($identifier) - { - $store = $this->getStoreInfo(); - $store['store'] = (string) $identifier; - $this->setDijitParam('store', $store); - return $this; - } - - /** - * Get datastore identifier - * - * @return string|null - */ - public function getStoreId() - { - $store = $this->getStoreInfo(); - if (array_key_exists('store', $store)) { - return $store['store']; - } - return null; - } - - /** - * Set datastore dijit type - * - * @param string $dojoType - * @return Zend_Dojo_Form_Element_ComboBox - */ - public function setStoreType($dojoType) - { - $store = $this->getStoreInfo(); - $store['type'] = (string) $dojoType; - $this->setDijitParam('store', $store); - return $this; - } - - /** - * Get datastore dijit type - * - * @return string|null - */ - public function getStoreType() - { - $store = $this->getStoreInfo(); - if (array_key_exists('type', $store)) { - return $store['type']; - } - return null; - } - - /** - * Set datastore parameters - * - * @param array $params - * @return Zend_Dojo_Form_Element_ComboBox - */ - public function setStoreParams(array $params) - { - $store = $this->getStoreInfo(); - $store['params'] = $params; - $this->setDijitParam('store', $store); - return $this; - } - - /** - * Get datastore params - * - * @return array - */ - public function getStoreParams() - { - $store = $this->getStoreInfo(); - if (array_key_exists('params', $store)) { - return $store['params']; - } - return array(); - } - - /** - * Set autocomplete flag - * - * @param bool $flag - * @return Zend_Dojo_Form_Element_ComboBox - */ - public function setAutocomplete($flag) - { - $this->setDijitParam('autocomplete', (bool) $flag); - return $this; - } - - /** - * Get autocomplete flag - * - * @return bool - */ - public function getAutocomplete() - { - if (!$this->hasDijitParam('autocomplete')) { - return false; - } - return $this->getDijitParam('autocomplete'); - } - - /** - * Is the value valid? - * - * @param string $value - * @param mixed $context - * @return bool - */ - public function isValid($value, $context = null) - { - $storeInfo = $this->getStoreInfo(); - if (!empty($storeInfo)) { - $this->setRegisterInArrayValidator(false); - } - return parent::isValid($value, $context); - } -} diff --git a/library/Zend/Dojo/Form/Element/CurrencyTextBox.php b/library/Zend/Dojo/Form/Element/CurrencyTextBox.php deleted file mode 100644 index 97e48b8cb6..0000000000 --- a/library/Zend/Dojo/Form/Element/CurrencyTextBox.php +++ /dev/null @@ -1,120 +0,0 @@ -setDijitParam('currency', (string) $currency); - return $this; - } - - /** - * Retrieve currency - * - * @return string|null - */ - public function getCurrency() - { - return $this->getDijitParam('currency'); - } - - /** - * Set currency symbol - * - * Casts to string, uppercases, and trims to three characters. - * - * @param string $symbol - * @return Zend_Dojo_Form_Element_CurrencyTextBox - */ - public function setSymbol($symbol) - { - $symbol = strtoupper((string) $symbol); - $length = strlen($symbol); - if (3 > $length) { - #require_once 'Zend/Form/Element/Exception.php'; - throw new Zend_Form_Element_Exception('Invalid symbol provided; please provide ISO 4217 alphabetic currency code'); - } - if (3 < $length) { - $symbol = substr($symbol, 0, 3); - } - - $this->setConstraint('symbol', $symbol); - return $this; - } - - /** - * Retrieve symbol - * - * @return string|null - */ - public function getSymbol() - { - return $this->getConstraint('symbol'); - } - - /** - * Set whether currency is fractional - * - * @param bool $flag - * @return Zend_Dojo_Form_Element_CurrencyTextBox - */ - public function setFractional($flag) - { - $this->setConstraint('fractional', (bool) $flag); - return $this; - } - - /** - * Get whether or not to present fractional values - * - * @return bool - */ - public function getFractional() - { - return ('true' == $this->getConstraint('fractional')); - } -} diff --git a/library/Zend/Dojo/Form/Element/DateTextBox.php b/library/Zend/Dojo/Form/Element/DateTextBox.php deleted file mode 100644 index 1e4f572fb0..0000000000 --- a/library/Zend/Dojo/Form/Element/DateTextBox.php +++ /dev/null @@ -1,214 +0,0 @@ -setConstraint('am,pm', (bool) $flag); - return $this; - } - - /** - * Retrieve am,pm flag - * - * @return bool - */ - public function getAmPm() - { - if (!$this->hasConstraint('am,pm')) { - return false; - } - return ('true' ==$this->getConstraint('am,pm')); - } - - /** - * Set strict flag - * - * @param bool $strict - * @return Zend_Dojo_Form_Element_DateTextBox - */ - public function setStrict($flag) - { - $this->setConstraint('strict', (bool) $flag); - return $this; - } - - /** - * Retrieve strict flag - * - * @return bool - */ - public function getStrict() - { - if (!$this->hasConstraint('strict')) { - return false; - } - return ('true' == $this->getConstraint('strict')); - } - - /** - * Set locale - * - * @param string $locale - * @return Zend_Dojo_Form_Element_DateTextBox - */ - public function setLocale($locale) - { - $this->setConstraint('locale', (string) $locale); - return $this; - } - - /** - * Retrieve locale - * - * @return string|null - */ - public function getLocale() - { - return $this->getConstraint('locale'); - } - - /** - * Set date format pattern - * - * @param string $pattern - * @return Zend_Dojo_Form_Element_NumberTextBox - */ - public function setDatePattern($pattern) - { - $this->setConstraint('datePattern', (string) $pattern); - return $this; - } - - /** - * Retrieve date format pattern - * - * @return string|null - */ - public function getDatePattern() - { - return $this->getConstraint('datePattern'); - } - - /** - * Set numeric format formatLength - * - * @see $_allowedFormatTypes - * @param string $formatLength - * @return Zend_Dojo_Form_Element_NumberTextBox - */ - public function setFormatLength($formatLength) - { - $formatLength = strtolower($formatLength); - if (!in_array($formatLength, $this->_allowedFormatTypes)) { - #require_once 'Zend/Form/Element/Exception.php'; - throw new Zend_Form_Element_Exception(sprintf('Invalid formatLength "%s" specified', $formatLength)); - } - - $this->setConstraint('formatLength', $formatLength); - return $this; - } - - /** - * Retrieve formatLength - * - * @return string|null - */ - public function getFormatLength() - { - return $this->getConstraint('formatLength'); - } - - /** - * Set numeric format Selector - * - * @see $_allowedSelectorTypes - * @param string $selector - * @return Zend_Dojo_Form_Element_NumberTextBox - */ - public function setSelector($selector) - { - $selector = strtolower($selector); - if (!in_array($selector, $this->_allowedSelectorTypes)) { - #require_once 'Zend/Form/Element/Exception.php'; - throw new Zend_Form_Element_Exception(sprintf('Invalid Selector "%s" specified', $selector)); - } - - $this->setConstraint('selector', $selector); - return $this; - } - - /** - * Retrieve selector - * - * @return string|null - */ - public function getSelector() - { - return $this->getConstraint('selector'); - } -} diff --git a/library/Zend/Dojo/Form/Element/Dijit.php b/library/Zend/Dojo/Form/Element/Dijit.php deleted file mode 100644 index 55be94429b..0000000000 --- a/library/Zend/Dojo/Form/Element/Dijit.php +++ /dev/null @@ -1,189 +0,0 @@ -addPrefixPath('Zend_Dojo_Form_Decorator', 'Zend/Dojo/Form/Decorator', 'decorator'); - parent::__construct($spec, $options); - } - - /** - * Set a dijit parameter - * - * @param string $key - * @param mixed $value - * @return Zend_Dojo_Form_Element_Dijit - */ - public function setDijitParam($key, $value) - { - $key = (string) $key; - $this->dijitParams[$key] = $value; - return $this; - } - - /** - * Set multiple dijit params at once - * - * @param array $params - * @return Zend_Dojo_Form_Element_Dijit - */ - public function setDijitParams(array $params) - { - $this->dijitParams = array_merge($this->dijitParams, $params); - return $this; - } - - /** - * Does the given dijit parameter exist? - * - * @param string $key - * @return bool - */ - public function hasDijitParam($key) - { - return array_key_exists($key, $this->dijitParams); - } - - /** - * Get a single dijit parameter - * - * @param string $key - * @return mixed - */ - public function getDijitParam($key) - { - $key = (string) $key; - if ($this->hasDijitParam($key)) { - return $this->dijitParams[$key]; - } - return null; - } - - /** - * Retrieve all dijit parameters - * - * @return array - */ - public function getDijitParams() - { - return $this->dijitParams; - } - - /** - * Remove a single dijit parameter - * - * @param string $key - * @return Zend_Dojo_Form_Element_Dijit - */ - public function removeDijitParam($key) - { - $key = (string) $key; - if (array_key_exists($key, $this->dijitParams)) { - unset($this->dijitParams[$key]); - } - return $this; - } - - /** - * Clear all dijit parameters - * - * @return Zend_Dojo_Form_Element_Dijit - */ - public function clearDijitParams() - { - $this->dijitParams = array(); - return $this; - } - - /** - * Load default decorators - * - * @return void - */ - public function loadDefaultDecorators() - { - if ($this->loadDefaultDecoratorsIsDisabled()) { - return; - } - - $decorators = $this->getDecorators(); - if (empty($decorators)) { - $this->addDecorator('DijitElement') - ->addDecorator('Errors') - ->addDecorator('Description', array('tag' => 'p', 'class' => 'description')) - ->addDecorator('HtmlTag', array('tag' => 'dd')) - ->addDecorator('Label', array('tag' => 'dt')); - } - } - - /** - * Set the view object - * - * Ensures that the view object has the dojo view helper path set. - * - * @param Zend_View_Interface $view - * @return Zend_Dojo_Form_Element_Dijit - */ - public function setView(Zend_View_Interface $view = null) - { - if (null !== $view) { - if (false === $view->getPluginLoader('helper')->getPaths('Zend_Dojo_View_Helper')) { - $view->addHelperPath('Zend/Dojo/View/Helper', 'Zend_Dojo_View_Helper'); - } - } - return parent::setView($view); - } -} diff --git a/library/Zend/Dojo/Form/Element/DijitMulti.php b/library/Zend/Dojo/Form/Element/DijitMulti.php deleted file mode 100644 index fb93d81436..0000000000 --- a/library/Zend/Dojo/Form/Element/DijitMulti.php +++ /dev/null @@ -1,303 +0,0 @@ -'. - * @var string - */ - protected $_separator = '
'; - - /** - * Which values are translated already? - * @var array - */ - protected $_translated = array(); - - /** - * Retrieve separator - * - * @return mixed - */ - public function getSeparator() - { - return $this->_separator; - } - - /** - * Set separator - * - * @param mixed $separator - * @return self - */ - public function setSeparator($separator) - { - $this->_separator = $separator; - return $this; - } - - /** - * Retrieve options array - * - * @return array - */ - protected function _getMultiOptions() - { - if (null === $this->options || !is_array($this->options)) { - $this->options = array(); - } - - return $this->options; - } - - /** - * Add an option - * - * @param string $option - * @param string $value - * @return Zend_Form_Element_Multi - */ - public function addMultiOption($option, $value = '') - { - $option = (string) $option; - $this->_getMultiOptions(); - if (!$this->_translateOption($option, $value)) { - $this->options[$option] = $value; - } - - return $this; - } - - /** - * Add many options at once - * - * @param array $options - * @return Zend_Form_Element_Multi - */ - public function addMultiOptions(array $options) - { - foreach ($options as $option => $value) { - if (is_array($value) - && array_key_exists('key', $value) - && array_key_exists('value', $value) - ) { - $this->addMultiOption($value['key'], $value['value']); - } else { - $this->addMultiOption($option, $value); - } - } - return $this; - } - - /** - * Set all options at once (overwrites) - * - * @param array $options - * @return Zend_Form_Element_Multi - */ - public function setMultiOptions(array $options) - { - $this->clearMultiOptions(); - return $this->addMultiOptions($options); - } - - /** - * Retrieve single multi option - * - * @param string $option - * @return mixed - */ - public function getMultiOption($option) - { - $option = (string) $option; - $this->_getMultiOptions(); - if (isset($this->options[$option])) { - $this->_translateOption($option, $this->options[$option]); - return $this->options[$option]; - } - - return null; - } - - /** - * Retrieve options - * - * @return array - */ - public function getMultiOptions() - { - $this->_getMultiOptions(); - foreach ($this->options as $option => $value) { - $this->_translateOption($option, $value); - } - return $this->options; - } - - /** - * Remove a single multi option - * - * @param string $option - * @return bool - */ - public function removeMultiOption($option) - { - $option = (string) $option; - $this->_getMultiOptions(); - if (isset($this->options[$option])) { - unset($this->options[$option]); - if (isset($this->_translated[$option])) { - unset($this->_translated[$option]); - } - return true; - } - - return false; - } - - /** - * Clear all options - * - * @return Zend_Form_Element_Multi - */ - public function clearMultiOptions() - { - $this->options = array(); - $this->_translated = array(); - return $this; - } - - /** - * Set flag indicating whether or not to auto-register inArray validator - * - * @param bool $flag - * @return Zend_Form_Element_Multi - */ - public function setRegisterInArrayValidator($flag) - { - $this->_registerInArrayValidator = (bool) $flag; - return $this; - } - - /** - * Get status of auto-register inArray validator flag - * - * @return bool - */ - public function registerInArrayValidator() - { - return $this->_registerInArrayValidator; - } - - /** - * Is the value provided valid? - * - * Autoregisters InArray validator if necessary. - * - * @param string $value - * @param mixed $context - * @return bool - */ - public function isValid($value, $context = null) - { - if ($this->registerInArrayValidator()) { - if (!$this->getValidator('InArray')) { - $options = $this->getMultiOptions(); - $this->addValidator( - 'InArray', - true, - array(array_keys($options)) - ); - } - } - return parent::isValid($value, $context); - } - - /** - * Translate an option - * - * @param string $option - * @param string $value - * @return bool - */ - protected function _translateOption($option, $value) - { - if (!isset($this->_translated[$option])) { - $this->options[$option] = $this->_translateValue($value); - if ($this->options[$option] === $value) { - return false; - } - $this->_translated[$option] = true; - return true; - } - - return false; - } - - /** - * Translate a value - * - * @param array|string $value - * @return array|string - */ - protected function _translateValue($value) - { - if (is_array($value)) { - foreach ($value as $key => $val) { - $value[$key] = $this->_translateValue($val); - } - return $value; - } else { - if (null !== ($translator = $this->getTranslator())) { - return $translator->translate($value); - } - - return $value; - } - } -} diff --git a/library/Zend/Dojo/Form/Element/Editor.php b/library/Zend/Dojo/Form/Element/Editor.php deleted file mode 100644 index b49834924a..0000000000 --- a/library/Zend/Dojo/Form/Element/Editor.php +++ /dev/null @@ -1,697 +0,0 @@ -getCaptureEvents(); - if (in_array($event, $captureEvents)) { - return $this; - } - - $captureEvents[] = (string) $event; - $this->setDijitParam('captureEvents', $captureEvents); - return $this; - } - - /** - * Add multiple capture events - * - * @param array $events - * @return Zend_Dojo_Form_Element_Editor - */ - public function addCaptureEvents(array $events) - { - foreach ($events as $event) { - $this->addCaptureEvent($event); - } - return $this; - } - - /** - * Overwrite many capture events at once - * - * @param array $events - * @return Zend_Dojo_Form_Element_Editor - */ - public function setCaptureEvents(array $events) - { - $this->clearCaptureEvents(); - $this->addCaptureEvents($events); - return $this; - } - - /** - * Get all capture events - * - * @return array - */ - public function getCaptureEvents() - { - if (!$this->hasDijitParam('captureEvents')) { - return array(); - } - return $this->getDijitParam('captureEvents'); - } - - /** - * Is a given capture event registered? - * - * @param string $event - * @return bool - */ - public function hasCaptureEvent($event) - { - $captureEvents = $this->getCaptureEvents(); - return in_array((string) $event, $captureEvents); - } - - /** - * Remove a given capture event - * - * @param string $event - * @return Zend_Dojo_Form_Element_Editor - */ - public function removeCaptureEvent($event) - { - $event = (string) $event; - $captureEvents = $this->getCaptureEvents(); - if (false === ($index = array_search($event, $captureEvents))) { - return $this; - } - unset($captureEvents[$index]); - $this->setDijitParam('captureEvents', $captureEvents); - return $this; - } - - /** - * Clear all capture events - * - * @return Zend_Dojo_Form_Element_Editor - */ - public function clearCaptureEvents() - { - return $this->removeDijitParam('captureEvents'); - } - - /** - * Add a single event to the dijit - * - * @param string $event - * @return Zend_Dojo_Form_Element_Editor - */ - public function addEvent($event) - { - $event = (string) $event; - $events = $this->getEvents(); - if (in_array($event, $events)) { - return $this; - } - - $events[] = (string) $event; - $this->setDijitParam('events', $events); - return $this; - } - - /** - * Add multiple events - * - * @param array $events - * @return Zend_Dojo_Form_Element_Editor - */ - public function addEvents(array $events) - { - foreach ($events as $event) { - $this->addEvent($event); - } - return $this; - } - - /** - * Overwrite many events at once - * - * @param array $events - * @return Zend_Dojo_Form_Element_Editor - */ - public function setEvents(array $events) - { - $this->clearEvents(); - $this->addEvents($events); - return $this; - } - - /** - * Get all events - * - * @return array - */ - public function getEvents() - { - if (!$this->hasDijitParam('events')) { - return array(); - } - return $this->getDijitParam('events'); - } - - /** - * Is a given event registered? - * - * @param string $event - * @return bool - */ - public function hasEvent($event) - { - $events = $this->getEvents(); - return in_array((string) $event, $events); - } - - /** - * Remove a given event - * - * @param string $event - * @return Zend_Dojo_Form_Element_Editor - */ - public function removeEvent($event) - { - $events = $this->getEvents(); - if (false === ($index = array_search($event, $events))) { - return $this; - } - unset($events[$index]); - $this->setDijitParam('events', $events); - return $this; - } - - /** - * Clear all events - * - * @return Zend_Dojo_Form_Element_Editor - */ - public function clearEvents() - { - return $this->removeDijitParam('events'); - } - - /** - * Add a single editor plugin - * - * @param string $plugin - * @return Zend_Dojo_Form_Element_Editor - */ - public function addPlugin($plugin) - { - $plugin = (string) $plugin; - $plugins = $this->getPlugins(); - if (in_array($plugin, $plugins) && $plugin !== '|') { - return $this; - } - - $plugins[] = (string) $plugin; - $this->setDijitParam('plugins', $plugins); - return $this; - } - - /** - * Add multiple plugins - * - * @param array $plugins - * @return Zend_Dojo_Form_Element_Editor - */ - public function addPlugins(array $plugins) - { - foreach ($plugins as $plugin) { - $this->addPlugin($plugin); - } - return $this; - } - - /** - * Overwrite many plugins at once - * - * @param array $plugins - * @return Zend_Dojo_Form_Element_Editor - */ - public function setPlugins(array $plugins) - { - $this->clearPlugins(); - $this->addPlugins($plugins); - return $this; - } - - /** - * Get all plugins - * - * @return array - */ - public function getPlugins() - { - if (!$this->hasDijitParam('plugins')) { - return array(); - } - return $this->getDijitParam('plugins'); - } - - /** - * Is a given plugin registered? - * - * @param string $plugin - * @return bool - */ - public function hasPlugin($plugin) - { - $plugins = $this->getPlugins(); - return in_array((string) $plugin, $plugins); - } - - /** - * Remove a given plugin - * - * @param string $plugin - * @return Zend_Dojo_Form_Element_Editor - */ - public function removePlugin($plugin) - { - $plugins = $this->getPlugins(); - if (false === ($index = array_search($plugin, $plugins))) { - return $this; - } - unset($plugins[$index]); - $this->setDijitParam('plugins', $plugins); - return $this; - } - - /** - * Clear all plugins - * - * @return Zend_Dojo_Form_Element_Editor - */ - public function clearPlugins() - { - return $this->removeDijitParam('plugins'); - } - - /** - * Set edit action interval - * - * @param int $interval - * @return Zend_Dojo_Form_Element_Editor - */ - public function setEditActionInterval($interval) - { - return $this->setDijitParam('editActionInterval', (int) $interval); - } - - /** - * Get edit action interval; defaults to 3 - * - * @return int - */ - public function getEditActionInterval() - { - if (!$this->hasDijitParam('editActionInterval')) { - $this->setEditActionInterval(3); - } - return $this->getDijitParam('editActionInterval'); - } - - /** - * Set focus on load flag - * - * @param bool $flag - * @return Zend_Dojo_Form_Element_Editor - */ - public function setFocusOnLoad($flag) - { - return $this->setDijitParam('focusOnLoad', (bool) $flag); - } - - /** - * Retrieve focus on load flag - * - * @return bool - */ - public function getFocusOnLoad() - { - if (!$this->hasDijitParam('focusOnLoad')) { - return false; - } - return $this->getDijitParam('focusOnLoad'); - } - - /** - * Set editor height - * - * @param string|int $height - * @return Zend_Dojo_Form_Element_Editor - */ - public function setHeight($height) - { - if (!preg_match('/^\d+(em|px|%)?$/i', $height)) { - #require_once 'Zend/Form/Element/Exception.php'; - throw new Zend_Form_Element_Exception('Invalid height provided; must be integer or CSS measurement'); - } - if (!preg_match('/(em|px|%)$/', $height)) { - $height .= 'px'; - } - return $this->setDijitParam('height', $height); - } - - /** - * Retrieve height - * - * @return string - */ - public function getHeight() - { - if (!$this->hasDijitParam('height')) { - return '300px'; - } - return $this->getDijitParam('height'); - } - - /** - * Set whether or not to inherit parent's width - * - * @param bool $flag - * @return Zend_Dojo_Form_Element_Editor - */ - public function setInheritWidth($flag) - { - return $this->setDijitParam('inheritWidth', (bool) $flag); - } - - /** - * Whether or not to inherit the parent's width - * - * @return bool - */ - public function getInheritWidth() - { - if (!$this->hasDijitParam('inheritWidth')) { - return false; - } - return $this->getDijitParam('inheritWidth'); - } - - /** - * Set minimum height of editor - * - * @param string|int $minHeight - * @return Zend_Dojo_Form_Element_Editor - */ - public function setMinHeight($minHeight) - { - if (!preg_match('/^\d+(em|px|%)?$/i', $minHeight)) { - #require_once 'Zend/Form/Element/Exception.php'; - throw new Zend_Form_Element_Exception('Invalid minHeight provided; must be integer or CSS measurement'); - } - if (!preg_match('/(em|px|%)$/', $minHeight)) { - $minHeight .= 'em'; - } - return $this->setDijitParam('minHeight', $minHeight); - } - - /** - * Get minimum height of editor - * - * @return string - */ - public function getMinHeight() - { - if (!$this->hasDijitParam('minHeight')) { - return '1em'; - } - return $this->getDijitParam('minHeight'); - } - - /** - * Add a custom stylesheet - * - * @param string $styleSheet - * @return Zend_Dojo_Form_Element_Editor - */ - public function addStyleSheet($styleSheet) - { - $stylesheets = $this->getStyleSheets(); - if (strstr($stylesheets, ';')) { - $stylesheets = explode(';', $stylesheets); - } elseif (!empty($stylesheets)) { - $stylesheets = (array) $stylesheets; - } else { - $stylesheets = array(); - } - if (!in_array($styleSheet, $stylesheets)) { - $stylesheets[] = (string) $styleSheet; - } - return $this->setDijitParam('styleSheets', implode(';', $stylesheets)); - } - - /** - * Add multiple custom stylesheets - * - * @param array $styleSheets - * @return Zend_Dojo_Form_Element_Editor - */ - public function addStyleSheets(array $styleSheets) - { - foreach ($styleSheets as $styleSheet) { - $this->addStyleSheet($styleSheet); - } - return $this; - } - - /** - * Overwrite all stylesheets - * - * @param array $styleSheets - * @return Zend_Dojo_Form_Element_Editor - */ - public function setStyleSheets(array $styleSheets) - { - $this->clearStyleSheets(); - return $this->addStyleSheets($styleSheets); - } - - /** - * Get all stylesheets - * - * @return string - */ - public function getStyleSheets() - { - if (!$this->hasDijitParam('styleSheets')) { - return ''; - } - return $this->getDijitParam('styleSheets'); - } - - /** - * Is a given stylesheet registered? - * - * @param string $styleSheet - * @return bool - */ - public function hasStyleSheet($styleSheet) - { - $styleSheets = $this->getStyleSheets(); - $styleSheets = explode(';', $styleSheets); - return in_array($styleSheet, $styleSheets); - } - - /** - * Remove a single stylesheet - * - * @param string $styleSheet - * @return Zend_Dojo_Form_Element_Editor - */ - public function removeStyleSheet($styleSheet) - { - $styleSheets = $this->getStyleSheets(); - $styleSheets = explode(';', $styleSheets); - if (false !== ($index = array_search($styleSheet, $styleSheets))) { - unset($styleSheets[$index]); - $this->setDijitParam('styleSheets', implode(';', $styleSheets)); - } - return $this; - } - - /** - * Clear all stylesheets - * - * @return Zend_Dojo_Form_Element_Editor - */ - public function clearStyleSheets() - { - if ($this->hasDijitParam('styleSheets')) { - $this->removeDijitParam('styleSheets'); - } - return $this; - } - - /** - * Set update interval - * - * @param int $interval - * @return Zend_Dojo_Form_Element_Editor - */ - public function setUpdateInterval($interval) - { - return $this->setDijitParam('updateInterval', (int) $interval); - } - - /** - * Get update interval - * - * @return int - */ - public function getUpdateInterval() - { - if (!$this->hasDijitParam('updateInterval')) { - return 200; - } - return $this->getDijitParam('updateInterval'); - } - - /** - * Add a single editor extra plugin. - * - * @param string $plugin - * @return Zend_Dojo_Form_Element_Editor - */ - public function addExtraPlugin($plugin) - { - $plugin = (string) $plugin; - $extraPlugins = $this->getExtraPlugins(); - if (in_array($plugin, $extraPlugins)) { - return $this; - } - - $extraPlugins[] = (string) $plugin; - $this->setDijitParam('extraPlugins', $extraPlugins); - return $this; - } - - /** - * Add multiple extra plugins. - * - * @param array $extraPlugins - * @return Zend_Dojo_Form_Element_Editor - */ - public function addExtraPlugins(array $plugins) - { - foreach ($plugins as $plugin) { - $this->addExtraPlugin($plugin); - } - return $this; - } - - /** - * Overwrite many extra plugins at once. - * - * @param array $plugins - * @return Zend_Dojo_Form_Element_Editor - */ - public function setExtraPlugins(array $plugins) - { - $this->clearExtraPlugins(); - $this->addExtraPlugins($plugins); - return $this; - } - - /** - * Get all extra plugins. - * - * @return array - */ - public function getExtraPlugins() - { - if (!$this->hasDijitParam('extraPlugins')) { - return array(); - } - return $this->getDijitParam('extraPlugins'); - } - - /** - * Is a given extra plugin registered? - * - * @param string $plugin - * @return bool - */ - public function hasExtraPlugin($plugin) - { - $extraPlugins = $this->getExtraPlugins(); - return in_array((string) $plugin, $extraPlugins); - } - - /** - * Remove a given extra plugin. - * - * @param string $plugin - * @return Zend_Dojo_Form_Element_Editor - */ - public function removeExtraPlugin($plugin) - { - $extraPlugins = $this->getExtraPlugins(); - if (false === ($index = array_search($plugin, $extraPlugins))) { - return $this; - } - unset($extraPlugins[$index]); - $this->setDijitParam('extraPlugins', $extraPlugins); - return $this; - } - - /** - * Clear all extra plugins. - * - * @return Zend_Dojo_Form_Element_Editor - */ - public function clearExtraPlugins() - { - return $this->removeDijitParam('extraPlugins'); - } -} diff --git a/library/Zend/Dojo/Form/Element/FilteringSelect.php b/library/Zend/Dojo/Form/Element/FilteringSelect.php deleted file mode 100644 index c882fd5c0d..0000000000 --- a/library/Zend/Dojo/Form/Element/FilteringSelect.php +++ /dev/null @@ -1,48 +0,0 @@ -hasDijitParam('topDecoration')) { - return $this->getDijitParam('topDecoration'); - } - return array(); - } - - /** - * Set dijit to use with top decoration - * - * @param mixed $dijit - * @return Zend_Dojo_Form_Element_HorizontalSlider - */ - public function setTopDecorationDijit($dijit) - { - $decoration = $this->getTopDecoration(); - $decoration['dijit'] = (string) $dijit; - $this->setDijitParam('topDecoration', $decoration); - return $this; - } - - /** - * Set container to use with top decoration - * - * @param mixed $container - * @return Zend_Dojo_Form_Element_HorizontalSlider - */ - public function setTopDecorationContainer($container) - { - $decoration = $this->getTopDecoration(); - $decoration['container'] = (string) $container; - $this->setDijitParam('topDecoration', $decoration); - return $this; - } - - /** - * Set labels to use with top decoration - * - * @param array $labels - * @return Zend_Dojo_Form_Element_HorizontalSlider - */ - public function setTopDecorationLabels(array $labels) - { - $decoration = $this->getTopDecoration(); - $decoration['labels'] = array_values($labels); - $this->setDijitParam('topDecoration', $decoration); - return $this; - } - - /** - * Set params to use with top decoration - * - * @param array $params - * @return Zend_Dojo_Form_Element_HorizontalSlider - */ - public function setTopDecorationParams(array $params) - { - $decoration = $this->getTopDecoration(); - $decoration['params'] = $params; - $this->setDijitParam('topDecoration', $decoration); - return $this; - } - - /** - * Set attribs to use with top decoration - * - * @param array $attribs - * @return Zend_Dojo_Form_Element_HorizontalSlider - */ - public function setTopDecorationAttribs(array $attribs) - { - $decoration = $this->getTopDecoration(); - $decoration['attribs'] = $attribs; - $this->setDijitParam('topDecoration', $decoration); - return $this; - } - - /** - * Get bottom decoration data - * - * @return array - */ - public function getBottomDecoration() - { - if ($this->hasDijitParam('bottomDecoration')) { - return $this->getDijitParam('bottomDecoration'); - } - return array(); - } - - /** - * Set dijit to use with bottom decoration - * - * @param mixed $dijit - * @return Zend_Dojo_Form_Element_HorizontalSlider - */ - public function setBottomDecorationDijit($dijit) - { - $decoration = $this->getBottomDecoration(); - $decoration['dijit'] = (string) $dijit; - $this->setDijitParam('bottomDecoration', $decoration); - return $this; - } - - /** - * Set container to use with bottom decoration - * - * @param mixed $container - * @return Zend_Dojo_Form_Element_HorizontalSlider - */ - public function setBottomDecorationContainer($container) - { - $decoration = $this->getBottomDecoration(); - $decoration['container'] = (string) $container; - $this->setDijitParam('bottomDecoration', $decoration); - return $this; - } - - /** - * Set labels to use with bottom decoration - * - * @param array $labels - * @return Zend_Dojo_Form_Element_HorizontalSlider - */ - public function setBottomDecorationLabels(array $labels) - { - $decoration = $this->getBottomDecoration(); - $decoration['labels'] = array_values($labels); - $this->setDijitParam('bottomDecoration', $decoration); - return $this; - } - - /** - * Set params to use with bottom decoration - * - * @param array $params - * @return Zend_Dojo_Form_Element_HorizontalSlider - */ - public function setBottomDecorationParams(array $params) - { - $decoration = $this->getBottomDecoration(); - $decoration['params'] = $params; - $this->setDijitParam('bottomDecoration', $decoration); - return $this; - } - - /** - * Set attribs to use with bottom decoration - * - * @param array $attribs - * @return Zend_Dojo_Form_Element_HorizontalSlider - */ - public function setBottomDecorationAttribs(array $attribs) - { - $decoration = $this->getBottomDecoration(); - $decoration['attribs'] = $attribs; - $this->setDijitParam('bottomDecoration', $decoration); - return $this; - } -} diff --git a/library/Zend/Dojo/Form/Element/NumberSpinner.php b/library/Zend/Dojo/Form/Element/NumberSpinner.php deleted file mode 100644 index 443352dcf1..0000000000 --- a/library/Zend/Dojo/Form/Element/NumberSpinner.php +++ /dev/null @@ -1,245 +0,0 @@ -setDijitParam('defaultTimeout', (int) $timeout); - return $this; - } - - /** - * Retrieve defaultTimeout - * - * @return int|null - */ - public function getDefaultTimeout() - { - return $this->getDijitParam('defaultTimeout'); - } - - /** - * Set timeoutChangeRate - * - * @param int $rate - * @return Zend_Dojo_Form_Element_NumberSpinner - */ - public function setTimeoutChangeRate($rate) - { - $this->setDijitParam('timeoutChangeRate', (int) $rate); - return $this; - } - - /** - * Retrieve timeoutChangeRate - * - * @return int|null - */ - public function getTimeoutChangeRate() - { - return $this->getDijitParam('timeoutChangeRate'); - } - - /** - * Set largeDelta - * - * @param int $delta - * @return Zend_Dojo_Form_Element_NumberSpinner - */ - public function setLargeDelta($delta) - { - $this->setDijitParam('largeDelta', (float) $delta); - return $this; - } - - /** - * Retrieve largeDelta - * - * @return int|null - */ - public function getLargeDelta() - { - return $this->getDijitParam('largeDelta'); - } - - /** - * Set smallDelta - * - * @param int $delta - * @return Zend_Dojo_Form_Element_NumberSpinner - */ - public function setSmallDelta($delta) - { - $this->setDijitParam('smallDelta', (float) $delta); - return $this; - } - - /** - * Retrieve smallDelta - * - * @return int|null - */ - public function getSmallDelta() - { - return $this->getDijitParam('smallDelta'); - } - - /** - * Set intermediateChanges flag - * - * @param bool $flag - * @return Zend_Dojo_Form_Element_TextBox - */ - public function setIntermediateChanges($flag) - { - $this->setDijitParam('intermediateChanges', (bool) $flag); - return $this; - } - - /** - * Retrieve intermediateChanges flag - * - * @return bool - */ - public function getIntermediateChanges() - { - if (!$this->hasDijitParam('intermediateChanges')) { - return false; - } - return $this->getDijitParam('intermediateChanges'); - } - - /** - * Set rangeMessage - * - * @param string $message - * @return Zend_Dojo_Form_Element_NumberSpinner - */ - public function setRangeMessage($message) - { - $this->setDijitParam('rangeMessage', (string) $message); - return $this; - } - - /** - * Retrieve rangeMessage - * - * @return string|null - */ - public function getRangeMessage() - { - return $this->getDijitParam('rangeMessage'); - } - - /** - * Set minimum value - * - * @param int $value - * @return Zend_Dojo_Form_Element_NumberSpinner - */ - public function setMin($value) - { - $constraints = array(); - if ($this->hasDijitParam('constraints')) { - $constraints = $this->getDijitParam('constraints'); - } - $constraints['min'] = (float) $value; - $this->setDijitParam('constraints', $constraints); - return $this; - } - - /** - * Get minimum value - * - * @return null|int - */ - public function getMin() - { - if (!$this->hasDijitParam('constraints')) { - return null; - } - $constraints = $this->getDijitParam('constraints'); - if (!array_key_exists('min', $constraints)) { - return null; - } - return $constraints['min']; - } - - /** - * Set maximum value - * - * @param int $value - * @return Zend_Dojo_Form_Element_NumberSpinner - */ - public function setMax($value) - { - $constraints = array(); - if ($this->hasDijitParam('constraints')) { - $constraints = $this->getDijitParam('constraints'); - } - $constraints['max'] = (float) $value; - $this->setDijitParam('constraints', $constraints); - return $this; - } - - /** - * Get maximum value - * - * @return null|int - */ - public function getMax() - { - if (!$this->hasDijitParam('constraints')) { - return null; - } - $constraints = $this->getDijitParam('constraints'); - if (!array_key_exists('max', $constraints)) { - return null; - } - return $constraints['max']; - } -} diff --git a/library/Zend/Dojo/Form/Element/NumberTextBox.php b/library/Zend/Dojo/Form/Element/NumberTextBox.php deleted file mode 100644 index c2e09e1457..0000000000 --- a/library/Zend/Dojo/Form/Element/NumberTextBox.php +++ /dev/null @@ -1,173 +0,0 @@ -setConstraint('locale', (string) $locale); - return $this; - } - - /** - * Retrieve locale - * - * @return string|null - */ - public function getLocale() - { - return $this->getConstraint('locale'); - } - - /** - * Set numeric format pattern - * - * @param string $pattern - * @return Zend_Dojo_Form_Element_NumberTextBox - */ - public function setPattern($pattern) - { - $this->setConstraint('pattern', (string) $pattern); - return $this; - } - - /** - * Retrieve numeric format pattern - * - * @return string|null - */ - public function getPattern() - { - return $this->getConstraint('pattern'); - } - - /** - * Set numeric format type - * - * @see $_allowedTypes - * @param string $type - * @return Zend_Dojo_Form_Element_NumberTextBox - */ - public function setType($type) - { - $type = strtolower($type); - if (!in_array($type, $this->_allowedTypes)) { - #require_once 'Zend/Form/Element/Exception.php'; - throw new Zend_Form_Element_Exception(sprintf('Invalid numeric type "%s" specified', $type)); - } - - $this->setConstraint('type', $type); - return $this; - } - - /** - * Retrieve type - * - * @return string|null - */ - public function getType() - { - return $this->getConstraint('type'); - } - - /** - * Set decimal places - * - * @param int $places - * @return Zend_Dojo_Form_Element_NumberTextBox - */ - public function setPlaces($places) - { - $this->setConstraint('places', (int) $places); - return $this; - } - - /** - * Retrieve decimal places - * - * @return int|null - */ - public function getPlaces() - { - return $this->getConstraint('places'); - } - - /** - * Set strict flag - * - * @param bool $strict - * @return Zend_Dojo_Form_Element_NumberTextBox - */ - public function setStrict($flag) - { - $this->setConstraint('strict', (bool) $flag); - return $this; - } - - /** - * Retrieve strict flag - * - * @return bool - */ - public function getStrict() - { - if (!$this->hasConstraint('strict')) { - return false; - } - return ('true' == $this->getConstraint('strict')); - } -} diff --git a/library/Zend/Dojo/Form/Element/PasswordTextBox.php b/library/Zend/Dojo/Form/Element/PasswordTextBox.php deleted file mode 100644 index fa43e45b11..0000000000 --- a/library/Zend/Dojo/Form/Element/PasswordTextBox.php +++ /dev/null @@ -1,42 +0,0 @@ -setDijitParam('clickSelect', (bool) $flag); - return $this; - } - - /** - * Retrieve clickSelect flag - * - * @return bool - */ - public function getClickSelect() - { - if (!$this->hasDijitParam('clickSelect')) { - return false; - } - return $this->getDijitParam('clickSelect'); - } - - /** - * Set intermediateChanges flag - * - * @param bool $intermediateChanges - * @return Zend_Dojo_Form_Element_TextBox - */ - public function setIntermediateChanges($flag) - { - $this->setDijitParam('intermediateChanges', (bool) $flag); - return $this; - } - - /** - * Retrieve intermediateChanges flag - * - * @return bool - */ - public function getIntermediateChanges() - { - if (!$this->hasDijitParam('intermediateChanges')) { - return false; - } - return $this->getDijitParam('intermediateChanges'); - } - - /** - * Set showButtons flag - * - * @param bool $showButtons - * @return Zend_Dojo_Form_Element_TextBox - */ - public function setShowButtons($flag) - { - $this->setDijitParam('showButtons', (bool) $flag); - return $this; - } - - /** - * Retrieve showButtons flag - * - * @return bool - */ - public function getShowButtons() - { - if (!$this->hasDijitParam('showButtons')) { - return false; - } - return $this->getDijitParam('showButtons'); - } - - /** - * Set discreteValues - * - * @param int $value - * @return Zend_Dojo_Form_Element_TextBox - */ - public function setDiscreteValues($value) - { - $this->setDijitParam('discreteValues', (int) $value); - return $this; - } - - /** - * Retrieve discreteValues - * - * @return int|null - */ - public function getDiscreteValues() - { - return $this->getDijitParam('discreteValues'); - } - - /** - * Set maximum - * - * @param int $value - * @return Zend_Dojo_Form_Element_TextBox - */ - public function setMaximum($value) - { - $this->setDijitParam('maximum', (int) $value); - return $this; - } - - /** - * Retrieve maximum - * - * @return int|null - */ - public function getMaximum() - { - return $this->getDijitParam('maximum'); - } - - /** - * Set minimum - * - * @param int $value - * @return Zend_Dojo_Form_Element_TextBox - */ - public function setMinimum($value) - { - $this->setDijitParam('minimum', (int) $value); - return $this; - } - - /** - * Retrieve minimum - * - * @return int|null - */ - public function getMinimum() - { - return $this->getDijitParam('minimum'); - } - - /** - * Set pageIncrement - * - * @param int $value - * @return Zend_Dojo_Form_Element_TextBox - */ - public function setPageIncrement($value) - { - $this->setDijitParam('pageIncrement', (int) $value); - return $this; - } - - /** - * Retrieve pageIncrement - * - * @return int|null - */ - public function getPageIncrement() - { - return $this->getDijitParam('pageIncrement'); - } -} diff --git a/library/Zend/Dojo/Form/Element/SubmitButton.php b/library/Zend/Dojo/Form/Element/SubmitButton.php deleted file mode 100644 index 76c526b63b..0000000000 --- a/library/Zend/Dojo/Form/Element/SubmitButton.php +++ /dev/null @@ -1,42 +0,0 @@ -setDijitParam('lowercase', (bool) $flag); - return $this; - } - - /** - * Retrieve lowercase flag - * - * @return bool - */ - public function getLowercase() - { - if (!$this->hasDijitParam('lowercase')) { - return false; - } - return $this->getDijitParam('lowercase'); - } - - /** - * Set propercase flag - * - * @param bool $propercase - * @return Zend_Dojo_Form_Element_TextBox - */ - public function setPropercase($flag) - { - $this->setDijitParam('propercase', (bool) $flag); - return $this; - } - - /** - * Retrieve propercase flag - * - * @return bool - */ - public function getPropercase() - { - if (!$this->hasDijitParam('propercase')) { - return false; - } - return $this->getDijitParam('propercase'); - } - - /** - * Set uppercase flag - * - * @param bool $uppercase - * @return Zend_Dojo_Form_Element_TextBox - */ - public function setUppercase($flag) - { - $this->setDijitParam('uppercase', (bool) $flag); - return $this; - } - - /** - * Retrieve uppercase flag - * - * @return bool - */ - public function getUppercase() - { - if (!$this->hasDijitParam('uppercase')) { - return false; - } - return $this->getDijitParam('uppercase'); - } - - /** - * Set trim flag - * - * @param bool $trim - * @return Zend_Dojo_Form_Element_TextBox - */ - public function setTrim($flag) - { - $this->setDijitParam('trim', (bool) $flag); - return $this; - } - - /** - * Retrieve trim flag - * - * @return bool - */ - public function getTrim() - { - if (!$this->hasDijitParam('trim')) { - return false; - } - return $this->getDijitParam('trim'); - } - - /** - * Set maxLength - * - * @param int $length - * @return Zend_Dojo_Form_Element_TextBox - */ - public function setMaxLength($length) - { - $this->setDijitParam('maxLength', (int) $length); - return $this; - } - - /** - * Retrieve maxLength - * - * @return int|null - */ - public function getMaxLength() - { - return $this->getDijitParam('maxLength'); - } -} diff --git a/library/Zend/Dojo/Form/Element/Textarea.php b/library/Zend/Dojo/Form/Element/Textarea.php deleted file mode 100644 index 676777fba7..0000000000 --- a/library/Zend/Dojo/Form/Element/Textarea.php +++ /dev/null @@ -1,42 +0,0 @@ -setConstraint('timePattern', (string) $pattern); - return $this; - } - - /** - * Retrieve time format pattern - * - * @return string|null - */ - public function getTimePattern() - { - return $this->getConstraint('timePattern'); - } - - /** - * Set clickableIncrement - * - * @param string $format - * @return Zend_Dojo_Form_Element_NumberTextBox - */ - public function setClickableIncrement($format) - { - $format = (string) $format; - $this->_validateIso8601($format); - $this->setConstraint('clickableIncrement', $format); - return $this; - } - - /** - * Retrieve clickableIncrement - * - * @return string|null - */ - public function getClickableIncrement() - { - return $this->getConstraint('clickableIncrement'); - } - - /** - * Set visibleIncrement - * - * @param string $format - * @return Zend_Dojo_Form_Element_NumberTextBox - */ - public function setVisibleIncrement($format) - { - $format = (string) $format; - $this->_validateIso8601($format); - $this->setConstraint('visibleIncrement', $format); - return $this; - } - - /** - * Retrieve visibleIncrement - * - * @return string|null - */ - public function getVisibleIncrement() - { - return $this->getConstraint('visibleIncrement'); - } - - /** - * Set visibleRange - * - * @param string $format - * @return Zend_Dojo_Form_Element_NumberTextBox - */ - public function setVisibleRange($format) - { - $format = (string) $format; - $this->_validateIso8601($format); - $this->setConstraint('visibleRange', $format); - return $this; - } - - /** - * Retrieve visibleRange - * - * @return string|null - */ - public function getVisibleRange() - { - return $this->getConstraint('visibleRange'); - } -} diff --git a/library/Zend/Dojo/Form/Element/ValidationTextBox.php b/library/Zend/Dojo/Form/Element/ValidationTextBox.php deleted file mode 100644 index 64b1909462..0000000000 --- a/library/Zend/Dojo/Form/Element/ValidationTextBox.php +++ /dev/null @@ -1,220 +0,0 @@ -setDijitParam('invalidMessage', (string) $message); - return $this; - } - - /** - * Retrieve invalidMessage - * - * @return string|null - */ - public function getInvalidMessage() - { - return $this->getDijitParam('invalidMessage'); - } - - /** - * Set promptMessage - * - * @param string $message - * @return Zend_Dojo_Form_Element_ValidationTextBox - */ - public function setPromptMessage($message) - { - $this->setDijitParam('promptMessage', (string) $message); - return $this; - } - - /** - * Retrieve promptMessage - * - * @return string|null - */ - public function getPromptMessage() - { - return $this->getDijitParam('promptMessage'); - } - - /** - * Set regExp - * - * @param string $regexp - * @return Zend_Dojo_Form_Element_ValidationTextBox - */ - public function setRegExp($regexp) - { - $this->setDijitParam('regExp', (string) $regexp); - return $this; - } - - /** - * Retrieve regExp - * - * @return string|null - */ - public function getRegExp() - { - return $this->getDijitParam('regExp'); - } - - /** - * Set an individual constraint - * - * @param string $key - * @param mixed $value - * @return Zend_Dojo_Form_Element_ValidationTextBox - */ - public function setConstraint($key, $value) - { - $constraints = $this->getConstraints(); - $constraints[(string) $key] = $value; - $this->setConstraints($constraints); - return $this; - } - - /** - * Set validation constraints - * - * Refer to Dojo dijit.form.ValidationTextBox documentation for valid - * structure. - * - * @param array $constraints - * @return Zend_Dojo_Form_Element_ValidationTextBox - */ - public function setConstraints(array $constraints) - { - $tmp = $this->getConstraints(); - $constraints = array_merge($tmp, $constraints); - array_walk_recursive($constraints, array($this, '_castBoolToString')); - $this->setDijitParam('constraints', $constraints); - return $this; - } - - /** - * Is the given constraint set? - * - * @param string $key - * @return bool - */ - public function hasConstraint($key) - { - $constraints = $this->getConstraints(); - return array_key_exists((string)$key, $constraints); - } - - /** - * Get an individual constraint - * - * @param string $key - * @return mixed - */ - public function getConstraint($key) - { - $key = (string) $key; - if (!$this->hasConstraint($key)) { - return null; - } - return $this->dijitParams['constraints'][$key]; - } - - /** - * Get constraints - * - * @return array - */ - public function getConstraints() - { - if ($this->hasDijitParam('constraints')) { - return $this->getDijitParam('constraints'); - } - return array(); - } - - /** - * Remove a single constraint - * - * @param string $key - * @return Zend_Dojo_Form_Element_ValidationTextBox - */ - public function removeConstraint($key) - { - $key = (string) $key; - if ($this->hasConstraint($key)) { - unset($this->dijitParams['constraints'][$key]); - } - return $this; - } - - /** - * Clear all constraints - * - * @return Zend_Dojo_Form_Element_ValidationTextBox - */ - public function clearConstraints() - { - return $this->removeDijitParam('constraints'); - } - - /** - * Cast a boolean value to a string - * - * @param mixed $item - * @param string $key - * @return void - */ - protected function _castBoolToString(&$item, $key) - { - if (is_bool($item)) { - $item = ($item) ? 'true' : 'false'; - } - } -} diff --git a/library/Zend/Dojo/Form/Element/VerticalSlider.php b/library/Zend/Dojo/Form/Element/VerticalSlider.php deleted file mode 100644 index d6e29c9acf..0000000000 --- a/library/Zend/Dojo/Form/Element/VerticalSlider.php +++ /dev/null @@ -1,208 +0,0 @@ -hasDijitParam('leftDecoration')) { - return $this->getDijitParam('leftDecoration'); - } - return array(); - } - - /** - * Set dijit to use with left decoration - * - * @param mixed $dijit - * @return Zend_Dojo_Form_Element_HorizontalSlider - */ - public function setLeftDecorationDijit($dijit) - { - $decoration = $this->getLeftDecoration(); - $decoration['dijit'] = (string) $dijit; - $this->setDijitParam('leftDecoration', $decoration); - return $this; - } - - /** - * Set container to use with left decoration - * - * @param mixed $container - * @return Zend_Dojo_Form_Element_HorizontalSlider - */ - public function setLeftDecorationContainer($container) - { - $decoration = $this->getLeftDecoration(); - $decoration['container'] = (string) $container; - $this->setDijitParam('leftDecoration', $decoration); - return $this; - } - - /** - * Set labels to use with left decoration - * - * @param array $labels - * @return Zend_Dojo_Form_Element_HorizontalSlider - */ - public function setLeftDecorationLabels(array $labels) - { - $decoration = $this->getLeftDecoration(); - $decoration['labels'] = array_values($labels); - $this->setDijitParam('leftDecoration', $decoration); - return $this; - } - - /** - * Set params to use with left decoration - * - * @param array $params - * @return Zend_Dojo_Form_Element_HorizontalSlider - */ - public function setLeftDecorationParams(array $params) - { - $decoration = $this->getLeftDecoration(); - $decoration['params'] = $params; - $this->setDijitParam('leftDecoration', $decoration); - return $this; - } - - /** - * Set attribs to use with left decoration - * - * @param array $attribs - * @return Zend_Dojo_Form_Element_HorizontalSlider - */ - public function setLeftDecorationAttribs(array $attribs) - { - $decoration = $this->getLeftDecoration(); - $decoration['attribs'] = $attribs; - $this->setDijitParam('leftDecoration', $decoration); - return $this; - } - - /** - * Get right decoration data - * - * @return array - */ - public function getRightDecoration() - { - if ($this->hasDijitParam('rightDecoration')) { - return $this->getDijitParam('rightDecoration'); - } - return array(); - } - - /** - * Set dijit to use with right decoration - * - * @param mixed $dijit - * @return Zend_Dojo_Form_Element_HorizontalSlider - */ - public function setRightDecorationDijit($dijit) - { - $decoration = $this->getRightDecoration(); - $decoration['dijit'] = (string) $dijit; - $this->setDijitParam('rightDecoration', $decoration); - return $this; - } - - /** - * Set container to use with right decoration - * - * @param mixed $container - * @return Zend_Dojo_Form_Element_HorizontalSlider - */ - public function setRightDecorationContainer($container) - { - $decoration = $this->getRightDecoration(); - $decoration['container'] = (string) $container; - $this->setDijitParam('rightDecoration', $decoration); - return $this; - } - - /** - * Set labels to use with right decoration - * - * @param array $labels - * @return Zend_Dojo_Form_Element_HorizontalSlider - */ - public function setRightDecorationLabels(array $labels) - { - $decoration = $this->getRightDecoration(); - $decoration['labels'] = array_values($labels); - $this->setDijitParam('rightDecoration', $decoration); - return $this; - } - - /** - * Set params to use with right decoration - * - * @param array $params - * @return Zend_Dojo_Form_Element_HorizontalSlider - */ - public function setRightDecorationParams(array $params) - { - $decoration = $this->getRightDecoration(); - $decoration['params'] = $params; - $this->setDijitParam('rightDecoration', $decoration); - return $this; - } - - /** - * Set attribs to use with right decoration - * - * @param array $attribs - * @return Zend_Dojo_Form_Element_HorizontalSlider - */ - public function setRightDecorationAttribs(array $attribs) - { - $decoration = $this->getRightDecoration(); - $decoration['attribs'] = $attribs; - $this->setDijitParam('rightDecoration', $decoration); - return $this; - } -} diff --git a/library/Zend/Dojo/Form/SubForm.php b/library/Zend/Dojo/Form/SubForm.php deleted file mode 100644 index cde6197f14..0000000000 --- a/library/Zend/Dojo/Form/SubForm.php +++ /dev/null @@ -1,94 +0,0 @@ -addPrefixPath('Zend_Dojo_Form_Decorator', 'Zend/Dojo/Form/Decorator', 'decorator') - ->addPrefixPath('Zend_Dojo_Form_Element', 'Zend/Dojo/Form/Element', 'element') - ->addElementPrefixPath('Zend_Dojo_Form_Decorator', 'Zend/Dojo/Form/Decorator', 'decorator') - ->addDisplayGroupPrefixPath('Zend_Dojo_Form_Decorator', 'Zend/Dojo/Form/Decorator') - ->setDefaultDisplayGroupClass('Zend_Dojo_Form_DisplayGroup'); - parent::__construct($options); - } - - /** - * Load the default decorators - * - * @return void - */ - public function loadDefaultDecorators() - { - if ($this->loadDefaultDecoratorsIsDisabled()) { - return; - } - - $decorators = $this->getDecorators(); - if (empty($decorators)) { - $this->addDecorator('FormElements') - ->addDecorator('HtmlTag', array('tag' => 'dl')) - ->addDecorator('ContentPane'); - } - } - - /** - * Get view - * - * @return Zend_View_Interface - */ - public function getView() - { - $view = parent::getView(); - if (!$this->_dojoViewPathRegistered) { - if (false === $view->getPluginLoader('helper')->getPaths('Zend_Dojo_View_Helper')) { - $view->addHelperPath('Zend/Dojo/View/Helper', 'Zend_Dojo_View_Helper'); - } - $this->_dojoViewPathRegistered = true; - } - return $view; - } -} diff --git a/library/Zend/Dojo/View/Exception.php b/library/Zend/Dojo/View/Exception.php deleted file mode 100644 index 83860a3384..0000000000 --- a/library/Zend/Dojo/View/Exception.php +++ /dev/null @@ -1,37 +0,0 @@ -_createLayoutContainer($id, $content, $params, $attribs); - } -} diff --git a/library/Zend/Dojo/View/Helper/AccordionPane.php b/library/Zend/Dojo/View/Helper/AccordionPane.php deleted file mode 100644 index 215339af54..0000000000 --- a/library/Zend/Dojo/View/Helper/AccordionPane.php +++ /dev/null @@ -1,66 +0,0 @@ -_createLayoutContainer($id, $content, $params, $attribs); - } -} diff --git a/library/Zend/Dojo/View/Helper/BorderContainer.php b/library/Zend/Dojo/View/Helper/BorderContainer.php deleted file mode 100644 index ab99939d39..0000000000 --- a/library/Zend/Dojo/View/Helper/BorderContainer.php +++ /dev/null @@ -1,79 +0,0 @@ -_styleIsRegistered) { - $this->view->headStyle()->appendStyle('html, body { height: 100%; width: 100%; margin: 0; padding: 0; }'); - $this->_styleIsRegistered = true; - } - - // and now we create it: - return $this->_createLayoutContainer($id, $content, $params, $attribs); - } -} diff --git a/library/Zend/Dojo/View/Helper/Button.php b/library/Zend/Dojo/View/Helper/Button.php deleted file mode 100644 index 656c765a42..0000000000 --- a/library/Zend/Dojo/View/Helper/Button.php +++ /dev/null @@ -1,68 +0,0 @@ -_prepareDijit($attribs, $params, 'element'); - - return $this->view->formButton($id, $value, $attribs); - } -} diff --git a/library/Zend/Dojo/View/Helper/CheckBox.php b/library/Zend/Dojo/View/Helper/CheckBox.php deleted file mode 100644 index 4144179e71..0000000000 --- a/library/Zend/Dojo/View/Helper/CheckBox.php +++ /dev/null @@ -1,100 +0,0 @@ -_prepareDijit($attribs, $params, 'element'); - - // strip options so they don't show up in markup - if (array_key_exists('options', $attribs)) { - unset($attribs['options']); - } - - // and now we create it: - $html = ''; - if (!strstr($id, '[]')) { - // hidden element for unchecked value - $html .= $this->_renderHiddenElement($id, $checkboxInfo['uncheckedValue']); - } - - // and final element - $html .= $this->_createFormElement($id, $checkboxInfo['checkedValue'], $params, $attribs); - - return $html; - } -} diff --git a/library/Zend/Dojo/View/Helper/ComboBox.php b/library/Zend/Dojo/View/Helper/ComboBox.php deleted file mode 100644 index cb20ef888d..0000000000 --- a/library/Zend/Dojo/View/Helper/ComboBox.php +++ /dev/null @@ -1,155 +0,0 @@ -_renderStore($params['store'], $id))) { - $params['store'] = $params['store']['store']; - if (is_string($store)) { - $html .= $store; - } - $html .= $this->_createFormElement($id, $value, $params, $attribs); - return $html; - } - unset($params['store']); - } elseif (array_key_exists('store', $params)) { - if (array_key_exists('storeType', $params)) { - $storeParams = array( - 'store' => $params['store'], - 'type' => $params['storeType'], - ); - unset($params['storeType']); - if (array_key_exists('storeParams', $params)) { - $storeParams['params'] = $params['storeParams']; - unset($params['storeParams']); - } - if (false !== ($store = $this->_renderStore($storeParams, $id))) { - if (is_string($store)) { - $html .= $store; - } - } - } - $html .= $this->_createFormElement($id, $value, $params, $attribs); - return $html; - } - - // required for correct type casting in declerative mode - if (isset($params['autocomplete'])) { - $params['autocomplete'] = ($params['autocomplete']) ? 'true' : 'false'; - } - // do as normal select - $attribs = $this->_prepareDijit($attribs, $params, 'element'); - return $this->view->formSelect($id, $value, $attribs, $options); - } - - /** - * Render data store element - * - * Renders to dojo view helper - * - * @param array $params - * @return string|false - */ - protected function _renderStore(array $params, $id) - { - if (!array_key_exists('store', $params) || !array_key_exists('type', $params)) { - return false; - } - - $this->dojo->requireModule($params['type']); - - $extraParams = array(); - $storeParams = array( - 'dojoType' => $params['type'], - 'jsId' => $params['store'], - ); - - if (array_key_exists('params', $params)) { - $storeParams = array_merge($storeParams, $params['params']); - $extraParams = $params['params']; - } - - if ($this->_useProgrammatic()) { - if (!$this->_useProgrammaticNoScript()) { - #require_once 'Zend/Json.php'; - $this->dojo->addJavascript('var ' . $storeParams['jsId'] . ";\n"); - $js = $storeParams['jsId'] . ' = ' - . 'new ' . $storeParams['dojoType'] . '(' - . Zend_Json::encode($extraParams) - . ");\n"; - $js = "function() {\n$js\n}"; - $this->dojo->_addZendLoad($js); - } - return true; - } - - return '_htmlAttribs($storeParams) . '>'; - } -} diff --git a/library/Zend/Dojo/View/Helper/ContentPane.php b/library/Zend/Dojo/View/Helper/ContentPane.php deleted file mode 100644 index dd28b19a1b..0000000000 --- a/library/Zend/Dojo/View/Helper/ContentPane.php +++ /dev/null @@ -1,66 +0,0 @@ -_createLayoutContainer($id, $content, $params, $attribs); - } -} diff --git a/library/Zend/Dojo/View/Helper/CurrencyTextBox.php b/library/Zend/Dojo/View/Helper/CurrencyTextBox.php deleted file mode 100644 index faaeaeb1e5..0000000000 --- a/library/Zend/Dojo/View/Helper/CurrencyTextBox.php +++ /dev/null @@ -1,68 +0,0 @@ -_createFormElement($id, $value, $params, $attribs); - } -} diff --git a/library/Zend/Dojo/View/Helper/CustomDijit.php b/library/Zend/Dojo/View/Helper/CustomDijit.php deleted file mode 100644 index 07c3685871..0000000000 --- a/library/Zend/Dojo/View/Helper/CustomDijit.php +++ /dev/null @@ -1,112 +0,0 @@ -_defaultDojoType) - ) { - #require_once 'Zend/Dojo/View/Exception.php'; - throw new Zend_Dojo_View_Exception('No dojoType specified; cannot create dijit'); - } elseif (array_key_exists('dojoType', $params)) { - $this->_dijit = $params['dojoType']; - $this->_module = $params['dojoType']; - unset($params['dojoType']); - } else { - $this->_dijit = $this->_defaultDojoType; - $this->_module = $this->_defaultDojoType; - } - - if (array_key_exists('rootNode', $params)) { - $this->setRootNode($params['rootNode']); - unset($params['rootNode']); - } - - return $this->_createLayoutContainer($id, $value, $params, $attribs); - } - - /** - * Begin capturing content. - * - * Requires that either the {@link $_defaultDojotype} property is set, or - * that you pass a value to the "dojoType" key of the $params argument. - * - * @param string $id - * @param array $params - * @param array $attribs - * @return void - */ - public function captureStart($id, array $params = array(), array $attribs = array()) - { - if (!array_key_exists('dojoType', $params) - && (null === $this->_defaultDojoType) - ) { - #require_once 'Zend/Dojo/View/Exception.php'; - throw new Zend_Dojo_View_Exception('No dojoType specified; cannot create dijit'); - } elseif (array_key_exists('dojoType', $params)) { - $this->_dijit = $params['dojoType']; - $this->_module = $params['dojoType']; - unset($params['dojoType']); - } else { - $this->_dijit = $this->_defaultDojoType; - $this->_module = $this->_defaultDojoType; - } - - return parent::captureStart($id, $params, $attribs); - } -} diff --git a/library/Zend/Dojo/View/Helper/DateTextBox.php b/library/Zend/Dojo/View/Helper/DateTextBox.php deleted file mode 100644 index f7dd8e7c83..0000000000 --- a/library/Zend/Dojo/View/Helper/DateTextBox.php +++ /dev/null @@ -1,68 +0,0 @@ -_createFormElement($id, $value, $params, $attribs); - } -} diff --git a/library/Zend/Dojo/View/Helper/Dijit.php b/library/Zend/Dojo/View/Helper/Dijit.php deleted file mode 100644 index b46751a43d..0000000000 --- a/library/Zend/Dojo/View/Helper/Dijit.php +++ /dev/null @@ -1,344 +0,0 @@ -dojo = $this->view->dojo(); - $this->dojo->enable(); - return $this; - } - - - /** - * Get root node type - * - * @return string - */ - public function getRootNode() - { - return $this->_rootNode; - } - - /** - * Set root node type - * - * @param string $value - * @return Zend_Dojo_View_Helper_Dijit - */ - public function setRootNode($value) - { - $this->_rootNode = $value; - return $this; - } - - /** - * Whether or not to use declarative dijit creation - * - * @return bool - */ - protected function _useDeclarative() - { - return Zend_Dojo_View_Helper_Dojo::useDeclarative(); - } - - /** - * Whether or not to use programmatic dijit creation - * - * @return bool - */ - protected function _useProgrammatic() - { - return Zend_Dojo_View_Helper_Dojo::useProgrammatic(); - } - - /** - * Whether or not to use programmatic dijit creation w/o script creation - * - * @return bool - */ - protected function _useProgrammaticNoScript() - { - return Zend_Dojo_View_Helper_Dojo::useProgrammaticNoScript(); - } - - /** - * Create a layout container - * - * @param int $id - * @param string $content - * @param array $params - * @param array $attribs - * @param string|null $dijit - * @return string - */ - protected function _createLayoutContainer($id, $content, array $params, array $attribs, $dijit = null) - { - $attribs['id'] = $id; - $attribs = $this->_prepareDijit($attribs, $params, 'layout', $dijit); - - $nodeType = $this->getRootNode(); - $html = '<' . $nodeType . $this->_htmlAttribs($attribs) . '>' - . $content - . "\n"; - - return $html; - } - - /** - * Create HTML representation of a dijit form element - * - * @param string $id - * @param string $value - * @param array $params - * @param array $attribs - * @param string|null $dijit - * @return string - */ - public function _createFormElement($id, $value, array $params, array $attribs, $dijit = null) - { - if (!array_key_exists('id', $attribs)) { - $attribs['id'] = $id; - } - $attribs['name'] = $id; - $attribs['value'] = (string) $value; - $attribs['type'] = $this->_elementType; - - $attribs = $this->_prepareDijit($attribs, $params, 'element', $dijit); - - $html = '_htmlAttribs($attribs) - . $this->getClosingBracket(); - return $html; - } - - /** - * Merge attributes and parameters - * - * Also sets up requires - * - * @param array $attribs - * @param array $params - * @param string $type - * @param string $dijit Dijit type to use (otherwise, pull from $_dijit) - * @return array - */ - protected function _prepareDijit(array $attribs, array $params, $type, $dijit = null) - { - $this->dojo->requireModule($this->_module); - - switch ($type) { - case 'layout': - $stripParams = array('id'); - break; - case 'element': - $stripParams = array('id', 'name', 'value', 'type'); - foreach (array('checked', 'disabled', 'readonly') as $attrib) { - if (array_key_exists($attrib, $attribs)) { - if ($attribs[$attrib]) { - $attribs[$attrib] = $attrib; - } else { - unset($attribs[$attrib]); - } - } - } - break; - case 'textarea': - $stripParams = array('id', 'name', 'type', 'degrade'); - break; - default: - } - - foreach ($stripParams as $param) { - if (array_key_exists($param, $params)) { - unset($params[$param]); - } - } - - // Normalize constraints, if present - foreach ($this->_jsonParams as $param) { - if (array_key_exists($param, $params)) { - #require_once 'Zend/Json.php'; - - if (is_array($params[$param])) { - $values = array(); - foreach ($params[$param] as $key => $value) { - if (!is_scalar($value)) { - continue; - } - $values[$key] = $value; - } - } elseif (is_string($params[$param])) { - $values = (array) $params[$param]; - } else { - $values = array(); - } - $values = Zend_Json::encode($values); - if ($this->_useDeclarative()) { - $values = str_replace('"', "'", $values); - } - $params[$param] = $values; - } - } - - $dijit = (null === $dijit) ? $this->_dijit : $dijit; - if ($this->_useDeclarative()) { - $attribs = array_merge($attribs, $params); - if (isset($attribs['required'])) { - $attribs['required'] = ($attribs['required']) ? 'true' : 'false'; - } - $attribs['dojoType'] = $dijit; - } elseif (!$this->_useProgrammaticNoScript()) { - $this->_createDijit($dijit, $attribs['id'], $params); - } - - return $attribs; - } - - /** - * Create a dijit programmatically - * - * @param string $dijit - * @param string $id - * @param array $params - * @return void - */ - protected function _createDijit($dijit, $id, array $params) - { - $params['dojoType'] = $dijit; - - array_walk_recursive($params, array($this, '_castBoolToString')); - - $this->dojo->setDijit($id, $params); - } - - /** - * Cast a boolean to a string value - * - * @param mixed $item - * @param string $key - * @return void - */ - protected function _castBoolToString(&$item, $key) - { - if (!is_bool($item)) { - return; - } - $item = ($item) ? "true" : "false"; - } - - /** - * Render a hidden element to hold a value - * - * @param string $id - * @param string|int|float $value - * @return string - */ - protected function _renderHiddenElement($id, $value) - { - $hiddenAttribs = array( - 'name' => $id, - 'value' => (string) $value, - 'type' => 'hidden', - ); - return '_htmlAttribs($hiddenAttribs) . $this->getClosingBracket(); - } - - /** - * Create JS function for retrieving parent form - * - * @return void - */ - protected function _createGetParentFormFunction() - { - $function =<<dojo->addJavascript($function); - } -} diff --git a/library/Zend/Dojo/View/Helper/DijitContainer.php b/library/Zend/Dojo/View/Helper/DijitContainer.php deleted file mode 100644 index 35f0f1a11f..0000000000 --- a/library/Zend/Dojo/View/Helper/DijitContainer.php +++ /dev/null @@ -1,92 +0,0 @@ -_captureLock)) { - #require_once 'Zend/Dojo/View/Exception.php'; - throw new Zend_Dojo_View_Exception(sprintf('Lock already exists for id "%s"', $id)); - } - - $this->_captureLock[$id] = true; - $this->_captureInfo[$id] = array( - 'params' => $params, - 'attribs' => $attribs, - ); - - ob_start(); - return; - } - - /** - * Finish capturing content for layout container - * - * @param string $id - * @return string - */ - public function captureEnd($id) - { - if (!array_key_exists($id, $this->_captureLock)) { - #require_once 'Zend/Dojo/View/Exception.php'; - throw new Zend_Dojo_View_Exception(sprintf('No capture lock exists for id "%s"; nothing to capture', $id)); - } - - $content = ob_get_clean(); - extract($this->_captureInfo[$id]); - unset($this->_captureLock[$id], $this->_captureInfo[$id]); - return $this->_createLayoutContainer($id, $content, $params, $attribs); - } -} diff --git a/library/Zend/Dojo/View/Helper/Dojo.php b/library/Zend/Dojo/View/Helper/Dojo.php deleted file mode 100644 index e05e4b8450..0000000000 --- a/library/Zend/Dojo/View/Helper/Dojo.php +++ /dev/null @@ -1,176 +0,0 @@ -_container = $registry[__CLASS__]; - } - - /** - * Set view object - * - * @param Zend_Dojo_View_Interface $view - * @return void - */ - public function setView(Zend_View_Interface $view) - { - $this->view = $view; - $this->_container->setView($view); - } - - /** - * Return dojo container - * - * @return Zend_Dojo_View_Helper_Dojo_Container - */ - public function dojo() - { - return $this->_container; - } - - /** - * Proxy to container methods - * - * @param string $method - * @param array $args - * @return mixed - * @throws Zend_Dojo_View_Exception For invalid method calls - */ - public function __call($method, $args) - { - if (!method_exists($this->_container, $method)) { - #require_once 'Zend/Dojo/View/Exception.php'; - throw new Zend_Dojo_View_Exception(sprintf('Invalid method "%s" called on dojo view helper', $method)); - } - - return call_user_func_array(array($this->_container, $method), $args); - } - - /** - * Set whether or not dijits should be created declaratively - * - * @return void - */ - public static function setUseDeclarative() - { - self::$_useProgrammatic = false; - } - - /** - * Set whether or not dijits should be created programmatically - * - * Optionally, specifiy whether or not dijit helpers should generate the - * programmatic dojo. - * - * @param int $style - * @return void - */ - public static function setUseProgrammatic($style = self::PROGRAMMATIC_SCRIPT) - { - if (!in_array($style, array(self::PROGRAMMATIC_SCRIPT, self::PROGRAMMATIC_NOSCRIPT))) { - $style = self::PROGRAMMATIC_SCRIPT; - } - self::$_useProgrammatic = $style; - } - - /** - * Should dijits be created declaratively? - * - * @return bool - */ - public static function useDeclarative() - { - return (false === self::$_useProgrammatic); - } - - /** - * Should dijits be created programmatically? - * - * @return bool - */ - public static function useProgrammatic() - { - return (false !== self::$_useProgrammatic); - } - - /** - * Should dijits be created programmatically but without scripts? - * - * @return bool - */ - public static function useProgrammaticNoScript() - { - return (self::PROGRAMMATIC_NOSCRIPT === self::$_useProgrammatic); - } -} diff --git a/library/Zend/Dojo/View/Helper/Dojo/Container.php b/library/Zend/Dojo/View/Helper/Dojo/Container.php deleted file mode 100644 index 6a6cfe439c..0000000000 --- a/library/Zend/Dojo/View/Helper/Dojo/Container.php +++ /dev/null @@ -1,1205 +0,0 @@ -view = $view; - } - - /** - * Enable dojo - * - * @return Zend_Dojo_View_Helper_Dojo_Container - */ - public function enable() - { - $this->_enabled = true; - return $this; - } - - /** - * Disable dojo - * - * @return Zend_Dojo_View_Helper_Dojo_Container - */ - public function disable() - { - $this->_enabled = false; - return $this; - } - - /** - * Is dojo enabled? - * - * @return bool - */ - public function isEnabled() - { - return $this->_enabled; - } - - /** - * Add options for the Dojo Container to use - * - * @param array|Zend_Config Array or Zend_Config object with options to use - * @return Zend_Dojo_View_Helper_Dojo_Container - */ - public function setOptions($options) - { - if($options instanceof Zend_Config) { - $options = $options->toArray(); - } - - foreach($options as $key => $value) { - $key = strtolower($key); - switch($key) { - case 'requiremodules': - $this->requireModule($value); - break; - case 'modulepaths': - foreach($value as $module => $path) { - $this->registerModulePath($module, $path); - } - break; - case 'layers': - $value = (array) $value; - foreach($value as $layer) { - $this->addLayer($layer); - } - break; - case 'cdnbase': - $this->setCdnBase($value); - break; - case 'cdnversion': - $this->setCdnVersion($value); - break; - case 'cdndojopath': - $this->setCdnDojoPath($value); - break; - case 'localpath': - $this->setLocalPath($value); - break; - case 'djconfig': - $this->setDjConfig($value); - break; - case 'stylesheetmodules': - $value = (array) $value; - foreach($value as $module) { - $this->addStylesheetModule($module); - } - break; - case 'stylesheets': - $value = (array) $value; - foreach($value as $stylesheet) { - $this->addStylesheet($stylesheet); - } - break; - case 'registerdojostylesheet': - $this->registerDojoStylesheet($value); - break; - case 'enable': - if($value) { - $this->enable(); - } else { - $this->disable(); - } - } - } - - return $this; - } - - /** - * Specify one or multiple modules to require - * - * @param string|array $modules - * @return Zend_Dojo_View_Helper_Dojo_Container - */ - public function requireModule($modules) - { - if (!is_string($modules) && !is_array($modules)) { - #require_once 'Zend/Dojo/View/Exception.php'; - throw new Zend_Dojo_View_Exception('Invalid module name specified; must be a string or an array of strings'); - } - - $modules = (array) $modules; - - foreach ($modules as $mod) { - if (!preg_match('/^[a-z][a-z0-9._-]+$/i', $mod)) { - #require_once 'Zend/Dojo/View/Exception.php'; - throw new Zend_Dojo_View_Exception(sprintf('Module name specified, "%s", contains invalid characters', (string) $mod)); - } - - if (!in_array($mod, $this->_modules)) { - $this->_modules[] = $mod; - } - } - - return $this; - } - - /** - * Retrieve list of modules to require - * - * @return array - */ - public function getModules() - { - return $this->_modules; - } - - /** - * Register a module path - * - * @param string $module The module to register a path for - * @param string $path The path to register for the module - * @return Zend_Dojo_View_Helper_Dojo_Container - */ - public function registerModulePath($module, $path) - { - $path = (string) $path; - if (!in_array($module, $this->_modulePaths)) { - $this->_modulePaths[$module] = $path; - } - - return $this; - } - - /** - * List registered module paths - * - * @return array - */ - public function getModulePaths() - { - return $this->_modulePaths; - } - - /** - * Add layer (custom build) path - * - * @param string $path - * @return Zend_Dojo_View_Helper_Dojo_Container - */ - public function addLayer($path) - { - $path = (string) $path; - if (!in_array($path, $this->_layers)) { - $this->_layers[] = $path; - } - - return $this; - } - - /** - * Get registered layers - * - * @return array - */ - public function getLayers() - { - return $this->_layers; - } - - /** - * Remove a registered layer - * - * @param string $path - * @return Zend_Dojo_View_Helper_Dojo_Container - */ - public function removeLayer($path) - { - $path = (string) $path; - $layers = array_flip($this->_layers); - if (array_key_exists($path, $layers)) { - unset($layers[$path]); - $this->_layers = array_keys($layers); - } - return $this; - } - - /** - * Clear all registered layers - * - * @return Zend_Dojo_View_Helper_Dojo_Container - */ - public function clearLayers() - { - $this->_layers = array(); - return $this; - } - - /** - * Set CDN base path - * - * @param string $url - * @return Zend_Dojo_View_Helper_Dojo_Container - */ - public function setCdnBase($url) - { - $this->_cdnBase = (string) $url; - return $this; - } - - /** - * Return CDN base URL - * - * @return string - */ - public function getCdnBase() - { - return $this->_cdnBase; - } - - /** - * Use CDN, using version specified - * - * @param string $version - * @return Zend_Dojo_View_Helper_Dojo_Container - */ - public function setCdnVersion($version = null) - { - $this->enable(); - if (preg_match('/^[1-9]\.[0-9]{1,2}(\.[0-9]{1,2})?$/', $version)) { - $this->_cdnVersion = $version; - } - return $this; - } - - /** - * Get CDN version - * - * @return string - */ - public function getCdnVersion() - { - return $this->_cdnVersion; - } - - /** - * Set CDN path to dojo (relative to CDN base + version) - * - * @param string $path - * @return Zend_Dojo_View_Helper_Dojo_Container - */ - public function setCdnDojoPath($path) - { - $this->_cdnDojoPath = (string) $path; - return $this; - } - - /** - * Get CDN path to dojo (relative to CDN base + version) - * - * @return string - */ - public function getCdnDojoPath() - { - return $this->_cdnDojoPath; - } - - /** - * Are we using the CDN? - * - * @return bool - */ - public function useCdn() - { - return !$this->useLocalPath(); - } - - /** - * Set path to local dojo - * - * @param string $path - * @return Zend_Dojo_View_Helper_Dojo_Container - */ - public function setLocalPath($path) - { - $this->enable(); - $this->_localPath = (string) $path; - return $this; - } - - /** - * Get local path to dojo - * - * @return string - */ - public function getLocalPath() - { - return $this->_localPath; - } - - /** - * Are we using a local path? - * - * @return bool - */ - public function useLocalPath() - { - return (null === $this->_localPath) ? false : true; - } - - /** - * Set Dojo configuration - * - * @param string $option - * @param mixed $value - * @return Zend_Dojo_View_Helper_Dojo_Container - */ - public function setDjConfig(array $config) - { - $this->_djConfig = $config; - return $this; - } - - /** - * Set Dojo configuration option - * - * @param string $option - * @param mixed $value - * @return Zend_Dojo_View_Helper_Dojo_Container - */ - public function setDjConfigOption($option, $value) - { - $option = (string) $option; - $this->_djConfig[$option] = $value; - return $this; - } - - /** - * Retrieve dojo configuration values - * - * @return array - */ - public function getDjConfig() - { - return $this->_djConfig; - } - - /** - * Get dojo configuration value - * - * @param string $option - * @param mixed $default - * @return mixed - */ - public function getDjConfigOption($option, $default = null) - { - $option = (string) $option; - if (array_key_exists($option, $this->_djConfig)) { - return $this->_djConfig[$option]; - } - return $default; - } - - /** - * Add a stylesheet by module name - * - * @param string $module - * @return Zend_Dojo_View_Helper_Dojo_Container - */ - public function addStylesheetModule($module) - { - if (!preg_match('/^[a-z0-9]+\.[a-z0-9_-]+(\.[a-z0-9_-]+)*$/i', $module)) { - #require_once 'Zend/Dojo/View/Exception.php'; - throw new Zend_Dojo_View_Exception('Invalid stylesheet module specified'); - } - if (!in_array($module, $this->_stylesheetModules)) { - $this->_stylesheetModules[] = $module; - } - return $this; - } - - /** - * Get all stylesheet modules currently registered - * - * @return array - */ - public function getStylesheetModules() - { - return $this->_stylesheetModules; - } - - /** - * Add a stylesheet - * - * @param string $path - * @return Zend_Dojo_View_Helper_Dojo_Container - */ - public function addStylesheet($path) - { - $path = (string) $path; - if (!in_array($path, $this->_stylesheets)) { - $this->_stylesheets[] = (string) $path; - } - return $this; - } - - /** - * Register the dojo.css stylesheet? - * - * With no arguments, returns the status of the flag; with arguments, sets - * the flag and returns the object. - * - * @param null|bool $flag - * @return Zend_Dojo_View_Helper_Dojo_Container|bool - */ - public function registerDojoStylesheet($flag = null) - { - if (null === $flag) { - return $this->_registerDojoStylesheet; - } - - $this->_registerDojoStylesheet = (bool) $flag; - return $this; - } - - /** - * Retrieve registered stylesheets - * - * @return array - */ - public function getStylesheets() - { - return $this->_stylesheets; - } - - /** - * Add a script to execute onLoad - * - * dojo.addOnLoad accepts: - * - function name - * - lambda - * - * @param string $callback Lambda - * @return Zend_Dojo_View_Helper_Dojo_Container - */ - public function addOnLoad($callback) - { - if (!in_array($callback, $this->_onLoadActions, true)) { - $this->_onLoadActions[] = $callback; - } - return $this; - } - - /** - * Prepend an onLoad event to the list of onLoad actions - * - * @param string $callback Lambda - * @return Zend_Dojo_View_Helper_Dojo_Container - */ - public function prependOnLoad($callback) - { - if (!in_array($callback, $this->_onLoadActions, true)) { - array_unshift($this->_onLoadActions, $callback); - } - return $this; - } - - /** - * Retrieve all registered onLoad actions - * - * @return array - */ - public function getOnLoadActions() - { - return $this->_onLoadActions; - } - - /** - * Start capturing routines to run onLoad - * - * @return bool - */ - public function onLoadCaptureStart() - { - if ($this->_captureLock) { - #require_once 'Zend/Dojo/View/Exception.php'; - throw new Zend_Dojo_View_Exception('Cannot nest onLoad captures'); - } - - $this->_captureLock = true; - ob_start(); - return; - } - - /** - * Stop capturing routines to run onLoad - * - * @return bool - */ - public function onLoadCaptureEnd() - { - $data = ob_get_clean(); - $this->_captureLock = false; - - $this->addOnLoad($data); - return true; - } - - /** - * Add a programmatic dijit - * - * @param string $id - * @param array $params - * @return Zend_Dojo_View_Helper_Dojo_Container - */ - public function addDijit($id, array $params) - { - if (array_key_exists($id, $this->_dijits)) { - #require_once 'Zend/Dojo/View/Exception.php'; - throw new Zend_Dojo_View_Exception(sprintf('Duplicate dijit with id "%s" already registered', $id)); - } - - $this->_dijits[$id] = array( - 'id' => $id, - 'params' => $params, - ); - - return $this; - } - - /** - * Set a programmatic dijit (overwrites) - * - * @param string $id - * @param array $params - * @return Zend_Dojo_View_Helper_Dojo_Container - */ - public function setDijit($id, array $params) - { - $this->removeDijit($id); - return $this->addDijit($id, $params); - } - - /** - * Add multiple dijits at once - * - * Expects an array of id => array $params pairs - * - * @param array $dijits - * @return Zend_Dojo_View_Helper_Dojo_Container - */ - public function addDijits(array $dijits) - { - foreach ($dijits as $id => $params) { - $this->addDijit($id, $params); - } - return $this; - } - - /** - * Set multiple dijits at once (overwrites) - * - * Expects an array of id => array $params pairs - * - * @param array $dijits - * @return Zend_Dojo_View_Helper_Dojo_Container - */ - public function setDijits(array $dijits) - { - $this->clearDijits(); - return $this->addDijits($dijits); - } - - /** - * Is the given programmatic dijit already registered? - * - * @param string $id - * @return bool - */ - public function hasDijit($id) - { - return array_key_exists($id, $this->_dijits); - } - - /** - * Retrieve a dijit by id - * - * @param string $id - * @return array|null - */ - public function getDijit($id) - { - if ($this->hasDijit($id)) { - return $this->_dijits[$id]['params']; - } - return null; - } - - /** - * Retrieve all dijits - * - * Returns dijits as an array of assoc arrays - * - * @return array - */ - public function getDijits() - { - return array_values($this->_dijits); - } - - /** - * Remove a programmatic dijit if it exists - * - * @param string $id - * @return Zend_Dojo_View_Helper_Dojo_Container - */ - public function removeDijit($id) - { - if (array_key_exists($id, $this->_dijits)) { - unset($this->_dijits[$id]); - } - - return $this; - } - - /** - * Clear all dijits - * - * @return Zend_Dojo_View_Helper_Dojo_Container - */ - public function clearDijits() - { - $this->_dijits = array(); - return $this; - } - - /** - * Render dijits as JSON structure - * - * @return string - */ - public function dijitsToJson() - { - #require_once 'Zend/Json.php'; - return Zend_Json::encode($this->getDijits(), false, array('enableJsonExprFinder' => true)); - } - - /** - * Create dijit loader functionality - * - * @return void - */ - public function registerDijitLoader() - { - if (!$this->_dijitLoaderRegistered) { - $js =<<requireModule('dojo.parser'); - $this->_addZendLoad($js); - $this->addJavascript('var zendDijits = ' . $this->dijitsToJson() . ';'); - $this->_dijitLoaderRegistered = true; - } - } - - /** - * Add arbitrary javascript to execute in dojo JS container - * - * @param string $js - * @return Zend_Dojo_View_Helper_Dojo_Container - */ - public function addJavascript($js) - { - $js = trim($js); - if (!in_array(substr($js, -1), array(';', '}'))) { - $js .= ';'; - } - - if (in_array($js, $this->_javascriptStatements)) { - return $this; - } - - $this->_javascriptStatements[] = $js; - return $this; - } - - /** - * Return all registered javascript statements - * - * @return array - */ - public function getJavascript() - { - return $this->_javascriptStatements; - } - - /** - * Clear arbitrary javascript stack - * - * @return Zend_Dojo_View_Helper_Dojo_Container - */ - public function clearJavascript() - { - $this->_javascriptStatements = array(); - return $this; - } - - /** - * Capture arbitrary javascript to include in dojo script - * - * @return void - */ - public function javascriptCaptureStart() - { - if ($this->_captureLock) { - #require_once 'Zend/Dojo/View/Exception.php'; - throw new Zend_Dojo_View_Exception('Cannot nest captures'); - } - - $this->_captureLock = true; - ob_start(); - return; - } - - /** - * Finish capturing arbitrary javascript to include in dojo script - * - * @return true - */ - public function javascriptCaptureEnd() - { - $data = ob_get_clean(); - $this->_captureLock = false; - - $this->addJavascript($data); - return true; - } - - /** - * String representation of dojo environment - * - * @return string - */ - public function __toString() - { - if (!$this->isEnabled()) { - return ''; - } - - $this->_isXhtml = $this->view->doctype()->isXhtml(); - - if (Zend_Dojo_View_Helper_Dojo::useDeclarative()) { - if (null === $this->getDjConfigOption('parseOnLoad')) { - $this->setDjConfigOption('parseOnLoad', true); - } - } - - if (!empty($this->_dijits)) { - $this->registerDijitLoader(); - } - - $html = $this->_renderStylesheets() . PHP_EOL - . $this->_renderDjConfig() . PHP_EOL - . $this->_renderDojoScriptTag() . PHP_EOL - . $this->_renderLayers() . PHP_EOL - . $this->_renderExtras(); - return $html; - } - - /** - * Retrieve local path to dojo resources for building relative paths - * - * @return string - */ - protected function _getLocalRelativePath() - { - if (null === $this->_localRelativePath) { - $localPath = $this->getLocalPath(); - $localPath = preg_replace('|[/\\\\]dojo[/\\\\]dojo.js[^/\\\\]*$|i', '', $localPath); - $this->_localRelativePath = $localPath; - } - return $this->_localRelativePath; - } - - /** - * Render dojo stylesheets - * - * @return string - */ - protected function _renderStylesheets() - { - if ($this->useCdn()) { - $base = $this->getCdnBase() - . $this->getCdnVersion(); - } else { - $base = $this->_getLocalRelativePath(); - } - - $registeredStylesheets = $this->getStylesheetModules(); - foreach ($registeredStylesheets as $stylesheet) { - $themeName = substr($stylesheet, strrpos($stylesheet, '.') + 1); - $stylesheet = str_replace('.', '/', $stylesheet); - $stylesheets[] = $base . '/' . $stylesheet . '/' . $themeName . '.css'; - } - - foreach ($this->getStylesheets() as $stylesheet) { - $stylesheets[] = $stylesheet; - } - - if ($this->_registerDojoStylesheet) { - $stylesheets[] = $base . '/dojo/resources/dojo.css'; - } - - if (empty($stylesheets)) { - return ''; - } - - $stylesheets = array_reverse($stylesheets); - $style = ''; - - return $style; - } - - /** - * Render DjConfig values - * - * @return string - */ - protected function _renderDjConfig() - { - $djConfigValues = $this->getDjConfig(); - if (empty($djConfigValues)) { - return ''; - } - - #require_once 'Zend/Json.php'; - $scriptTag = ''; - - return $scriptTag; - } - - /** - * Render dojo script tag - * - * Renders Dojo script tag by utilizing either local path provided or the - * CDN. If any djConfig values were set, they will be serialized and passed - * with that attribute. - * - * @return string - */ - protected function _renderDojoScriptTag() - { - if ($this->useCdn()) { - $source = $this->getCdnBase() - . $this->getCdnVersion() - . $this->getCdnDojoPath(); - } else { - $source = $this->getLocalPath(); - } - - $scriptTag = ''; - return $scriptTag; - } - - /** - * Render layers (custom builds) as script tags - * - * @return string - */ - protected function _renderLayers() - { - $layers = $this->getLayers(); - if (empty($layers)) { - return ''; - } - - $enc = 'UTF-8'; - if ($this->view instanceof Zend_View_Interface - && method_exists($this->view, 'getEncoding') - ) { - $enc = $this->view->getEncoding(); - } - - $html = array(); - foreach ($layers as $path) { - $html[] = sprintf( - '', - htmlspecialchars($path, ENT_QUOTES, $enc) - ); - } - - return implode("\n", $html); - } - - /** - * Render dojo module paths and requires - * - * @return string - */ - protected function _renderExtras() - { - $js = array(); - $modulePaths = $this->getModulePaths(); - if (!empty($modulePaths)) { - foreach ($modulePaths as $module => $path) { - $js[] = 'dojo.registerModulePath("' . $this->view->escape($module) . '", "' . $this->view->escape($path) . '");'; - } - } - - $modules = $this->getModules(); - if (!empty($modules)) { - foreach ($modules as $module) { - $js[] = 'dojo.require("' . $this->view->escape($module) . '");'; - } - } - - $onLoadActions = array(); - // Get Zend specific onLoad actions; these will always be first to - // ensure that dijits are created in the correct order - foreach ($this->_getZendLoadActions() as $callback) { - $onLoadActions[] = 'dojo.addOnLoad(' . $callback . ');'; - } - - // Get all other onLoad actions - foreach ($this->getOnLoadActions() as $callback) { - $onLoadActions[] = 'dojo.addOnLoad(' . $callback . ');'; - } - - $javascript = implode("\n ", $this->getJavascript()); - - $content = ''; - if (!empty($js)) { - $content .= implode("\n ", $js) . "\n"; - } - - if (!empty($onLoadActions)) { - $content .= implode("\n ", $onLoadActions) . "\n"; - } - - if (!empty($javascript)) { - $content .= $javascript . "\n"; - } - - if (preg_match('/^\s*$/s', $content)) { - return ''; - } - - $html = ''; - return $html; - } - - /** - * Add an onLoad action related to ZF dijit creation - * - * This method is public, but prefixed with an underscore to indicate that - * it should not normally be called by userland code. It is pertinent to - * ensuring that the correct order of operations occurs during dijit - * creation. - * - * @param string $callback - * @return Zend_Dojo_View_Helper_Dojo_Container - */ - public function _addZendLoad($callback) - { - if (!in_array($callback, $this->_zendLoadActions, true)) { - $this->_zendLoadActions[] = $callback; - } - return $this; - } - - /** - * Retrieve all ZF dijit callbacks - * - * @return array - */ - public function _getZendLoadActions() - { - return $this->_zendLoadActions; - } -} diff --git a/library/Zend/Dojo/View/Helper/Editor.php b/library/Zend/Dojo/View/Helper/Editor.php deleted file mode 100644 index 1430a02fe3..0000000000 --- a/library/Zend/Dojo/View/Helper/Editor.php +++ /dev/null @@ -1,199 +0,0 @@ - 'LinkDialog', - 'insertImage' => 'LinkDialog', - 'fontName' => 'FontChoice', - 'fontSize' => 'FontChoice', - 'formatBlock' => 'FontChoice', - 'foreColor' => 'TextColor', - 'hiliteColor' => 'TextColor', - 'enterKeyHandling' => 'EnterKeyHandling', - 'fullScreen' => 'FullScreen', - 'newPage' => 'NewPage', - 'print' => 'Print', - 'tabIndent' => 'TabIndent', - 'toggleDir' => 'ToggleDir', - 'viewSource' => 'ViewSource' - ); - - /** - * JSON-encoded parameters - * @var array - */ - protected $_jsonParams = array('captureEvents', 'events', 'plugins', 'extraPlugins'); - - /** - * dijit.Editor - * - * @param string $id - * @param string $value - * @param array $params - * @param array $attribs - * @return string - */ - public function editor($id, $value = null, $params = array(), $attribs = array()) - { - if (isset($params['plugins'])) { - foreach ($this->_getRequiredModules($params['plugins']) as $module) { - $this->dojo->requireModule($module); - } - } - - // Previous versions allowed specifying "degrade" to allow using a - // textarea instead of a div -- but this is insecure. Removing the - // parameter if set to prevent its injection in the dijit. - if (isset($params['degrade'])) { - unset($params['degrade']); - } - - $hiddenName = $id; - if (array_key_exists('id', $attribs)) { - $hiddenId = $attribs['id']; - } else { - $hiddenId = $hiddenName; - } - $hiddenId = $this->_normalizeId($hiddenId); - - $textareaName = $this->_normalizeEditorName($hiddenName); - $textareaId = $hiddenId . '-Editor'; - - $hiddenAttribs = array( - 'id' => $hiddenId, - 'name' => $hiddenName, - 'value' => $value, - 'type' => 'hidden', - ); - $attribs['id'] = $textareaId; - - $this->_createGetParentFormFunction(); - $this->_createEditorOnSubmit($hiddenId, $textareaId); - - $attribs = $this->_prepareDijit($attribs, $params, 'textarea'); - - $html = '_htmlAttribs($attribs) . '>' - . $value - . "\n"; - - // Embed a textarea in a