8 * This source file is subject to the new BSD license that is bundled
9 * with this package in the file LICENSE.txt.
10 * It is also available through the world-wide-web at this URL:
11 * http://framework.zend.com/license/new-bsd
12 * If you did not receive a copy of the license and are unable to
13 * obtain it through the world-wide-web, please send an email
14 * to license@zend.com so we can send you a copy immediately.
19 * @copyright Copyright (c) 2005-2010 Zend Technologies USA Inc. (http://www.zend.com)
20 * @license http://framework.zend.com/license/new-bsd New BSD License
27 require_once 'Zend/Gdata/App/Feed.php';
30 * Zend_Gdata_Http_Client
32 require_once 'Zend/Http/Client.php';
37 require_once 'Zend/Version.php';
40 * Zend_Gdata_App_MediaSource
42 require_once 'Zend/Gdata/App/MediaSource.php';
45 * Provides Atom Publishing Protocol (APP) functionality. This class and all
46 * other components of Zend_Gdata_App are designed to work independently from
47 * other Zend_Gdata components in order to interact with generic APP services.
52 * @copyright Copyright (c) 2005-2010 Zend Technologies USA Inc. (http://www.zend.com)
53 * @license http://framework.zend.com/license/new-bsd New BSD License
58 /** Default major protocol version.
60 * @see _majorProtocolVersion
62 const DEFAULT_MAJOR_PROTOCOL_VERSION = 1;
64 /** Default minor protocol version.
66 * @see _minorProtocolVersion
68 const DEFAULT_MINOR_PROTOCOL_VERSION = null;
71 * Client object used to communicate
73 * @var Zend_Http_Client
75 protected $_httpClient;
78 * Client object used to communicate in static context
80 * @var Zend_Http_Client
82 protected static $_staticHttpClient = null;
85 * Override HTTP PUT and DELETE request methods?
89 protected static $_httpMethodOverride = false;
92 * Enable gzipped responses?
96 protected static $_gzipEnabled = false;
99 * Use verbose exception messages. In the case of HTTP errors,
100 * use the body of the HTTP response in the exception message.
104 protected static $_verboseExceptionMessages = true;
107 * Default URI to which to POST.
111 protected $_defaultPostUri = null;
114 * Packages to search for classes when using magic __call method, in order.
118 protected $_registeredPackages = array(
119 'Zend_Gdata_App_Extension',
123 * Maximum number of redirects to follow during HTTP operations
127 protected static $_maxRedirects = 5;
130 * Indicates the major protocol version that should be used.
131 * At present, recognized values are either 1 or 2. However, any integer
132 * value >= 1 is considered valid.
134 * Under most circumtances, this will be automatically set by
135 * Zend_Gdata_App subclasses.
137 * @see setMajorProtocolVersion()
138 * @see getMajorProtocolVersion()
140 protected $_majorProtocolVersion;
143 * Indicates the minor protocol version that should be used. Can be set
144 * to either an integer >= 0, or NULL if no minor version should be sent
147 * At present, this field is not used by any Google services, but may be
148 * used in the future.
150 * Under most circumtances, this will be automatically set by
151 * Zend_Gdata_App subclasses.
153 * @see setMinorProtocolVersion()
154 * @see getMinorProtocolVersion()
156 protected $_minorProtocolVersion;
159 * Whether we want to use XML to object mapping when fetching data.
163 protected $_useObjectMapping = true;
166 * Create Gdata object
168 * @param Zend_Http_Client $client
169 * @param string $applicationId
171 public function __construct($client = null, $applicationId = 'MyCompany-MyApp-1.0')
173 $this->setHttpClient($client, $applicationId);
174 // Set default protocol version. Subclasses should override this as
175 // needed once a given service supports a new version.
176 $this->setMajorProtocolVersion(self::DEFAULT_MAJOR_PROTOCOL_VERSION);
177 $this->setMinorProtocolVersion(self::DEFAULT_MINOR_PROTOCOL_VERSION);
181 * Adds a Zend Framework package to the $_registeredPackages array.
182 * This array is searched when using the magic __call method below
183 * to instantiante new objects.
185 * @param string $name The name of the package (eg Zend_Gdata_App)
188 public function registerPackage($name)
190 array_unshift($this->_registeredPackages, $name);
194 * Retrieve feed as string or object
196 * @param string $uri The uri from which to retrieve the feed
197 * @param string $className The class which is used as the return type
198 * @return string|Zend_Gdata_App_Feed Returns string only if the object
199 * mapping has been disabled explicitly
200 * by passing false to the
201 * useObjectMapping() function.
203 public function getFeed($uri, $className='Zend_Gdata_App_Feed')
205 return $this->importUrl($uri, $className, null);
209 * Retrieve entry as string or object
212 * @param string $className The class which is used as the return type
213 * @return string|Zend_Gdata_App_Entry Returns string only if the object
214 * mapping has been disabled explicitly
215 * by passing false to the
216 * useObjectMapping() function.
218 public function getEntry($uri, $className='Zend_Gdata_App_Entry')
220 return $this->importUrl($uri, $className, null);
224 * Get the Zend_Http_Client object used for communication
226 * @return Zend_Http_Client
228 public function getHttpClient()
230 return $this->_httpClient;
234 * Set the Zend_Http_Client object used for communication
236 * @param Zend_Http_Client $client The client to use for communication
237 * @throws Zend_Gdata_App_HttpException
238 * @return Zend_Gdata_App Provides a fluent interface
240 public function setHttpClient($client,
241 $applicationId = 'MyCompany-MyApp-1.0')
243 if ($client === null) {
244 $client = new Zend_Http_Client();
246 if (!$client instanceof Zend_Http_Client) {
247 require_once 'Zend/Gdata/App/HttpException.php';
248 throw new Zend_Gdata_App_HttpException(
249 'Argument is not an instance of Zend_Http_Client.');
251 $userAgent = $applicationId . ' Zend_Framework_Gdata/' .
252 Zend_Version::VERSION;
253 $client->setHeaders('User-Agent', $userAgent);
254 $client->setConfig(array(
255 'strictredirects' => true
258 $this->_httpClient = $client;
259 self::setStaticHttpClient($client);
264 * Set the static HTTP client instance
266 * Sets the static HTTP client object to use for retrieving the feed.
268 * @param Zend_Http_Client $httpClient
271 public static function setStaticHttpClient(Zend_Http_Client $httpClient)
273 self::$_staticHttpClient = $httpClient;
278 * Gets the HTTP client object. If none is set, a new Zend_Http_Client will be used.
280 * @return Zend_Http_Client
282 public static function getStaticHttpClient()
284 if (!self::$_staticHttpClient instanceof Zend_Http_Client) {
285 $client = new Zend_Http_Client();
286 $userAgent = 'Zend_Framework_Gdata/' . Zend_Version::VERSION;
287 $client->setHeaders('User-Agent', $userAgent);
288 $client->setConfig(array(
289 'strictredirects' => true
292 self::$_staticHttpClient = $client;
294 return self::$_staticHttpClient;
298 * Toggle using POST instead of PUT and DELETE HTTP methods
300 * Some feed implementations do not accept PUT and DELETE HTTP
301 * methods, or they can't be used because of proxies or other
302 * measures. This allows turning on using POST where PUT and
303 * DELETE would normally be used; in addition, an
304 * X-Method-Override header will be sent with a value of PUT or
305 * DELETE as appropriate.
307 * @param boolean $override Whether to override PUT and DELETE with POST.
310 public static function setHttpMethodOverride($override = true)
312 self::$_httpMethodOverride = $override;
316 * Get the HTTP override state
320 public static function getHttpMethodOverride()
322 return self::$_httpMethodOverride;
326 * Toggle requesting gzip encoded responses
328 * @param boolean $enabled Whether or not to enable gzipped responses
331 public static function setGzipEnabled($enabled = false)
333 if ($enabled && !function_exists('gzinflate')) {
334 require_once 'Zend/Gdata/App/InvalidArgumentException.php';
335 throw new Zend_Gdata_App_InvalidArgumentException(
336 'You cannot enable gzipped responses if the zlib module ' .
337 'is not enabled in your PHP installation.');
340 self::$_gzipEnabled = $enabled;
344 * Get the HTTP override state
348 public static function getGzipEnabled()
350 return self::$_gzipEnabled;
354 * Get whether to use verbose exception messages
356 * In the case of HTTP errors, use the body of the HTTP response
357 * in the exception message.
361 public static function getVerboseExceptionMessages()
363 return self::$_verboseExceptionMessages;
367 * Set whether to use verbose exception messages
369 * In the case of HTTP errors, use the body of the HTTP response
370 * in the exception message.
372 * @param boolean $verbose Whether to use verbose exception messages
374 public static function setVerboseExceptionMessages($verbose)
376 self::$_verboseExceptionMessages = $verbose;
380 * Set the maximum number of redirects to follow during HTTP operations
382 * @param int $maxRedirects Maximum number of redirects to follow
385 public static function setMaxRedirects($maxRedirects)
387 self::$_maxRedirects = $maxRedirects;
391 * Get the maximum number of redirects to follow during HTTP operations
393 * @return int Maximum number of redirects to follow
395 public static function getMaxRedirects()
397 return self::$_maxRedirects;
401 * Set the major protocol version that should be used. Values < 1 will
402 * cause a Zend_Gdata_App_InvalidArgumentException to be thrown.
404 * @see _majorProtocolVersion
405 * @param int $value The major protocol version to use.
406 * @throws Zend_Gdata_App_InvalidArgumentException
408 public function setMajorProtocolVersion($value)
410 if (!($value >= 1)) {
411 require_once('Zend/Gdata/App/InvalidArgumentException.php');
412 throw new Zend_Gdata_App_InvalidArgumentException(
413 'Major protocol version must be >= 1');
415 $this->_majorProtocolVersion = $value;
419 * Get the major protocol version that is in use.
421 * @see _majorProtocolVersion
422 * @return int The major protocol version in use.
424 public function getMajorProtocolVersion()
426 return $this->_majorProtocolVersion;
430 * Set the minor protocol version that should be used. If set to NULL, no
431 * minor protocol version will be sent to the server. Values < 0 will
432 * cause a Zend_Gdata_App_InvalidArgumentException to be thrown.
434 * @see _minorProtocolVersion
435 * @param (int|NULL) $value The minor protocol version to use.
436 * @throws Zend_Gdata_App_InvalidArgumentException
438 public function setMinorProtocolVersion($value)
440 if (!($value >= 0)) {
441 require_once('Zend/Gdata/App/InvalidArgumentException.php');
442 throw new Zend_Gdata_App_InvalidArgumentException(
443 'Minor protocol version must be >= 0');
445 $this->_minorProtocolVersion = $value;
449 * Get the minor protocol version that is in use.
451 * @see _minorProtocolVersion
452 * @return (int|NULL) The major protocol version in use, or NULL if no
453 * minor version is specified.
455 public function getMinorProtocolVersion()
457 return $this->_minorProtocolVersion;
461 * Provides pre-processing for HTTP requests to APP services.
463 * 1. Checks the $data element and, if it's an entry, extracts the XML,
464 * multipart data, edit link (PUT,DELETE), etc.
465 * 2. If $data is a string, sets the default content-type header as
466 * 'application/atom+xml' if it's not already been set.
467 * 3. Adds a x-http-method override header and changes the HTTP method
468 * to 'POST' if necessary as per getHttpMethodOverride()
470 * @param string $method The HTTP method for the request - 'GET', 'POST',
472 * @param string $url The URL to which this request is being performed,
473 * or null if found in $data
474 * @param array $headers An associative array of HTTP headers for this
476 * @param mixed $data The Zend_Gdata_App_Entry or XML for the
477 * body of the request
478 * @param string $contentTypeOverride The override value for the
479 * content type of the request body
480 * @return array An associative array containing the determined
481 * 'method', 'url', 'data', 'headers', 'contentType'
483 public function prepareRequest($method,
487 $contentTypeOverride = null)
489 // As a convenience, if $headers is null, we'll convert it back to
491 if ($headers === null) {
496 $finalContentType = null;
498 $url = $this->_defaultPostUri;
501 if (is_string($data)) {
503 if ($contentTypeOverride === null) {
504 $finalContentType = 'application/atom+xml';
506 } elseif ($data instanceof Zend_Gdata_App_MediaEntry) {
507 $rawData = $data->encode();
508 if ($data->getMediaSource() !== null) {
509 $finalContentType = $rawData->getContentType();
510 $headers['MIME-version'] = '1.0';
511 $headers['Slug'] = $data->getMediaSource()->getSlug();
513 $finalContentType = 'application/atom+xml';
515 if ($method == 'PUT' || $method == 'DELETE') {
516 $editLink = $data->getEditLink();
517 if ($editLink != null && $url == null) {
518 $url = $editLink->getHref();
521 } elseif ($data instanceof Zend_Gdata_App_Entry) {
522 $rawData = $data->saveXML();
523 $finalContentType = 'application/atom+xml';
524 if ($method == 'PUT' || $method == 'DELETE') {
525 $editLink = $data->getEditLink();
526 if ($editLink != null) {
527 $url = $editLink->getHref();
530 } elseif ($data instanceof Zend_Gdata_App_MediaSource) {
531 $rawData = $data->encode();
532 if ($data->getSlug() !== null) {
533 $headers['Slug'] = $data->getSlug();
535 $finalContentType = $data->getContentType();
538 if ($method == 'DELETE') {
542 // Set an If-Match header if:
543 // - This isn't a DELETE
544 // - If this isn't a GET, the Etag isn't weak
545 // - A similar header (If-Match/If-None-Match) hasn't already been
547 if ($method != 'DELETE' && (
548 !array_key_exists('If-Match', $headers) &&
549 !array_key_exists('If-None-Match', $headers)
551 $allowWeak = $method == 'GET';
552 if ($ifMatchHeader = $this->generateIfMatchHeaderData(
553 $data, $allowWeak)) {
554 $headers['If-Match'] = $ifMatchHeader;
558 if ($method != 'POST' && $method != 'GET' && Zend_Gdata_App::getHttpMethodOverride()) {
559 $headers['x-http-method-override'] = $method;
562 $headers['x-http-method-override'] = null;
565 if ($contentTypeOverride != null) {
566 $finalContentType = $contentTypeOverride;
569 return array('method' => $method, 'url' => $url,
570 'data' => $rawData, 'headers' => $headers,
571 'contentType' => $finalContentType);
575 * Performs a HTTP request using the specified method
577 * @param string $method The HTTP method for the request - 'GET', 'POST',
579 * @param string $url The URL to which this request is being performed
580 * @param array $headers An associative array of HTTP headers
582 * @param string $body The body of the HTTP request
583 * @param string $contentType The value for the content type
584 * of the request body
585 * @param int $remainingRedirects Number of redirects to follow if request
587 * @return Zend_Http_Response The response object
589 public function performHttpRequest($method, $url, $headers = null,
590 $body = null, $contentType = null, $remainingRedirects = null)
592 require_once 'Zend/Http/Client/Exception.php';
593 if ($remainingRedirects === null) {
594 $remainingRedirects = self::getMaxRedirects();
596 if ($headers === null) {
599 // Append a Gdata version header if protocol v2 or higher is in use.
600 // (Protocol v1 does not use this header.)
601 $major = $this->getMajorProtocolVersion();
602 $minor = $this->getMinorProtocolVersion();
604 $headers['GData-Version'] = $major +
605 (($minor === null) ? '.' + $minor : '');
608 // check the overridden method
609 if (($method == 'POST' || $method == 'PUT') && $body === null &&
610 $headers['x-http-method-override'] != 'DELETE') {
611 require_once 'Zend/Gdata/App/InvalidArgumentException.php';
612 throw new Zend_Gdata_App_InvalidArgumentException(
613 'You must specify the data to post as either a ' .
614 'string or a child of Zend_Gdata_App_Entry');
617 require_once 'Zend/Gdata/App/InvalidArgumentException.php';
618 throw new Zend_Gdata_App_InvalidArgumentException(
619 'You must specify an URI to which to post.');
621 $headers['Content-Type'] = $contentType;
622 if (Zend_Gdata_App::getGzipEnabled()) {
623 // some services require the word 'gzip' to be in the user-agent
624 // header in addition to the accept-encoding header
625 if (strpos($this->_httpClient->getHeader('User-Agent'),
627 $headers['User-Agent'] =
628 $this->_httpClient->getHeader('User-Agent') . ' (gzip)';
630 $headers['Accept-encoding'] = 'gzip, deflate';
632 $headers['Accept-encoding'] = 'identity';
635 // Make sure the HTTP client object is 'clean' before making a request
636 // In addition to standard headers to reset via resetParameters(),
637 // also reset the Slug and If-Match headers
638 $this->_httpClient->resetParameters();
639 $this->_httpClient->setHeaders(array('Slug', 'If-Match'));
641 // Set the params for the new request to be performed
642 $this->_httpClient->setHeaders($headers);
643 $uri = Zend_Uri_Http::fromString($url);
644 preg_match("/^(.*?)(\?.*)?$/", $url, $matches);
645 $this->_httpClient->setUri($matches[1]);
646 $queryArray = $uri->getQueryAsArray();
647 foreach ($queryArray as $name => $value) {
648 $this->_httpClient->setParameterGet($name, $value);
652 $this->_httpClient->setConfig(array('maxredirects' => 0));
654 // Set the proper adapter if we are handling a streaming upload
655 $usingMimeStream = false;
656 $oldHttpAdapter = null;
658 if ($body instanceof Zend_Gdata_MediaMimeStream) {
659 $usingMimeStream = true;
660 $this->_httpClient->setRawDataStream($body, $contentType);
661 $oldHttpAdapter = $this->_httpClient->getAdapter();
663 if ($oldHttpAdapter instanceof Zend_Http_Client_Adapter_Proxy) {
664 require_once 'Zend/Gdata/HttpAdapterStreamingProxy.php';
665 $newAdapter = new Zend_Gdata_HttpAdapterStreamingProxy();
667 require_once 'Zend/Gdata/HttpAdapterStreamingSocket.php';
668 $newAdapter = new Zend_Gdata_HttpAdapterStreamingSocket();
670 $this->_httpClient->setAdapter($newAdapter);
672 $this->_httpClient->setRawData($body, $contentType);
676 $response = $this->_httpClient->request($method);
678 if ($usingMimeStream) {
679 $this->_httpClient->setAdapter($oldHttpAdapter);
681 } catch (Zend_Http_Client_Exception $e) {
683 if ($usingMimeStream) {
684 $this->_httpClient->setAdapter($oldHttpAdapter);
686 require_once 'Zend/Gdata/App/HttpException.php';
687 throw new Zend_Gdata_App_HttpException($e->getMessage(), $e);
689 if ($response->isRedirect() && $response->getStatus() != '304') {
690 if ($remainingRedirects > 0) {
691 $newUrl = $response->getHeader('Location');
692 $response = $this->performHttpRequest(
693 $method, $newUrl, $headers, $body,
694 $contentType, $remainingRedirects);
696 require_once 'Zend/Gdata/App/HttpException.php';
697 throw new Zend_Gdata_App_HttpException(
698 'Number of redirects exceeds maximum', null, $response);
701 if (!$response->isSuccessful()) {
702 require_once 'Zend/Gdata/App/HttpException.php';
703 $exceptionMessage = 'Expected response code 200, got ' .
704 $response->getStatus();
705 if (self::getVerboseExceptionMessages()) {
706 $exceptionMessage .= "\n" . $response->getBody();
708 $exception = new Zend_Gdata_App_HttpException($exceptionMessage);
709 $exception->setResponse($response);
716 * Imports a feed located at $uri.
719 * @param Zend_Http_Client $client The client used for communication
720 * @param string $className The class which is used as the return type
721 * @throws Zend_Gdata_App_Exception
722 * @return string|Zend_Gdata_App_Feed Returns string only if the object
723 * mapping has been disabled explicitly
724 * by passing false to the
725 * useObjectMapping() function.
727 public static function import($uri, $client = null,
728 $className='Zend_Gdata_App_Feed')
730 $app = new Zend_Gdata_App($client);
731 $requestData = $app->prepareRequest('GET', $uri);
732 $response = $app->performHttpRequest(
733 $requestData['method'], $requestData['url']);
735 $feedContent = $response->getBody();
736 if (!$this->_useObjectMapping) {
739 $feed = self::importString($feedContent, $className);
740 if ($client != null) {
741 $feed->setHttpClient($client);
747 * Imports the specified URL (non-statically).
749 * @param string $url The URL to import
750 * @param string $className The class which is used as the return type
751 * @param array $extraHeaders Extra headers to add to the request, as an
752 * array of string-based key/value pairs.
753 * @throws Zend_Gdata_App_Exception
754 * @return string|Zend_Gdata_App_Feed Returns string only if the object
755 * mapping has been disabled explicitly
756 * by passing false to the
757 * useObjectMapping() function.
759 public function importUrl($url, $className='Zend_Gdata_App_Feed',
760 $extraHeaders = array())
762 $response = $this->get($url, $extraHeaders);
764 $feedContent = $response->getBody();
765 if (!$this->_useObjectMapping) {
769 $protocolVersionStr = $response->getHeader('GData-Version');
770 $majorProtocolVersion = null;
771 $minorProtocolVersion = null;
772 if ($protocolVersionStr !== null) {
773 // Extract protocol major and minor version from header
774 $delimiterPos = strpos($protocolVersionStr, '.');
775 $length = strlen($protocolVersionStr);
776 $major = substr($protocolVersionStr, 0, $delimiterPos);
777 $minor = substr($protocolVersionStr, $delimiterPos + 1, $length);
778 $majorProtocolVersion = $major;
779 $minorProtocolVersion = $minor;
782 $feed = self::importString($feedContent, $className,
783 $majorProtocolVersion, $minorProtocolVersion);
784 if ($this->getHttpClient() != null) {
785 $feed->setHttpClient($this->getHttpClient());
787 $etag = $response->getHeader('ETag');
788 if ($etag !== null) {
789 $feed->setEtag($etag);
796 * Imports a feed represented by $string.
798 * @param string $string
799 * @param string $className The class which is used as the return type
800 * @param integer $majorProcolVersion (optional) The major protocol version
801 * of the data model object that is to be created.
802 * @param integer $minorProcolVersion (optional) The minor protocol version
803 * of the data model object that is to be created.
804 * @throws Zend_Gdata_App_Exception
805 * @return Zend_Gdata_App_Feed
807 public static function importString($string,
808 $className='Zend_Gdata_App_Feed', $majorProtocolVersion = null,
809 $minorProtocolVersion = null)
811 if (!class_exists($className, false)) {
812 require_once 'Zend/Loader.php';
813 @Zend_Loader::loadClass($className);
816 // Load the feed as an XML DOMDocument object
817 @ini_set('track_errors', 1);
818 $doc = new DOMDocument();
819 $success = @$doc->loadXML($string);
820 @ini_restore('track_errors');
823 require_once 'Zend/Gdata/App/Exception.php';
824 throw new Zend_Gdata_App_Exception(
825 "DOMDocument cannot parse XML: $php_errormsg");
828 $feed = new $className();
829 $feed->setMajorProtocolVersion($majorProtocolVersion);
830 $feed->setMinorProtocolVersion($minorProtocolVersion);
831 $feed->transferFromXML($string);
832 $feed->setHttpClient(self::getstaticHttpClient());
838 * Imports a feed from a file located at $filename.
840 * @param string $filename
841 * @param string $className The class which is used as the return type
842 * @param string $useIncludePath Whether the include_path should be searched
843 * @throws Zend_Gdata_App_Exception
844 * @return Zend_Gdata_App_Feed
846 public static function importFile($filename,
847 $className='Zend_Gdata_App_Feed', $useIncludePath = false)
849 @ini_set('track_errors', 1);
850 $feed = @file_get_contents($filename, $useIncludePath);
851 @ini_restore('track_errors');
852 if ($feed === false) {
853 require_once 'Zend/Gdata/App/Exception.php';
854 throw new Zend_Gdata_App_Exception(
855 "File could not be loaded: $php_errormsg");
857 return self::importString($feed, $className);
861 * GET a URI using client object.
863 * @param string $uri GET URI
864 * @param array $extraHeaders Extra headers to add to the request, as an
865 * array of string-based key/value pairs.
866 * @throws Zend_Gdata_App_HttpException
867 * @return Zend_Http_Response
869 public function get($uri, $extraHeaders = array())
871 $requestData = $this->prepareRequest('GET', $uri, $extraHeaders);
872 return $this->performHttpRequest(
873 $requestData['method'], $requestData['url'],
874 $requestData['headers']);
878 * POST data with client object
880 * @param mixed $data The Zend_Gdata_App_Entry or XML to post
881 * @param string $uri POST URI
882 * @param array $headers Additional HTTP headers to insert.
883 * @param string $contentType Content-type of the data
884 * @param array $extraHeaders Extra headers to add to the request, as an
885 * array of string-based key/value pairs.
886 * @return Zend_Http_Response
887 * @throws Zend_Gdata_App_Exception
888 * @throws Zend_Gdata_App_HttpException
889 * @throws Zend_Gdata_App_InvalidArgumentException
891 public function post($data, $uri = null, $remainingRedirects = null,
892 $contentType = null, $extraHeaders = null)
894 $requestData = $this->prepareRequest(
895 'POST', $uri, $extraHeaders, $data, $contentType);
896 return $this->performHttpRequest(
897 $requestData['method'], $requestData['url'],
898 $requestData['headers'], $requestData['data'],
899 $requestData['contentType']);
903 * PUT data with client object
905 * @param mixed $data The Zend_Gdata_App_Entry or XML to post
906 * @param string $uri PUT URI
907 * @param array $headers Additional HTTP headers to insert.
908 * @param string $contentType Content-type of the data
909 * @param array $extraHeaders Extra headers to add to the request, as an
910 * array of string-based key/value pairs.
911 * @return Zend_Http_Response
912 * @throws Zend_Gdata_App_Exception
913 * @throws Zend_Gdata_App_HttpException
914 * @throws Zend_Gdata_App_InvalidArgumentException
916 public function put($data, $uri = null, $remainingRedirects = null,
917 $contentType = null, $extraHeaders = null)
919 $requestData = $this->prepareRequest(
920 'PUT', $uri, $extraHeaders, $data, $contentType);
921 return $this->performHttpRequest(
922 $requestData['method'], $requestData['url'],
923 $requestData['headers'], $requestData['data'],
924 $requestData['contentType']);
928 * DELETE entry with client object
930 * @param mixed $data The Zend_Gdata_App_Entry or URL to delete
932 * @throws Zend_Gdata_App_Exception
933 * @throws Zend_Gdata_App_HttpException
934 * @throws Zend_Gdata_App_InvalidArgumentException
936 public function delete($data, $remainingRedirects = null)
938 if (is_string($data)) {
939 $requestData = $this->prepareRequest('DELETE', $data);
943 $requestData = $this->prepareRequest(
944 'DELETE', null, $headers, $data);
946 return $this->performHttpRequest($requestData['method'],
948 $requestData['headers'],
950 $requestData['contentType'],
951 $remainingRedirects);
955 * Inserts an entry to a given URI and returns the response as a
956 * fully formed Entry.
958 * @param mixed $data The Zend_Gdata_App_Entry or XML to post
959 * @param string $uri POST URI
960 * @param string $className The class of entry to be returned.
961 * @param array $extraHeaders Extra headers to add to the request, as an
962 * array of string-based key/value pairs.
963 * @return Zend_Gdata_App_Entry The entry returned by the service after
966 public function insertEntry($data, $uri, $className='Zend_Gdata_App_Entry',
967 $extraHeaders = array())
969 if (!class_exists($className, false)) {
970 require_once 'Zend/Loader.php';
971 @Zend_Loader::loadClass($className);
974 $response = $this->post($data, $uri, null, null, $extraHeaders);
976 $returnEntry = new $className($response->getBody());
977 $returnEntry->setHttpClient(self::getstaticHttpClient());
979 $etag = $response->getHeader('ETag');
980 if ($etag !== null) {
981 $returnEntry->setEtag($etag);
990 * @param mixed $data Zend_Gdata_App_Entry or XML (w/ID and link rel='edit')
991 * @param string|null The URI to send requests to, or null if $data
993 * @param string|null The name of the class that should be deserialized
994 * from the server response. If null, then 'Zend_Gdata_App_Entry'
996 * @param array $extraHeaders Extra headers to add to the request, as an
997 * array of string-based key/value pairs.
998 * @return Zend_Gdata_App_Entry The entry returned from the server
999 * @throws Zend_Gdata_App_Exception
1001 public function updateEntry($data, $uri = null, $className = null,
1002 $extraHeaders = array())
1004 if ($className === null && $data instanceof Zend_Gdata_App_Entry) {
1005 $className = get_class($data);
1006 } elseif ($className === null) {
1007 $className = 'Zend_Gdata_App_Entry';
1010 if (!class_exists($className, false)) {
1011 require_once 'Zend/Loader.php';
1012 @Zend_Loader::loadClass($className);
1015 $response = $this->put($data, $uri, null, null, $extraHeaders);
1016 $returnEntry = new $className($response->getBody());
1017 $returnEntry->setHttpClient(self::getstaticHttpClient());
1019 $etag = $response->getHeader('ETag');
1020 if ($etag !== null) {
1021 $returnEntry->setEtag($etag);
1024 return $returnEntry;
1028 * Provides a magic factory method to instantiate new objects with
1029 * shorter syntax than would otherwise be required by the Zend Framework
1030 * naming conventions. For instance, to construct a new
1031 * Zend_Gdata_Calendar_Extension_Color, a developer simply needs to do
1032 * $gCal->newColor(). For this magic constructor, packages are searched
1033 * in the same order as which they appear in the $_registeredPackages
1036 * @param string $method The method name being called
1037 * @param array $args The arguments passed to the call
1038 * @throws Zend_Gdata_App_Exception
1040 public function __call($method, $args)
1042 if (preg_match('/^new(\w+)/', $method, $matches)) {
1043 $class = $matches[1];
1044 $foundClassName = null;
1045 foreach ($this->_registeredPackages as $name) {
1047 // Autoloading disabled on next line for compatibility
1048 // with magic factories. See ZF-6660.
1049 if (!class_exists($name . '_' . $class, false)) {
1050 require_once 'Zend/Loader.php';
1051 @Zend_Loader::loadClass($name . '_' . $class);
1053 $foundClassName = $name . '_' . $class;
1055 } catch (Zend_Exception $e) {
1056 // package wasn't here- continue searching
1059 if ($foundClassName != null) {
1060 $reflectionObj = new ReflectionClass($foundClassName);
1061 $instance = $reflectionObj->newInstanceArgs($args);
1062 if ($instance instanceof Zend_Gdata_App_FeedEntryParent) {
1063 $instance->setHttpClient($this->_httpClient);
1065 // Propogate version data
1066 $instance->setMajorProtocolVersion(
1067 $this->_majorProtocolVersion);
1068 $instance->setMinorProtocolVersion(
1069 $this->_minorProtocolVersion);
1073 require_once 'Zend/Gdata/App/Exception.php';
1074 throw new Zend_Gdata_App_Exception(
1075 "Unable to find '${class}' in registered packages");
1078 require_once 'Zend/Gdata/App/Exception.php';
1079 throw new Zend_Gdata_App_Exception("No such method ${method}");
1084 * Retrieve all entries for a feed, iterating through pages as necessary.
1085 * Be aware that calling this function on a large dataset will take a
1086 * significant amount of time to complete. In some cases this may cause
1087 * execution to timeout without proper precautions in place.
1089 * @param $feed The feed to iterate through.
1090 * @return mixed A new feed of the same type as the one originally
1091 * passed in, containing all relevent entries.
1093 public function retrieveAllEntriesForFeed($feed) {
1094 $feedClass = get_class($feed);
1095 $reflectionObj = new ReflectionClass($feedClass);
1096 $result = $reflectionObj->newInstance();
1098 foreach ($feed as $entry) {
1099 $result->addEntry($entry);
1102 $next = $feed->getLink('next');
1103 if ($next !== null) {
1104 $feed = $this->getFeed($next->href, $feedClass);
1109 while ($feed != null);
1114 * This method enables logging of requests by changing the
1115 * Zend_Http_Client_Adapter used for performing the requests.
1116 * NOTE: This will not work if you have customized the adapter
1117 * already to use a proxy server or other interface.
1119 * @param $logfile The logfile to use when logging the requests
1121 public function enableRequestDebugLogging($logfile)
1123 $this->_httpClient->setConfig(array(
1124 'adapter' => 'Zend_Gdata_App_LoggingHttpClientAdapterSocket',
1125 'logfile' => $logfile
1130 * Retrieve next set of results based on a given feed.
1132 * @param Zend_Gdata_App_Feed $feed The feed from which to
1133 * retreive the next set of results.
1134 * @param string $className (optional) The class of feed to be returned.
1135 * If null, the next feed (if found) will be the same class as
1136 * the feed that was given as the first argument.
1137 * @return Zend_Gdata_App_Feed|null Returns a
1138 * Zend_Gdata_App_Feed or null if no next set of results
1141 public function getNextFeed($feed, $className = null)
1143 $nextLink = $feed->getNextLink();
1147 $nextLinkHref = $nextLink->getHref();
1149 if ($className === null) {
1150 $className = get_class($feed);
1153 return $this->getFeed($nextLinkHref, $className);
1157 * Retrieve previous set of results based on a given feed.
1159 * @param Zend_Gdata_App_Feed $feed The feed from which to
1160 * retreive the previous set of results.
1161 * @param string $className (optional) The class of feed to be returned.
1162 * If null, the previous feed (if found) will be the same class as
1163 * the feed that was given as the first argument.
1164 * @return Zend_Gdata_App_Feed|null Returns a
1165 * Zend_Gdata_App_Feed or null if no previous set of results
1168 public function getPreviousFeed($feed, $className = null)
1170 $previousLink = $feed->getPreviousLink();
1171 if (!$previousLink) {
1174 $previousLinkHref = $previousLink->getHref();
1176 if ($className === null) {
1177 $className = get_class($feed);
1180 return $this->getFeed($previousLinkHref, $className);
1184 * Returns the data for an If-Match header based on the current Etag
1185 * property. If Etags are not supported by the server or cannot be
1186 * extracted from the data, then null will be returned.
1188 * @param boolean $allowWeak If false, then if a weak Etag is detected,
1189 * then return null rather than the Etag.
1190 * @return string|null $data
1192 public function generateIfMatchHeaderData($data, $allowWeek)
1195 // Set an If-Match header if an ETag has been set (version >= 2 only)
1196 if ($this->_majorProtocolVersion >= 2 &&
1197 $data instanceof Zend_Gdata_App_Entry) {
1198 $etag = $data->getEtag();
1199 if (($etag !== null) &&
1200 ($allowWeek || substr($etag, 0, 2) != 'W/')) {
1201 $result = $data->getEtag();
1208 * Determine whether service object is using XML to object mapping.
1210 * @return boolean True if service object is using XML to object mapping,
1213 public function usingObjectMapping()
1215 return $this->_useObjectMapping;
1219 * Enable/disable the use of XML to object mapping.
1221 * @param boolean $value Pass in true to use the XML to object mapping.
1222 * Pass in false or null to disable it.
1225 public function useObjectMapping($value)
1227 if ($value === True) {
1228 $this->_useObjectMapping = true;
1230 $this->_useObjectMapping = false;