| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307 |
- <?php
- /**
- * Zend Framework
- *
- * LICENSE
- *
- * This source file is subject to the new BSD license that is bundled
- * with this package in the file LICENSE.txt.
- * It is also available through the world-wide-web at this URL:
- * http://framework.zend.com/license/new-bsd
- * If you did not receive a copy of the license and are unable to
- * obtain it through the world-wide-web, please send an email
- * to license@zend.com so we can send you a copy immediately.
- *
- * @category Zend
- * @package Zend_Service
- * @subpackage Twitter
- * @copyright Copyright (c) 2005-2015 Zend Technologies USA Inc. (http://www.zend.com)
- * @license http://framework.zend.com/license/new-bsd New BSD License
- * @version $Id$
- */
- /**
- * @see Zend_Http_Client
- */
- require_once 'Zend/Http/Client.php';
- /**
- * @see Zend_Http_CookieJar
- */
- require_once 'Zend/Http/CookieJar.php';
- /**
- * @see Zend_Oauth_Consumer
- */
- require_once 'Zend/Oauth/Consumer.php';
- /**
- * @see Zend_Oauth_Token_Access
- */
- require_once 'Zend/Oauth/Token/Access.php';
- /**
- * @see Zend_Service_Twitter_Response
- */
- require_once 'Zend/Service/Twitter/Response.php';
- /**
- * @category Zend
- * @package Zend_Service
- * @subpackage Twitter
- * @copyright Copyright (c) 2005-2015 Zend Technologies USA Inc. (http://www.zend.com)
- * @license http://framework.zend.com/license/new-bsd New BSD License
- */
- class Zend_Service_Twitter
- {
- /**
- * Base URI for all API calls
- */
- const API_BASE_URI = 'https://api.twitter.com/1.1/';
- /**
- * OAuth Endpoint
- */
- const OAUTH_BASE_URI = 'https://api.twitter.com/oauth';
- /**
- * 246 is the current limit for a status message, 140 characters are displayed
- * initially, with the remainder linked from the web UI or client. The limit is
- * applied to a html encoded UTF-8 string (i.e. entities are counted in the limit
- * which may appear unusual but is a security measure).
- *
- * This should be reviewed in the future...
- */
- const STATUS_MAX_CHARACTERS = 246;
- /**
- * @var array
- */
- protected $cookieJar;
- /**
- * Date format for 'since' strings
- *
- * @var string
- */
- protected $dateFormat = 'D, d M Y H:i:s T';
- /**
- * @var Zend_Http_Client
- */
- protected $httpClient = null;
- /**
- * Current method type (for method proxying)
- *
- * @var string
- */
- protected $methodType;
- /**
- * Oauth Consumer
- *
- * @var Zend_Oauth_Consumer
- */
- protected $oauthConsumer = null;
- /**
- * Types of API methods
- *
- * @var array
- */
- protected $methodTypes = array(
- 'account',
- 'application',
- 'blocks',
- 'directmessages',
- 'favorites',
- 'friendships',
- 'search',
- 'statuses',
- 'users',
- );
- /**
- * Options passed to constructor
- *
- * @var array
- */
- protected $options = array();
- /**
- * Username
- *
- * @var string
- */
- protected $username;
- /**
- * Constructor
- *
- * @param null|array|Zend_Config $options
- * @param null|Zend_Oauth_Consumer $consumer
- * @param null|Zend_Http_Client $httpClient
- */
- public function __construct($options = null, Zend_Oauth_Consumer $consumer = null, Zend_Http_Client $httpClient = null)
- {
- if ($options instanceof Zend_Config) {
- $options = $options->toArray();
- }
- if (!is_array($options)) {
- $options = array();
- }
- $this->options = $options;
- if (isset($options['username'])) {
- $this->setUsername($options['username']);
- }
- $accessToken = false;
- if (isset($options['accessToken'])) {
- $accessToken = $options['accessToken'];
- } elseif (isset($options['access_token'])) {
- $accessToken = $options['access_token'];
- }
- $oauthOptions = array();
- if (isset($options['oauthOptions'])) {
- $oauthOptions = $options['oauthOptions'];
- } elseif (isset($options['oauth_options'])) {
- $oauthOptions = $options['oauth_options'];
- }
- $oauthOptions['siteUrl'] = self::OAUTH_BASE_URI;
- $httpClientOptions = array();
- if (isset($options['httpClientOptions'])) {
- $httpClientOptions = $options['httpClientOptions'];
- } elseif (isset($options['http_client_options'])) {
- $httpClientOptions = $options['http_client_options'];
- }
- // If we have an OAuth access token, use the HTTP client it provides
- if ($accessToken && is_array($accessToken)
- && (isset($accessToken['token']) && isset($accessToken['secret']))
- ) {
- $token = new Zend_Oauth_Token_Access();
- $token->setToken($accessToken['token']);
- $token->setTokenSecret($accessToken['secret']);
- $accessToken = $token;
- }
- if ($accessToken && $accessToken instanceof Zend_Oauth_Token_Access) {
- $oauthOptions['token'] = $accessToken;
- $this->setHttpClient($accessToken->getHttpClient($oauthOptions, self::OAUTH_BASE_URI, $httpClientOptions));
- return;
- }
- // See if we were passed an http client
- if (isset($options['httpClient']) && null === $httpClient) {
- $httpClient = $options['httpClient'];
- } elseif (isset($options['http_client']) && null === $httpClient) {
- $httpClient = $options['http_client'];
- }
- if ($httpClient instanceof Zend_Http_Client) {
- $this->httpClient = $httpClient;
- } else {
- $this->setHttpClient(new Zend_Http_Client(null, $httpClientOptions));
- }
- // Set the OAuth consumer
- if ($consumer === null) {
- $consumer = new Zend_Oauth_Consumer($oauthOptions);
- }
- $this->oauthConsumer = $consumer;
- }
- /**
- * Proxy service methods
- *
- * @param string $type
- * @return Twitter
- * @throws Exception\DomainException If method not in method types list
- */
- public function __get($type)
- {
- $type = strtolower($type);
- $type = str_replace('_', '', $type);
- if (!in_array($type, $this->methodTypes)) {
- require_once 'Zend/Service/Twitter/Exception.php';
- throw new Zend_Service_Twitter_Exception(
- 'Invalid method type "' . $type . '"'
- );
- }
- $this->methodType = $type;
- return $this;
- }
- /**
- * Method overloading
- *
- * @param string $method
- * @param array $params
- * @return mixed
- * @throws Exception\BadMethodCallException if unable to find method
- */
- public function __call($method, $params)
- {
- if (method_exists($this->oauthConsumer, $method)) {
- $return = call_user_func_array(array($this->oauthConsumer, $method), $params);
- if ($return instanceof Zend_Oauth_Token_Access) {
- $this->setHttpClient($return->getHttpClient($this->options));
- }
- return $return;
- }
- if (empty($this->methodType)) {
- require_once 'Zend/Service/Twitter/Exception.php';
- throw new Zend_Service_Twitter_Exception(
- 'Invalid method "' . $method . '"'
- );
- }
- $test = str_replace('_', '', strtolower($method));
- $test = $this->methodType . $test;
- if (!method_exists($this, $test)) {
- require_once 'Zend/Service/Twitter/Exception.php';
- throw new Zend_Service_Twitter_Exception(
- 'Invalid method "' . $test . '"'
- );
- }
- return call_user_func_array(array($this, $test), $params);
- }
- /**
- * Set HTTP client
- *
- * @param Zend_Http_Client $client
- * @return self
- */
- public function setHttpClient(Zend_Http_Client $client)
- {
- $this->httpClient = $client;
- $this->httpClient->setHeaders(array('Accept-Charset' => 'ISO-8859-1,utf-8'));
- return $this;
- }
- /**
- * Get the HTTP client
- *
- * Lazy loads one if none present
- *
- * @return Zend_Http_Client
- */
- public function getHttpClient()
- {
- if (null === $this->httpClient) {
- $this->setHttpClient(new Zend_Http_Client());
- }
- return $this->httpClient;
- }
- /**
- * Retrieve username
- *
- * @return string
- */
- public function getUsername()
- {
- return $this->username;
- }
- /**
- * Set username
- *
- * @param string $value
- * @return self
- */
- public function setUsername($value)
- {
- $this->username = $value;
- return $this;
- }
- /**
- * Checks for an authorised state
- *
- * @return bool
- */
- public function isAuthorised()
- {
- if ($this->getHttpClient() instanceof Zend_Oauth_Client) {
- return true;
- }
- return false;
- }
- /**
- * Verify Account Credentials
- *
- * @throws Zend_Http_Client_Exception if HTTP request fails or times out
- * @throws Exception\DomainException if unable to decode JSON payload
- * @return Zend_Service_Twitter_Response
- */
- public function accountVerifyCredentials()
- {
- $this->init();
- $response = $this->get('account/verify_credentials');
- return new Zend_Service_Twitter_Response($response);
- }
- /**
- * Returns the number of api requests you have left per hour.
- *
- * @todo Have a separate payload object to represent rate limits
- * @throws Zend_Http_Client_Exception if HTTP request fails or times out
- * @throws Exception\DomainException if unable to decode JSON payload
- * @return Zend_Service_Twitter_Response
- */
- public function applicationRateLimitStatus()
- {
- $this->init();
- $response = $this->get('application/rate_limit_status');
- return new Zend_Service_Twitter_Response($response);
- }
- /**
- * Blocks the user specified in the ID parameter as the authenticating user.
- * Destroys a friendship to the blocked user if it exists.
- *
- * @param integer|string $id The ID or screen name of a user to block.
- * @throws Exception\DomainException if unable to decode JSON payload
- * @return Zend_Service_Twitter_Response
- */
- public function blocksCreate($id)
- {
- $this->init();
- $path = 'blocks/create';
- $params = $this->createUserParameter($id, array());
- $response = $this->post($path, $params);
- return new Zend_Service_Twitter_Response($response);
- }
- /**
- * Un-blocks the user specified in the ID parameter for the authenticating user
- *
- * @param integer|string $id The ID or screen_name of the user to un-block.
- * @throws Exception\DomainException if unable to decode JSON payload
- * @return Zend_Service_Twitter_Response
- */
- public function blocksDestroy($id)
- {
- $this->init();
- $path = 'blocks/destroy';
- $params = $this->createUserParameter($id, array());
- $response = $this->post($path, $params);
- return new Zend_Service_Twitter_Response($response);
- }
- /**
- * Returns an array of user ids that the authenticating user is blocking
- *
- * @param integer $cursor Optional. Specifies the cursor position at which to begin listing ids; defaults to first "page" of results.
- * @throws Exception\DomainException if unable to decode JSON payload
- * @return Zend_Service_Twitter_Response
- */
- public function blocksIds($cursor = -1)
- {
- $this->init();
- $path = 'blocks/ids';
- $response = $this->get($path, array('cursor' => $cursor));
- return new Zend_Service_Twitter_Response($response);
- }
- /**
- * Returns an array of user objects that the authenticating user is blocking
- *
- * @param integer $cursor Optional. Specifies the cursor position at which to begin listing ids; defaults to first "page" of results.
- * @throws Exception\DomainException if unable to decode JSON payload
- * @return Zend_Service_Twitter_Response
- */
- public function blocksList($cursor = -1)
- {
- $this->init();
- $path = 'blocks/list';
- $response = $this->get($path, array('cursor' => $cursor));
- return new Zend_Service_Twitter_Response($response);
- }
- /**
- * Destroy a direct message
- *
- * @param int $id ID of message to destroy
- * @throws Zend_Http_Client_Exception if HTTP request fails or times out
- * @throws Exception\DomainException if unable to decode JSON payload
- * @return Zend_Service_Twitter_Response
- */
- public function directMessagesDestroy($id)
- {
- $this->init();
- $path = 'direct_messages/destroy';
- $params = array('id' => $this->validInteger($id));
- $response = $this->post($path, $params);
- return new Zend_Service_Twitter_Response($response);
- }
- /**
- * Retrieve direct messages for the current user
- *
- * $options may include one or more of the following keys
- * - count: return page X of results
- * - since_id: return statuses only greater than the one specified
- * - max_id: return statuses with an ID less than (older than) or equal to that specified
- * - include_entities: setting to false will disable embedded entities
- * - skip_status:setting to true, "t", or 1 will omit the status in returned users
- *
- * @param array $options
- * @throws Zend_Http_Client_Exception if HTTP request fails or times out
- * @throws Exception\DomainException if unable to decode JSON payload
- * @return Zend_Service_Twitter_Response
- */
- public function directMessagesMessages(array $options = array())
- {
- $this->init();
- $path = 'direct_messages';
- $params = array();
- foreach ($options as $key => $value) {
- switch (strtolower($key)) {
- case 'count':
- $params['count'] = (int) $value;
- break;
- case 'since_id':
- $params['since_id'] = $this->validInteger($value);
- break;
- case 'max_id':
- $params['max_id'] = $this->validInteger($value);
- break;
- case 'include_entities':
- $params['include_entities'] = (bool) $value;
- break;
- case 'skip_status':
- $params['skip_status'] = (bool) $value;
- break;
- default:
- break;
- }
- }
- $response = $this->get($path, $params);
- return new Zend_Service_Twitter_Response($response);
- }
- /**
- * Send a direct message to a user
- *
- * @param int|string $user User to whom to send message
- * @param string $text Message to send to user
- * @throws Exception\InvalidArgumentException if message is empty
- * @throws Exception\OutOfRangeException if message is too long
- * @throws Zend_Http_Client_Exception if HTTP request fails or times out
- * @throws Exception\DomainException if unable to decode JSON payload
- * @return Zend_Service_Twitter_Response
- */
- public function directMessagesNew($user, $text)
- {
- $this->init();
- $path = 'direct_messages/new';
- $len = iconv_strlen($text, 'UTF-8');
- if (0 == $len) {
- require_once 'Zend/Service/Twitter/Exception.php';
- throw new Zend_Service_Twitter_Exception(
- 'Direct message must contain at least one character'
- );
- } elseif (140 < $len) {
- require_once 'Zend/Service/Twitter/Exception.php';
- throw new Zend_Service_Twitter_Exception(
- 'Direct message must contain no more than 140 characters'
- );
- }
- $params = $this->createUserParameter($user, array());
- $params['text'] = $text;
- $response = $this->post($path, $params);
- return new Zend_Service_Twitter_Response($response);
- }
- /**
- * Retrieve list of direct messages sent by current user
- *
- * $options may include one or more of the following keys
- * - count: return page X of results
- * - page: return starting at page
- * - since_id: return statuses only greater than the one specified
- * - max_id: return statuses with an ID less than (older than) or equal to that specified
- * - include_entities: setting to false will disable embedded entities
- *
- * @param array $options
- * @throws Zend_Http_Client_Exception if HTTP request fails or times out
- * @throws Exception\DomainException if unable to decode JSON payload
- * @return Zend_Service_Twitter_Response
- */
- public function directMessagesSent(array $options = array())
- {
- $this->init();
- $path = 'direct_messages/sent';
- $params = array();
- foreach ($options as $key => $value) {
- switch (strtolower($key)) {
- case 'count':
- $params['count'] = (int) $value;
- break;
- case 'page':
- $params['page'] = (int) $value;
- break;
- case 'since_id':
- $params['since_id'] = $this->validInteger($value);
- break;
- case 'max_id':
- $params['max_id'] = $this->validInteger($value);
- break;
- case 'include_entities':
- $params['include_entities'] = (bool) $value;
- break;
- default:
- break;
- }
- }
- $response = $this->get($path, $params);
- return new Zend_Service_Twitter_Response($response);
- }
- /**
- * Mark a status as a favorite
- *
- * @param int $id Status ID you want to mark as a favorite
- * @throws Zend_Http_Client_Exception if HTTP request fails or times out
- * @throws Exception\DomainException if unable to decode JSON payload
- * @return Zend_Service_Twitter_Response
- */
- public function favoritesCreate($id)
- {
- $this->init();
- $path = 'favorites/create';
- $params = array('id' => $this->validInteger($id));
- $response = $this->post($path, $params);
- return new Zend_Service_Twitter_Response($response);
- }
- /**
- * Remove a favorite
- *
- * @param int $id Status ID you want to de-list as a favorite
- * @throws Zend_Http_Client_Exception if HTTP request fails or times out
- * @throws Exception\DomainException if unable to decode JSON payload
- * @return Zend_Service_Twitter_Response
- */
- public function favoritesDestroy($id)
- {
- $this->init();
- $path = 'favorites/destroy';
- $params = array('id' => $this->validInteger($id));
- $response = $this->post($path, $params);
- return new Zend_Service_Twitter_Response($response);
- }
- /**
- * Fetch favorites
- *
- * $options may contain one or more of the following:
- * - user_id: Id of a user for whom to fetch favorites
- * - screen_name: Screen name of a user for whom to fetch favorites
- * - count: number of tweets to attempt to retrieve, up to 200
- * - since_id: return results only after the specified tweet id
- * - max_id: return results with an ID less than (older than) or equal to the specified ID
- * - include_entities: when set to false, entities member will be omitted
- *
- * @param array $params
- * @throws Zend_Http_Client_Exception if HTTP request fails or times out
- * @throws Exception\DomainException if unable to decode JSON payload
- * @return Zend_Service_Twitter_Response
- */
- public function favoritesList(array $options = array())
- {
- $this->init();
- $path = 'favorites/list';
- $params = array();
- foreach ($options as $key => $value) {
- switch (strtolower($key)) {
- case 'user_id':
- $params['user_id'] = $this->validInteger($value);
- break;
- case 'screen_name':
- $params['screen_name'] = $value;
- break;
- case 'count':
- $params['count'] = (int) $value;
- break;
- case 'since_id':
- $params['since_id'] = $this->validInteger($value);
- break;
- case 'max_id':
- $params['max_id'] = $this->validInteger($value);
- break;
- case 'include_entities':
- $params['include_entities'] = (bool) $value;
- break;
- default:
- break;
- }
- }
- $response = $this->get($path, $params);
- return new Zend_Service_Twitter_Response($response);
- }
- /**
- * Create friendship
- *
- * @param int|string $id User ID or name of new friend
- * @param array $params Additional parameters to pass
- * @throws Zend_Http_Client_Exception if HTTP request fails or times out
- * @throws Exception\DomainException if unable to decode JSON payload
- * @return Zend_Service_Twitter_Response
- */
- public function friendshipsCreate($id, array $params = array())
- {
- $this->init();
- $path = 'friendships/create';
- $params = $this->createUserParameter($id, $params);
- $allowed = array(
- 'user_id' => null,
- 'screen_name' => null,
- 'follow' => null,
- );
- $params = array_intersect_key($params, $allowed);
- $response = $this->post($path, $params);
- return new Zend_Service_Twitter_Response($response);
- }
- /**
- * Destroy friendship
- *
- * @param int|string $id User ID or name of friend to remove
- * @throws Zend_Http_Client_Exception if HTTP request fails or times out
- * @throws Exception\DomainException if unable to decode JSON payload
- * @return Zend_Service_Twitter_Response
- */
- public function friendshipsDestroy($id)
- {
- $this->init();
- $path = 'friendships/destroy';
- $params = $this->createUserParameter($id, array());
- $response = $this->post($path, $params);
- return new Zend_Service_Twitter_Response($response);
- }
- /**
- * Search tweets
- *
- * $options may include any of the following:
- * - geocode: a string of the form "latitude, longitude, radius"
- * - lang: restrict tweets to the two-letter language code
- * - locale: query is in the given two-letter language code
- * - result_type: what type of results to receive: mixed, recent, or popular
- * - count: number of tweets to return per page; up to 100
- * - until: return tweets generated before the given date
- * - since_id: return resutls with an ID greater than (more recent than) the given ID
- * - max_id: return results with an ID less than (older than) the given ID
- * - include_entities: whether or not to include embedded entities
- *
- * @param string $query
- * @param array $options
- * @throws Zend_Http_Client_Exception if HTTP request fails or times out
- * @throws Exception\DomainException if unable to decode JSON payload
- * @return Zend_Service_Twitter_Response
- */
- public function searchTweets($query, array $options = array())
- {
- $this->init();
- $path = 'search/tweets';
- $len = iconv_strlen($query, 'UTF-8');
- if (0 == $len) {
- require_once 'Zend/Service/Twitter/Exception.php';
- throw new Zend_Service_Twitter_Exception(
- 'Query must contain at least one character'
- );
- }
- $params = array('q' => $query);
- foreach ($options as $key => $value) {
- switch (strtolower($key)) {
- case 'geocode':
- if (!substr_count($value, ',') !== 2) {
- require_once 'Zend/Service/Twitter/Exception.php';
- throw new Zend_Service_Twitter_Exception(
- '"geocode" must be of the format "latitude,longitude,radius"'
- );
- }
- list($latitude, $longitude, $radius) = explode(',', $value);
- $radius = trim($radius);
- if (!preg_match('/^\d+(mi|km)$/', $radius)) {
- require_once 'Zend/Service/Twitter/Exception.php';
- throw new Zend_Service_Twitter_Exception(
- 'Radius segment of "geocode" must be of the format "[unit](mi|km)"'
- );
- }
- $latitude = (float) $latitude;
- $longitude = (float) $longitude;
- $params['geocode'] = $latitude . ',' . $longitude . ',' . $radius;
- break;
- case 'lang':
- if (strlen($value) > 2) {
- require_once 'Zend/Service/Twitter/Exception.php';
- throw new Zend_Service_Twitter_Exception(
- 'Query language must be a 2 character string'
- );
- }
- $params['lang'] = strtolower($value);
- break;
- case 'locale':
- if (strlen($value) > 2) {
- require_once 'Zend/Service/Twitter/Exception.php';
- throw new Zend_Service_Twitter_Exception(
- 'Query locale must be a 2 character string'
- );
- }
- $params['locale'] = strtolower($value);
- break;
- case 'result_type':
- $value = strtolower($value);
- if (!in_array($value, array('mixed', 'recent', 'popular'))) {
- require_once 'Zend/Service/Twitter/Exception.php';
- throw new Zend_Service_Twitter_Exception(
- 'result_type must be one of "mixed", "recent", or "popular"'
- );
- }
- $params['result_type'] = $value;
- break;
- case 'count':
- $value = (int) $value;
- if (1 > $value || 100 < $value) {
- require_once 'Zend/Service/Twitter/Exception.php';
- throw new Zend_Service_Twitter_Exception(
- 'count must be between 1 and 100'
- );
- }
- $params['count'] = $value;
- break;
- case 'until':
- if (!preg_match('/^\d{4}-\d{2}-\d{2}$/', $value)) {
- require_once 'Zend/Service/Twitter/Exception.php';
- throw new Zend_Service_Twitter_Exception(
- '"until" must be a date in the format YYYY-MM-DD'
- );
- }
- $params['until'] = $value;
- break;
- case 'since_id':
- $params['since_id'] = $this->validInteger($value);
- break;
- case 'max_id':
- $params['max_id'] = $this->validInteger($value);
- break;
- case 'include_entities':
- $params['include_entities'] = (bool) $value;
- break;
- default:
- break;
- }
- }
- $response = $this->get($path, $params);
- return new Zend_Service_Twitter_Response($response);
- }
- /**
- * Destroy a status message
- *
- * @param int $id ID of status to destroy
- * @throws Zend_Http_Client_Exception if HTTP request fails or times out
- * @throws Exception\DomainException if unable to decode JSON payload
- * @return Zend_Service_Twitter_Response
- */
- public function statusesDestroy($id)
- {
- $this->init();
- $path = 'statuses/destroy/' . $this->validInteger($id);
- $response = $this->post($path);
- return new Zend_Service_Twitter_Response($response);
- }
- /**
- * Friend Timeline Status
- *
- * $options may include one or more of the following keys
- * - count: number of tweets to attempt to retrieve, up to 200
- * - since_id: return results only after the specified tweet id
- * - max_id: return results with an ID less than (older than) or equal to the specified ID
- * - trim_user: when set to true, "t", or 1, user object in tweets will include only author's ID.
- * - contributor_details: when set to true, includes screen_name of each contributor
- * - include_entities: when set to false, entities member will be omitted
- * - exclude_replies: when set to true, will strip replies appearing in the timeline
- *
- * @param array $params
- * @throws Zend_Http_Client_Exception if HTTP request fails or times out
- * @throws Exception\DomainException if unable to decode JSON payload
- * @return Zend_Service_Twitter_Response
- */
- public function statusesHomeTimeline(array $options = array())
- {
- $this->init();
- $path = 'statuses/home_timeline';
- $params = array();
- foreach ($options as $key => $value) {
- switch (strtolower($key)) {
- case 'count':
- $params['count'] = (int) $value;
- break;
- case 'since_id':
- $params['since_id'] = $this->validInteger($value);
- break;
- case 'max_id':
- $params['max_id'] = $this->validInteger($value);
- break;
- case 'trim_user':
- if (in_array($value, array(true, 'true', 't', 1, '1'))) {
- $value = true;
- } else {
- $value = false;
- }
- $params['trim_user'] = $value;
- break;
- case 'contributor_details:':
- $params['contributor_details:'] = (bool) $value;
- break;
- case 'include_entities':
- $params['include_entities'] = (bool) $value;
- break;
- case 'exclude_replies':
- $params['exclude_replies'] = (bool) $value;
- break;
- default:
- break;
- }
- }
- $response = $this->get($path, $params);
- return new Zend_Service_Twitter_Response($response);
- }
- /**
- * Get status replies
- *
- * $options may include one or more of the following keys
- * - count: number of tweets to attempt to retrieve, up to 200
- * - since_id: return results only after the specified tweet id
- * - max_id: return results with an ID less than (older than) or equal to the specified ID
- * - trim_user: when set to true, "t", or 1, user object in tweets will include only author's ID.
- * - contributor_details: when set to true, includes screen_name of each contributor
- * - include_entities: when set to false, entities member will be omitted
- *
- * @param array $options
- * @throws Zend_Http_Client_Exception if HTTP request fails or times out
- * @throws Exception\DomainException if unable to decode JSON payload
- * @return Zend_Service_Twitter_Response
- */
- public function statusesMentionsTimeline(array $options = array())
- {
- $this->init();
- $path = 'statuses/mentions_timeline';
- $params = array();
- foreach ($options as $key => $value) {
- switch (strtolower($key)) {
- case 'count':
- $params['count'] = (int) $value;
- break;
- case 'since_id':
- $params['since_id'] = $this->validInteger($value);
- break;
- case 'max_id':
- $params['max_id'] = $this->validInteger($value);
- break;
- case 'trim_user':
- if (in_array($value, array(true, 'true', 't', 1, '1'))) {
- $value = true;
- } else {
- $value = false;
- }
- $params['trim_user'] = $value;
- break;
- case 'contributor_details:':
- $params['contributor_details:'] = (bool) $value;
- break;
- case 'include_entities':
- $params['include_entities'] = (bool) $value;
- break;
- default:
- break;
- }
- }
- $response = $this->get($path, $params);
- return new Zend_Service_Twitter_Response($response);
- }
- /**
- * Public Timeline status
- *
- * @throws Zend_Http_Client_Exception if HTTP request fails or times out
- * @throws Exception\DomainException if unable to decode JSON payload
- * @return Zend_Service_Twitter_Response
- */
- public function statusesSample()
- {
- $this->init();
- $path = 'statuses/sample';
- $response = $this->get($path);
- return new Zend_Service_Twitter_Response($response);
- }
- /**
- * Show a single status
- *
- * @param int $id Id of status to show
- * @throws Zend_Http_Client_Exception if HTTP request fails or times out
- * @throws Exception\DomainException if unable to decode JSON payload
- * @return Zend_Service_Twitter_Response
- */
- public function statusesShow($id)
- {
- $this->init();
- $path = 'statuses/show/' . $this->validInteger($id);
- $response = $this->get($path);
- return new Zend_Service_Twitter_Response($response);
- }
- /**
- * Update user's current status
- *
- * @todo Support additional parameters supported by statuses/update endpoint
- * @param string $status
- * @param null|int $inReplyToStatusId
- * @throws Zend_Http_Client_Exception if HTTP request fails or times out
- * @throws Exception\OutOfRangeException if message is too long
- * @throws Exception\InvalidArgumentException if message is empty
- * @throws Exception\DomainException if unable to decode JSON payload
- * @return Zend_Service_Twitter_Response
- */
- public function statusesUpdate($status, $inReplyToStatusId = null)
- {
- $this->init();
- $path = 'statuses/update';
- $len = iconv_strlen(htmlspecialchars($status, ENT_QUOTES, 'UTF-8'), 'UTF-8');
- if ($len > self::STATUS_MAX_CHARACTERS) {
- require_once 'Zend/Service/Twitter/Exception.php';
- throw new Zend_Service_Twitter_Exception(
- 'Status must be no more than '
- . self::STATUS_MAX_CHARACTERS
- . ' characters in length'
- );
- } elseif (0 == $len) {
- require_once 'Zend/Service/Twitter/Exception.php';
- throw new Zend_Service_Twitter_Exception(
- 'Status must contain at least one character'
- );
- }
- $params = array('status' => $status);
- $inReplyToStatusId = $this->validInteger($inReplyToStatusId);
- if ($inReplyToStatusId) {
- $params['in_reply_to_status_id'] = $inReplyToStatusId;
- }
- $response = $this->post($path, $params);
- return new Zend_Service_Twitter_Response($response);
- }
- /**
- * User Timeline status
- *
- * $options may include one or more of the following keys
- * - user_id: Id of a user for whom to fetch favorites
- * - screen_name: Screen name of a user for whom to fetch favorites
- * - count: number of tweets to attempt to retrieve, up to 200
- * - since_id: return results only after the specified tweet id
- * - max_id: return results with an ID less than (older than) or equal to the specified ID
- * - trim_user: when set to true, "t", or 1, user object in tweets will include only author's ID.
- * - exclude_replies: when set to true, will strip replies appearing in the timeline
- * - contributor_details: when set to true, includes screen_name of each contributor
- * - include_rts: when set to false, will strip native retweets
- *
- * @throws Zend_Http_Client_Exception if HTTP request fails or times out
- * @throws Exception\DomainException if unable to decode JSON payload
- * @return Zend_Service_Twitter_Response
- */
- public function statusesUserTimeline(array $options = array())
- {
- $this->init();
- $path = 'statuses/user_timeline';
- $params = array();
- foreach ($options as $key => $value) {
- switch (strtolower($key)) {
- case 'user_id':
- $params['user_id'] = $this->validInteger($value);
- break;
- case 'screen_name':
- $params['screen_name'] = $this->validateScreenName($value);
- break;
- case 'count':
- $params['count'] = (int) $value;
- break;
- case 'since_id':
- $params['since_id'] = $this->validInteger($value);
- break;
- case 'max_id':
- $params['max_id'] = $this->validInteger($value);
- break;
- case 'trim_user':
- if (in_array($value, array(true, 'true', 't', 1, '1'))) {
- $value = true;
- } else {
- $value = false;
- }
- $params['trim_user'] = $value;
- break;
- case 'contributor_details:':
- $params['contributor_details:'] = (bool) $value;
- break;
- case 'exclude_replies':
- $params['exclude_replies'] = (bool) $value;
- break;
- case 'include_rts':
- $params['include_rts'] = (bool) $value;
- break;
- default:
- break;
- }
- }
- $response = $this->get($path, $params);
- return new Zend_Service_Twitter_Response($response);
- }
- /**
- * Search users
- *
- * $options may include any of the following:
- * - page: the page of results to retrieve
- * - count: the number of users to retrieve per page; max is 20
- * - include_entities: if set to boolean true, include embedded entities
- *
- * @param string $query
- * @param array $options
- * @throws Zend_Http_Client_Exception if HTTP request fails or times out
- * @throws Exception\DomainException if unable to decode JSON payload
- * @return Zend_Service_Twitter_Response
- */
- public function usersSearch($query, array $options = array())
- {
- $this->init();
- $path = 'users/search';
- $len = iconv_strlen($query, 'UTF-8');
- if (0 == $len) {
- require_once 'Zend/Service/Twitter/Exception.php';
- throw new Zend_Service_Twitter_Exception(
- 'Query must contain at least one character'
- );
- }
- $params = array('q' => $query);
- foreach ($options as $key => $value) {
- switch (strtolower($key)) {
- case 'count':
- $value = (int) $value;
- if (1 > $value || 20 < $value) {
- require_once 'Zend/Service/Twitter/Exception.php';
- throw new Zend_Service_Twitter_Exception(
- 'count must be between 1 and 20'
- );
- }
- $params['count'] = $value;
- break;
- case 'page':
- $params['page'] = (int) $value;
- break;
- case 'include_entities':
- $params['include_entities'] = (bool) $value;
- break;
- default:
- break;
- }
- }
- $response = $this->get($path, $params);
- return new Zend_Service_Twitter_Response($response);
- }
- /**
- * Show extended information on a user
- *
- * @param int|string $id User ID or name
- * @throws Zend_Http_Client_Exception if HTTP request fails or times out
- * @throws Exception\DomainException if unable to decode JSON payload
- * @return Zend_Service_Twitter_Response
- */
- public function usersShow($id)
- {
- $this->init();
- $path = 'users/show';
- $params = $this->createUserParameter($id, array());
- $response = $this->get($path, $params);
- return new Zend_Service_Twitter_Response($response);
- }
- /**
- * Initialize HTTP authentication
- *
- * @return void
- * @throws Exception\DomainException if unauthorised
- */
- protected function init()
- {
- if (!$this->isAuthorised() && $this->getUsername() !== null) {
- require_once 'Zend/Service/Twitter/Exception.php';
- throw new Zend_Service_Twitter_Exception(
- 'Twitter session is unauthorised. You need to initialize '
- . __CLASS__ . ' with an OAuth Access Token or use '
- . 'its OAuth functionality to obtain an Access Token before '
- . 'attempting any API actions that require authorisation'
- );
- }
- $client = $this->getHttpClient();
- $client->resetParameters();
- if (null === $this->cookieJar) {
- $cookieJar = $client->getCookieJar();
- if (null === $cookieJar) {
- $cookieJar = new Zend_Http_CookieJar();
- }
- $this->cookieJar = $cookieJar;
- $this->cookieJar->reset();
- } else {
- $client->setCookieJar($this->cookieJar);
- }
- }
- /**
- * Protected function to validate that the integer is valid or return a 0
- *
- * @param $int
- * @throws Zend_Http_Client_Exception if HTTP request fails or times out
- * @return integer
- */
- protected function validInteger($int)
- {
- if (preg_match("/(\d+)/", $int)) {
- return $int;
- }
- return 0;
- }
- /**
- * Validate a screen name using Twitter rules
- *
- * @param string $name
- * @return string
- * @throws Exception\InvalidArgumentException
- */
- protected function validateScreenName($name)
- {
- if (!preg_match('/^[a-zA-Z0-9_]{0,20}$/', $name)) {
- require_once 'Zend/Service/Twitter/Exception.php';
- throw new Zend_Service_Twitter_Exception(
- 'Screen name, "' . $name
- . '" should only contain alphanumeric characters and'
- . ' underscores, and not exceed 15 characters.');
- }
- return $name;
- }
- /**
- * Call a remote REST web service URI
- *
- * @param string $path The path to append to the URI
- * @param Zend_Http_Client $client
- * @throws Zend_Http_Client_Exception
- * @return void
- */
- protected function prepare($path, Zend_Http_Client $client)
- {
- $client->setUri(self::API_BASE_URI . $path . '.json');
- /**
- * Do this each time to ensure oauth calls do not inject new params
- */
- $client->resetParameters();
- }
- /**
- * Performs an HTTP GET request to the $path.
- *
- * @param string $path
- * @param array $query Array of GET parameters
- * @throws Zend_Http_Client_Exception
- * @return Zend_Http_Response
- */
- protected function get($path, array $query = array())
- {
- $client = $this->getHttpClient();
- $this->prepare($path, $client);
- $client->setParameterGet($query);
- $response = $client->request(Zend_Http_Client::GET);
- return $response;
- }
- /**
- * Performs an HTTP POST request to $path.
- *
- * @param string $path
- * @param mixed $data Raw data to send
- * @throws Zend_Http_Client_Exception
- * @return Zend_Http_Response
- */
- protected function post($path, $data = null)
- {
- $client = $this->getHttpClient();
- $this->prepare($path, $client);
- $response = $this->performPost(Zend_Http_Client::POST, $data, $client);
- return $response;
- }
- /**
- * Perform a POST or PUT
- *
- * Performs a POST or PUT request. Any data provided is set in the HTTP
- * client. String data is pushed in as raw POST data; array or object data
- * is pushed in as POST parameters.
- *
- * @param mixed $method
- * @param mixed $data
- * @return Zend_Http_Response
- */
- protected function performPost($method, $data, Zend_Http_Client $client)
- {
- if (is_string($data)) {
- $client->setRawData($data);
- } elseif (is_array($data) || is_object($data)) {
- $client->setParameterPost((array) $data);
- }
- return $client->request($method);
- }
- /**
- * Create a parameter representing the user
- *
- * Determines if $id is an integer, and, if so, sets the "user_id" parameter.
- * If not, assumes the $id is the "screen_name".
- *
- * @param int|string $id
- * @param array $params
- * @return array
- */
- protected function createUserParameter($id, array $params)
- {
- if ($this->validInteger($id)) {
- $params['user_id'] = $id;
- return $params;
- }
- $params['screen_name'] = $this->validateScreenName($id);
- return $params;
- }
- }
|