Twitter.php 32 KB

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