PageRenderTime 49ms CodeModel.GetById 19ms RepoModel.GetById 0ms app.codeStats 0ms

/application/libraries/twilio.php

https://github.com/murrion/BlackLog_Public
PHP | 537 lines | 405 code | 38 blank | 94 comment | 14 complexity | e73c495d5337a31c965408f2243366a5 MD5 | raw file
  1. <?php
  2. /*
  3. Copyright (c) 2009 Twilio, Inc.
  4. Permission is hereby granted, free of charge, to any person
  5. obtaining a copy of this software and associated documentation
  6. files (the "Software"), to deal in the Software without
  7. restriction, including without limitation the rights to use,
  8. copy, modify, merge, publish, distribute, sublicense, and/or sell
  9. copies of the Software, and to permit persons to whom the
  10. Software is furnished to do so, subject to the following
  11. conditions:
  12. The above copyright notice and this permission notice shall be
  13. included in all copies or substantial portions of the Software.
  14. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  15. EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
  16. OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  17. NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
  18. HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
  19. WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
  20. FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
  21. OTHER DEALINGS IN THE SOFTWARE.
  22. */
  23. // VERSION: 2.0.5
  24. // Twilio REST Helpers
  25. // ========================================================================
  26. // ensure Curl is installed
  27. if (!extension_loaded("curl"))
  28. throw(new Exception(
  29. "Curl extension is required for TwilioRestClient to work"));
  30. /*
  31. * TwilioRestResponse holds all the REST response data
  32. * Before using the reponse, check IsError to see if an exception
  33. * occurred with the data sent to Twilio
  34. * ResponseXml will contain a SimpleXml object with the response xml
  35. * ResponseText contains the raw string response
  36. * Url and QueryString are from the request
  37. * HttpStatus is the response code of the request
  38. */
  39. class TwilioRestResponse
  40. {
  41. public $ResponseText;
  42. public $ResponseXml;
  43. public $HttpStatus;
  44. public $Url;
  45. public $QueryString;
  46. public $IsError;
  47. public $ErrorMessage;
  48. public function __construct($url, $text, $status)
  49. {
  50. preg_match('/([^?]+)\??(.*)/', $url, $matches);
  51. $this->Url = $matches[1];
  52. $this->QueryString = $matches[2];
  53. $this->ResponseText = $text;
  54. $this->HttpStatus = $status;
  55. if ($this->HttpStatus != 204)
  56. $this->ResponseXml = @simplexml_load_string($text);
  57. if ($this->IsError = ($status >= 400))
  58. $this->ErrorMessage =
  59. (string) $this->ResponseXml->RestException->Message;
  60. }
  61. }
  62. /* TwilioRestClient throws TwilioException on error
  63. * Useful to catch this exception separately from general PHP
  64. * exceptions, if you want
  65. */
  66. class TwilioException extends Exception
  67. {
  68. }
  69. /*
  70. * TwilioRestBaseClient: the core Rest client, talks to the Twilio REST
  71. * API. Returns a TwilioRestResponse object for all responses if Twilio's
  72. * API was reachable Throws a TwilioException if Twilio's REST API was
  73. * unreachable
  74. */
  75. class TwilioRestClient
  76. {
  77. protected $Endpoint;
  78. protected $AccountSid;
  79. protected $AuthToken;
  80. /*
  81. * __construct
  82. * $username : Your AccountSid
  83. * $password : Your account's AuthToken
  84. * $endpoint : The Twilio REST Service URL, currently defaults to
  85. * the proper URL
  86. */
  87. public function __construct($accountSid, $authToken, $endpoint = "https://api.twilio.com")
  88. {
  89. $this->AccountSid = $accountSid;
  90. $this->AuthToken = $authToken;
  91. $this->Endpoint = $endpoint;
  92. }
  93. /*
  94. * sendRequst
  95. * Sends a REST Request to the Twilio REST API
  96. * $path : the URL (relative to the endpoint URL, after the /v1)
  97. * $method : the HTTP method to use, defaults to GET
  98. * $vars : for POST or PUT, a key/value associative array of data to
  99. * send, for GET will be appended to the URL as query params
  100. */
  101. public function request($path, $method = "GET", $vars = array())
  102. {
  103. $fp = null;
  104. $tmpfile = "";
  105. $encoded = "";
  106. foreach ($vars AS $key => $value)
  107. $encoded .= "$key=" . urlencode($value) . "&";
  108. $encoded = substr($encoded, 0, -1);
  109. // construct full url
  110. $url = "{$this->Endpoint}/$path";
  111. // if GET and vars, append them
  112. if ($method == "GET")
  113. $url .= (FALSE === strpos($path, '?') ? "?" : "&") . $encoded;
  114. // initialize a new curl object
  115. $curl = curl_init($url);
  116. curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
  117. curl_setopt($curl, CURLOPT_RETURNTRANSFER, TRUE);
  118. switch (strtoupper($method))
  119. {
  120. case "GET":
  121. curl_setopt($curl, CURLOPT_HTTPGET, TRUE);
  122. break;
  123. case "POST":
  124. curl_setopt($curl, CURLOPT_POST, TRUE);
  125. curl_setopt($curl, CURLOPT_POSTFIELDS, $encoded);
  126. break;
  127. case "PUT":
  128. // curl_setopt($curl, CURLOPT_PUT, TRUE);
  129. curl_setopt($curl, CURLOPT_POSTFIELDS, $encoded);
  130. curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "PUT");
  131. file_put_contents($tmpfile = tempnam("/tmp", "put_"), $encoded);
  132. curl_setopt($curl, CURLOPT_INFILE, $fp = fopen($tmpfile, 'r'));
  133. curl_setopt($curl, CURLOPT_INFILESIZE, filesize($tmpfile));
  134. break;
  135. case "DELETE":
  136. curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "DELETE");
  137. break;
  138. default:
  139. throw(new TwilioException("Unknown method $method"));
  140. break;
  141. }
  142. // send credentials
  143. curl_setopt($curl, CURLOPT_USERPWD, $pwd = "{$this->AccountSid}:{$this->AuthToken}");
  144. // do the request. If FALSE, then an exception occurred
  145. if (FALSE === ($result = curl_exec($curl)))
  146. throw(new TwilioException(
  147. "Curl failed with error " . curl_error($curl)));
  148. // get result code
  149. $responseCode = curl_getinfo($curl, CURLINFO_HTTP_CODE);
  150. // unlink tmpfiles
  151. if ($fp)
  152. fclose($fp);
  153. if (strlen($tmpfile))
  154. unlink($tmpfile);
  155. return new TwilioRestResponse($url, $result, $responseCode);
  156. }
  157. }
  158. // Twiml Response Helpers
  159. // ========================================================================
  160. /*
  161. * Verb: Base class for all TwiML verbs used in creating Responses
  162. * Throws a TwilioException if an non-supported attribute or
  163. * attribute value is added to the verb. All methods in Verb are protected
  164. * or private
  165. */
  166. class Verb
  167. {
  168. private $tag;
  169. private $body;
  170. private $attr;
  171. private $children;
  172. /*
  173. * __construct
  174. * $body : Verb contents
  175. * $body : Verb attributes
  176. */
  177. function __construct($body=NULL, $attr = array())
  178. {
  179. if (is_array($body))
  180. {
  181. $attr = $body;
  182. $body = NULL;
  183. }
  184. $this->tag = get_class($this);
  185. $this->body = $body;
  186. $this->attr = array();
  187. $this->children = array();
  188. self::addAttributes($attr);
  189. }
  190. /*
  191. * addAttributes
  192. * $attr : A key/value array of attributes to be added
  193. * $valid : A key/value array containging the accepted attributes
  194. * for this verb
  195. * Throws an exception if an invlaid attribute is found
  196. */
  197. private function addAttributes($attr)
  198. {
  199. foreach ($attr as $key => $value)
  200. {
  201. if (in_array($key, $this->valid))
  202. $this->attr[$key] = $value;
  203. else
  204. throw new TwilioException($key . ', ' . $value .
  205. " is not a supported attribute pair");
  206. }
  207. }
  208. /*
  209. * append
  210. * Nests other verbs inside self.
  211. */
  212. function append($verb)
  213. {
  214. if (is_null($this->nesting))
  215. throw new TwilioException($this->tag . " doesn't support nesting");
  216. else if (!is_object($verb))
  217. throw new TwilioException($verb->tag . " is not an object");
  218. else if (!in_array(get_class($verb), $this->nesting))
  219. throw new TwilioException($verb->tag . " is not an allowed verb here");
  220. else
  221. {
  222. $this->children[] = $verb;
  223. return $verb;
  224. }
  225. }
  226. /*
  227. * set
  228. * $attr : An attribute to be added
  229. * $valid : The attrbute value for this verb
  230. * No error checking here
  231. */
  232. function set($key, $value)
  233. {
  234. $this->attr[$key] = $value;
  235. }
  236. /* Convenience Methods */
  237. function addSay($body=NULL, $attr = array())
  238. {
  239. return self::append(new Say($body, $attr));
  240. }
  241. function addPlay($body=NULL, $attr = array())
  242. {
  243. return self::append(new Play($body, $attr));
  244. }
  245. function addDial($body=NULL, $attr = array())
  246. {
  247. return self::append(new Dial($body, $attr));
  248. }
  249. function addNumber($body=NULL, $attr = array())
  250. {
  251. return self::append(new Number($body, $attr));
  252. }
  253. function addGather($attr = array())
  254. {
  255. return self::append(new Gather($attr));
  256. }
  257. function addRecord($attr = array())
  258. {
  259. return self::append(new Record(NULL, $attr));
  260. }
  261. function addHangup()
  262. {
  263. return self::append(new Hangup());
  264. }
  265. function addRedirect($body=NULL, $attr = array())
  266. {
  267. return self::append(new Redirect($body, $attr));
  268. }
  269. function addPause($attr = array())
  270. {
  271. return self::append(new Pause($attr));
  272. }
  273. function addConference($body=NULL, $attr = array())
  274. {
  275. return self::append(new Conference($body, $attr));
  276. }
  277. function addSms($body=NULL, $attr = array())
  278. {
  279. return self::append(new Sms($body, $attr));
  280. }
  281. /*
  282. * write
  283. * Output the XML for this verb and all it's children
  284. * $parent: This verb's parent verb
  285. * $writeself : If FALSE, Verb will not output itself,
  286. * only its children
  287. */
  288. protected function write($parent, $writeself=TRUE)
  289. {
  290. if ($writeself)
  291. {
  292. $elem = $parent->addChild($this->tag, $this->body);
  293. foreach ($this->attr as $key => $value)
  294. $elem->addAttribute($key, $value);
  295. foreach ($this->children as $child)
  296. $child->write($elem);
  297. }
  298. else
  299. {
  300. foreach ($this->children as $child)
  301. $child->write($parent);
  302. }
  303. }
  304. }
  305. class Response extends Verb
  306. {
  307. private $xml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><Response></Response>";
  308. protected $nesting = array('Say', 'Play', 'Gather', 'Record',
  309. 'Dial', 'Redirect', 'Pause', 'Hangup', 'Sms');
  310. function __construct()
  311. {
  312. parent::__construct(NULL);
  313. }
  314. function Respond($sendHeader = true)
  315. {
  316. // try to force the xml data type
  317. // this is generally unneeded by Twilio, but nice to have
  318. if ($sendHeader)
  319. {
  320. if (!headers_sent())
  321. {
  322. header("Content-type: text/xml");
  323. }
  324. }
  325. $simplexml = new SimpleXMLElement($this->xml);
  326. $this->write($simplexml, FALSE);
  327. print $simplexml->asXML();
  328. }
  329. function asURL($encode = TRUE)
  330. {
  331. $simplexml = new SimpleXMLElement($this->xml);
  332. $this->write($simplexml, FALSE);
  333. if ($encode)
  334. return urlencode($simplexml->asXML());
  335. else
  336. return $simplexml->asXML();
  337. }
  338. }
  339. class Say extends Verb
  340. {
  341. protected $valid = array('voice', 'language', 'loop');
  342. }
  343. class Play extends Verb
  344. {
  345. protected $valid = array('loop');
  346. }
  347. class Record extends Verb
  348. {
  349. protected $valid = array('action', 'method', 'timeout', 'finishOnKey',
  350. 'maxLength', 'transcribe', 'transcribeCallback');
  351. }
  352. class Dial extends Verb
  353. {
  354. protected $valid = array('action', 'method', 'timeout', 'hangupOnStar',
  355. 'timeLimit', 'callerId');
  356. protected $nesting = array('Number', 'Conference');
  357. }
  358. class Redirect extends Verb
  359. {
  360. protected $valid = array('method');
  361. }
  362. class Pause extends Verb
  363. {
  364. protected $valid = array('length');
  365. function __construct($attr = array())
  366. {
  367. parent::__construct(NULL, $attr);
  368. }
  369. }
  370. class Hangup extends Verb
  371. {
  372. function __construct()
  373. {
  374. parent::__construct(NULL, array());
  375. }
  376. }
  377. class Gather extends Verb
  378. {
  379. protected $valid = array('action', 'method', 'timeout', 'finishOnKey',
  380. 'numDigits');
  381. protected $nesting = array('Say', 'Play', 'Pause');
  382. function __construct($attr = array())
  383. {
  384. parent::__construct(NULL, $attr);
  385. }
  386. }
  387. class Number extends Verb
  388. {
  389. protected $valid = array('url', 'sendDigits');
  390. }
  391. class Conference extends Verb
  392. {
  393. protected $valid = array('muted', 'beep', 'startConferenceOnEnter',
  394. 'endConferenceOnExit', 'waitUrl', 'waitMethod');
  395. }
  396. class Sms extends Verb
  397. {
  398. protected $valid = array('to', 'from', 'action', 'method', 'statusCallback');
  399. }
  400. // Twilio Utility function and Request Validation
  401. // ========================================================================
  402. class TwilioUtils
  403. {
  404. protected $AccountSid;
  405. protected $AuthToken;
  406. function __construct($id, $token)
  407. {
  408. $this->AuthToken = $token;
  409. $this->AccountSid = $id;
  410. }
  411. public function validateRequest($expected_signature, $url, $data = array())
  412. {
  413. // sort the array by keys
  414. ksort($data);
  415. // append them to the data string in order
  416. // with no delimiters
  417. foreach ($data AS $key => $value)
  418. $url .= "$key$value";
  419. // This function calculates the HMAC hash of the data with the key
  420. // passed in
  421. // Note: hash_hmac requires PHP 5 >= 5.1.2 or PECL hash:1.1-1.5
  422. // Or http://pear.php.net/package/Crypt_HMAC/
  423. $calculated_signature = base64_encode(hash_hmac("sha1", $url, $this->AuthToken, true));
  424. return $calculated_signature == $expected_signature;
  425. }
  426. }
  427. ?>