Twitter.php 45 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307
  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 Twitter
  18. * @copyright Copyright (c) 2005-2013 Zend Technologies USA Inc. (http://www.zend.com)
  19. * @license http://framework.zend.com/license/new-bsd New BSD License
  20. * @version $Id$
  21. */
  22. /**
  23. * @see Zend_Http_Client
  24. */
  25. require_once 'Zend/Http/Client.php';
  26. /**
  27. * @see Zend_Http_CookieJar
  28. */
  29. require_once 'Zend/Http/CookieJar.php';
  30. /**
  31. * @see Zend_Oauth_Consumer
  32. */
  33. require_once 'Zend/Oauth/Consumer.php';
  34. /**
  35. * @see Zend_Oauth_Token_Access
  36. */
  37. require_once 'Zend/Oauth/Token/Access.php';
  38. /**
  39. * @see Zend_Service_Twitter_Response
  40. */
  41. require_once 'Zend/Service/Twitter/Response.php';
  42. /**
  43. * @category Zend
  44. * @package Zend_Service
  45. * @subpackage Twitter
  46. * @copyright Copyright (c) 2005-2013 Zend Technologies USA Inc. (http://www.zend.com)
  47. * @license http://framework.zend.com/license/new-bsd New BSD License
  48. */
  49. class Zend_Service_Twitter
  50. {
  51. /**
  52. * Base URI for all API calls
  53. */
  54. const API_BASE_URI = 'https://api.twitter.com/1.1/';
  55. /**
  56. * OAuth Endpoint
  57. */
  58. const OAUTH_BASE_URI = 'https://api.twitter.com/oauth';
  59. /**
  60. * 246 is the current limit for a status message, 140 characters are displayed
  61. * initially, with the remainder linked from the web UI or client. The limit is
  62. * applied to a html encoded UTF-8 string (i.e. entities are counted in the limit
  63. * which may appear unusual but is a security measure).
  64. *
  65. * This should be reviewed in the future...
  66. */
  67. const STATUS_MAX_CHARACTERS = 246;
  68. /**
  69. * @var array
  70. */
  71. protected $cookieJar;
  72. /**
  73. * Date format for 'since' strings
  74. *
  75. * @var string
  76. */
  77. protected $dateFormat = 'D, d M Y H:i:s T';
  78. /**
  79. * @var Zend_Http_Client
  80. */
  81. protected $httpClient = null;
  82. /**
  83. * Current method type (for method proxying)
  84. *
  85. * @var string
  86. */
  87. protected $methodType;
  88. /**
  89. * Oauth Consumer
  90. *
  91. * @var Zend_Oauth_Consumer
  92. */
  93. protected $oauthConsumer = null;
  94. /**
  95. * Types of API methods
  96. *
  97. * @var array
  98. */
  99. protected $methodTypes = array(
  100. 'account',
  101. 'application',
  102. 'blocks',
  103. 'directmessages',
  104. 'favorites',
  105. 'friendships',
  106. 'search',
  107. 'statuses',
  108. 'users',
  109. );
  110. /**
  111. * Options passed to constructor
  112. *
  113. * @var array
  114. */
  115. protected $options = array();
  116. /**
  117. * Username
  118. *
  119. * @var string
  120. */
  121. protected $username;
  122. /**
  123. * Constructor
  124. *
  125. * @param null|array|Zend_Config $options
  126. * @param null|Zend_Oauth_Consumer $consumer
  127. * @param null|Zend_Http_Client $httpClient
  128. */
  129. public function __construct($options = null, Zend_Oauth_Consumer $consumer = null, Zend_Http_Client $httpClient = null)
  130. {
  131. if ($options instanceof Zend_Config) {
  132. $options = $options->toArray();
  133. }
  134. if (!is_array($options)) {
  135. $options = array();
  136. }
  137. $this->options = $options;
  138. if (isset($options['username'])) {
  139. $this->setUsername($options['username']);
  140. }
  141. $accessToken = false;
  142. if (isset($options['accessToken'])) {
  143. $accessToken = $options['accessToken'];
  144. } elseif (isset($options['access_token'])) {
  145. $accessToken = $options['access_token'];
  146. }
  147. $oauthOptions = array();
  148. if (isset($options['oauthOptions'])) {
  149. $oauthOptions = $options['oauthOptions'];
  150. } elseif (isset($options['oauth_options'])) {
  151. $oauthOptions = $options['oauth_options'];
  152. }
  153. $oauthOptions['siteUrl'] = self::OAUTH_BASE_URI;
  154. $httpClientOptions = array();
  155. if (isset($options['httpClientOptions'])) {
  156. $httpClientOptions = $options['httpClientOptions'];
  157. } elseif (isset($options['http_client_options'])) {
  158. $httpClientOptions = $options['http_client_options'];
  159. }
  160. // If we have an OAuth access token, use the HTTP client it provides
  161. if ($accessToken && is_array($accessToken)
  162. && (isset($accessToken['token']) && isset($accessToken['secret']))
  163. ) {
  164. $token = new Zend_Oauth_Token_Access();
  165. $token->setToken($accessToken['token']);
  166. $token->setTokenSecret($accessToken['secret']);
  167. $accessToken = $token;
  168. }
  169. if ($accessToken && $accessToken instanceof Zend_Oauth_Token_Access) {
  170. $oauthOptions['token'] = $accessToken;
  171. $this->setHttpClient($accessToken->getHttpClient($oauthOptions, self::OAUTH_BASE_URI, $httpClientOptions));
  172. return;
  173. }
  174. // See if we were passed an http client
  175. if (isset($options['httpClient']) && null === $httpClient) {
  176. $httpClient = $options['httpClient'];
  177. } elseif (isset($options['http_client']) && null === $httpClient) {
  178. $httpClient = $options['http_client'];
  179. }
  180. if ($httpClient instanceof Zend_Http_Client) {
  181. $this->httpClient = $httpClient;
  182. } else {
  183. $this->setHttpClient(new Zend_Http_Client(null, $httpClientOptions));
  184. }
  185. // Set the OAuth consumer
  186. if ($consumer === null) {
  187. $consumer = new Zend_Oauth_Consumer($oauthOptions);
  188. }
  189. $this->oauthConsumer = $consumer;
  190. }
  191. /**
  192. * Proxy service methods
  193. *
  194. * @param string $type
  195. * @return Twitter
  196. * @throws Exception\DomainException If method not in method types list
  197. */
  198. public function __get($type)
  199. {
  200. $type = strtolower($type);
  201. $type = str_replace('_', '', $type);
  202. if (!in_array($type, $this->methodTypes)) {
  203. require_once 'Zend/Service/Twitter/Exception.php';
  204. throw new Zend_Service_Twitter_Exception(
  205. 'Invalid method type "' . $type . '"'
  206. );
  207. }
  208. $this->methodType = $type;
  209. return $this;
  210. }
  211. /**
  212. * Method overloading
  213. *
  214. * @param string $method
  215. * @param array $params
  216. * @return mixed
  217. * @throws Exception\BadMethodCallException if unable to find method
  218. */
  219. public function __call($method, $params)
  220. {
  221. if (method_exists($this->oauthConsumer, $method)) {
  222. $return = call_user_func_array(array($this->oauthConsumer, $method), $params);
  223. if ($return instanceof Zend_Oauth_Token_Access) {
  224. $this->setHttpClient($return->getHttpClient($this->options));
  225. }
  226. return $return;
  227. }
  228. if (empty($this->methodType)) {
  229. require_once 'Zend/Service/Twitter/Exception.php';
  230. throw new Zend_Service_Twitter_Exception(
  231. 'Invalid method "' . $method . '"'
  232. );
  233. }
  234. $test = str_replace('_', '', strtolower($method));
  235. $test = $this->methodType . $test;
  236. if (!method_exists($this, $test)) {
  237. require_once 'Zend/Service/Twitter/Exception.php';
  238. throw new Zend_Service_Twitter_Exception(
  239. 'Invalid method "' . $test . '"'
  240. );
  241. }
  242. return call_user_func_array(array($this, $test), $params);
  243. }
  244. /**
  245. * Set HTTP client
  246. *
  247. * @param Zend_Http_Client $client
  248. * @return self
  249. */
  250. public function setHttpClient(Zend_Http_Client $client)
  251. {
  252. $this->httpClient = $client;
  253. $this->httpClient->setHeaders(array('Accept-Charset' => 'ISO-8859-1,utf-8'));
  254. return $this;
  255. }
  256. /**
  257. * Get the HTTP client
  258. *
  259. * Lazy loads one if none present
  260. *
  261. * @return Zend_Http_Client
  262. */
  263. public function getHttpClient()
  264. {
  265. if (null === $this->httpClient) {
  266. $this->setHttpClient(new Zend_Http_Client());
  267. }
  268. return $this->httpClient;
  269. }
  270. /**
  271. * Retrieve username
  272. *
  273. * @return string
  274. */
  275. public function getUsername()
  276. {
  277. return $this->username;
  278. }
  279. /**
  280. * Set username
  281. *
  282. * @param string $value
  283. * @return self
  284. */
  285. public function setUsername($value)
  286. {
  287. $this->username = $value;
  288. return $this;
  289. }
  290. /**
  291. * Checks for an authorised state
  292. *
  293. * @return bool
  294. */
  295. public function isAuthorised()
  296. {
  297. if ($this->getHttpClient() instanceof Zend_Oauth_Client) {
  298. return true;
  299. }
  300. return false;
  301. }
  302. /**
  303. * Verify Account Credentials
  304. *
  305. * @throws Zend_Http_Client_Exception if HTTP request fails or times out
  306. * @throws Exception\DomainException if unable to decode JSON payload
  307. * @return Zend_Service_Twitter_Response
  308. */
  309. public function accountVerifyCredentials()
  310. {
  311. $this->init();
  312. $response = $this->get('account/verify_credentials');
  313. return new Zend_Service_Twitter_Response($response);
  314. }
  315. /**
  316. * Returns the number of api requests you have left per hour.
  317. *
  318. * @todo Have a separate payload object to represent rate limits
  319. * @throws Zend_Http_Client_Exception if HTTP request fails or times out
  320. * @throws Exception\DomainException if unable to decode JSON payload
  321. * @return Zend_Service_Twitter_Response
  322. */
  323. public function applicationRateLimitStatus()
  324. {
  325. $this->init();
  326. $response = $this->get('application/rate_limit_status');
  327. return new Zend_Service_Twitter_Response($response);
  328. }
  329. /**
  330. * Blocks the user specified in the ID parameter as the authenticating user.
  331. * Destroys a friendship to the blocked user if it exists.
  332. *
  333. * @param integer|string $id The ID or screen name of a user to block.
  334. * @throws Exception\DomainException if unable to decode JSON payload
  335. * @return Zend_Service_Twitter_Response
  336. */
  337. public function blocksCreate($id)
  338. {
  339. $this->init();
  340. $path = 'blocks/create';
  341. $params = $this->createUserParameter($id, array());
  342. $response = $this->post($path, $params);
  343. return new Zend_Service_Twitter_Response($response);
  344. }
  345. /**
  346. * Un-blocks the user specified in the ID parameter for the authenticating user
  347. *
  348. * @param integer|string $id The ID or screen_name of the user to un-block.
  349. * @throws Exception\DomainException if unable to decode JSON payload
  350. * @return Zend_Service_Twitter_Response
  351. */
  352. public function blocksDestroy($id)
  353. {
  354. $this->init();
  355. $path = 'blocks/destroy';
  356. $params = $this->createUserParameter($id, array());
  357. $response = $this->post($path, $params);
  358. return new Zend_Service_Twitter_Response($response);
  359. }
  360. /**
  361. * Returns an array of user ids that the authenticating user is blocking
  362. *
  363. * @param integer $cursor Optional. Specifies the cursor position at which to begin listing ids; defaults to first "page" of results.
  364. * @throws Exception\DomainException if unable to decode JSON payload
  365. * @return Zend_Service_Twitter_Response
  366. */
  367. public function blocksIds($cursor = -1)
  368. {
  369. $this->init();
  370. $path = 'blocks/ids';
  371. $response = $this->get($path, array('cursor' => $cursor));
  372. return new Zend_Service_Twitter_Response($response);
  373. }
  374. /**
  375. * Returns an array of user objects that the authenticating user is blocking
  376. *
  377. * @param integer $cursor Optional. Specifies the cursor position at which to begin listing ids; defaults to first "page" of results.
  378. * @throws Exception\DomainException if unable to decode JSON payload
  379. * @return Zend_Service_Twitter_Response
  380. */
  381. public function blocksList($cursor = -1)
  382. {
  383. $this->init();
  384. $path = 'blocks/list';
  385. $response = $this->get($path, array('cursor' => $cursor));
  386. return new Zend_Service_Twitter_Response($response);
  387. }
  388. /**
  389. * Destroy a direct message
  390. *
  391. * @param int $id ID of message to destroy
  392. * @throws Zend_Http_Client_Exception if HTTP request fails or times out
  393. * @throws Exception\DomainException if unable to decode JSON payload
  394. * @return Zend_Service_Twitter_Response
  395. */
  396. public function directMessagesDestroy($id)
  397. {
  398. $this->init();
  399. $path = 'direct_messages/destroy';
  400. $params = array('id' => $this->validInteger($id));
  401. $response = $this->post($path, $params);
  402. return new Zend_Service_Twitter_Response($response);
  403. }
  404. /**
  405. * Retrieve direct messages for the current user
  406. *
  407. * $options may include one or more of the following keys
  408. * - count: return page X of results
  409. * - since_id: return statuses only greater than the one specified
  410. * - max_id: return statuses with an ID less than (older than) or equal to that specified
  411. * - include_entities: setting to false will disable embedded entities
  412. * - skip_status:setting to true, "t", or 1 will omit the status in returned users
  413. *
  414. * @param array $options
  415. * @throws Zend_Http_Client_Exception if HTTP request fails or times out
  416. * @throws Exception\DomainException if unable to decode JSON payload
  417. * @return Zend_Service_Twitter_Response
  418. */
  419. public function directMessagesMessages(array $options = array())
  420. {
  421. $this->init();
  422. $path = 'direct_messages';
  423. $params = array();
  424. foreach ($options as $key => $value) {
  425. switch (strtolower($key)) {
  426. case 'count':
  427. $params['count'] = (int) $value;
  428. break;
  429. case 'since_id':
  430. $params['since_id'] = $this->validInteger($value);
  431. break;
  432. case 'max_id':
  433. $params['max_id'] = $this->validInteger($value);
  434. break;
  435. case 'include_entities':
  436. $params['include_entities'] = (bool) $value;
  437. break;
  438. case 'skip_status':
  439. $params['skip_status'] = (bool) $value;
  440. break;
  441. default:
  442. break;
  443. }
  444. }
  445. $response = $this->get($path, $params);
  446. return new Zend_Service_Twitter_Response($response);
  447. }
  448. /**
  449. * Send a direct message to a user
  450. *
  451. * @param int|string $user User to whom to send message
  452. * @param string $text Message to send to user
  453. * @throws Exception\InvalidArgumentException if message is empty
  454. * @throws Exception\OutOfRangeException if message is too long
  455. * @throws Zend_Http_Client_Exception if HTTP request fails or times out
  456. * @throws Exception\DomainException if unable to decode JSON payload
  457. * @return Zend_Service_Twitter_Response
  458. */
  459. public function directMessagesNew($user, $text)
  460. {
  461. $this->init();
  462. $path = 'direct_messages/new';
  463. $len = iconv_strlen($text, 'UTF-8');
  464. if (0 == $len) {
  465. require_once 'Zend/Service/Twitter/Exception.php';
  466. throw new Zend_Service_Twitter_Exception(
  467. 'Direct message must contain at least one character'
  468. );
  469. } elseif (140 < $len) {
  470. require_once 'Zend/Service/Twitter/Exception.php';
  471. throw new Zend_Service_Twitter_Exception(
  472. 'Direct message must contain no more than 140 characters'
  473. );
  474. }
  475. $params = $this->createUserParameter($user, array());
  476. $params['text'] = $text;
  477. $response = $this->post($path, $params);
  478. return new Zend_Service_Twitter_Response($response);
  479. }
  480. /**
  481. * Retrieve list of direct messages sent by current user
  482. *
  483. * $options may include one or more of the following keys
  484. * - count: return page X of results
  485. * - page: return starting at page
  486. * - since_id: return statuses only greater than the one specified
  487. * - max_id: return statuses with an ID less than (older than) or equal to that specified
  488. * - include_entities: setting to false will disable embedded entities
  489. *
  490. * @param array $options
  491. * @throws Zend_Http_Client_Exception if HTTP request fails or times out
  492. * @throws Exception\DomainException if unable to decode JSON payload
  493. * @return Zend_Service_Twitter_Response
  494. */
  495. public function directMessagesSent(array $options = array())
  496. {
  497. $this->init();
  498. $path = 'direct_messages/sent';
  499. $params = array();
  500. foreach ($options as $key => $value) {
  501. switch (strtolower($key)) {
  502. case 'count':
  503. $params['count'] = (int) $value;
  504. break;
  505. case 'page':
  506. $params['page'] = (int) $value;
  507. break;
  508. case 'since_id':
  509. $params['since_id'] = $this->validInteger($value);
  510. break;
  511. case 'max_id':
  512. $params['max_id'] = $this->validInteger($value);
  513. break;
  514. case 'include_entities':
  515. $params['include_entities'] = (bool) $value;
  516. break;
  517. default:
  518. break;
  519. }
  520. }
  521. $response = $this->get($path, $params);
  522. return new Zend_Service_Twitter_Response($response);
  523. }
  524. /**
  525. * Mark a status as a favorite
  526. *
  527. * @param int $id Status ID you want to mark as a favorite
  528. * @throws Zend_Http_Client_Exception if HTTP request fails or times out
  529. * @throws Exception\DomainException if unable to decode JSON payload
  530. * @return Zend_Service_Twitter_Response
  531. */
  532. public function favoritesCreate($id)
  533. {
  534. $this->init();
  535. $path = 'favorites/create';
  536. $params = array('id' => $this->validInteger($id));
  537. $response = $this->post($path, $params);
  538. return new Zend_Service_Twitter_Response($response);
  539. }
  540. /**
  541. * Remove a favorite
  542. *
  543. * @param int $id Status ID you want to de-list as a favorite
  544. * @throws Zend_Http_Client_Exception if HTTP request fails or times out
  545. * @throws Exception\DomainException if unable to decode JSON payload
  546. * @return Zend_Service_Twitter_Response
  547. */
  548. public function favoritesDestroy($id)
  549. {
  550. $this->init();
  551. $path = 'favorites/destroy';
  552. $params = array('id' => $this->validInteger($id));
  553. $response = $this->post($path, $params);
  554. return new Zend_Service_Twitter_Response($response);
  555. }
  556. /**
  557. * Fetch favorites
  558. *
  559. * $options may contain one or more of the following:
  560. * - user_id: Id of a user for whom to fetch favorites
  561. * - screen_name: Screen name of a user for whom to fetch favorites
  562. * - count: number of tweets to attempt to retrieve, up to 200
  563. * - since_id: return results only after the specified tweet id
  564. * - max_id: return results with an ID less than (older than) or equal to the specified ID
  565. * - include_entities: when set to false, entities member will be omitted
  566. *
  567. * @param array $params
  568. * @throws Zend_Http_Client_Exception if HTTP request fails or times out
  569. * @throws Exception\DomainException if unable to decode JSON payload
  570. * @return Zend_Service_Twitter_Response
  571. */
  572. public function favoritesList(array $options = array())
  573. {
  574. $this->init();
  575. $path = 'favorites/list';
  576. $params = array();
  577. foreach ($options as $key => $value) {
  578. switch (strtolower($key)) {
  579. case 'user_id':
  580. $params['user_id'] = $this->validInteger($value);
  581. break;
  582. case 'screen_name':
  583. $params['screen_name'] = $value;
  584. break;
  585. case 'count':
  586. $params['count'] = (int) $value;
  587. break;
  588. case 'since_id':
  589. $params['since_id'] = $this->validInteger($value);
  590. break;
  591. case 'max_id':
  592. $params['max_id'] = $this->validInteger($value);
  593. break;
  594. case 'include_entities':
  595. $params['include_entities'] = (bool) $value;
  596. break;
  597. default:
  598. break;
  599. }
  600. }
  601. $response = $this->get($path, $params);
  602. return new Zend_Service_Twitter_Response($response);
  603. }
  604. /**
  605. * Create friendship
  606. *
  607. * @param int|string $id User ID or name of new friend
  608. * @param array $params Additional parameters to pass
  609. * @throws Zend_Http_Client_Exception if HTTP request fails or times out
  610. * @throws Exception\DomainException if unable to decode JSON payload
  611. * @return Zend_Service_Twitter_Response
  612. */
  613. public function friendshipsCreate($id, array $params = array())
  614. {
  615. $this->init();
  616. $path = 'friendships/create';
  617. $params = $this->createUserParameter($id, $params);
  618. $allowed = array(
  619. 'user_id' => null,
  620. 'screen_name' => null,
  621. 'follow' => null,
  622. );
  623. $params = array_intersect_key($params, $allowed);
  624. $response = $this->post($path, $params);
  625. return new Zend_Service_Twitter_Response($response);
  626. }
  627. /**
  628. * Destroy friendship
  629. *
  630. * @param int|string $id User ID or name of friend to remove
  631. * @throws Zend_Http_Client_Exception if HTTP request fails or times out
  632. * @throws Exception\DomainException if unable to decode JSON payload
  633. * @return Zend_Service_Twitter_Response
  634. */
  635. public function friendshipsDestroy($id)
  636. {
  637. $this->init();
  638. $path = 'friendships/destroy';
  639. $params = $this->createUserParameter($id, array());
  640. $response = $this->post($path, $params);
  641. return new Zend_Service_Twitter_Response($response);
  642. }
  643. /**
  644. * Search tweets
  645. *
  646. * $options may include any of the following:
  647. * - geocode: a string of the form "latitude, longitude, radius"
  648. * - lang: restrict tweets to the two-letter language code
  649. * - locale: query is in the given two-letter language code
  650. * - result_type: what type of results to receive: mixed, recent, or popular
  651. * - count: number of tweets to return per page; up to 100
  652. * - until: return tweets generated before the given date
  653. * - since_id: return resutls with an ID greater than (more recent than) the given ID
  654. * - max_id: return results with an ID less than (older than) the given ID
  655. * - include_entities: whether or not to include embedded entities
  656. *
  657. * @param string $query
  658. * @param array $options
  659. * @throws Zend_Http_Client_Exception if HTTP request fails or times out
  660. * @throws Exception\DomainException if unable to decode JSON payload
  661. * @return Zend_Service_Twitter_Response
  662. */
  663. public function searchTweets($query, array $options = array())
  664. {
  665. $this->init();
  666. $path = 'search/tweets';
  667. $len = iconv_strlen($query, 'UTF-8');
  668. if (0 == $len) {
  669. require_once 'Zend/Service/Twitter/Exception.php';
  670. throw new Zend_Service_Twitter_Exception(
  671. 'Query must contain at least one character'
  672. );
  673. }
  674. $params = array('q' => $query);
  675. foreach ($options as $key => $value) {
  676. switch (strtolower($key)) {
  677. case 'geocode':
  678. if (!substr_count($value, ',') !== 2) {
  679. require_once 'Zend/Service/Twitter/Exception.php';
  680. throw new Zend_Service_Twitter_Exception(
  681. '"geocode" must be of the format "latitude,longitude,radius"'
  682. );
  683. }
  684. list($latitude, $longitude, $radius) = explode(',', $value);
  685. $radius = trim($radius);
  686. if (!preg_match('/^\d+(mi|km)$/', $radius)) {
  687. require_once 'Zend/Service/Twitter/Exception.php';
  688. throw new Zend_Service_Twitter_Exception(
  689. 'Radius segment of "geocode" must be of the format "[unit](mi|km)"'
  690. );
  691. }
  692. $latitude = (float) $latitude;
  693. $longitude = (float) $longitude;
  694. $params['geocode'] = $latitude . ',' . $longitude . ',' . $radius;
  695. break;
  696. case 'lang':
  697. if (strlen($value) > 2) {
  698. require_once 'Zend/Service/Twitter/Exception.php';
  699. throw new Zend_Service_Twitter_Exception(
  700. 'Query language must be a 2 character string'
  701. );
  702. }
  703. $params['lang'] = strtolower($value);
  704. break;
  705. case 'locale':
  706. if (strlen($value) > 2) {
  707. require_once 'Zend/Service/Twitter/Exception.php';
  708. throw new Zend_Service_Twitter_Exception(
  709. 'Query locale must be a 2 character string'
  710. );
  711. }
  712. $params['locale'] = strtolower($value);
  713. break;
  714. case 'result_type':
  715. $value = strtolower($value);
  716. if (!in_array($value, array('mixed', 'recent', 'popular'))) {
  717. require_once 'Zend/Service/Twitter/Exception.php';
  718. throw new Zend_Service_Twitter_Exception(
  719. 'result_type must be one of "mixed", "recent", or "popular"'
  720. );
  721. }
  722. $params['result_type'] = $value;
  723. break;
  724. case 'count':
  725. $value = (int) $value;
  726. if (1 > $value || 100 < $value) {
  727. require_once 'Zend/Service/Twitter/Exception.php';
  728. throw new Zend_Service_Twitter_Exception(
  729. 'count must be between 1 and 100'
  730. );
  731. }
  732. $params['count'] = $value;
  733. break;
  734. case 'until':
  735. if (!preg_match('/^\d{4}-\d{2}-\d{2}$/', $value)) {
  736. require_once 'Zend/Service/Twitter/Exception.php';
  737. throw new Zend_Service_Twitter_Exception(
  738. '"until" must be a date in the format YYYY-MM-DD'
  739. );
  740. }
  741. $params['until'] = $value;
  742. break;
  743. case 'since_id':
  744. $params['since_id'] = $this->validInteger($value);
  745. break;
  746. case 'max_id':
  747. $params['max_id'] = $this->validInteger($value);
  748. break;
  749. case 'include_entities':
  750. $params['include_entities'] = (bool) $value;
  751. break;
  752. default:
  753. break;
  754. }
  755. }
  756. $response = $this->get($path, $params);
  757. return new Zend_Service_Twitter_Response($response);
  758. }
  759. /**
  760. * Destroy a status message
  761. *
  762. * @param int $id ID of status to destroy
  763. * @throws Zend_Http_Client_Exception if HTTP request fails or times out
  764. * @throws Exception\DomainException if unable to decode JSON payload
  765. * @return Zend_Service_Twitter_Response
  766. */
  767. public function statusesDestroy($id)
  768. {
  769. $this->init();
  770. $path = 'statuses/destroy/' . $this->validInteger($id);
  771. $response = $this->post($path);
  772. return new Zend_Service_Twitter_Response($response);
  773. }
  774. /**
  775. * Friend Timeline Status
  776. *
  777. * $options may include one or more of the following keys
  778. * - count: number of tweets to attempt to retrieve, up to 200
  779. * - since_id: return results only after the specified tweet id
  780. * - max_id: return results with an ID less than (older than) or equal to the specified ID
  781. * - trim_user: when set to true, "t", or 1, user object in tweets will include only author's ID.
  782. * - contributor_details: when set to true, includes screen_name of each contributor
  783. * - include_entities: when set to false, entities member will be omitted
  784. * - exclude_replies: when set to true, will strip replies appearing in the timeline
  785. *
  786. * @param array $params
  787. * @throws Zend_Http_Client_Exception if HTTP request fails or times out
  788. * @throws Exception\DomainException if unable to decode JSON payload
  789. * @return Zend_Service_Twitter_Response
  790. */
  791. public function statusesHomeTimeline(array $options = array())
  792. {
  793. $this->init();
  794. $path = 'statuses/home_timeline';
  795. $params = array();
  796. foreach ($options as $key => $value) {
  797. switch (strtolower($key)) {
  798. case 'count':
  799. $params['count'] = (int) $value;
  800. break;
  801. case 'since_id':
  802. $params['since_id'] = $this->validInteger($value);
  803. break;
  804. case 'max_id':
  805. $params['max_id'] = $this->validInteger($value);
  806. break;
  807. case 'trim_user':
  808. if (in_array($value, array(true, 'true', 't', 1, '1'))) {
  809. $value = true;
  810. } else {
  811. $value = false;
  812. }
  813. $params['trim_user'] = $value;
  814. break;
  815. case 'contributor_details:':
  816. $params['contributor_details:'] = (bool) $value;
  817. break;
  818. case 'include_entities':
  819. $params['include_entities'] = (bool) $value;
  820. break;
  821. case 'exclude_replies':
  822. $params['exclude_replies'] = (bool) $value;
  823. break;
  824. default:
  825. break;
  826. }
  827. }
  828. $response = $this->get($path, $params);
  829. return new Zend_Service_Twitter_Response($response);
  830. }
  831. /**
  832. * Get status replies
  833. *
  834. * $options may include one or more of the following keys
  835. * - count: number of tweets to attempt to retrieve, up to 200
  836. * - since_id: return results only after the specified tweet id
  837. * - max_id: return results with an ID less than (older than) or equal to the specified ID
  838. * - trim_user: when set to true, "t", or 1, user object in tweets will include only author's ID.
  839. * - contributor_details: when set to true, includes screen_name of each contributor
  840. * - include_entities: when set to false, entities member will be omitted
  841. *
  842. * @param array $options
  843. * @throws Zend_Http_Client_Exception if HTTP request fails or times out
  844. * @throws Exception\DomainException if unable to decode JSON payload
  845. * @return Zend_Service_Twitter_Response
  846. */
  847. public function statusesMentionsTimeline(array $options = array())
  848. {
  849. $this->init();
  850. $path = 'statuses/mentions_timeline';
  851. $params = array();
  852. foreach ($options as $key => $value) {
  853. switch (strtolower($key)) {
  854. case 'count':
  855. $params['count'] = (int) $value;
  856. break;
  857. case 'since_id':
  858. $params['since_id'] = $this->validInteger($value);
  859. break;
  860. case 'max_id':
  861. $params['max_id'] = $this->validInteger($value);
  862. break;
  863. case 'trim_user':
  864. if (in_array($value, array(true, 'true', 't', 1, '1'))) {
  865. $value = true;
  866. } else {
  867. $value = false;
  868. }
  869. $params['trim_user'] = $value;
  870. break;
  871. case 'contributor_details:':
  872. $params['contributor_details:'] = (bool) $value;
  873. break;
  874. case 'include_entities':
  875. $params['include_entities'] = (bool) $value;
  876. break;
  877. default:
  878. break;
  879. }
  880. }
  881. $response = $this->get($path, $params);
  882. return new Zend_Service_Twitter_Response($response);
  883. }
  884. /**
  885. * Public Timeline status
  886. *
  887. * @throws Zend_Http_Client_Exception if HTTP request fails or times out
  888. * @throws Exception\DomainException if unable to decode JSON payload
  889. * @return Zend_Service_Twitter_Response
  890. */
  891. public function statusesSample()
  892. {
  893. $this->init();
  894. $path = 'statuses/sample';
  895. $response = $this->get($path);
  896. return new Zend_Service_Twitter_Response($response);
  897. }
  898. /**
  899. * Show a single status
  900. *
  901. * @param int $id Id of status to show
  902. * @throws Zend_Http_Client_Exception if HTTP request fails or times out
  903. * @throws Exception\DomainException if unable to decode JSON payload
  904. * @return Zend_Service_Twitter_Response
  905. */
  906. public function statusesShow($id)
  907. {
  908. $this->init();
  909. $path = 'statuses/show/' . $this->validInteger($id);
  910. $response = $this->get($path);
  911. return new Zend_Service_Twitter_Response($response);
  912. }
  913. /**
  914. * Update user's current status
  915. *
  916. * @todo Support additional parameters supported by statuses/update endpoint
  917. * @param string $status
  918. * @param null|int $inReplyToStatusId
  919. * @throws Zend_Http_Client_Exception if HTTP request fails or times out
  920. * @throws Exception\OutOfRangeException if message is too long
  921. * @throws Exception\InvalidArgumentException if message is empty
  922. * @throws Exception\DomainException if unable to decode JSON payload
  923. * @return Zend_Service_Twitter_Response
  924. */
  925. public function statusesUpdate($status, $inReplyToStatusId = null)
  926. {
  927. $this->init();
  928. $path = 'statuses/update';
  929. $len = iconv_strlen(htmlspecialchars($status, ENT_QUOTES, 'UTF-8'), 'UTF-8');
  930. if ($len > self::STATUS_MAX_CHARACTERS) {
  931. require_once 'Zend/Service/Twitter/Exception.php';
  932. throw new Zend_Service_Twitter_Exception(
  933. 'Status must be no more than '
  934. . self::STATUS_MAX_CHARACTERS
  935. . ' characters in length'
  936. );
  937. } elseif (0 == $len) {
  938. require_once 'Zend/Service/Twitter/Exception.php';
  939. throw new Zend_Service_Twitter_Exception(
  940. 'Status must contain at least one character'
  941. );
  942. }
  943. $params = array('status' => $status);
  944. $inReplyToStatusId = $this->validInteger($inReplyToStatusId);
  945. if ($inReplyToStatusId) {
  946. $params['in_reply_to_status_id'] = $inReplyToStatusId;
  947. }
  948. $response = $this->post($path, $params);
  949. return new Zend_Service_Twitter_Response($response);
  950. }
  951. /**
  952. * User Timeline status
  953. *
  954. * $options may include one or more of the following keys
  955. * - user_id: Id of a user for whom to fetch favorites
  956. * - screen_name: Screen name of a user for whom to fetch favorites
  957. * - count: number of tweets to attempt to retrieve, up to 200
  958. * - since_id: return results only after the specified tweet id
  959. * - max_id: return results with an ID less than (older than) or equal to the specified ID
  960. * - trim_user: when set to true, "t", or 1, user object in tweets will include only author's ID.
  961. * - exclude_replies: when set to true, will strip replies appearing in the timeline
  962. * - contributor_details: when set to true, includes screen_name of each contributor
  963. * - include_rts: when set to false, will strip native retweets
  964. *
  965. * @throws Zend_Http_Client_Exception if HTTP request fails or times out
  966. * @throws Exception\DomainException if unable to decode JSON payload
  967. * @return Zend_Service_Twitter_Response
  968. */
  969. public function statusesUserTimeline(array $options = array())
  970. {
  971. $this->init();
  972. $path = 'statuses/user_timeline';
  973. $params = array();
  974. foreach ($options as $key => $value) {
  975. switch (strtolower($key)) {
  976. case 'user_id':
  977. $params['user_id'] = $this->validInteger($value);
  978. break;
  979. case 'screen_name':
  980. $params['screen_name'] = $this->validateScreenName($value);
  981. break;
  982. case 'count':
  983. $params['count'] = (int) $value;
  984. break;
  985. case 'since_id':
  986. $params['since_id'] = $this->validInteger($value);
  987. break;
  988. case 'max_id':
  989. $params['max_id'] = $this->validInteger($value);
  990. break;
  991. case 'trim_user':
  992. if (in_array($value, array(true, 'true', 't', 1, '1'))) {
  993. $value = true;
  994. } else {
  995. $value = false;
  996. }
  997. $params['trim_user'] = $value;
  998. break;
  999. case 'contributor_details:':
  1000. $params['contributor_details:'] = (bool) $value;
  1001. break;
  1002. case 'exclude_replies':
  1003. $params['exclude_replies'] = (bool) $value;
  1004. break;
  1005. case 'include_rts':
  1006. $params['include_rts'] = (bool) $value;
  1007. break;
  1008. default:
  1009. break;
  1010. }
  1011. }
  1012. $response = $this->get($path, $params);
  1013. return new Zend_Service_Twitter_Response($response);
  1014. }
  1015. /**
  1016. * Search users
  1017. *
  1018. * $options may include any of the following:
  1019. * - page: the page of results to retrieve
  1020. * - count: the number of users to retrieve per page; max is 20
  1021. * - include_entities: if set to boolean true, include embedded entities
  1022. *
  1023. * @param string $query
  1024. * @param array $options
  1025. * @throws Zend_Http_Client_Exception if HTTP request fails or times out
  1026. * @throws Exception\DomainException if unable to decode JSON payload
  1027. * @return Zend_Service_Twitter_Response
  1028. */
  1029. public function usersSearch($query, array $options = array())
  1030. {
  1031. $this->init();
  1032. $path = 'users/search';
  1033. $len = iconv_strlen($query, 'UTF-8');
  1034. if (0 == $len) {
  1035. require_once 'Zend/Service/Twitter/Exception.php';
  1036. throw new Zend_Service_Twitter_Exception(
  1037. 'Query must contain at least one character'
  1038. );
  1039. }
  1040. $params = array('q' => $query);
  1041. foreach ($options as $key => $value) {
  1042. switch (strtolower($key)) {
  1043. case 'count':
  1044. $value = (int) $value;
  1045. if (1 > $value || 20 < $value) {
  1046. require_once 'Zend/Service/Twitter/Exception.php';
  1047. throw new Zend_Service_Twitter_Exception(
  1048. 'count must be between 1 and 20'
  1049. );
  1050. }
  1051. $params['count'] = $value;
  1052. break;
  1053. case 'page':
  1054. $params['page'] = (int) $value;
  1055. break;
  1056. case 'include_entities':
  1057. $params['include_entities'] = (bool) $value;
  1058. break;
  1059. default:
  1060. break;
  1061. }
  1062. }
  1063. $response = $this->get($path, $params);
  1064. return new Zend_Service_Twitter_Response($response);
  1065. }
  1066. /**
  1067. * Show extended information on a user
  1068. *
  1069. * @param int|string $id User ID or name
  1070. * @throws Zend_Http_Client_Exception if HTTP request fails or times out
  1071. * @throws Exception\DomainException if unable to decode JSON payload
  1072. * @return Zend_Service_Twitter_Response
  1073. */
  1074. public function usersShow($id)
  1075. {
  1076. $this->init();
  1077. $path = 'users/show';
  1078. $params = $this->createUserParameter($id, array());
  1079. $response = $this->get($path, $params);
  1080. return new Zend_Service_Twitter_Response($response);
  1081. }
  1082. /**
  1083. * Initialize HTTP authentication
  1084. *
  1085. * @return void
  1086. * @throws Exception\DomainException if unauthorised
  1087. */
  1088. protected function init()
  1089. {
  1090. if (!$this->isAuthorised() && $this->getUsername() !== null) {
  1091. require_once 'Zend/Service/Twitter/Exception.php';
  1092. throw new Zend_Service_Twitter_Exception(
  1093. 'Twitter session is unauthorised. You need to initialize '
  1094. . __CLASS__ . ' with an OAuth Access Token or use '
  1095. . 'its OAuth functionality to obtain an Access Token before '
  1096. . 'attempting any API actions that require authorisation'
  1097. );
  1098. }
  1099. $client = $this->getHttpClient();
  1100. $client->resetParameters();
  1101. if (null === $this->cookieJar) {
  1102. $cookieJar = $client->getCookieJar();
  1103. if (null === $cookieJar) {
  1104. $cookieJar = new Zend_Http_CookieJar();
  1105. }
  1106. $this->cookieJar = $cookieJar;
  1107. $this->cookieJar->reset();
  1108. } else {
  1109. $client->setCookieJar($this->cookieJar);
  1110. }
  1111. }
  1112. /**
  1113. * Protected function to validate that the integer is valid or return a 0
  1114. *
  1115. * @param $int
  1116. * @throws Zend_Http_Client_Exception if HTTP request fails or times out
  1117. * @return integer
  1118. */
  1119. protected function validInteger($int)
  1120. {
  1121. if (preg_match("/(\d+)/", $int)) {
  1122. return $int;
  1123. }
  1124. return 0;
  1125. }
  1126. /**
  1127. * Validate a screen name using Twitter rules
  1128. *
  1129. * @param string $name
  1130. * @return string
  1131. * @throws Exception\InvalidArgumentException
  1132. */
  1133. protected function validateScreenName($name)
  1134. {
  1135. if (!preg_match('/^[a-zA-Z0-9_]{0,20}$/', $name)) {
  1136. require_once 'Zend/Service/Twitter/Exception.php';
  1137. throw new Zend_Service_Twitter_Exception(
  1138. 'Screen name, "' . $name
  1139. . '" should only contain alphanumeric characters and'
  1140. . ' underscores, and not exceed 15 characters.');
  1141. }
  1142. return $name;
  1143. }
  1144. /**
  1145. * Call a remote REST web service URI
  1146. *
  1147. * @param string $path The path to append to the URI
  1148. * @param Zend_Http_Client $client
  1149. * @throws Zend_Http_Client_Exception
  1150. * @return void
  1151. */
  1152. protected function prepare($path, Zend_Http_Client $client)
  1153. {
  1154. $client->setUri(self::API_BASE_URI . $path . '.json');
  1155. /**
  1156. * Do this each time to ensure oauth calls do not inject new params
  1157. */
  1158. $client->resetParameters();
  1159. }
  1160. /**
  1161. * Performs an HTTP GET request to the $path.
  1162. *
  1163. * @param string $path
  1164. * @param array $query Array of GET parameters
  1165. * @throws Zend_Http_Client_Exception
  1166. * @return Zend_Http_Response
  1167. */
  1168. protected function get($path, array $query = array())
  1169. {
  1170. $client = $this->getHttpClient();
  1171. $this->prepare($path, $client);
  1172. $client->setParameterGet($query);
  1173. $response = $client->request(Zend_Http_Client::GET);
  1174. return $response;
  1175. }
  1176. /**
  1177. * Performs an HTTP POST request to $path.
  1178. *
  1179. * @param string $path
  1180. * @param mixed $data Raw data to send
  1181. * @throws Zend_Http_Client_Exception
  1182. * @return Zend_Http_Response
  1183. */
  1184. protected function post($path, $data = null)
  1185. {
  1186. $client = $this->getHttpClient();
  1187. $this->prepare($path, $client);
  1188. $response = $this->performPost(Zend_Http_Client::POST, $data, $client);
  1189. return $response;
  1190. }
  1191. /**
  1192. * Perform a POST or PUT
  1193. *
  1194. * Performs a POST or PUT request. Any data provided is set in the HTTP
  1195. * client. String data is pushed in as raw POST data; array or object data
  1196. * is pushed in as POST parameters.
  1197. *
  1198. * @param mixed $method
  1199. * @param mixed $data
  1200. * @return Zend_Http_Response
  1201. */
  1202. protected function performPost($method, $data, Zend_Http_Client $client)
  1203. {
  1204. if (is_string($data)) {
  1205. $client->setRawData($data);
  1206. } elseif (is_array($data) || is_object($data)) {
  1207. $client->setParameterPost((array) $data);
  1208. }
  1209. return $client->request($method);
  1210. }
  1211. /**
  1212. * Create a parameter representing the user
  1213. *
  1214. * Determines if $id is an integer, and, if so, sets the "user_id" parameter.
  1215. * If not, assumes the $id is the "screen_name".
  1216. *
  1217. * @param int|string $id
  1218. * @param array $params
  1219. * @return array
  1220. */
  1221. protected function createUserParameter($id, array $params)
  1222. {
  1223. if ($this->validInteger($id)) {
  1224. $params['user_id'] = $id;
  1225. return $params;
  1226. }
  1227. $params['screen_name'] = $this->validateScreenName($id);
  1228. return $params;
  1229. }
  1230. }