[ Index ]

PHP Cross Reference of moodle-2.8

title

Body

[close]

/lib/zend/Zend/Service/ -> Flickr.php (source)

   1  <?php
   2  
   3  /**
   4   * Zend Framework
   5   *
   6   * LICENSE
   7   *
   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 [email protected] so we can send you a copy immediately.
  15   *
  16   * @category   Zend
  17   * @package    Zend_Service
  18   * @subpackage Flickr
  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
  21   * @version    $Id$
  22   */
  23  
  24  
  25  /**
  26   * @category   Zend
  27   * @package    Zend_Service
  28   * @subpackage Flickr
  29   * @copyright  Copyright (c) 2005-2010 Zend Technologies USA Inc. (http://www.zend.com)
  30   * @license    http://framework.zend.com/license/new-bsd     New BSD License
  31   */
  32  class Zend_Service_Flickr
  33  {
  34      /**
  35       * Base URI for the REST client
  36       */
  37      const URI_BASE = 'http://www.flickr.com';
  38  
  39      /**
  40       * Your Flickr API key
  41       *
  42       * @var string
  43       */
  44      public $apiKey;
  45  
  46      /**
  47       * Reference to REST client object
  48       *
  49       * @var Zend_Rest_Client
  50       */
  51      protected $_restClient = null;
  52  
  53  
  54      /**
  55       * Performs object initializations
  56       *
  57       *  # Sets up character encoding
  58       *  # Saves the API key
  59       *
  60       * @param  string $apiKey Your Flickr API key
  61       * @return void
  62       */
  63      public function __construct($apiKey)
  64      {
  65          iconv_set_encoding('output_encoding', 'UTF-8');
  66          iconv_set_encoding('input_encoding', 'UTF-8');
  67          iconv_set_encoding('internal_encoding', 'UTF-8');
  68  
  69          $this->apiKey = (string) $apiKey;
  70      }
  71  
  72  
  73      /**
  74       * Find Flickr photos by tag.
  75       *
  76       * Query options include:
  77       *
  78       *  # per_page:        how many results to return per query
  79       *  # page:            the starting page offset.  first result will be (page - 1) * per_page + 1
  80       *  # tag_mode:        Either 'any' for an OR combination of tags,
  81       *                     or 'all' for an AND combination. Default is 'any'.
  82       *  # min_upload_date: Minimum upload date to search on.  Date should be a unix timestamp.
  83       *  # max_upload_date: Maximum upload date to search on.  Date should be a unix timestamp.
  84       *  # min_taken_date:  Minimum upload date to search on.  Date should be a MySQL datetime.
  85       *  # max_taken_date:  Maximum upload date to search on.  Date should be a MySQL datetime.
  86       *
  87       * @param  string|array $query   A single tag or an array of tags.
  88       * @param  array        $options Additional parameters to refine your query.
  89       * @return Zend_Service_Flickr_ResultSet
  90       * @throws Zend_Service_Exception
  91       */
  92      public function tagSearch($query, array $options = array())
  93      {
  94          static $method = 'flickr.photos.search';
  95          static $defaultOptions = array('per_page' => 10,
  96                                         'page'     => 1,
  97                                         'tag_mode' => 'or',
  98                                         'extras'   => 'license, date_upload, date_taken, owner_name, icon_server');
  99  
 100          $options['tags'] = is_array($query) ? implode(',', $query) : $query;
 101  
 102          $options = $this->_prepareOptions($method, $options, $defaultOptions);
 103  
 104          $this->_validateTagSearch($options);
 105  
 106          // now search for photos
 107          $restClient = $this->getRestClient();
 108          $restClient->getHttpClient()->resetParameters();
 109          $response = $restClient->restGet('/services/rest/', $options);
 110  
 111          if ($response->isError()) {
 112              /**
 113               * @see Zend_Service_Exception
 114               */
 115              require_once 'Zend/Service/Exception.php';
 116              throw new Zend_Service_Exception('An error occurred sending request. Status code: '
 117                                             . $response->getStatus());
 118          }
 119  
 120          $dom = new DOMDocument();
 121          $dom->loadXML($response->getBody());
 122  
 123          self::_checkErrors($dom);
 124  
 125          /**
 126           * @see Zend_Service_Flickr_ResultSet
 127           */
 128          require_once 'Zend/Service/Flickr/ResultSet.php';
 129          return new Zend_Service_Flickr_ResultSet($dom, $this);
 130      }
 131  
 132  
 133      /**
 134       * Finds photos by a user's username or email.
 135       *
 136       * Additional query options include:
 137       *
 138       *  # per_page:        how many results to return per query
 139       *  # page:            the starting page offset.  first result will be (page - 1) * per_page + 1
 140       *  # min_upload_date: Minimum upload date to search on.  Date should be a unix timestamp.
 141       *  # max_upload_date: Maximum upload date to search on.  Date should be a unix timestamp.
 142       *  # min_taken_date:  Minimum upload date to search on.  Date should be a MySQL datetime.
 143       *  # max_taken_date:  Maximum upload date to search on.  Date should be a MySQL datetime.
 144       *
 145       * @param  string $query   username or email
 146       * @param  array  $options Additional parameters to refine your query.
 147       * @return Zend_Service_Flickr_ResultSet
 148       * @throws Zend_Service_Exception
 149       */
 150      public function userSearch($query, array $options = null)
 151      {
 152          static $method = 'flickr.people.getPublicPhotos';
 153          static $defaultOptions = array('per_page' => 10,
 154                                         'page'     => 1,
 155                                         'extras'   => 'license, date_upload, date_taken, owner_name, icon_server');
 156  
 157  
 158          // can't access by username, must get ID first
 159          if (strchr($query, '@')) {
 160              // optimistically hope this is an email
 161              $options['user_id'] = $this->getIdByEmail($query);
 162          } else {
 163              // we can safely ignore this exception here
 164              $options['user_id'] = $this->getIdByUsername($query);
 165          }
 166  
 167          $options = $this->_prepareOptions($method, $options, $defaultOptions);
 168          $this->_validateUserSearch($options);
 169  
 170          // now search for photos
 171          $restClient = $this->getRestClient();
 172          $restClient->getHttpClient()->resetParameters();
 173          $response = $restClient->restGet('/services/rest/', $options);
 174  
 175          if ($response->isError()) {
 176              /**
 177               * @see Zend_Service_Exception
 178               */
 179              require_once 'Zend/Service/Exception.php';
 180              throw new Zend_Service_Exception('An error occurred sending request. Status code: '
 181                                             . $response->getStatus());
 182          }
 183  
 184          $dom = new DOMDocument();
 185          $dom->loadXML($response->getBody());
 186  
 187          self::_checkErrors($dom);
 188  
 189          /**
 190           * @see Zend_Service_Flickr_ResultSet
 191           */
 192          require_once 'Zend/Service/Flickr/ResultSet.php';
 193          return new Zend_Service_Flickr_ResultSet($dom, $this);
 194      }
 195  
 196      /**
 197       * Finds photos in a group's pool.
 198       *
 199       * @param  string $query   group id
 200       * @param  array  $options Additional parameters to refine your query.
 201       * @return Zend_Service_Flickr_ResultSet
 202       * @throws Zend_Service_Exception
 203       */
 204      public function groupPoolGetPhotos($query, array $options = array())
 205      {
 206          static $method = 'flickr.groups.pools.getPhotos';
 207          static $defaultOptions = array('per_page' => 10,
 208                                         'page'     => 1,
 209                                         'extras'   => 'license, date_upload, date_taken, owner_name, icon_server');
 210  
 211          if (empty($query) || !is_string($query)) {
 212              /**
 213               * @see Zend_Service_Exception
 214               */
 215              require_once 'Zend/Service/Exception.php';
 216              throw new Zend_Service_Exception('You must supply a group id');
 217          }
 218  
 219          $options['group_id'] = $query;
 220  
 221          $options = $this->_prepareOptions($method, $options, $defaultOptions);
 222  
 223          $this->_validateGroupPoolGetPhotos($options);
 224  
 225          // now search for photos
 226          $restClient = $this->getRestClient();
 227          $restClient->getHttpClient()->resetParameters();
 228          $response = $restClient->restGet('/services/rest/', $options);
 229  
 230          if ($response->isError()) {
 231              /**
 232              * @see Zend_Service_Exception
 233              */
 234              require_once 'Zend/Service/Exception.php';
 235              throw new Zend_Service_Exception('An error occurred sending request. Status code: '
 236                                             . $response->getStatus());
 237          }
 238  
 239          $dom = new DOMDocument();
 240          $dom->loadXML($response->getBody());
 241  
 242          self::_checkErrors($dom);
 243  
 244          /**
 245          * @see Zend_Service_Flickr_ResultSet
 246          */
 247          require_once 'Zend/Service/Flickr/ResultSet.php';
 248          return new Zend_Service_Flickr_ResultSet($dom, $this);
 249      }
 250  
 251  
 252  
 253      /**
 254       * Utility function to find Flickr User IDs for usernames.
 255       *
 256       * (You can only find a user's photo with their NSID.)
 257       *
 258       * @param  string $username the username
 259       * @return string the NSID (userid)
 260       * @throws Zend_Service_Exception
 261       */
 262      public function getIdByUsername($username)
 263      {
 264          static $method = 'flickr.people.findByUsername';
 265  
 266          $options = array('api_key' => $this->apiKey, 'method' => $method, 'username' => (string) $username);
 267  
 268          if (empty($username)) {
 269              /**
 270               * @see Zend_Service_Exception
 271               */
 272              require_once 'Zend/Service/Exception.php';
 273              throw new Zend_Service_Exception('You must supply a username');
 274          }
 275  
 276          $restClient = $this->getRestClient();
 277          $restClient->getHttpClient()->resetParameters();
 278          $response = $restClient->restGet('/services/rest/', $options);
 279  
 280          if ($response->isError()) {
 281              /**
 282               * @see Zend_Service_Exception
 283               */
 284              require_once 'Zend/Service/Exception.php';
 285              throw new Zend_Service_Exception('An error occurred sending request. Status code: '
 286                                             . $response->getStatus());
 287          }
 288  
 289          $dom = new DOMDocument();
 290          $dom->loadXML($response->getBody());
 291          self::_checkErrors($dom);
 292          $xpath = new DOMXPath($dom);
 293          return (string) $xpath->query('//user')->item(0)->getAttribute('id');
 294      }
 295  
 296  
 297      /**
 298       * Utility function to find Flickr User IDs for emails.
 299       *
 300       * (You can only find a user's photo with their NSID.)
 301       *
 302       * @param  string $email the email
 303       * @return string the NSID (userid)
 304       * @throws Zend_Service_Exception
 305       */
 306      public function getIdByEmail($email)
 307      {
 308          static $method = 'flickr.people.findByEmail';
 309  
 310          if (empty($email)) {
 311              /**
 312               * @see Zend_Service_Exception
 313               */
 314              require_once 'Zend/Service/Exception.php';
 315              throw new Zend_Service_Exception('You must supply an e-mail address');
 316          }
 317  
 318          $options = array('api_key' => $this->apiKey, 'method' => $method, 'find_email' => (string) $email);
 319  
 320          $restClient = $this->getRestClient();
 321          $restClient->getHttpClient()->resetParameters();
 322          $response = $restClient->restGet('/services/rest/', $options);
 323  
 324          if ($response->isError()) {
 325              /**
 326               * @see Zend_Service_Exception
 327               */
 328              require_once 'Zend/Service/Exception.php';
 329              throw new Zend_Service_Exception('An error occurred sending request. Status code: '
 330                                             . $response->getStatus());
 331          }
 332  
 333          $dom = new DOMDocument();
 334          $dom->loadXML($response->getBody());
 335          self::_checkErrors($dom);
 336          $xpath = new DOMXPath($dom);
 337          return (string) $xpath->query('//user')->item(0)->getAttribute('id');
 338      }
 339  
 340  
 341      /**
 342       * Returns Flickr photo details by for the given photo ID
 343       *
 344       * @param  string $id the NSID
 345       * @return array of Zend_Service_Flickr_Image, details for the specified image
 346       * @throws Zend_Service_Exception
 347       */
 348      public function getImageDetails($id)
 349      {
 350          static $method = 'flickr.photos.getSizes';
 351  
 352          if (empty($id)) {
 353              /**
 354               * @see Zend_Service_Exception
 355               */
 356              require_once 'Zend/Service/Exception.php';
 357              throw new Zend_Service_Exception('You must supply a photo ID');
 358          }
 359  
 360          $options = array('api_key' => $this->apiKey, 'method' => $method, 'photo_id' => $id);
 361  
 362          $restClient = $this->getRestClient();
 363          $restClient->getHttpClient()->resetParameters();
 364          $response = $restClient->restGet('/services/rest/', $options);
 365  
 366          $dom = new DOMDocument();
 367          $dom->loadXML($response->getBody());
 368          $xpath = new DOMXPath($dom);
 369          self::_checkErrors($dom);
 370          $retval = array();
 371          /**
 372           * @see Zend_Service_Flickr_Image
 373           */
 374          require_once 'Zend/Service/Flickr/Image.php';
 375          foreach ($xpath->query('//size') as $size) {
 376              $label = (string) $size->getAttribute('label');
 377              $retval[$label] = new Zend_Service_Flickr_Image($size);
 378          }
 379  
 380          return $retval;
 381      }
 382  
 383  
 384      /**
 385       * Returns a reference to the REST client, instantiating it if necessary
 386       *
 387       * @return Zend_Rest_Client
 388       */
 389      public function getRestClient()
 390      {
 391          if (null === $this->_restClient) {
 392              /**
 393               * @see Zend_Rest_Client
 394               */
 395              require_once 'Zend/Rest/Client.php';
 396              $this->_restClient = new Zend_Rest_Client(self::URI_BASE);
 397          }
 398  
 399          return $this->_restClient;
 400      }
 401  
 402  
 403      /**
 404       * Validate User Search Options
 405       *
 406       * @param  array $options
 407       * @return void
 408       * @throws Zend_Service_Exception
 409       */
 410      protected function _validateUserSearch(array $options)
 411      {
 412          $validOptions = array('api_key', 'method', 'user_id', 'per_page', 'page', 'extras', 'min_upload_date',
 413                                'min_taken_date', 'max_upload_date', 'max_taken_date', 'safe_search');
 414  
 415          $this->_compareOptions($options, $validOptions);
 416  
 417          /**
 418           * @see Zend_Validate_Between
 419           */
 420          require_once 'Zend/Validate/Between.php';
 421          $between = new Zend_Validate_Between(1, 500, true);
 422          if (!$between->isValid($options['per_page'])) {
 423              /**
 424               * @see Zend_Service_Exception
 425               */
 426              require_once 'Zend/Service/Exception.php';
 427              throw new Zend_Service_Exception($options['per_page'] . ' is not valid for the "per_page" option');
 428          }
 429  
 430          /**
 431           * @see Zend_Validate_Int
 432           */
 433          require_once 'Zend/Validate/Int.php';
 434          $int = new Zend_Validate_Int();
 435          if (!$int->isValid($options['page'])) {
 436              /**
 437               * @see Zend_Service_Exception
 438               */
 439              require_once 'Zend/Service/Exception.php';
 440              throw new Zend_Service_Exception($options['page'] . ' is not valid for the "page" option');
 441          }
 442  
 443          // validate extras, which are delivered in csv format
 444          if ($options['extras']) {
 445              $extras = explode(',', $options['extras']);
 446              $validExtras = array('license', 'date_upload', 'date_taken', 'owner_name', 'icon_server');
 447              foreach($extras as $extra) {
 448                  /**
 449                   * @todo The following does not do anything [yet], so it is commented out.
 450                   */
 451                  //in_array(trim($extra), $validExtras);
 452              }
 453          }
 454      }
 455  
 456  
 457      /**
 458       * Validate Tag Search Options
 459       *
 460       * @param  array $options
 461       * @return void
 462       * @throws Zend_Service_Exception
 463       */
 464      protected function _validateTagSearch(array $options)
 465      {
 466          $validOptions = array('method', 'api_key', 'user_id', 'tags', 'tag_mode', 'text', 'min_upload_date',
 467                                'max_upload_date', 'min_taken_date', 'max_taken_date', 'license', 'sort',
 468                                'privacy_filter', 'bbox', 'accuracy', 'safe_search', 'content_type', 'machine_tags',
 469                                'machine_tag_mode', 'group_id', 'contacts', 'woe_id', 'place_id', 'media', 'has_geo',
 470                                'geo_context', 'lat', 'lon', 'radius', 'radius_units', 'is_commons', 'is_gallery',
 471                                'extras', 'per_page', 'page');
 472  
 473          $this->_compareOptions($options, $validOptions);
 474  
 475          /**
 476           * @see Zend_Validate_Between
 477           */
 478          require_once 'Zend/Validate/Between.php';
 479          $between = new Zend_Validate_Between(1, 500, true);
 480          if (!$between->isValid($options['per_page'])) {
 481              /**
 482               * @see Zend_Service_Exception
 483               */
 484              require_once 'Zend/Service/Exception.php';
 485              throw new Zend_Service_Exception($options['per_page'] . ' is not valid for the "per_page" option');
 486          }
 487  
 488          /**
 489           * @see Zend_Validate_Int
 490           */
 491          require_once 'Zend/Validate/Int.php';
 492          $int = new Zend_Validate_Int();
 493          if (!$int->isValid($options['page'])) {
 494              /**
 495               * @see Zend_Service_Exception
 496               */
 497              require_once 'Zend/Service/Exception.php';
 498              throw new Zend_Service_Exception($options['page'] . ' is not valid for the "page" option');
 499          }
 500  
 501          // validate extras, which are delivered in csv format
 502          if ($options['extras']) {
 503              $extras = explode(',', $options['extras']);
 504              $validExtras = array('license', 'date_upload', 'date_taken', 'owner_name', 'icon_server');
 505              foreach($extras as $extra) {
 506                  /**
 507                   * @todo The following does not do anything [yet], so it is commented out.
 508                   */
 509                  //in_array(trim($extra), $validExtras);
 510              }
 511          }
 512  
 513      }
 514  
 515  
 516      /**
 517      * Validate Group Search Options
 518      *
 519      * @param  array $options
 520      * @throws Zend_Service_Exception
 521      * @return void
 522      */
 523      protected function _validateGroupPoolGetPhotos(array $options)
 524      {
 525          $validOptions = array('api_key', 'tags', 'method', 'group_id', 'per_page', 'page', 'extras', 'user_id');
 526  
 527          $this->_compareOptions($options, $validOptions);
 528  
 529          /**
 530          * @see Zend_Validate_Between
 531          */
 532          require_once 'Zend/Validate/Between.php';
 533          $between = new Zend_Validate_Between(1, 500, true);
 534          if (!$between->isValid($options['per_page'])) {
 535              /**
 536              * @see Zend_Service_Exception
 537              */
 538              require_once 'Zend/Service/Exception.php';
 539              throw new Zend_Service_Exception($options['per_page'] . ' is not valid for the "per_page" option');
 540          }
 541  
 542          /**
 543          * @see Zend_Validate_Int
 544          */
 545          require_once 'Zend/Validate/Int.php';
 546          $int = new Zend_Validate_Int();
 547  
 548          if (!$int->isValid($options['page'])) {
 549              /**
 550              * @see Zend_Service_Exception
 551              */
 552              require_once 'Zend/Service/Exception.php';
 553              throw new Zend_Service_Exception($options['page'] . ' is not valid for the "page" option');
 554          }
 555  
 556          // validate extras, which are delivered in csv format
 557          if (isset($options['extras'])) {
 558              $extras = explode(',', $options['extras']);
 559              $validExtras = array('license', 'date_upload', 'date_taken', 'owner_name', 'icon_server');
 560              foreach($extras as $extra) {
 561                  /**
 562                  * @todo The following does not do anything [yet], so it is commented out.
 563                  */
 564                  //in_array(trim($extra), $validExtras);
 565              }
 566          }
 567      }
 568  
 569  
 570      /**
 571       * Throws an exception if and only if the response status indicates a failure
 572       *
 573       * @param  DOMDocument $dom
 574       * @return void
 575       * @throws Zend_Service_Exception
 576       */
 577      protected static function _checkErrors(DOMDocument $dom)
 578      {
 579          if ($dom->documentElement->getAttribute('stat') === 'fail') {
 580              $xpath = new DOMXPath($dom);
 581              $err = $xpath->query('//err')->item(0);
 582              /**
 583               * @see Zend_Service_Exception
 584               */
 585              require_once 'Zend/Service/Exception.php';
 586              throw new Zend_Service_Exception('Search failed due to error: ' . $err->getAttribute('msg')
 587                                             . ' (error #' . $err->getAttribute('code') . ')');
 588          }
 589      }
 590  
 591  
 592      /**
 593       * Prepare options for the request
 594       *
 595       * @param  string $method         Flickr Method to call
 596       * @param  array  $options        User Options
 597       * @param  array  $defaultOptions Default Options
 598       * @return array Merged array of user and default/required options
 599       */
 600      protected function _prepareOptions($method, array $options, array $defaultOptions)
 601      {
 602          $options['method']  = (string) $method;
 603          $options['api_key'] = $this->apiKey;
 604  
 605          return array_merge($defaultOptions, $options);
 606      }
 607  
 608  
 609      /**
 610       * Throws an exception if and only if any user options are invalid
 611       *
 612       * @param  array $options      User options
 613       * @param  array $validOptions Valid options
 614       * @return void
 615       * @throws Zend_Service_Exception
 616       */
 617      protected function _compareOptions(array $options, array $validOptions)
 618      {
 619          $difference = array_diff(array_keys($options), $validOptions);
 620          if ($difference) {
 621              /**
 622               * @see Zend_Service_Exception
 623               */
 624              require_once 'Zend/Service/Exception.php';
 625              throw new Zend_Service_Exception('The following parameters are invalid: ' . implode(',', $difference));
 626          }
 627      }
 628  }
 629  


Generated: Fri Nov 28 20:29:05 2014 Cross-referenced by PHPXref 0.7.1