Twitter.php 32 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040
  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 mixed $int
  868. * @return integer
  869. */
  870. protected function _validInteger($int)
  871. {
  872. if (preg_match("/(\d+)/", $int)) {
  873. return $int;
  874. }
  875. return 0;
  876. }
  877. /**
  878. * Validate a screen name using Twitter rules
  879. *
  880. * @param string $name
  881. * @throws Zend_Service_Twitter_Exception
  882. * @return string
  883. */
  884. protected function _validateScreenName($name)
  885. {
  886. if (!preg_match('/^[a-zA-Z0-9_]{0,15}$/', $name)) {
  887. require_once 'Zend/Service/Twitter/Exception.php';
  888. throw new Zend_Service_Twitter_Exception(
  889. 'Screen name, "' . $name
  890. . '" should only contain alphanumeric characters and'
  891. . ' underscores, and not exceed 15 characters.');
  892. }
  893. return $name;
  894. }
  895. /**
  896. * Call a remote REST web service URI and return the Zend_Http_Response object
  897. *
  898. * @param string $path The path to append to the URI
  899. * @throws Zend_Rest_Client_Exception
  900. * @return void
  901. */
  902. protected function _prepare($path)
  903. {
  904. // Get the URI object and configure it
  905. if (!$this->_uri instanceof Zend_Uri_Http) {
  906. require_once 'Zend/Rest/Client/Exception.php';
  907. throw new Zend_Rest_Client_Exception(
  908. 'URI object must be set before performing call'
  909. );
  910. }
  911. $uri = $this->_uri->getUri();
  912. if ($path[0] != '/' && $uri[strlen($uri) - 1] != '/') {
  913. $path = '/' . $path;
  914. }
  915. $this->_uri->setPath($path);
  916. /**
  917. * Get the HTTP client and configure it for the endpoint URI.
  918. * Do this each time because the Zend_Http_Client instance is shared
  919. * among all Zend_Service_Abstract subclasses.
  920. */
  921. $this->_localHttpClient->resetParameters()->setUri((string) $this->_uri);
  922. }
  923. /**
  924. * Performs an HTTP GET request to the $path.
  925. *
  926. * @param string $path
  927. * @param array $query Array of GET parameters
  928. * @throws Zend_Http_Client_Exception
  929. * @return Zend_Http_Response
  930. */
  931. protected function _get($path, array $query = null)
  932. {
  933. $this->_prepare($path);
  934. $this->_localHttpClient->setParameterGet($query);
  935. return $this->_localHttpClient->request(Zend_Http_Client::GET);
  936. }
  937. /**
  938. * Performs an HTTP POST request to $path.
  939. *
  940. * @param string $path
  941. * @param mixed $data Raw data to send
  942. * @throws Zend_Http_Client_Exception
  943. * @return Zend_Http_Response
  944. */
  945. protected function _post($path, $data = null)
  946. {
  947. $this->_prepare($path);
  948. return $this->_performPost(Zend_Http_Client::POST, $data);
  949. }
  950. /**
  951. * Perform a POST or PUT
  952. *
  953. * Performs a POST or PUT request. Any data provided is set in the HTTP
  954. * client. String data is pushed in as raw POST data; array or object data
  955. * is pushed in as POST parameters.
  956. *
  957. * @param mixed $method
  958. * @param mixed $data
  959. * @return Zend_Http_Response
  960. */
  961. protected function _performPost($method, $data = null)
  962. {
  963. $client = $this->_localHttpClient;
  964. if (is_string($data)) {
  965. $client->setRawData($data);
  966. } elseif (is_array($data) || is_object($data)) {
  967. $client->setParameterPost((array) $data);
  968. }
  969. return $client->request($method);
  970. }
  971. }