Twitter.php 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041
  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-2010 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_Rest_Client
  24. */
  25. require_once 'Zend/Rest/Client.php';
  26. /**
  27. * @see Zend_Rest_Client_Result
  28. */
  29. require_once 'Zend/Rest/Client/Result.php';
  30. /**
  31. * @see Zend_Oauth_Consumer
  32. */
  33. require_once 'Zend/Oauth/Consumer.php';
  34. /**
  35. * @category Zend
  36. * @package Zend_Service
  37. * @subpackage Twitter
  38. * @copyright Copyright (c) 2005-2010 Zend Technologies USA Inc. (http://www.zend.com)
  39. * @license http://framework.zend.com/license/new-bsd New BSD License
  40. */
  41. class Zend_Service_Twitter extends Zend_Rest_Client
  42. {
  43. /**
  44. * 246 is the current limit for a status message, 140 characters are displayed
  45. * initially, with the remainder linked from the web UI or client. The limit is
  46. * applied to a html encoded UTF-8 string (i.e. entities are counted in the limit
  47. * which may appear unusual but is a security measure).
  48. *
  49. * This should be reviewed in the future...
  50. */
  51. const STATUS_MAX_CHARACTERS = 246;
  52. /**
  53. * OAuth Endpoint
  54. */
  55. const OAUTH_BASE_URI = 'http://twitter.com/oauth';
  56. /**
  57. * @var Zend_Http_CookieJar
  58. */
  59. protected $_cookieJar;
  60. /**
  61. * Date format for 'since' strings
  62. *
  63. * @var string
  64. */
  65. protected $_dateFormat = 'D, d M Y H:i:s T';
  66. /**
  67. * Username
  68. *
  69. * @var string
  70. */
  71. protected $_username;
  72. /**
  73. * Current method type (for method proxying)
  74. *
  75. * @var string
  76. */
  77. protected $_methodType;
  78. /**
  79. * Zend_Oauth Consumer
  80. *
  81. * @var Zend_Oauth_Consumer
  82. */
  83. protected $_oauthConsumer = null;
  84. /**
  85. * Types of API methods
  86. *
  87. * @var array
  88. */
  89. protected $_methodTypes = array(
  90. 'status',
  91. 'user',
  92. 'directMessage',
  93. 'friendship',
  94. 'account',
  95. 'favorite',
  96. 'block'
  97. );
  98. /**
  99. * Options passed to constructor
  100. *
  101. * @var array
  102. */
  103. protected $_options = array();
  104. /**
  105. * Local HTTP Client cloned from statically set client
  106. *
  107. * @var Zend_Http_Client
  108. */
  109. protected $_localHttpClient = null;
  110. /**
  111. * Constructor
  112. *
  113. * @param array $options Optional options array
  114. * @return void
  115. */
  116. public function __construct($options = null, Zend_Oauth_Consumer $consumer = null)
  117. {
  118. $this->setUri('http://api.twitter.com');
  119. if (!is_array($options)) $options = array();
  120. $options['siteUrl'] = self::OAUTH_BASE_URI;
  121. if ($options instanceof Zend_Config) {
  122. $options = $options->toArray();
  123. }
  124. $this->_options = $options;
  125. if (isset($options['username'])) {
  126. $this->setUsername($options['username']);
  127. }
  128. if (isset($options['accessToken'])
  129. && $options['accessToken'] instanceof Zend_Oauth_Token_Access) {
  130. $this->setLocalHttpClient($options['accessToken']->getHttpClient($options));
  131. } else {
  132. $this->setLocalHttpClient(clone self::getHttpClient());
  133. if ($consumer === null) {
  134. $this->_oauthConsumer = new Zend_Oauth_Consumer($options);
  135. } else {
  136. $this->_oauthConsumer = $consumer;
  137. }
  138. }
  139. }
  140. /**
  141. * Set local HTTP client as distinct from the static HTTP client
  142. * as inherited from Zend_Rest_Client.
  143. *
  144. * @param Zend_Http_Client $client
  145. * @return self
  146. */
  147. public function setLocalHttpClient(Zend_Http_Client $client)
  148. {
  149. $this->_localHttpClient = $client;
  150. $this->_localHttpClient->setHeaders('Accept-Charset', 'ISO-8859-1,utf-8');
  151. return $this;
  152. }
  153. /**
  154. * Get the local HTTP client as distinct from the static HTTP client
  155. * inherited from Zend_Rest_Client
  156. *
  157. * @return Zend_Http_Client
  158. */
  159. public function getLocalHttpClient()
  160. {
  161. return $this->_localHttpClient;
  162. }
  163. /**
  164. * Checks for an authorised state
  165. *
  166. * @return bool
  167. */
  168. public function isAuthorised()
  169. {
  170. if ($this->getLocalHttpClient() instanceof Zend_Oauth_Client) {
  171. return true;
  172. }
  173. return false;
  174. }
  175. /**
  176. * Retrieve username
  177. *
  178. * @return string
  179. */
  180. public function getUsername()
  181. {
  182. return $this->_username;
  183. }
  184. /**
  185. * Set username
  186. *
  187. * @param string $value
  188. * @return Zend_Service_Twitter
  189. */
  190. public function setUsername($value)
  191. {
  192. $this->_username = $value;
  193. return $this;
  194. }
  195. /**
  196. * Proxy service methods
  197. *
  198. * @param string $type
  199. * @return Zend_Service_Twitter
  200. * @throws Zend_Service_Twitter_Exception If method not in method types list
  201. */
  202. public function __get($type)
  203. {
  204. if (!in_array($type, $this->_methodTypes)) {
  205. include_once 'Zend/Service/Twitter/Exception.php';
  206. throw new Zend_Service_Twitter_Exception(
  207. 'Invalid method type "' . $type . '"'
  208. );
  209. }
  210. $this->_methodType = $type;
  211. return $this;
  212. }
  213. /**
  214. * Method overloading
  215. *
  216. * @param string $method
  217. * @param array $params
  218. * @return mixed
  219. * @throws Zend_Service_Twitter_Exception if unable to find method
  220. */
  221. public function __call($method, $params)
  222. {
  223. if (method_exists($this->_oauthConsumer, $method)) {
  224. $return = call_user_func_array(array($this->_oauthConsumer, $method), $params);
  225. if ($return instanceof Zend_Oauth_Token_Access) {
  226. $this->setLocalHttpClient($return->getHttpClient($this->_options));
  227. }
  228. return $return;
  229. }
  230. if (empty($this->_methodType)) {
  231. include_once 'Zend/Service/Twitter/Exception.php';
  232. throw new Zend_Service_Twitter_Exception(
  233. 'Invalid method "' . $method . '"'
  234. );
  235. }
  236. $test = $this->_methodType . ucfirst($method);
  237. if (!method_exists($this, $test)) {
  238. include_once 'Zend/Service/Twitter/Exception.php';
  239. throw new Zend_Service_Twitter_Exception(
  240. 'Invalid method "' . $test . '"'
  241. );
  242. }
  243. return call_user_func_array(array($this, $test), $params);
  244. }
  245. /**
  246. * Initialize HTTP authentication
  247. *
  248. * @return void
  249. */
  250. protected function _init()
  251. {
  252. if (!$this->isAuthorised() && $this->getUsername() !== null) {
  253. require_once 'Zend/Service/Twitter/Exception.php';
  254. throw new Zend_Service_Twitter_Exception(
  255. 'Twitter session is unauthorised. You need to initialize '
  256. . 'Zend_Service_Twitter with an OAuth Access Token or use '
  257. . 'its OAuth functionality to obtain an Access Token before '
  258. . 'attempting any API actions that require authorisation'
  259. );
  260. }
  261. $client = $this->_localHttpClient;
  262. $client->resetParameters();
  263. if (null == $this->_cookieJar) {
  264. $client->setCookieJar();
  265. $this->_cookieJar = $client->getCookieJar();
  266. } else {
  267. $client->setCookieJar($this->_cookieJar);
  268. }
  269. }
  270. /**
  271. * Set date header
  272. *
  273. * @param int|string $value
  274. * @deprecated Not supported by Twitter since April 08, 2009
  275. * @return void
  276. */
  277. protected function _setDate($value)
  278. {
  279. if (is_int($value)) {
  280. $date = date($this->_dateFormat, $value);
  281. } else {
  282. $date = date($this->_dateFormat, strtotime($value));
  283. }
  284. $this->_localHttpClient->setHeaders('If-Modified-Since', $date);
  285. }
  286. /**
  287. * Public Timeline status
  288. *
  289. * @throws Zend_Http_Client_Exception if HTTP request fails or times out
  290. * @return Zend_Rest_Client_Result
  291. */
  292. public function statusPublicTimeline()
  293. {
  294. $this->_init();
  295. $path = '/1/statuses/public_timeline.xml';
  296. $response = $this->_get($path);
  297. return new Zend_Rest_Client_Result($response->getBody());
  298. }
  299. /**
  300. * Friend Timeline Status
  301. *
  302. * $params may include one or more of the following keys
  303. * - id: ID of a friend whose timeline you wish to receive
  304. * - count: how many statuses to return
  305. * - since_id: return results only after the specific tweet
  306. * - page: return page X of results
  307. *
  308. * @param array $params
  309. * @throws Zend_Http_Client_Exception if HTTP request fails or times out
  310. * @return void
  311. */
  312. public function statusFriendsTimeline(array $params = array())
  313. {
  314. $this->_init();
  315. $path = '/1/statuses/friends_timeline';
  316. $_params = array();
  317. foreach ($params as $key => $value) {
  318. switch (strtolower($key)) {
  319. case 'count':
  320. $count = (int) $value;
  321. if (0 >= $count) {
  322. $count = 1;
  323. } elseif (200 < $count) {
  324. $count = 200;
  325. }
  326. $_params['count'] = (int) $count;
  327. break;
  328. case 'since_id':
  329. $_params['since_id'] = $this->_validInteger($value);
  330. break;
  331. case 'page':
  332. $_params['page'] = (int) $value;
  333. break;
  334. default:
  335. break;
  336. }
  337. }
  338. $path .= '.xml';
  339. $response = $this->_get($path, $_params);
  340. return new Zend_Rest_Client_Result($response->getBody());
  341. }
  342. /**
  343. * User Timeline status
  344. *
  345. * $params may include one or more of the following keys
  346. * - id: ID of a friend whose timeline you wish to receive
  347. * - since_id: return results only after the tweet id specified
  348. * - page: return page X of results
  349. * - count: how many statuses to return
  350. * - max_id: returns only statuses with an ID less than or equal to the specified ID
  351. * - user_id: specifies the ID of the user for whom to return the user_timeline
  352. * - screen_name: specfies the screen name of the user for whom to return the user_timeline
  353. * - include_rts: whether or not to return retweets
  354. * - trim_user: whether to return just the user ID or a full user object; omit to return full object
  355. * - include_entities: whether or not to return entities nodes with tweet metadata
  356. *
  357. * @throws Zend_Http_Client_Exception if HTTP request fails or times out
  358. * @return Zend_Rest_Client_Result
  359. */
  360. public function statusUserTimeline(array $params = array())
  361. {
  362. $this->_init();
  363. $path = '/1/statuses/user_timeline';
  364. $_params = array();
  365. foreach ($params as $key => $value) {
  366. switch (strtolower($key)) {
  367. case 'id':
  368. $path .= '/' . $value;
  369. break;
  370. case 'page':
  371. $_params['page'] = (int) $value;
  372. break;
  373. case 'count':
  374. $count = (int) $value;
  375. if (0 >= $count) {
  376. $count = 1;
  377. } elseif (200 < $count) {
  378. $count = 200;
  379. }
  380. $_params['count'] = $count;
  381. break;
  382. case 'user_id':
  383. $_params['user_id'] = $this->_validInteger($value);
  384. break;
  385. case 'screen_name':
  386. $_params['screen_name'] = $this->_validateScreenName($value);
  387. break;
  388. case 'since_id':
  389. $_params['since_id'] = $this->_validInteger($value);
  390. break;
  391. case 'max_id':
  392. $_params['max_id'] = $this->_validInteger($value);
  393. break;
  394. case 'include_rts':
  395. case 'trim_user':
  396. case 'include_entities':
  397. $_params[strtolower($key)] = $value ? '1' : '0';
  398. break;
  399. default:
  400. break;
  401. }
  402. }
  403. $path .= '.xml';
  404. $response = $this->_get($path, $_params);
  405. return new Zend_Rest_Client_Result($response->getBody());
  406. }
  407. /**
  408. * Show a single status
  409. *
  410. * @param int $id Id of status to show
  411. * @throws Zend_Http_Client_Exception if HTTP request fails or times out
  412. * @return Zend_Rest_Client_Result
  413. */
  414. public function statusShow($id)
  415. {
  416. $this->_init();
  417. $path = '/1/statuses/show/' . $this->_validInteger($id) . '.xml';
  418. $response = $this->_get($path);
  419. return new Zend_Rest_Client_Result($response->getBody());
  420. }
  421. /**
  422. * Update user's current status
  423. *
  424. * @param string $status
  425. * @param int $in_reply_to_status_id
  426. * @return Zend_Rest_Client_Result
  427. * @throws Zend_Http_Client_Exception if HTTP request fails or times out
  428. * @throws Zend_Service_Twitter_Exception if message is too short or too long
  429. */
  430. public function statusUpdate($status, $inReplyToStatusId = null)
  431. {
  432. $this->_init();
  433. $path = '/1/statuses/update.xml';
  434. $len = iconv_strlen(htmlspecialchars($status, ENT_QUOTES, 'UTF-8'), 'UTF-8');
  435. if ($len > self::STATUS_MAX_CHARACTERS) {
  436. include_once 'Zend/Service/Twitter/Exception.php';
  437. throw new Zend_Service_Twitter_Exception(
  438. 'Status must be no more than '
  439. . self::STATUS_MAX_CHARACTERS
  440. . ' characters in length'
  441. );
  442. } elseif (0 == $len) {
  443. include_once 'Zend/Service/Twitter/Exception.php';
  444. throw new Zend_Service_Twitter_Exception(
  445. 'Status must contain at least one character'
  446. );
  447. }
  448. $data = array('status' => $status);
  449. if (is_numeric($inReplyToStatusId) && !empty($inReplyToStatusId)) {
  450. $data['in_reply_to_status_id'] = $inReplyToStatusId;
  451. }
  452. $response = $this->_post($path, $data);
  453. return new Zend_Rest_Client_Result($response->getBody());
  454. }
  455. /**
  456. * Get status replies
  457. *
  458. * $params may include one or more of the following keys
  459. * - since_id: return results only after the specified tweet id
  460. * - page: return page X of results
  461. *
  462. * @throws Zend_Http_Client_Exception if HTTP request fails or times out
  463. * @return Zend_Rest_Client_Result
  464. */
  465. public function statusReplies(array $params = array())
  466. {
  467. $this->_init();
  468. $path = '/1/statuses/mentions.xml';
  469. $_params = array();
  470. foreach ($params as $key => $value) {
  471. switch (strtolower($key)) {
  472. case 'since_id':
  473. $_params['since_id'] = $this->_validInteger($value);
  474. break;
  475. case 'page':
  476. $_params['page'] = (int) $value;
  477. break;
  478. default:
  479. break;
  480. }
  481. }
  482. $response = $this->_get($path, $_params);
  483. return new Zend_Rest_Client_Result($response->getBody());
  484. }
  485. /**
  486. * Destroy a status message
  487. *
  488. * @param int $id ID of status to destroy
  489. * @throws Zend_Http_Client_Exception if HTTP request fails or times out
  490. * @return Zend_Rest_Client_Result
  491. */
  492. public function statusDestroy($id)
  493. {
  494. $this->_init();
  495. $path = '/1/statuses/destroy/' . $this->_validInteger($id) . '.xml';
  496. $response = $this->_post($path);
  497. return new Zend_Rest_Client_Result($response->getBody());
  498. }
  499. /**
  500. * User friends
  501. *
  502. * @param int|string $id Id or username of user for whom to fetch friends
  503. * @throws Zend_Http_Client_Exception if HTTP request fails or times out
  504. * @return Zend_Rest_Client_Result
  505. */
  506. public function userFriends(array $params = array())
  507. {
  508. $this->_init();
  509. $path = '/1/statuses/friends';
  510. $_params = array();
  511. foreach ($params as $key => $value) {
  512. switch (strtolower($key)) {
  513. case 'id':
  514. $path .= '/' . $value;
  515. break;
  516. case 'page':
  517. $_params['page'] = (int) $value;
  518. break;
  519. default:
  520. break;
  521. }
  522. }
  523. $path .= '.xml';
  524. $response = $this->_get($path, $_params);
  525. return new Zend_Rest_Client_Result($response->getBody());
  526. }
  527. /**
  528. * User Followers
  529. *
  530. * @param bool $lite If true, prevents inline inclusion of current status for followers; defaults to false
  531. * @throws Zend_Http_Client_Exception if HTTP request fails or times out
  532. * @return Zend_Rest_Client_Result
  533. */
  534. public function userFollowers($lite = false)
  535. {
  536. $this->_init();
  537. $path = '/1/statuses/followers.xml';
  538. if ($lite) {
  539. $this->lite = 'true';
  540. }
  541. $response = $this->_get($path);
  542. return new Zend_Rest_Client_Result($response->getBody());
  543. }
  544. /**
  545. * Show extended information on a user
  546. *
  547. * @param int|string $id User ID or name
  548. * @throws Zend_Http_Client_Exception if HTTP request fails or times out
  549. * @return Zend_Rest_Client_Result
  550. */
  551. public function userShow($id)
  552. {
  553. $this->_init();
  554. $path = '/1/users/show.xml';
  555. $response = $this->_get($path, array('id'=>$id));
  556. return new Zend_Rest_Client_Result($response->getBody());
  557. }
  558. /**
  559. * Retrieve direct messages for the current user
  560. *
  561. * $params may include one or more of the following keys
  562. * - since_id: return statuses only greater than the one specified
  563. * - page: return page X of results
  564. *
  565. * @param array $params
  566. * @throws Zend_Http_Client_Exception if HTTP request fails or times out
  567. * @return Zend_Rest_Client_Result
  568. */
  569. public function directMessageMessages(array $params = array())
  570. {
  571. $this->_init();
  572. $path = '/1/direct_messages.xml';
  573. $_params = array();
  574. foreach ($params as $key => $value) {
  575. switch (strtolower($key)) {
  576. case 'since_id':
  577. $_params['since_id'] = $this->_validInteger($value);
  578. break;
  579. case 'page':
  580. $_params['page'] = (int) $value;
  581. break;
  582. default:
  583. break;
  584. }
  585. }
  586. $response = $this->_get($path, $_params);
  587. return new Zend_Rest_Client_Result($response->getBody());
  588. }
  589. /**
  590. * Retrieve list of direct messages sent by current user
  591. *
  592. * $params may include one or more of the following keys
  593. * - since_id: return statuses only greater than the one specified
  594. * - page: return page X of results
  595. *
  596. * @param array $params
  597. * @throws Zend_Http_Client_Exception if HTTP request fails or times out
  598. * @return Zend_Rest_Client_Result
  599. */
  600. public function directMessageSent(array $params = array())
  601. {
  602. $this->_init();
  603. $path = '/1/direct_messages/sent.xml';
  604. $_params = array();
  605. foreach ($params as $key => $value) {
  606. switch (strtolower($key)) {
  607. case 'since_id':
  608. $_params['since_id'] = $this->_validInteger($value);
  609. break;
  610. case 'page':
  611. $_params['page'] = (int) $value;
  612. break;
  613. default:
  614. break;
  615. }
  616. }
  617. $response = $this->_get($path, $_params);
  618. return new Zend_Rest_Client_Result($response->getBody());
  619. }
  620. /**
  621. * Send a direct message to a user
  622. *
  623. * @param int|string $user User to whom to send message
  624. * @param string $text Message to send to user
  625. * @return Zend_Rest_Client_Result
  626. * @throws Zend_Service_Twitter_Exception if message is too short or too long
  627. * @throws Zend_Http_Client_Exception if HTTP request fails or times out
  628. */
  629. public function directMessageNew($user, $text)
  630. {
  631. $this->_init();
  632. $path = '/1/direct_messages/new.xml';
  633. $len = iconv_strlen($text, 'UTF-8');
  634. if (0 == $len) {
  635. throw new Zend_Service_Twitter_Exception(
  636. 'Direct message must contain at least one character'
  637. );
  638. } elseif (140 < $len) {
  639. throw new Zend_Service_Twitter_Exception(
  640. 'Direct message must contain no more than 140 characters'
  641. );
  642. }
  643. $data = array('user' => $user, 'text' => $text);
  644. $response = $this->_post($path, $data);
  645. return new Zend_Rest_Client_Result($response->getBody());
  646. }
  647. /**
  648. * Destroy a direct message
  649. *
  650. * @param int $id ID of message to destroy
  651. * @throws Zend_Http_Client_Exception if HTTP request fails or times out
  652. * @return Zend_Rest_Client_Result
  653. */
  654. public function directMessageDestroy($id)
  655. {
  656. $this->_init();
  657. $path = '/1/direct_messages/destroy/' . $this->_validInteger($id) . '.xml';
  658. $response = $this->_post($path);
  659. return new Zend_Rest_Client_Result($response->getBody());
  660. }
  661. /**
  662. * Create friendship
  663. *
  664. * @param int|string $id User ID or name of new friend
  665. * @throws Zend_Http_Client_Exception if HTTP request fails or times out
  666. * @return Zend_Rest_Client_Result
  667. */
  668. public function friendshipCreate($id)
  669. {
  670. $this->_init();
  671. $path = '/1/friendships/create/' . $id . '.xml';
  672. $response = $this->_post($path);
  673. return new Zend_Rest_Client_Result($response->getBody());
  674. }
  675. /**
  676. * Destroy friendship
  677. *
  678. * @param int|string $id User ID or name of friend to remove
  679. * @throws Zend_Http_Client_Exception if HTTP request fails or times out
  680. * @return Zend_Rest_Client_Result
  681. */
  682. public function friendshipDestroy($id)
  683. {
  684. $this->_init();
  685. $path = '/1/friendships/destroy/' . $id . '.xml';
  686. $response = $this->_post($path);
  687. return new Zend_Rest_Client_Result($response->getBody());
  688. }
  689. /**
  690. * Friendship exists
  691. *
  692. * @param int|string $id User ID or name of friend to see if they are your friend
  693. * @throws Zend_Http_Client_Exception if HTTP request fails or times out
  694. * @return Zend_Rest_Client_result
  695. */
  696. public function friendshipExists($id)
  697. {
  698. $this->_init();
  699. $path = '/1/friendships/exists.xml';
  700. $data = array('user_a' => $this->getUsername(), 'user_b' => $id);
  701. $response = $this->_get($path, $data);
  702. return new Zend_Rest_Client_Result($response->getBody());
  703. }
  704. /**
  705. * Verify Account Credentials
  706. * @throws Zend_Http_Client_Exception if HTTP request fails or times out
  707. *
  708. * @return Zend_Rest_Client_Result
  709. */
  710. public function accountVerifyCredentials()
  711. {
  712. $this->_init();
  713. $response = $this->_get('/1/account/verify_credentials.xml');
  714. return new Zend_Rest_Client_Result($response->getBody());
  715. }
  716. /**
  717. * End current session
  718. *
  719. * @throws Zend_Http_Client_Exception if HTTP request fails or times out
  720. * @return true
  721. */
  722. public function accountEndSession()
  723. {
  724. $this->_init();
  725. $this->_get('/1/account/end_session');
  726. return true;
  727. }
  728. /**
  729. * Returns the number of api requests you have left per hour.
  730. *
  731. * @throws Zend_Http_Client_Exception if HTTP request fails or times out
  732. * @return Zend_Rest_Client_Result
  733. */
  734. public function accountRateLimitStatus()
  735. {
  736. $this->_init();
  737. $response = $this->_get('/1/account/rate_limit_status.xml');
  738. return new Zend_Rest_Client_Result($response->getBody());
  739. }
  740. /**
  741. * Fetch favorites
  742. *
  743. * $params may contain one or more of the following:
  744. * - 'id': Id of a user for whom to fetch favorites
  745. * - 'page': Retrieve a different page of resuls
  746. *
  747. * @param array $params
  748. * @throws Zend_Http_Client_Exception if HTTP request fails or times out
  749. * @return Zend_Rest_Client_Result
  750. */
  751. public function favoriteFavorites(array $params = array())
  752. {
  753. $this->_init();
  754. $path = '/1/favorites';
  755. $_params = array();
  756. foreach ($params as $key => $value) {
  757. switch (strtolower($key)) {
  758. case 'id':
  759. $path .= '/' . $this->_validInteger($value);
  760. break;
  761. case 'page':
  762. $_params['page'] = (int) $value;
  763. break;
  764. default:
  765. break;
  766. }
  767. }
  768. $path .= '.xml';
  769. $response = $this->_get($path, $_params);
  770. return new Zend_Rest_Client_Result($response->getBody());
  771. }
  772. /**
  773. * Mark a status as a favorite
  774. *
  775. * @param int $id Status ID you want to mark as a favorite
  776. * @throws Zend_Http_Client_Exception if HTTP request fails or times out
  777. * @return Zend_Rest_Client_Result
  778. */
  779. public function favoriteCreate($id)
  780. {
  781. $this->_init();
  782. $path = '/1/favorites/create/' . $this->_validInteger($id) . '.xml';
  783. $response = $this->_post($path);
  784. return new Zend_Rest_Client_Result($response->getBody());
  785. }
  786. /**
  787. * Remove a favorite
  788. *
  789. * @param int $id Status ID you want to de-list as a favorite
  790. * @throws Zend_Http_Client_Exception if HTTP request fails or times out
  791. * @return Zend_Rest_Client_Result
  792. */
  793. public function favoriteDestroy($id)
  794. {
  795. $this->_init();
  796. $path = '/1/favorites/destroy/' . $this->_validInteger($id) . '.xml';
  797. $response = $this->_post($path);
  798. return new Zend_Rest_Client_Result($response->getBody());
  799. }
  800. /**
  801. * Blocks the user specified in the ID parameter as the authenticating user.
  802. * Destroys a friendship to the blocked user if it exists.
  803. *
  804. * @param integer|string $id The ID or screen name of a user to block.
  805. * @return Zend_Rest_Client_Result
  806. */
  807. public function blockCreate($id)
  808. {
  809. $this->_init();
  810. $path = '/1/blocks/create/' . $id . '.xml';
  811. $response = $this->_post($path);
  812. return new Zend_Rest_Client_Result($response->getBody());
  813. }
  814. /**
  815. * Un-blocks the user specified in the ID parameter for the authenticating user
  816. *
  817. * @param integer|string $id The ID or screen_name of the user to un-block.
  818. * @return Zend_Rest_Client_Result
  819. */
  820. public function blockDestroy($id)
  821. {
  822. $this->_init();
  823. $path = '/1/blocks/destroy/' . $id . '.xml';
  824. $response = $this->_post($path);
  825. return new Zend_Rest_Client_Result($response->getBody());
  826. }
  827. /**
  828. * Returns if the authenticating user is blocking a target user.
  829. *
  830. * @param string|integer $id The ID or screen_name of the potentially blocked user.
  831. * @param boolean $returnResult Instead of returning a boolean return the rest response from twitter
  832. * @return Boolean|Zend_Rest_Client_Result
  833. */
  834. public function blockExists($id, $returnResult = false)
  835. {
  836. $this->_init();
  837. $path = '/1/blocks/exists/' . $id . '.xml';
  838. $response = $this->_get($path);
  839. $cr = new Zend_Rest_Client_Result($response->getBody());
  840. if ($returnResult === true)
  841. return $cr;
  842. if (!empty($cr->request)) {
  843. return false;
  844. }
  845. return true;
  846. }
  847. /**
  848. * Returns an array of user objects that the authenticating user is blocking
  849. *
  850. * @param integer $page Optional. Specifies the page number of the results beginning at 1. A single page contains 20 ids.
  851. * @param boolean $returnUserIds Optional. Returns only the userid's instead of the whole user object
  852. * @return Zend_Rest_Client_Result
  853. */
  854. public function blockBlocking($page = 1, $returnUserIds = false)
  855. {
  856. $this->_init();
  857. $path = '/1/blocks/blocking';
  858. if ($returnUserIds === true) {
  859. $path .= '/ids';
  860. }
  861. $path .= '.xml';
  862. $response = $this->_get($path, array('page' => $page));
  863. return new Zend_Rest_Client_Result($response->getBody());
  864. }
  865. /**
  866. * Protected function to validate that the integer is valid or return a 0
  867. * @param $int
  868. * @throws Zend_Http_Client_Exception if HTTP request fails or times out
  869. * @return integer
  870. */
  871. protected function _validInteger($int)
  872. {
  873. if (preg_match("/(\d+)/", $int)) {
  874. return $int;
  875. }
  876. return 0;
  877. }
  878. /**
  879. * Validate a screen name using Twitter rules
  880. *
  881. * @param string $name
  882. * @throws Zend_Service_Twitter_Exception
  883. * @return string
  884. */
  885. protected function _validateScreenName($name)
  886. {
  887. if (!preg_match('/^[a-zA-Z0-9_]{0,15}$/', $name)) {
  888. require_once 'Zend/Service/Twitter/Exception.php';
  889. throw new Zend_Service_Twitter_Exception(
  890. 'Screen name, "' . $name
  891. . '" should only contain alphanumeric characters and'
  892. . ' underscores, and not exceed 15 characters.');
  893. }
  894. return $name;
  895. }
  896. /**
  897. * Call a remote REST web service URI and return the Zend_Http_Response object
  898. *
  899. * @param string $path The path to append to the URI
  900. * @throws Zend_Rest_Client_Exception
  901. * @return void
  902. */
  903. protected function _prepare($path)
  904. {
  905. // Get the URI object and configure it
  906. if (!$this->_uri instanceof Zend_Uri_Http) {
  907. require_once 'Zend/Rest/Client/Exception.php';
  908. throw new Zend_Rest_Client_Exception(
  909. 'URI object must be set before performing call'
  910. );
  911. }
  912. $uri = $this->_uri->getUri();
  913. if ($path[0] != '/' && $uri[strlen($uri) - 1] != '/') {
  914. $path = '/' . $path;
  915. }
  916. $this->_uri->setPath($path);
  917. /**
  918. * Get the HTTP client and configure it for the endpoint URI.
  919. * Do this each time because the Zend_Http_Client instance is shared
  920. * among all Zend_Service_Abstract subclasses.
  921. */
  922. $this->_localHttpClient->resetParameters()->setUri((string) $this->_uri);
  923. }
  924. /**
  925. * Performs an HTTP GET request to the $path.
  926. *
  927. * @param string $path
  928. * @param array $query Array of GET parameters
  929. * @throws Zend_Http_Client_Exception
  930. * @return Zend_Http_Response
  931. */
  932. protected function _get($path, array $query = null)
  933. {
  934. $this->_prepare($path);
  935. $this->_localHttpClient->setParameterGet($query);
  936. return $this->_localHttpClient->request(Zend_Http_Client::GET);
  937. }
  938. /**
  939. * Performs an HTTP POST request to $path.
  940. *
  941. * @param string $path
  942. * @param mixed $data Raw data to send
  943. * @throws Zend_Http_Client_Exception
  944. * @return Zend_Http_Response
  945. */
  946. protected function _post($path, $data = null)
  947. {
  948. $this->_prepare($path);
  949. return $this->_performPost(Zend_Http_Client::POST, $data);
  950. }
  951. /**
  952. * Perform a POST or PUT
  953. *
  954. * Performs a POST or PUT request. Any data provided is set in the HTTP
  955. * client. String data is pushed in as raw POST data; array or object data
  956. * is pushed in as POST parameters.
  957. *
  958. * @param mixed $method
  959. * @param mixed $data
  960. * @return Zend_Http_Response
  961. */
  962. protected function _performPost($method, $data = null)
  963. {
  964. $client = $this->_localHttpClient;
  965. if (is_string($data)) {
  966. $client->setRawData($data);
  967. } elseif (is_array($data) || is_object($data)) {
  968. $client->setParameterPost((array) $data);
  969. }
  970. return $client->request($method);
  971. }
  972. }