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-2009 Zend Technologies USA Inc. (http://www.zend.com)
19 * @license http://framework.zend.com/license/new-bsd New BSD License
23 * @see Zend_Rest_Client
25 require_once 'Zend/Rest/Client.php';
27 * @see Zend_Rest_Client_Result
29 require_once 'Zend/Rest/Client/Result.php';
32 * @package Zend_Service
34 * @copyright Copyright (c) 2005-2009 Zend Technologies USA Inc. (http://www.zend.com)
35 * @license http://framework.zend.com/license/new-bsd New BSD License
37 class Zend_Service_Twitter extends Zend_Rest_Client
41 * 246 is the current limit for a status message, 140 characters are displayed
42 * initially, with the remainder linked from the web UI or client. The limit is
43 * applied to a html encoded UTF-8 string (i.e. entities are counted in the limit
44 * which may appear unusual but is a security measure).
46 * This should be reviewed in the future...
48 const STATUS_MAX_CHARACTERS = 246;
51 * Whether or not authorization has been initialized for the current user.
54 protected $_authInitialized = false;
56 * @var Zend_Http_CookieJar
58 protected $_cookieJar;
60 * Date format for 'since' strings
63 protected $_dateFormat = 'D, d M Y H:i:s T';
75 * Current method type (for method proxying)
78 protected $_methodType;
80 * Types of API methods
83 protected $_methodTypes = array('status', 'user', 'directMessage', 'friendship', 'account', 'favorite', 'block');
86 * Local HTTP Client cloned from statically set client
87 * @var Zend_Http_Client
89 protected $_localHttpClient = null;
94 * @param string $username
95 * @param string $password
98 public function __construct($username, $password = null)
100 $this->setLocalHttpClient(clone self::getHttpClient());
101 if (is_array($username) && is_null($password)) {
102 if (isset($username['username']) && isset($username['password'])) {
103 $this->setUsername($username['username']);
104 $this->setPassword($username['password']);
105 } elseif (isset($username[0]) && isset($username[1])) {
106 $this->setUsername($username[0]);
107 $this->setPassword($username[1]);
110 $this->setUsername($username);
111 $this->setPassword($password);
113 $this->setUri('http://twitter.com');
114 $this->_localHttpClient->setHeaders('Accept-Charset', 'ISO-8859-1,utf-8');
118 * Set local HTTP client as distinct from the static HTTP client
119 * as inherited from Zend_Rest_Client.
121 * @param Zend_Http_Client $client
124 public function setLocalHttpClient(Zend_Http_Client $client)
126 $this->_localHttpClient = $client;
130 public function getLocalHttpClient()
132 return $this->_localHttpClient;
140 public function getUsername()
142 return $this->_username;
148 * @param string $value
149 * @return Zend_Service_Twitter
151 public function setUsername($value)
153 $this->_username = $value;
154 $this->_authInitialized = false;
163 public function getPassword()
165 return $this->_password;
171 * @param string $value
172 * @return Zend_Service_Twitter
174 public function setPassword($value)
176 $this->_password = $value;
177 $this->_authInitialized = false;
182 * Proxy service methods
184 * @param string $type
185 * @return Zend_Service_Twitter
186 * @throws Zend_Service_Twitter_Exception if method is not in method types list
188 public function __get($type)
190 if (!in_array($type, $this->_methodTypes)) {
191 include_once 'Zend/Service/Twitter/Exception.php';
192 throw new Zend_Service_Twitter_Exception('Invalid method type "' . $type . '"');
194 $this->_methodType = $type;
201 * @param string $method
202 * @param array $params
204 * @throws Zend_Service_Twitter_Exception if unable to find method
206 public function __call($method, $params)
208 if (empty($this->_methodType)) {
209 include_once 'Zend/Service/Twitter/Exception.php';
210 throw new Zend_Service_Twitter_Exception('Invalid method "' . $method . '"');
212 $test = $this->_methodType . ucfirst($method);
213 if (!method_exists($this, $test)) {
214 include_once 'Zend/Service/Twitter/Exception.php';
215 throw new Zend_Service_Twitter_Exception('Invalid method "' . $test . '"');
218 return call_user_func_array(array($this, $test), $params);
222 * Initialize HTTP authentication
226 protected function _init()
228 $client = $this->_localHttpClient;
229 $client->resetParameters();
230 if (null == $this->_cookieJar) {
231 $client->setCookieJar();
232 $this->_cookieJar = $client->getCookieJar();
234 $client->setCookieJar($this->_cookieJar);
236 if (!$this->_authInitialized) {
237 $client->setAuth($this->getUsername(), $this->getPassword());
238 $this->_authInitialized = true;
245 * @param int|string $value
246 * @deprecated Not supported by Twitter since April 08, 2009
249 protected function _setDate($value)
251 if (is_int($value)) {
252 $date = date($this->_dateFormat, $value);
254 $date = date($this->_dateFormat, strtotime($value));
256 $this->_localHttpClient->setHeaders('If-Modified-Since', $date);
260 * Public Timeline status
262 * @throws Zend_Http_Client_Exception if HTTP request fails or times out
263 * @return Zend_Rest_Client_Result
265 public function statusPublicTimeline()
268 $path = '/statuses/public_timeline.xml';
269 $response = $this->_get($path);
270 return new Zend_Rest_Client_Result($response->getBody());
274 * Friend Timeline Status
276 * $params may include one or more of the following keys
277 * - id: ID of a friend whose timeline you wish to receive
278 * - count: how many statuses to return
279 * - since_id: return results only after the specific tweet
280 * - page: return page X of results
282 * @param array $params
283 * @throws Zend_Http_Client_Exception if HTTP request fails or times out
286 public function statusFriendsTimeline(array $params = array())
289 $path = '/statuses/friends_timeline';
291 foreach ($params as $key => $value) {
292 switch (strtolower($key)) {
294 $count = (int) $value;
297 } elseif (200 < $count) {
300 $_params['count'] = (int) $count;
303 $_params['since_id'] = $this->_validInteger($value);
306 $_params['page'] = (int) $value;
313 $response = $this->_get($path, $_params);
314 return new Zend_Rest_Client_Result($response->getBody());
318 * User Timeline status
320 * $params may include one or more of the following keys
321 * - id: ID of a friend whose timeline you wish to receive
322 * - since_id: return results only after the tweet id specified
323 * - page: return page X of results
324 * - count: how many statuses to return
325 * - max_id: returns only statuses with an ID less than or equal to the specified ID
326 * - user_id: specfies the ID of the user for whom to return the user_timeline
327 * - screen_name: specfies the screen name of the user for whom to return the user_timeline
329 * @throws Zend_Http_Client_Exception if HTTP request fails or times out
330 * @return Zend_Rest_Client_Result
332 public function statusUserTimeline(array $params = array())
335 $path = '/statuses/user_timeline';
337 foreach ($params as $key => $value) {
338 switch (strtolower($key)) {
340 $path .= '/' . $value;
343 $_params['page'] = (int) $value;
346 $count = (int) $value;
349 } elseif (200 < $count) {
352 $_params['count'] = $count;
355 $_params['user_id'] = $this->_validInteger($value);
358 $_params['screen_name'] = $this->_validateScreenName($value);
361 $_params['since_id'] = $this->_validInteger($value);
364 $_params['max_id'] = $this->_validInteger($value);
371 $response = $this->_get($path, $_params);
372 return new Zend_Rest_Client_Result($response->getBody());
376 * Show a single status
378 * @param int $id Id of status to show
379 * @throws Zend_Http_Client_Exception if HTTP request fails or times out
380 * @return Zend_Rest_Client_Result
382 public function statusShow($id)
385 $path = '/statuses/show/' . $this->_validInteger($id) . '.xml';
386 $response = $this->_get($path);
387 return new Zend_Rest_Client_Result($response->getBody());
391 * Update user's current status
393 * @param string $status
394 * @param int $in_reply_to_status_id
395 * @return Zend_Rest_Client_Result
396 * @throws Zend_Http_Client_Exception if HTTP request fails or times out
397 * @throws Zend_Service_Twitter_Exception if message is too short or too long
399 public function statusUpdate($status, $in_reply_to_status_id = null)
402 $path = '/statuses/update.xml';
403 $len = iconv_strlen(htmlspecialchars($status, ENT_QUOTES, 'UTF-8'), 'UTF-8');
404 if ($len > self::STATUS_MAX_CHARACTERS) {
405 include_once 'Zend/Service/Twitter/Exception.php';
406 throw new Zend_Service_Twitter_Exception('Status must be no more than ' . self::STATUS_MAX_CHARACTERS . ' characters in length');
407 } elseif (0 == $len) {
408 include_once 'Zend/Service/Twitter/Exception.php';
409 throw new Zend_Service_Twitter_Exception('Status must contain at least one character');
411 $data = array('status' => $status);
412 if (is_numeric($in_reply_to_status_id) && !empty($in_reply_to_status_id)) {
413 $data['in_reply_to_status_id'] = $in_reply_to_status_id;
415 //$this->status = $status;
416 $response = $this->_post($path, $data);
417 return new Zend_Rest_Client_Result($response->getBody());
423 * $params may include one or more of the following keys
424 * - since_id: return results only after the specified tweet id
425 * - page: return page X of results
427 * @throws Zend_Http_Client_Exception if HTTP request fails or times out
428 * @return Zend_Rest_Client_Result
430 public function statusReplies(array $params = array())
433 $path = '/statuses/replies.xml';
435 foreach ($params as $key => $value) {
436 switch (strtolower($key)) {
438 $_params['since_id'] = $this->_validInteger($value);
441 $_params['page'] = (int) $value;
447 $response = $this->_get($path, $_params);
448 return new Zend_Rest_Client_Result($response->getBody());
452 * Destroy a status message
454 * @param int $id ID of status to destroy
455 * @throws Zend_Http_Client_Exception if HTTP request fails or times out
456 * @return Zend_Rest_Client_Result
458 public function statusDestroy($id)
461 $path = '/statuses/destroy/' . $this->_validInteger($id) . '.xml';
462 $response = $this->_post($path);
463 return new Zend_Rest_Client_Result($response->getBody());
469 * @param int|string $id Id or username of user for whom to fetch friends
470 * @throws Zend_Http_Client_Exception if HTTP request fails or times out
471 * @return Zend_Rest_Client_Result
473 public function userFriends(array $params = array())
476 $path = '/statuses/friends';
479 foreach ($params as $key => $value) {
480 switch (strtolower($key)) {
482 $path .= '/' . $value;
485 $_params['page'] = (int) $value;
493 $response = $this->_get($path, $_params);
494 return new Zend_Rest_Client_Result($response->getBody());
500 * @param bool $lite If true, prevents inline inclusion of current status for followers; defaults to false
501 * @throws Zend_Http_Client_Exception if HTTP request fails or times out
502 * @return Zend_Rest_Client_Result
504 public function userFollowers($lite = false)
507 $path = '/statuses/followers.xml';
509 $this->lite = 'true';
511 $response = $this->_get($path);
512 return new Zend_Rest_Client_Result($response->getBody());
518 * @throws Zend_Http_Client_Exception if HTTP request fails or times out
519 * @return Zend_Rest_Client_Result
521 public function userFeatured()
524 $path = '/statuses/featured.xml';
525 $response = $this->_get($path);
526 return new Zend_Rest_Client_Result($response->getBody());
530 * Show extended information on a user
532 * @param int|string $id User ID or name
533 * @throws Zend_Http_Client_Exception if HTTP request fails or times out
534 * @return Zend_Rest_Client_Result
536 public function userShow($id)
539 $path = '/users/show/' . $id . '.xml';
540 $response = $this->_get($path);
541 return new Zend_Rest_Client_Result($response->getBody());
545 * Retrieve direct messages for the current user
547 * $params may include one or more of the following keys
548 * - since_id: return statuses only greater than the one specified
549 * - page: return page X of results
551 * @param array $params
552 * @throws Zend_Http_Client_Exception if HTTP request fails or times out
553 * @return Zend_Rest_Client_Result
555 public function directMessageMessages(array $params = array())
558 $path = '/direct_messages.xml';
560 foreach ($params as $key => $value) {
561 switch (strtolower($key)) {
563 $_params['since_id'] = $this->_validInteger($value);
566 $_params['page'] = (int) $value;
572 $response = $this->_get($path, $_params);
573 return new Zend_Rest_Client_Result($response->getBody());
577 * Retrieve list of direct messages sent by current user
579 * $params may include one or more of the following keys
580 * - since_id: return statuses only greater than the one specified
581 * - page: return page X of results
583 * @param array $params
584 * @throws Zend_Http_Client_Exception if HTTP request fails or times out
585 * @return Zend_Rest_Client_Result
587 public function directMessageSent(array $params = array())
590 $path = '/direct_messages/sent.xml';
592 foreach ($params as $key => $value) {
593 switch (strtolower($key)) {
595 $_params['since_id'] = $this->_validInteger($value);
598 $_params['page'] = (int) $value;
604 $response = $this->_get($path, $_params);
605 return new Zend_Rest_Client_Result($response->getBody());
609 * Send a direct message to a user
611 * @param int|string $user User to whom to send message
612 * @param string $text Message to send to user
613 * @return Zend_Rest_Client_Result
614 * @throws Zend_Service_Twitter_Exception if message is too short or too long
615 * @throws Zend_Http_Client_Exception if HTTP request fails or times out
617 public function directMessageNew($user, $text)
620 $path = '/direct_messages/new.xml';
621 $len = iconv_strlen($text, 'UTF-8');
623 throw new Zend_Service_Twitter_Exception('Direct message must contain at least one character');
624 } elseif (140 < $len) {
625 throw new Zend_Service_Twitter_Exception('Direct message must contain no more than 140 characters');
627 $data = array('user' => $user, 'text' => $text);
628 $response = $this->_post($path, $data);
629 return new Zend_Rest_Client_Result($response->getBody());
633 * Destroy a direct message
635 * @param int $id ID of message to destroy
636 * @throws Zend_Http_Client_Exception if HTTP request fails or times out
637 * @return Zend_Rest_Client_Result
639 public function directMessageDestroy($id)
642 $path = '/direct_messages/destroy/' . $this->_validInteger($id) . '.xml';
643 $response = $this->_post($path);
644 return new Zend_Rest_Client_Result($response->getBody());
650 * @param int|string $id User ID or name of new friend
651 * @throws Zend_Http_Client_Exception if HTTP request fails or times out
652 * @return Zend_Rest_Client_Result
654 public function friendshipCreate($id)
657 $path = '/friendships/create/' . $id . '.xml';
658 $response = $this->_post($path);
659 return new Zend_Rest_Client_Result($response->getBody());
665 * @param int|string $id User ID or name of friend to remove
666 * @throws Zend_Http_Client_Exception if HTTP request fails or times out
667 * @return Zend_Rest_Client_Result
669 public function friendshipDestroy($id)
672 $path = '/friendships/destroy/' . $id . '.xml';
673 $response = $this->_post($path);
674 return new Zend_Rest_Client_Result($response->getBody());
680 * @param int|string $id User ID or name of friend to see if they are your friend
681 * @throws Zend_Http_Client_Exception if HTTP request fails or times out
682 * @return Zend_Rest_Client_result
684 public function friendshipExists($id)
687 $path = '/friendships/exists.xml';
688 $data = array('user_a' => $this->getUsername(), 'user_b' => $id);
689 $response = $this->_get($path, $data);
690 return new Zend_Rest_Client_Result($response->getBody());
694 * Verify Account Credentials
695 * @throws Zend_Http_Client_Exception if HTTP request fails or times out
697 * @return Zend_Rest_Client_Result
699 public function accountVerifyCredentials()
702 $response = $this->_get('/account/verify_credentials.xml');
703 return new Zend_Rest_Client_Result($response->getBody());
707 * End current session
709 * @throws Zend_Http_Client_Exception if HTTP request fails or times out
712 public function accountEndSession()
715 $this->_get('/account/end_session');
720 * Returns the number of api requests you have left per hour.
722 * @throws Zend_Http_Client_Exception if HTTP request fails or times out
723 * @return Zend_Rest_Client_Result
725 public function accountRateLimitStatus()
728 $response = $this->_get('/account/rate_limit_status.xml');
729 return new Zend_Rest_Client_Result($response->getBody());
735 * $params may contain one or more of the following:
736 * - 'id': Id of a user for whom to fetch favorites
737 * - 'page': Retrieve a different page of resuls
739 * @param array $params
740 * @throws Zend_Http_Client_Exception if HTTP request fails or times out
741 * @return Zend_Rest_Client_Result
743 public function favoriteFavorites(array $params = array())
746 $path = '/favorites';
748 foreach ($params as $key => $value) {
749 switch (strtolower($key)) {
751 $path .= '/' . $this->_validInteger($value);
754 $_params['page'] = (int) $value;
761 $response = $this->_get($path, $_params);
762 return new Zend_Rest_Client_Result($response->getBody());
766 * Mark a status as a favorite
768 * @param int $id Status ID you want to mark as a favorite
769 * @throws Zend_Http_Client_Exception if HTTP request fails or times out
770 * @return Zend_Rest_Client_Result
772 public function favoriteCreate($id)
775 $path = '/favorites/create/' . $this->_validInteger($id) . '.xml';
776 $response = $this->_post($path);
777 return new Zend_Rest_Client_Result($response->getBody());
783 * @param int $id Status ID you want to de-list as a favorite
784 * @throws Zend_Http_Client_Exception if HTTP request fails or times out
785 * @return Zend_Rest_Client_Result
787 public function favoriteDestroy($id)
790 $path = '/favorites/destroy/' . $this->_validInteger($id) . '.xml';
791 $response = $this->_post($path);
792 return new Zend_Rest_Client_Result($response->getBody());
796 * Blocks the user specified in the ID parameter as the authenticating user.
797 * Destroys a friendship to the blocked user if it exists.
799 * @param integer|string $id The ID or screen name of a user to block.
800 * @return Zend_Rest_Client_Result
802 public function blockCreate($id)
805 $path = '/blocks/create/' . $id . '.xml';
806 $response = $this->_post($path);
807 return new Zend_Rest_Client_Result($response->getBody());
811 * Un-blocks the user specified in the ID parameter for the authenticating user
813 * @param integer|string $id The ID or screen_name of the user to un-block.
814 * @return Zend_Rest_Client_Result
816 public function blockDestroy($id)
819 $path = '/blocks/destroy/' . $id . '.xml';
820 $response = $this->_post($path);
821 return new Zend_Rest_Client_Result($response->getBody());
825 * Returns if the authenticating user is blocking a target user.
827 * @param string|integer $id The ID or screen_name of the potentially blocked user.
828 * @param boolean $returnResult Instead of returning a boolean return the rest response from twitter
829 * @return Boolean|Zend_Rest_Client_Result
831 public function blockExists($id, $returnResult = false)
834 $path = '/blocks/exists/' . $id . '.xml';
835 $response = $this->_get($path);
837 $cr = new Zend_Rest_Client_Result($response->getBody());
839 if ($returnResult === true)
842 if (!empty($cr->request)) {
850 * Returns an array of user objects that the authenticating user is blocking
852 * @param integer $page Optional. Specifies the page number of the results beginning at 1. A single page contains 20 ids.
853 * @param boolean $returnUserIds Optional. Returns only the userid's instead of the whole user object
854 * @return Zend_Rest_Client_Result
856 public function blockBlocking($page = 1, $returnUserIds = false)
859 $path = '/blocks/blocking';
860 if ($returnUserIds === true) {
864 $response = $this->_get($path, array('page' => $page));
865 return new Zend_Rest_Client_Result($response->getBody());
869 * Protected function to validate that the integer is valid or return a 0
\r
871 * @throws Zend_Http_Client_Exception if HTTP request fails or times out
\r
874 protected function _validInteger($int)
876 if (preg_match("/(\d+)/", $int)) {
883 * Validate a screen name using Twitter rules
885 * @param string $name
886 * @throws Zend_Service_Twitter_Exception
889 protected function _validateScreenName($name)
891 if (!preg_match('/^[a-zA-Z0-9_]{0,20}$/', $name)) {
892 require_once 'Zend/Service/Twitter/Exception.php';
893 throw new Zend_Service_Twitter_Exception('Screen name, "' . $name . '" should only contain alphanumeric characters and' . ' underscores, and not exceed 15 characters.');
899 * Call a remote REST web service URI and return the Zend_Http_Response object
901 * @param string $path The path to append to the URI
902 * @throws Zend_Rest_Client_Exception
905 protected function _prepare($path)
907 // Get the URI object and configure it
908 if (!$this->_uri instanceof Zend_Uri_Http) {
909 require_once 'Zend/Rest/Client/Exception.php';
910 throw new Zend_Rest_Client_Exception('URI object must be set before performing call');
913 $uri = $this->_uri->getUri();
915 if ($path[0] != '/' && $uri[strlen($uri) - 1] != '/') {
919 $this->_uri->setPath($path);
922 * Get the HTTP client and configure it for the endpoint URI. Do this each time
923 * because the Zend_Http_Client instance is shared among all Zend_Service_Abstract subclasses.
925 $this->_localHttpClient->resetParameters()->setUri($this->_uri);
929 * Performs an HTTP GET request to the $path.
931 * @param string $path
932 * @param array $query Array of GET parameters
933 * @throws Zend_Http_Client_Exception
934 * @return Zend_Http_Response
936 protected function _get($path, array $query = null)
938 $this->_prepare($path);
939 $this->_localHttpClient->setParameterGet($query);
940 return $this->_localHttpClient->request('GET');
944 * Performs an HTTP POST request to $path.
946 * @param string $path
947 * @param mixed $data Raw data to send
948 * @throws Zend_Http_Client_Exception
949 * @return Zend_Http_Response
951 protected function _post($path, $data = null)
953 $this->_prepare($path);
954 return $this->_performPost('POST', $data);
958 * Perform a POST or PUT
960 * Performs a POST or PUT request. Any data provided is set in the HTTP
961 * client. String data is pushed in as raw POST data; array or object data
962 * is pushed in as POST parameters.
964 * @param mixed $method
966 * @return Zend_Http_Response
968 protected function _performPost($method, $data = null)
970 $client = $this->_localHttpClient;
971 if (is_string($data)) {
972 $client->setRawData($data);
973 } elseif (is_array($data) || is_object($data)) {
974 $client->setParameterPost((array) $data);
976 return $client->request($method);