PageRenderTime 28ms CodeModel.GetById 0ms RepoModel.GetById 0ms app.codeStats 0ms

/application/helpers/account/jmathai-twitter-async/EpiTwitter.php

https://gitlab.com/ahsanullah716/auth_master
PHP | 294 lines | 227 code | 44 blank | 23 comment | 19 complexity | 105aaeaed22e80b78ca9ae6acacefdcb MD5 | raw file
  1. <?php
  2. /*
  3. * Class to integrate with Twitter's API.
  4. * Authenticated calls are done using OAuth and require access tokens for a user.
  5. * API calls which do not require authentication do not require tokens (i.e. search/trends)
  6. *
  7. * Full documentation available on github
  8. * http://wiki.github.com/jmathai/twitter-async
  9. *
  10. * @author Jaisen Mathai <jaisen@jmathai.com>
  11. */
  12. class EpiTwitter extends EpiOAuth {
  13. const EPITWITTER_SIGNATURE_METHOD = 'HMAC-SHA1';
  14. const EPITWITTER_AUTH_OAUTH = 'oauth';
  15. const EPITWITTER_AUTH_BASIC = 'basic';
  16. protected $requestTokenUrl = 'https://api.twitter.com/oauth/request_token';
  17. protected $accessTokenUrl = 'https://api.twitter.com/oauth/access_token';
  18. protected $authorizeUrl = 'https://api.twitter.com/oauth/authorize';
  19. protected $authenticateUrl = 'https://api.twitter.com/oauth/authenticate';
  20. protected $apiUrl = 'http://api.twitter.com';
  21. protected $apiVersionedUrl = 'http://api.twitter.com';
  22. protected $searchUrl = 'http://search.twitter.com';
  23. protected $userAgent = 'EpiTwitter (http://github.com/jmathai/twitter-async/tree/)';
  24. protected $apiVersion = '1.1';
  25. protected $isAsynchronous = FALSE;
  26. /* OAuth methods */
  27. public function delete($endpoint, $params = NULL)
  28. {
  29. return $this->request('DELETE', $endpoint, $params);
  30. }
  31. public function get($endpoint, $params = NULL)
  32. {
  33. return $this->request('GET', $endpoint, $params);
  34. }
  35. public function post($endpoint, $params = NULL)
  36. {
  37. return $this->request('POST', $endpoint, $params);
  38. }
  39. /* Basic auth methods */
  40. public function delete_basic($endpoint, $params = NULL, $username = NULL, $password = NULL)
  41. {
  42. return $this->request_basic('DELETE', $endpoint, $params, $username, $password);
  43. }
  44. public function get_basic($endpoint, $params = NULL, $username = NULL, $password = NULL)
  45. {
  46. return $this->request_basic('GET', $endpoint, $params, $username, $password);
  47. }
  48. public function post_basic($endpoint, $params = NULL, $username = NULL, $password = NULL)
  49. {
  50. return $this->request_basic('POST', $endpoint, $params, $username, $password);
  51. }
  52. public function useApiVersion($version = NULL)
  53. {
  54. $this->apiVersion = $version;
  55. }
  56. public function useAsynchronous($async = TRUE)
  57. {
  58. $this->isAsynchronous = (bool)$async;
  59. }
  60. public function __construct($consumerKey = NULL, $consumerSecret = NULL, $oauthToken = NULL, $oauthTokenSecret = NULL)
  61. {
  62. parent::__construct($consumerKey, $consumerSecret, self::EPITWITTER_SIGNATURE_METHOD);
  63. $this->setToken($oauthToken, $oauthTokenSecret);
  64. }
  65. public function __call($name, $params = NULL /*, $username, $password*/)
  66. {
  67. $parts = explode('_', $name);
  68. $method = strtoupper(array_shift($parts));
  69. $parts = implode('_', $parts);
  70. $endpoint = '/'.preg_replace('/[A-Z]|[0-9]+/e', "'/'.strtolower('\\0')", $parts).'.json';
  71. /* HACK: this is required for list support that starts with a user id */
  72. $endpoint = str_replace('//', '/', $endpoint);
  73. $args = ! empty($params) ? array_shift($params) : NULL;
  74. // calls which do not have a consumerKey are assumed to not require authentication
  75. if ($this->consumerKey === NULL)
  76. {
  77. $username = NULL;
  78. $password = NULL;
  79. if ( ! empty($params))
  80. {
  81. $username = array_shift($params);
  82. $password = ! empty($params) ? array_shift($params) : NULL;
  83. }
  84. return $this->request_basic($method, $endpoint, $args, $username, $password);
  85. }
  86. return $this->request($method, $endpoint, $args);
  87. }
  88. private function getApiUrl($endpoint)
  89. {
  90. if (preg_match('@^/search[./]?(?=(json|daily|current|weekly))@', $endpoint)) return "{$this->searchUrl}{$endpoint}";
  91. elseif ( ! empty($this->apiVersion)) return "{$this->apiVersionedUrl}/{$this->apiVersion}{$endpoint}";
  92. else
  93. return "{$this->apiUrl}{$endpoint}";
  94. }
  95. private function request($method, $endpoint, $params = NULL)
  96. {
  97. $url = $this->getUrl($this->getApiUrl($endpoint));
  98. $resp = new EpiTwitterJson(call_user_func(array($this, 'httpRequest'), $method, $url, $params, $this->isMultipart($params)), $this->debug);
  99. if ( ! $this->isAsynchronous) $resp->response;
  100. return $resp;
  101. }
  102. private function request_basic($method, $endpoint, $params = NULL, $username = NULL, $password = NULL)
  103. {
  104. $url = $this->getApiUrl($endpoint);
  105. if ($method === 'GET') $url .= is_null($params) ? '' : '?'.http_build_query($params, '', '&');
  106. $ch = curl_init($url);
  107. curl_setopt($ch, CURLOPT_HTTPHEADER, array('Expect:'));
  108. curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
  109. curl_setopt($ch, CURLOPT_TIMEOUT, $this->requestTimeout);
  110. curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $method);
  111. if ($method === 'POST' && $params !== NULL)
  112. {
  113. if ($this->isMultipart($params)) curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
  114. else
  115. curl_setopt($ch, CURLOPT_POSTFIELDS, $this->buildHttpQueryRaw($params));
  116. }
  117. if ( ! empty($username) && ! empty($password)) curl_setopt($ch, CURLOPT_USERPWD, "{$username}:{$password}");
  118. $resp = new EpiTwitterJson(EpiCurl::getInstance()->addCurl($ch), $this->debug);
  119. if ( ! $this->isAsynchronous) $resp->response;
  120. return $resp;
  121. }
  122. }
  123. class EpiTwitterJson implements ArrayAccess, Countable, IteratorAggregate {
  124. private $debug;
  125. private $__resp;
  126. public function __construct($response, $debug = FALSE)
  127. {
  128. $this->__resp = $response;
  129. $this->debug = $debug;
  130. }
  131. // ensure that calls complete by blocking for results, NOOP if already returned
  132. public function __destruct()
  133. {
  134. $this->responseText;
  135. }
  136. // Implementation of the IteratorAggregate::getIterator() to support foreach ($this as $...)
  137. public function getIterator()
  138. {
  139. if ($this->__obj)
  140. {
  141. return new ArrayIterator($this->__obj);
  142. }
  143. else
  144. {
  145. return new ArrayIterator($this->response);
  146. }
  147. }
  148. // Implementation of Countable::count() to support count($this)
  149. public function count()
  150. {
  151. return count($this->response);
  152. }
  153. // Next four functions are to support ArrayAccess interface
  154. // 1
  155. public function offsetSet($offset, $value)
  156. {
  157. $this->response[$offset] = $value;
  158. }
  159. // 2
  160. public function offsetExists($offset)
  161. {
  162. return isset($this->response[$offset]);
  163. }
  164. // 3
  165. public function offsetUnset($offset)
  166. {
  167. unset($this->response[$offset]);
  168. }
  169. // 4
  170. public function offsetGet($offset)
  171. {
  172. return isset($this->response[$offset]) ? $this->response[$offset] : NULL;
  173. }
  174. public function __get($name)
  175. {
  176. $accessible = array('responseText' => 1, 'headers' => 1, 'code' => 1);
  177. $this->responseText = $this->__resp->data;
  178. $this->headers = $this->__resp->headers;
  179. $this->code = $this->__resp->code;
  180. if (isset($accessible[$name]) && $accessible[$name]) return $this->$name;
  181. elseif (($this->code < 200 || $this->code >= 400) && ! isset($accessible[$name])) EpiTwitterException::raise($this->__resp, $this->debug);
  182. // Call appears ok so we can fill in the response
  183. $this->response = json_decode($this->responseText, 1);
  184. $this->__obj = json_decode($this->responseText);
  185. if (gettype($this->__obj) === 'object')
  186. {
  187. foreach ($this->__obj as $k => $v)
  188. {
  189. $this->$k = $v;
  190. }
  191. }
  192. if (property_exists($this, $name))
  193. {
  194. return $this->$name;
  195. }
  196. return NULL;
  197. }
  198. public function __isset($name)
  199. {
  200. $value = self::__get($name);
  201. return ! empty($name);
  202. }
  203. }
  204. class EpiTwitterException extends Exception {
  205. public static function raise($response, $debug)
  206. {
  207. $message = $response->data;
  208. switch ($response->code)
  209. {
  210. case 400:
  211. throw new EpiTwitterBadRequestException($message, $response->code);
  212. case 401:
  213. throw new EpiTwitterNotAuthorizedException($message, $response->code);
  214. case 403:
  215. throw new EpiTwitterForbiddenException($message, $response->code);
  216. case 404:
  217. throw new EpiTwitterNotFoundException($message, $response->code);
  218. case 406:
  219. throw new EpiTwitterNotAcceptableException($message, $response->code);
  220. case 420:
  221. throw new EpiTwitterEnhanceYourCalmException($message, $response->code);
  222. case 500:
  223. throw new EpiTwitterInternalServerException($message, $response->code);
  224. case 502:
  225. throw new EpiTwitterBadGatewayException($message, $response->code);
  226. case 503:
  227. throw new EpiTwitterServiceUnavailableException($message, $response->code);
  228. default:
  229. throw new EpiTwitterException($message, $response->code);
  230. }
  231. }
  232. }
  233. class EpiTwitterBadRequestException extends EpiTwitterException {
  234. }
  235. class EpiTwitterNotAuthorizedException extends EpiTwitterException {
  236. }
  237. class EpiTwitterForbiddenException extends EpiTwitterException {
  238. }
  239. class EpiTwitterNotFoundException extends EpiTwitterException {
  240. }
  241. class EpiTwitterNotAcceptableException extends EpiTwitterException {
  242. }
  243. class EpiTwitterEnhanceYourCalmException extends EpiTwitterException {
  244. }
  245. class EpiTwitterInternalServerException extends EpiTwitterException {
  246. }
  247. class EpiTwitterBadGatewayException extends EpiTwitterException {
  248. }
  249. class EpiTwitterServiceUnavailableException extends EpiTwitterException {
  250. }