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.
16 * @package Zend_Service
18 * @copyright Copyright (c) 2005-2010 Zend Technologies USA Inc. (http://www.zend.com)
19 * @license http://framework.zend.com/license/new-bsd New BSD License
24 * @see Zend_Rest_Client
26 require_once 'Zend/Rest/Client.php';
29 * @see Zend_Rest_Client_Result
31 require_once 'Zend/Rest/Client/Result.php';
34 * @see Zend_Oauth_Consumer
36 require_once 'Zend/Oauth/Consumer.php';
40 * @package Zend_Service
42 * @copyright Copyright (c) 2005-2010 Zend Technologies USA Inc. (http://www.zend.com)
43 * @license http://framework.zend.com/license/new-bsd New BSD License
45 class Zend_Service_Twitter
extends Zend_Rest_Client
49 * 246 is the current limit for a status message, 140 characters are displayed
50 * initially, with the remainder linked from the web UI or client. The limit is
51 * applied to a html encoded UTF-8 string (i.e. entities are counted in the limit
52 * which may appear unusual but is a security measure).
54 * This should be reviewed in the future...
56 const STATUS_MAX_CHARACTERS
= 246;
61 const OAUTH_BASE_URI
= 'http://twitter.com/oauth';
64 * @var Zend_Http_CookieJar
66 protected $_cookieJar;
69 * Date format for 'since' strings
73 protected $_dateFormat = 'D, d M Y H:i:s T';
83 * Current method type (for method proxying)
87 protected $_methodType;
92 * @var Zend_Oauth_Consumer
94 protected $_oauthConsumer = null;
97 * Types of API methods
101 protected $_methodTypes = array(
112 * Options passed to constructor
116 protected $_options = array();
119 * Local HTTP Client cloned from statically set client
121 * @var Zend_Http_Client
123 protected $_localHttpClient = null;
128 * @param array $options Optional options array
131 public function __construct(array $options = null, Zend_Oauth_Consumer
$consumer = null)
133 $this->setUri('http://api.twitter.com');
134 if (!is_array($options)) $options = array();
135 $options['siteUrl'] = self
::OAUTH_BASE_URI
;
136 if ($options instanceof Zend_Config
) {
137 $options = $options->toArray();
139 $this->_options
= $options;
140 if (isset($options['username'])) {
141 $this->setUsername($options['username']);
143 if (isset($options['accessToken'])
144 && $options['accessToken'] instanceof Zend_Oauth_Token_Access
) {
145 $this->setLocalHttpClient($options['accessToken']->getHttpClient($options));
147 $this->setLocalHttpClient(clone self
::getHttpClient());
148 if (is_null($consumer)) {
149 $this->_oauthConsumer
= new Zend_Oauth_Consumer($options);
151 $this->_oauthConsumer
= $consumer;
157 * Set local HTTP client as distinct from the static HTTP client
158 * as inherited from Zend_Rest_Client.
160 * @param Zend_Http_Client $client
163 public function setLocalHttpClient(Zend_Http_Client
$client)
165 $this->_localHttpClient
= $client;
166 $this->_localHttpClient
->setHeaders('Accept-Charset', 'ISO-8859-1,utf-8');
171 * Get the local HTTP client as distinct from the static HTTP client
172 * inherited from Zend_Rest_Client
174 * @return Zend_Http_Client
176 public function getLocalHttpClient()
178 return $this->_localHttpClient
;
182 * Checks for an authorised state
186 public function isAuthorised()
188 if ($this->getLocalHttpClient() instanceof Zend_Oauth_Client
) {
199 public function getUsername()
201 return $this->_username
;
207 * @param string $value
208 * @return Zend_Service_Twitter
210 public function setUsername($value)
212 $this->_username
= $value;
217 * Proxy service methods
219 * @param string $type
220 * @return Zend_Service_Twitter
221 * @throws Zend_Service_Twitter_Exception If method not in method types list
223 public function __get($type)
225 if (!in_array($type, $this->_methodTypes
)) {
226 include_once 'Zend/Service/Twitter/Exception.php';
227 throw new Zend_Service_Twitter_Exception(
228 'Invalid method type "' . $type . '"'
231 $this->_methodType
= $type;
238 * @param string $method
239 * @param array $params
241 * @throws Zend_Service_Twitter_Exception if unable to find method
243 public function __call($method, $params)
245 if (method_exists($this->_oauthConsumer
, $method)) {
246 $return = call_user_func_array(array($this->_oauthConsumer
, $method), $params);
247 if ($return instanceof Zend_Oauth_Token_Access
) {
248 $this->setLocalHttpClient($return->getHttpClient($this->_options
));
252 if (empty($this->_methodType
)) {
253 include_once 'Zend/Service/Twitter/Exception.php';
254 throw new Zend_Service_Twitter_Exception(
255 'Invalid method "' . $method . '"'
258 $test = $this->_methodType
. ucfirst($method);
259 if (!method_exists($this, $test)) {
260 include_once 'Zend/Service/Twitter/Exception.php';
261 throw new Zend_Service_Twitter_Exception(
262 'Invalid method "' . $test . '"'
266 return call_user_func_array(array($this, $test), $params);
270 * Initialize HTTP authentication
274 protected function _init()
276 if (!$this->isAuthorised() && $this->getUsername() !== null) {
277 require_once 'Zend/Service/Twitter/Exception.php';
278 throw new Zend_Service_Twitter_Exception(
279 'Twitter session is unauthorised. You need to initialize '
280 . 'Zend_Service_Twitter with an OAuth Access Token or use '
281 . 'its OAuth functionality to obtain an Access Token before '
282 . 'attempting any API actions that require authorisation'
285 $client = $this->_localHttpClient
;
286 $client->resetParameters();
287 if (null == $this->_cookieJar
) {
288 $client->setCookieJar();
289 $this->_cookieJar
= $client->getCookieJar();
291 $client->setCookieJar($this->_cookieJar
);
298 * @param int|string $value
299 * @deprecated Not supported by Twitter since April 08, 2009
302 protected function _setDate($value)
304 if (is_int($value)) {
305 $date = date($this->_dateFormat
, $value);
307 $date = date($this->_dateFormat
, strtotime($value));
309 $this->_localHttpClient
->setHeaders('If-Modified-Since', $date);
313 * Public Timeline status
315 * @throws Zend_Http_Client_Exception if HTTP request fails or times out
316 * @return Zend_Rest_Client_Result
318 public function statusPublicTimeline()
321 $path = '/1/statuses/public_timeline.xml';
322 $response = $this->_get($path);
323 return new Zend_Rest_Client_Result($response->getBody());
327 * Friend Timeline Status
329 * $params may include one or more of the following keys
330 * - id: ID of a friend whose timeline you wish to receive
331 * - count: how many statuses to return
332 * - since_id: return results only after the specific tweet
333 * - page: return page X of results
335 * @param array $params
336 * @throws Zend_Http_Client_Exception if HTTP request fails or times out
339 public function statusFriendsTimeline(array $params = array())
342 $path = '/1/statuses/friends_timeline';
344 foreach ($params as $key => $value) {
345 switch (strtolower($key)) {
347 $count = (int) $value;
350 } elseif (200 < $count) {
353 $_params['count'] = (int) $count;
356 $_params['since_id'] = $this->_validInteger($value);
359 $_params['page'] = (int) $value;
366 $response = $this->_get($path, $_params);
367 return new Zend_Rest_Client_Result($response->getBody());
371 * User Timeline status
373 * $params may include one or more of the following keys
374 * - id: ID of a friend whose timeline you wish to receive
375 * - since_id: return results only after the tweet id specified
376 * - page: return page X of results
377 * - count: how many statuses to return
378 * - max_id: returns only statuses with an ID less than or equal to the specified ID
379 * - user_id: specfies the ID of the user for whom to return the user_timeline
380 * - screen_name: specfies the screen name of the user for whom to return the user_timeline
382 * @throws Zend_Http_Client_Exception if HTTP request fails or times out
383 * @return Zend_Rest_Client_Result
385 public function statusUserTimeline(array $params = array())
388 $path = '/1/statuses/user_timeline';
390 foreach ($params as $key => $value) {
391 switch (strtolower($key)) {
393 $path .= '/' . $value;
396 $_params['page'] = (int) $value;
399 $count = (int) $value;
402 } elseif (200 < $count) {
405 $_params['count'] = $count;
408 $_params['user_id'] = $this->_validInteger($value);
411 $_params['screen_name'] = $this->_validateScreenName($value);
414 $_params['since_id'] = $this->_validInteger($value);
417 $_params['max_id'] = $this->_validInteger($value);
424 $response = $this->_get($path, $_params);
425 return new Zend_Rest_Client_Result($response->getBody());
429 * Show a single status
431 * @param int $id Id of status to show
432 * @throws Zend_Http_Client_Exception if HTTP request fails or times out
433 * @return Zend_Rest_Client_Result
435 public function statusShow($id)
438 $path = '/1/statuses/show/' . $this->_validInteger($id) . '.xml';
439 $response = $this->_get($path);
440 return new Zend_Rest_Client_Result($response->getBody());
444 * Update user's current status
446 * @param string $status
447 * @param int $in_reply_to_status_id
448 * @return Zend_Rest_Client_Result
449 * @throws Zend_Http_Client_Exception if HTTP request fails or times out
450 * @throws Zend_Service_Twitter_Exception if message is too short or too long
452 public function statusUpdate($status, $inReplyToStatusId = null)
455 $path = '/1/statuses/update.xml';
456 $len = iconv_strlen(htmlspecialchars($status, ENT_QUOTES
, 'UTF-8'), 'UTF-8');
457 if ($len > self
::STATUS_MAX_CHARACTERS
) {
458 include_once 'Zend/Service/Twitter/Exception.php';
459 throw new Zend_Service_Twitter_Exception(
460 'Status must be no more than '
461 . self
::STATUS_MAX_CHARACTERS
462 . ' characters in length'
464 } elseif (0 == $len) {
465 include_once 'Zend/Service/Twitter/Exception.php';
466 throw new Zend_Service_Twitter_Exception(
467 'Status must contain at least one character'
470 $data = array('status' => $status);
471 if (is_numeric($inReplyToStatusId) && !empty($inReplyToStatusId)) {
472 $data['in_reply_to_status_id'] = $inReplyToStatusId;
474 $response = $this->_post($path, $data);
475 return new Zend_Rest_Client_Result($response->getBody());
481 * $params may include one or more of the following keys
482 * - since_id: return results only after the specified tweet id
483 * - page: return page X of results
485 * @throws Zend_Http_Client_Exception if HTTP request fails or times out
486 * @return Zend_Rest_Client_Result
488 public function statusReplies(array $params = array())
491 $path = '/1/statuses/mentions.xml';
493 foreach ($params as $key => $value) {
494 switch (strtolower($key)) {
496 $_params['since_id'] = $this->_validInteger($value);
499 $_params['page'] = (int) $value;
505 $response = $this->_get($path, $_params);
506 return new Zend_Rest_Client_Result($response->getBody());
510 * Destroy a status message
512 * @param int $id ID of status to destroy
513 * @throws Zend_Http_Client_Exception if HTTP request fails or times out
514 * @return Zend_Rest_Client_Result
516 public function statusDestroy($id)
519 $path = '/1/statuses/destroy/' . $this->_validInteger($id) . '.xml';
520 $response = $this->_post($path);
521 return new Zend_Rest_Client_Result($response->getBody());
527 * @param int|string $id Id or username of user for whom to fetch friends
528 * @throws Zend_Http_Client_Exception if HTTP request fails or times out
529 * @return Zend_Rest_Client_Result
531 public function userFriends(array $params = array())
534 $path = '/1/statuses/friends';
537 foreach ($params as $key => $value) {
538 switch (strtolower($key)) {
540 $path .= '/' . $value;
543 $_params['page'] = (int) $value;
551 $response = $this->_get($path, $_params);
552 return new Zend_Rest_Client_Result($response->getBody());
558 * @param bool $lite If true, prevents inline inclusion of current status for followers; defaults to false
559 * @throws Zend_Http_Client_Exception if HTTP request fails or times out
560 * @return Zend_Rest_Client_Result
562 public function userFollowers($lite = false)
565 $path = '/1/statuses/followers.xml';
567 $this->lite
= 'true';
569 $response = $this->_get($path);
570 return new Zend_Rest_Client_Result($response->getBody());
574 * Show extended information on a user
576 * @param int|string $id User ID or name
577 * @throws Zend_Http_Client_Exception if HTTP request fails or times out
578 * @return Zend_Rest_Client_Result
580 public function userShow($id)
583 $path = '/1/users/show.xml';
584 $response = $this->_get($path, array('id'=>$id));
585 return new Zend_Rest_Client_Result($response->getBody());
589 * Retrieve direct messages for the current user
591 * $params may include one or more of the following keys
592 * - since_id: return statuses only greater than the one specified
593 * - page: return page X of results
595 * @param array $params
596 * @throws Zend_Http_Client_Exception if HTTP request fails or times out
597 * @return Zend_Rest_Client_Result
599 public function directMessageMessages(array $params = array())
602 $path = '/1/direct_messages.xml';
604 foreach ($params as $key => $value) {
605 switch (strtolower($key)) {
607 $_params['since_id'] = $this->_validInteger($value);
610 $_params['page'] = (int) $value;
616 $response = $this->_get($path, $_params);
617 return new Zend_Rest_Client_Result($response->getBody());
621 * Retrieve list of direct messages sent by current user
623 * $params may include one or more of the following keys
624 * - since_id: return statuses only greater than the one specified
625 * - page: return page X of results
627 * @param array $params
628 * @throws Zend_Http_Client_Exception if HTTP request fails or times out
629 * @return Zend_Rest_Client_Result
631 public function directMessageSent(array $params = array())
634 $path = '/1/direct_messages/sent.xml';
636 foreach ($params as $key => $value) {
637 switch (strtolower($key)) {
639 $_params['since_id'] = $this->_validInteger($value);
642 $_params['page'] = (int) $value;
648 $response = $this->_get($path, $_params);
649 return new Zend_Rest_Client_Result($response->getBody());
653 * Send a direct message to a user
655 * @param int|string $user User to whom to send message
656 * @param string $text Message to send to user
657 * @return Zend_Rest_Client_Result
658 * @throws Zend_Service_Twitter_Exception if message is too short or too long
659 * @throws Zend_Http_Client_Exception if HTTP request fails or times out
661 public function directMessageNew($user, $text)
664 $path = '/1/direct_messages/new.xml';
665 $len = iconv_strlen($text, 'UTF-8');
667 throw new Zend_Service_Twitter_Exception(
668 'Direct message must contain at least one character'
670 } elseif (140 < $len) {
671 throw new Zend_Service_Twitter_Exception(
672 'Direct message must contain no more than 140 characters'
675 $data = array('user' => $user, 'text' => $text);
676 $response = $this->_post($path, $data);
677 return new Zend_Rest_Client_Result($response->getBody());
681 * Destroy a direct message
683 * @param int $id ID of message to destroy
684 * @throws Zend_Http_Client_Exception if HTTP request fails or times out
685 * @return Zend_Rest_Client_Result
687 public function directMessageDestroy($id)
690 $path = '/1/direct_messages/destroy/' . $this->_validInteger($id) . '.xml';
691 $response = $this->_post($path);
692 return new Zend_Rest_Client_Result($response->getBody());
698 * @param int|string $id User ID or name of new friend
699 * @throws Zend_Http_Client_Exception if HTTP request fails or times out
700 * @return Zend_Rest_Client_Result
702 public function friendshipCreate($id)
705 $path = '/1/friendships/create/' . $id . '.xml';
706 $response = $this->_post($path);
707 return new Zend_Rest_Client_Result($response->getBody());
713 * @param int|string $id User ID or name of friend to remove
714 * @throws Zend_Http_Client_Exception if HTTP request fails or times out
715 * @return Zend_Rest_Client_Result
717 public function friendshipDestroy($id)
720 $path = '/1/friendships/destroy/' . $id . '.xml';
721 $response = $this->_post($path);
722 return new Zend_Rest_Client_Result($response->getBody());
728 * @param int|string $id User ID or name of friend to see if they are your friend
729 * @throws Zend_Http_Client_Exception if HTTP request fails or times out
730 * @return Zend_Rest_Client_result
732 public function friendshipExists($id)
735 $path = '/1/friendships/exists.xml';
736 $data = array('user_a' => $this->getUsername(), 'user_b' => $id);
737 $response = $this->_get($path, $data);
738 return new Zend_Rest_Client_Result($response->getBody());
742 * Verify Account Credentials
743 * @throws Zend_Http_Client_Exception if HTTP request fails or times out
745 * @return Zend_Rest_Client_Result
747 public function accountVerifyCredentials()
750 $response = $this->_get('/1/account/verify_credentials.xml');
751 return new Zend_Rest_Client_Result($response->getBody());
755 * End current session
757 * @throws Zend_Http_Client_Exception if HTTP request fails or times out
760 public function accountEndSession()
763 $this->_get('/1/account/end_session');
768 * Returns the number of api requests you have left per hour.
770 * @throws Zend_Http_Client_Exception if HTTP request fails or times out
771 * @return Zend_Rest_Client_Result
773 public function accountRateLimitStatus()
776 $response = $this->_get('/1/account/rate_limit_status.xml');
777 return new Zend_Rest_Client_Result($response->getBody());
783 * $params may contain one or more of the following:
784 * - 'id': Id of a user for whom to fetch favorites
785 * - 'page': Retrieve a different page of resuls
787 * @param array $params
788 * @throws Zend_Http_Client_Exception if HTTP request fails or times out
789 * @return Zend_Rest_Client_Result
791 public function favoriteFavorites(array $params = array())
794 $path = '/1/favorites';
796 foreach ($params as $key => $value) {
797 switch (strtolower($key)) {
799 $path .= '/' . $this->_validInteger($value);
802 $_params['page'] = (int) $value;
809 $response = $this->_get($path, $_params);
810 return new Zend_Rest_Client_Result($response->getBody());
814 * Mark a status as a favorite
816 * @param int $id Status ID you want to mark as a favorite
817 * @throws Zend_Http_Client_Exception if HTTP request fails or times out
818 * @return Zend_Rest_Client_Result
820 public function favoriteCreate($id)
823 $path = '/1/favorites/create/' . $this->_validInteger($id) . '.xml';
824 $response = $this->_post($path);
825 return new Zend_Rest_Client_Result($response->getBody());
831 * @param int $id Status ID you want to de-list as a favorite
832 * @throws Zend_Http_Client_Exception if HTTP request fails or times out
833 * @return Zend_Rest_Client_Result
835 public function favoriteDestroy($id)
838 $path = '/1/favorites/destroy/' . $this->_validInteger($id) . '.xml';
839 $response = $this->_post($path);
840 return new Zend_Rest_Client_Result($response->getBody());
844 * Blocks the user specified in the ID parameter as the authenticating user.
845 * Destroys a friendship to the blocked user if it exists.
847 * @param integer|string $id The ID or screen name of a user to block.
848 * @return Zend_Rest_Client_Result
850 public function blockCreate($id)
853 $path = '/1/blocks/create/' . $id . '.xml';
854 $response = $this->_post($path);
855 return new Zend_Rest_Client_Result($response->getBody());
859 * Un-blocks the user specified in the ID parameter for the authenticating user
861 * @param integer|string $id The ID or screen_name of the user to un-block.
862 * @return Zend_Rest_Client_Result
864 public function blockDestroy($id)
867 $path = '/1/blocks/destroy/' . $id . '.xml';
868 $response = $this->_post($path);
869 return new Zend_Rest_Client_Result($response->getBody());
873 * Returns if the authenticating user is blocking a target user.
875 * @param string|integer $id The ID or screen_name of the potentially blocked user.
876 * @param boolean $returnResult Instead of returning a boolean return the rest response from twitter
877 * @return Boolean|Zend_Rest_Client_Result
879 public function blockExists($id, $returnResult = false)
882 $path = '/1/blocks/exists/' . $id . '.xml';
883 $response = $this->_get($path);
885 $cr = new Zend_Rest_Client_Result($response->getBody());
887 if ($returnResult === true)
890 if (!empty($cr->request
)) {
898 * Returns an array of user objects that the authenticating user is blocking
900 * @param integer $page Optional. Specifies the page number of the results beginning at 1. A single page contains 20 ids.
901 * @param boolean $returnUserIds Optional. Returns only the userid's instead of the whole user object
902 * @return Zend_Rest_Client_Result
904 public function blockBlocking($page = 1, $returnUserIds = false)
907 $path = '/1/blocks/blocking';
908 if ($returnUserIds === true) {
912 $response = $this->_get($path, array('page' => $page));
913 return new Zend_Rest_Client_Result($response->getBody());
917 * Protected function to validate that the integer is valid or return a 0
919 * @throws Zend_Http_Client_Exception if HTTP request fails or times out
922 protected function _validInteger($int)
924 if (preg_match("/(\d+)/", $int)) {
931 * Validate a screen name using Twitter rules
933 * @param string $name
934 * @throws Zend_Service_Twitter_Exception
937 protected function _validateScreenName($name)
939 if (!preg_match('/^[a-zA-Z0-9_]{0,20}$/', $name)) {
940 require_once 'Zend/Service/Twitter/Exception.php';
941 throw new Zend_Service_Twitter_Exception(
942 'Screen name, "' . $name
943 . '" should only contain alphanumeric characters and'
944 . ' underscores, and not exceed 15 characters.');
950 * Call a remote REST web service URI and return the Zend_Http_Response object
952 * @param string $path The path to append to the URI
953 * @throws Zend_Rest_Client_Exception
956 protected function _prepare($path)
958 // Get the URI object and configure it
959 if (!$this->_uri
instanceof Zend_Uri_Http
) {
960 require_once 'Zend/Rest/Client/Exception.php';
961 throw new Zend_Rest_Client_Exception(
962 'URI object must be set before performing call'
966 $uri = $this->_uri
->getUri();
968 if ($path[0] != '/' && $uri[strlen($uri) - 1] != '/') {
972 $this->_uri
->setPath($path);
975 * Get the HTTP client and configure it for the endpoint URI.
976 * Do this each time because the Zend_Http_Client instance is shared
977 * among all Zend_Service_Abstract subclasses.
979 $this->_localHttpClient
->resetParameters()->setUri((string) $this->_uri
);
983 * Performs an HTTP GET request to the $path.
985 * @param string $path
986 * @param array $query Array of GET parameters
987 * @throws Zend_Http_Client_Exception
988 * @return Zend_Http_Response
990 protected function _get($path, array $query = null)
992 $this->_prepare($path);
993 $this->_localHttpClient
->setParameterGet($query);
994 return $this->_localHttpClient
->request(Zend_Http_Client
::GET
);
998 * Performs an HTTP POST request to $path.
1000 * @param string $path
1001 * @param mixed $data Raw data to send
1002 * @throws Zend_Http_Client_Exception
1003 * @return Zend_Http_Response
1005 protected function _post($path, $data = null)
1007 $this->_prepare($path);
1008 return $this->_performPost(Zend_Http_Client
::POST
, $data);
1012 * Perform a POST or PUT
1014 * Performs a POST or PUT request. Any data provided is set in the HTTP
1015 * client. String data is pushed in as raw POST data; array or object data
1016 * is pushed in as POST parameters.
1018 * @param mixed $method
1019 * @param mixed $data
1020 * @return Zend_Http_Response
1022 protected function _performPost($method, $data = null)
1024 $client = $this->_localHttpClient
;
1025 if (is_string($data)) {
1026 $client->setRawData($data);
1027 } elseif (is_array($data) ||
is_object($data)) {
1028 $client->setParameterPost((array) $data);
1030 return $client->request($method);