Twitter.php 45 KB

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