PageRenderTime 628ms CodeModel.GetById 413ms app.highlight 53ms RepoModel.GetById 148ms app.codeStats 0ms

/library/Zend/Service/SlideShare.php

https://bitbucket.org/baruffaldi/webapp-urltube
PHP | 609 lines | 294 code | 99 blank | 216 comment | 32 complexity | b7fd36959c6a131f59eee0d8b06c2a59 MD5 | raw file
  1<?php
  2/**
  3 * Zend Framework
  4 *
  5 * LICENSE
  6 *
  7 * This source file is subject to the new BSD license that is bundled
  8 * with this package in the file LICENSE.txt.
  9 * It is also available through the world-wide-web at this URL:
 10 * http://framework.zend.com/license/new-bsd
 11 * If you did not receive a copy of the license and are unable to
 12 * obtain it through the world-wide-web, please send an email
 13 * to license@zend.com so we can send you a copy immediately.
 14 *
 15 * @category   Zend
 16 * @package    Zend_Service
 17 * @subpackage SlideShare
 18 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 19 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 20 * @version    $Id: SlideShare.php 9094 2008-03-30 18:36:55Z thomas $
 21 */
 22
 23/**
 24 * Zend_Http_Client
 25 */
 26require_once 'Zend/Http/Client.php';
 27
 28/**
 29 * Zend_Cache
 30 */
 31require_once 'Zend/Cache.php';
 32
 33/**
 34 * Zend_Service_SlideShare_Exception
 35 */
 36require_once 'Zend/Service/SlideShare/Exception.php';
 37
 38/**
 39 * Zend_Service_SlideShare_SlideShow
 40 */
 41require_once 'Zend/Service/SlideShare/SlideShow.php';
 42
 43/**
 44 * The Zend_Service_SlideShare component is used to interface with the
 45 * slideshare.net web server to retrieve slide shows hosted on the web site for
 46 * display or other processing.
 47 *
 48 * @category   Zend
 49 * @package    Zend_Service
 50 * @subpackage SlideShare
 51 * @throws     Zend_Service_SlideShare_Exception
 52 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 53 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 54 */
 55class Zend_Service_SlideShare
 56{
 57
 58    /**
 59     * Web service result code mapping
 60     */
 61    const SERVICE_ERROR_BAD_APIKEY       = 1;
 62    const SERVICE_ERROR_BAD_AUTH         = 2;
 63    const SERVICE_ERROR_MISSING_TITLE    = 3;
 64    const SERVICE_ERROR_MISSING_FILE     = 4;
 65    const SERVICE_ERROR_EMPTY_TITLE      = 5;
 66    const SERVICE_ERROR_NOT_SOURCEOBJ    = 6;
 67    const SERVICE_ERROR_INVALID_EXT      = 7;
 68    const SERVICE_ERROR_FILE_TOO_BIG     = 8;
 69    const SERVICE_ERROR_SHOW_NOT_FOUND   = 9;
 70    const SERVICE_ERROR_USER_NOT_FOUND   = 10;
 71    const SERVICE_ERROR_GROUP_NOT_FOUND  = 11;
 72    const SERVICE_ERROR_MISSING_TAG      = 12;
 73    const SERVICE_ERROR_DAILY_LIMIT      = 99;
 74    const SERVICE_ERROR_ACCOUNT_BLOCKED  = 100;
 75
 76    /**
 77     * Slide share Web service communication URIs
 78     */
 79    const SERVICE_UPLOAD_URI                  = 'http://www.slideshare.net/api/1/upload_slideshow';
 80    const SERVICE_GET_SHOW_URI                = 'http://www.slideshare.net/api/1/get_slideshow';
 81    const SERVICE_GET_SHOW_BY_USER_URI        = 'http://www.slideshare.net/api/1/get_slideshow_by_user';
 82    const SERVICE_GET_SHOW_BY_TAG_URI         = 'http://www.slideshare.net/api/1/get_slideshow_by_tag';
 83    const SERVICE_GET_SHOW_BY_GROUP_URI       = 'http://www.slideshare.net/api/1/get_slideshows_from_group';
 84
 85    /**
 86     * The MIME type of Slideshow files
 87     *
 88     */
 89    const POWERPOINT_MIME_TYPE    = "application/vnd.ms-powerpoint";
 90
 91    /**
 92     * The API key to use in requests
 93     *
 94     * @var string The API key
 95     */
 96    protected $_apiKey;
 97
 98    /**
 99     * The shared secret to use in requests
100     *
101     * @var string the Shared secret
102     */
103    protected $_sharedSecret;
104
105    /**
106     * The username to use in requests
107     *
108     * @var string the username
109     */
110    protected $_username;
111
112    /**
113     * The password to use in requests
114     *
115     * @var string the password
116     */
117    protected $_password;
118
119    /**
120     * The HTTP Client object to use to perform requests
121     *
122     * @var Zend_Http_Client
123     */
124    protected $_httpclient;
125
126    /**
127     * The Cache object to use to perform caching
128     *
129     * @var Zend_Cache_Core
130     */
131    protected $_cacheobject;
132
133    /**
134     * Sets the Zend_Http_Client object to use in requests. If not provided a default will
135     * be used.
136     *
137     * @param Zend_Http_Client $client The HTTP client instance to use
138     * @return Zend_Service_SlideShare
139     */
140    public function setHttpClient(Zend_Http_Client $client)
141    {
142        $this->_httpclient = $client;
143        return $this;
144    }
145
146    /**
147     * Returns the instance of the Zend_Http_Client which will be used. Creates an instance
148     * of Zend_Http_Client if no previous client was set.
149     *
150     * @return Zend_Http_Client The HTTP client which will be used
151     */
152    public function getHttpClient()
153    {
154
155        if(!($this->_httpclient instanceof Zend_Http_Client)) {
156            $client = new Zend_Http_Client();
157            $client->setConfig(array('maxredirects' => 2,
158                                     'timeout' => 5));
159
160            $this->setHttpClient($client);
161        }
162
163        $this->_httpclient->resetParameters();
164        return $this->_httpclient;
165    }
166
167    /**
168     * Sets the Zend_Cache object to use to cache the results of API queries
169     *
170     * @param Zend_Cache_Core $cacheobject The Zend_Cache object used
171     * @return Zend_Service_SlideShare
172     */
173    public function setCacheObject(Zend_Cache_Core $cacheobject)
174    {
175        $this->_cacheobject = $cacheobject;
176        return $this;
177    }
178
179    /**
180     * Gets the Zend_Cache object which will be used to cache API queries. If no cache object
181     * was previously set the the default will be used (Filesystem caching in /tmp with a life
182     * time of 43200 seconds)
183     *
184     * @return Zend_Cache_Core The object used in caching
185     */
186    public function getCacheObject()
187    {
188
189        if(!($this->_cacheobject instanceof Zend_Cache_Core)) {
190            $cache = Zend_Cache::factory('Core', 'File', array('lifetime' => 43200,
191                                                               'automatic_serialization' => true),
192                                                         array('cache_dir' => '/tmp'));
193
194            $this->setCacheObject($cache);
195        }
196
197        return $this->_cacheobject;
198    }
199
200    /**
201     * Returns the user name used for API calls
202     *
203     * @return string The username
204     */
205    public function getUserName()
206    {
207        return $this->_username;
208    }
209
210    /**
211     * Sets the user name to use for API calls
212     *
213     * @param string $un The username to use
214     * @return Zend_Service_SlideShare
215     */
216    public function setUserName($un)
217    {
218        $this->_username = $un;
219        return $this;
220    }
221
222    /**
223     * Gets the password to use in API calls
224     *
225     * @return string the password to use in API calls
226     */
227    public function getPassword()
228    {
229        return $this->_password;
230    }
231
232    /**
233     * Sets the password to use in API calls
234     *
235     * @param string $pw The password to use
236     * @return Zend_Service_SlideShare
237     */
238    public function setPassword($pw)
239    {
240        $this->_password = (string)$pw;
241        return $this;
242    }
243
244    /**
245     * Gets the API key to be used in making API calls
246     *
247     * @return string the API Key
248     */
249    public function getApiKey()
250    {
251        return $this->_apiKey;
252    }
253
254    /**
255     * Sets the API key to be used in making API calls
256     *
257     * @param string $key The API key to use
258     * @return Zend_Service_SlideShare
259     */
260    public function setApiKey($key)
261    {
262        $this->_apiKey = (string)$key;
263        return $this;
264    }
265
266    /**
267     * Gets the shared secret used in making API calls
268     *
269     * @return string the Shared secret
270     */
271    public function getSharedSecret()
272    {
273        return $this->_sharedSecret;
274    }
275
276    /**
277     * Sets the shared secret used in making API calls
278     *
279     * @param string $secret the shared secret
280     * @return Zend_Service_SlideShare
281     */
282    public function setSharedSecret($secret)
283    {
284        $this->_sharedSecret = (string)$secret;
285        return $this;
286    }
287
288    /**
289     * The Constructor
290     *
291     * @param string $apikey The API key
292     * @param string $sharedSecret The shared secret
293     * @param string $username The username
294     * @param string $password The password
295     */
296    public function __construct($apikey, $sharedSecret, $username = null, $password = null)
297    {
298        $this->setApiKey($apikey)
299             ->setSharedSecret($sharedSecret)
300             ->setUserName($username)
301             ->setPassword($password);
302
303        $this->_httpclient = new Zend_Http_Client();
304    }
305
306    /**
307     * Uploads the specified Slide show the the server
308     *
309     * @param Zend_Service_SlideShare_SlideShow $ss The slide show object representing the slide show to upload
310     * @param boolean $make_src_public Determines if the the slide show's source file is public or not upon upload
311     * @return Zend_Service_SlideShare_SlideShow The passed Slide show object, with the new assigned ID provided
312     */
313    public function uploadSlideShow(Zend_Service_SlideShare_SlideShow $ss, $make_src_public = true)
314    {
315
316        $timestamp = time();
317
318        $params = array('api_key' => $this->getApiKey(),
319                        'ts' => $timestamp,
320                        'hash' => sha1($this->getSharedSecret().$timestamp),
321                        'username' => $this->getUserName(),
322                        'password' => $this->getPassword(),
323                        'slideshow_title' => $ss->getTitle());
324
325        $description = $ss->getDescription();
326        $tags = $ss->getTags();
327
328        $filename = $ss->getFilename();
329
330        if(!file_exists($filename) || !is_readable($filename)) {
331            throw new Zend_Service_SlideShare_Exception("Specified Slideshow for upload not found or unreadable");
332        }
333
334        if(!empty($description)) {
335            $params['slideshow_description'] = $description;
336        } else {
337            $params['slideshow_description'] = "";
338        }
339
340        if(!empty($tags)) {
341            $tmp = array();
342            foreach($tags as $tag) {
343                $tmp[] = "\"$tag\"";
344            }
345            $params['slideshow_tags'] = implode(' ', $tmp);
346        } else {
347            $params['slideshow_tags'] = "";
348        }
349
350
351        $client = $this->getHttpClient();
352        $client->setUri(self::SERVICE_UPLOAD_URI);
353        $client->setParameterPost($params);
354        $client->setFileUpload($filename, "slideshow_srcfile");
355
356        try {
357            $response = $client->request('POST');
358        } catch(Zend_Http_Client_Exception $e) {
359            throw new Zend_Service_SlideShare_Exception("Service Request Failed: {$e->getMessage()}");
360        }
361
362        $sxe = simplexml_load_string($response->getBody());
363
364        if($sxe->getName() == "SlideShareServiceError") {
365            $message = (string)$sxe->Message[0];
366            list($code, $error_str) = explode(':', $message);
367            throw new Zend_Service_SlideShare_Exception(trim($error_str), $code);
368        }
369
370        if(!$sxe->getName() == "SlideShowUploaded") {
371            throw new Zend_Service_SlideShare_Exception("Unknown XML Respons Received");
372        }
373
374        $ss->setId((int)(string)$sxe->SlideShowID);
375
376        return $ss;
377    }
378
379    /**
380     * Retrieves a slide show's information based on slide show ID
381     *
382     * @param int $ss_id The slide show ID
383     * @return Zend_Service_SlideShare_SlideShow the Slideshow object
384     */
385    public function getSlideShow($ss_id)
386    {
387        $timestamp = time();
388
389        $params = array('api_key' => $this->getApiKey(),
390                        'ts' => $timestamp,
391                        'hash' => sha1($this->getSharedSecret().$timestamp),
392                        'slideshow_id' => $ss_id);
393
394        $cache = $this->getCacheObject();
395
396        $cache_key = md5("__zendslideshare_cache_$ss_id");
397
398        if(!$retval = $cache->load($cache_key)) {
399            $client = $this->getHttpClient();
400
401            $client->setUri(self::SERVICE_GET_SHOW_URI);
402            $client->setParameterPost($params);
403
404            try {
405                $response = $client->request('POST');
406            } catch(Zend_Http_Client_Exception $e) {
407                throw new Zend_Service_SlideShare_Exception("Service Request Failed: {$e->getMessage()}");
408            }
409
410            $sxe = simplexml_load_string($response->getBody());
411
412            if($sxe->getName() == "SlideShareServiceError") {
413                $message = (string)$sxe->Message[0];
414                list($code, $error_str) = explode(':', $message);
415                throw new Zend_Service_SlideShare_Exception(trim($error_str), $code);
416            }
417
418            if(!$sxe->getName() == 'Slideshows') {
419                throw new Zend_Service_SlideShare_Exception('Unknown XML Repsonse Received');
420            }
421
422            $retval = $this->_slideShowNodeToObject(clone $sxe->Slideshow[0]);
423
424            $cache->save($retval, $cache_key);
425        }
426
427        return $retval;
428    }
429
430    /**
431     * Retrieves an array of slide shows for a given username
432     *
433     * @param string $username The username to retrieve slide shows from
434     * @param int $offset The offset of the list to start retrieving from
435     * @param int $limit The maximum number of slide shows to retrieve
436     * @return array An array of Zend_Service_SlideShare_SlideShow objects
437     */
438    public function getSlideShowsByUsername($username, $offset = null, $limit = null)
439    {
440        return $this->_getSlideShowsByType('username_for', $username, $offset, $limit);
441    }
442
443    /**
444     * Retrieves an array of slide shows based on tag
445     *
446     * @param string $tag The tag to retrieve slide shows with
447     * @param int $offset The offset of the list to start retrieving from
448     * @param int $limit The maximum number of slide shows to retrieve
449     * @return array An array of Zend_Service_SlideShare_SlideShow objects
450     */
451    public function getSlideShowsByTag($tag, $offset = null, $limit = null)
452    {
453
454        if(is_array($tag)) {
455            $tmp = array();
456            foreach($tag as $t) {
457                $tmp[] = "\"$t\"";
458            }
459
460            $tag = implode(" ", $tmp);
461        }
462
463        return $this->_getSlideShowsByType('tag', $tag, $offset, $limit);
464    }
465
466    /**
467     * Retrieves an array of slide shows based on group name
468     *
469     * @param string $group The group name to retrieve slide shows for
470     * @param int $offset The offset of the list to start retrieving from
471     * @param int $limit The maximum number of slide shows to retrieve
472     * @return array An array of Zend_Service_SlideShare_SlideShow objects
473     */
474    public function getSlideShowsByGroup($group, $offset = null, $limit = null)
475    {
476        return $this->_getSlideShowsByType('group_name', $group, $offset, $limit);
477    }
478
479    /**
480     * Retrieves Zend_Service_SlideShare_SlideShow object arrays based on the type of
481     * list desired
482     *
483     * @param string $key The type of slide show object to retrieve
484     * @param string $value The specific search query for the slide show type to look up
485     * @param int $offset The offset of the list to start retrieving from
486     * @param int $limit The maximum number of slide shows to retrieve
487     * @return array An array of Zend_Service_SlideShare_SlideShow objects
488     */
489    protected function _getSlideShowsByType($key, $value, $offset = null, $limit = null)
490    {
491
492        $key = strtolower($key);
493
494        switch($key) {
495            case 'username_for':
496                $responseTag = 'User';
497                $queryUri = self::SERVICE_GET_SHOW_BY_USER_URI;
498                break;
499            case 'group_name':
500                $responseTag = 'Group';
501                $queryUri = self::SERVICE_GET_SHOW_BY_GROUP_URI;
502                break;
503            case 'tag':
504                $responseTag = 'Tag';
505                $queryUri = self::SERVICE_GET_SHOW_BY_TAG_URI;
506                break;
507            default:
508                throw new Zend_Service_SlideShare_Exception("Invalid SlideShare Query");
509        }
510
511        $timestamp = time();
512
513        $params = array('api_key' => $this->getApiKey(),
514                        'ts' => $timestamp,
515                        'hash' => sha1($this->getSharedSecret().$timestamp),
516                        $key => $value);
517
518        if(!is_null($offset)) {
519            $params['offset'] = (int)$offset;
520        }
521
522        if(!is_null($limit)) {
523            $params['limit'] = (int)$limit;
524        }
525
526        $cache = $this->getCacheObject();
527
528        $cache_key = md5($key.$value.$offset.$limit);
529
530        if(!$retval = $cache->load($cache_key)) {
531
532            $client = $this->getHttpClient();
533
534            $client->setUri($queryUri);
535            $client->setParameterPost($params);
536
537            try {
538                $response = $client->request('POST');
539            } catch(Zend_Http_Client_Exception $e) {
540                throw new Zend_Service_SlideShare_Exception("Service Request Failed: {$e->getMessage()}");
541            }
542
543            $sxe = simplexml_load_string($response->getBody());
544
545            if($sxe->getName() == "SlideShareServiceError") {
546                $message = (string)$sxe->Message[0];
547                list($code, $error_str) = explode(':', $message);
548                throw new Zend_Service_SlideShare_Exception(trim($error_str), $code);
549            }
550
551            if(!$sxe->getName() == $responseTag) {
552                throw new Zend_Service_SlideShare_Exception('Unknown or Invalid XML Repsonse Received');
553            }
554
555            $retval = array();
556
557            foreach($sxe->children() as $node) {
558                if($node->getName() == 'Slideshow') {
559                    $retval[] = $this->_slideShowNodeToObject($node);
560                }
561            }
562
563            $cache->save($retval, $cache_key);
564        }
565
566        return $retval;
567    }
568
569    /**
570     * Converts a SimpleXMLElement object representing a response from the service
571     * into a Zend_Service_SlideShare_SlideShow object
572     *
573     * @param SimpleXMLElement $node The input XML from the slideshare.net service
574     * @return Zend_Service_SlideShare_SlideShow The resulting object
575     */
576    protected function _slideShowNodeToObject(SimpleXMLElement $node)
577    {
578
579        if($node->getName() == 'Slideshow') {
580
581            $ss = new Zend_Service_SlideShare_SlideShow();
582
583            $ss->setId((string)$node->ID);
584            $ss->setDescription((string)$node->Description);
585            $ss->setEmbedCode((string)$node->EmbedCode);
586            $ss->setNumViews((string)$node->Views);
587            $ss->setPermaLink((string)$node->Permalink);
588            $ss->setStatus((string)$node->Status);
589            $ss->setStatusDescription((string)$node->StatusDescription);
590
591            foreach(explode(",", (string)$node->Tags) as $tag) {
592
593                if(!in_array($tag, $ss->getTags())) {
594                    $ss->addTag($tag);
595                }
596            }
597
598            $ss->setThumbnailUrl((string)$node->Thumbnail);
599            $ss->setTitle((string)$node->Title);
600            $ss->setLocation((string)$node->Location);
601            $ss->setTranscript((string)$node->Transcript);
602
603            return $ss;
604
605        }
606
607        throw new Zend_Service_SlideShare_Exception("Was not provided the expected XML Node for processing");
608    }
609}