PageRenderTime 40ms CodeModel.GetById 13ms RepoModel.GetById 1ms app.codeStats 0ms

/OpenVBX/libraries/twilio.php

https://github.com/ibnoe/OpenVBX
PHP | 564 lines | 362 code | 95 blank | 107 comment | 31 complexity | a8f91549e53ecd68d190b68daa26961f 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.1
  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. public $ResponseText;
  41. public $ResponseXml;
  42. public $HttpStatus;
  43. public $Url;
  44. public $QueryString;
  45. public $IsError;
  46. public $ErrorMessage;
  47. public function __construct($url, $text, $status) {
  48. preg_match('/([^?]+)\??(.*)/', $url, $matches);
  49. $this->Url = $matches[1];
  50. $this->QueryString = $matches[2];
  51. $this->ResponseText = $text;
  52. $this->HttpStatus = $status;
  53. if($this->HttpStatus != 204)
  54. $this->ResponseXml = @simplexml_load_string($text);
  55. if($this->IsError = ($status >= 400))
  56. $this->ErrorMessage =
  57. (string)$this->ResponseXml->RestException->Message;
  58. }
  59. }
  60. /* TwilioRestClient throws TwilioException on error
  61. * Useful to catch this exception separately from general PHP
  62. * exceptions, if you want
  63. */
  64. class TwilioException extends Exception {}
  65. /*
  66. * TwilioRestBaseClient: the core Rest client, talks to the Twilio REST
  67. * API. Returns a TwilioRestResponse object for all responses if Twilio's
  68. * API was reachable Throws a TwilioException if Twilio's REST API was
  69. * unreachable
  70. */
  71. class TwilioRestClient {
  72. protected $Endpoint;
  73. protected $AccountSid;
  74. protected $AuthToken;
  75. /*
  76. * __construct
  77. * $username : Your AccountSid
  78. * $password : Your account's AuthToken
  79. * $endpoint : The Twilio REST Service URL, currently defaults to
  80. * the proper URL
  81. */
  82. public function __construct($accountSid, $authToken,
  83. $endpoint = "https://api.twilio.com/2010-04-01") {
  84. $this->AccountSid = $accountSid;
  85. $this->AuthToken = $authToken;
  86. $this->Endpoint = $endpoint;
  87. }
  88. /*
  89. * sendRequst
  90. * Sends a REST Request to the Twilio REST API
  91. * $path : the URL (relative to the endpoint URL, after the /v1)
  92. * $method : the HTTP method to use, defaults to GET
  93. * $vars : for POST or PUT, a key/value associative array of data to
  94. * send, for GET will be appended to the URL as query params
  95. */
  96. public function request($path, $method = "GET", $vars = array()) {
  97. $fp = null;
  98. $tmpfile = "";
  99. $encoded = "";
  100. foreach($vars AS $key=>$value)
  101. $encoded .= "$key=".urlencode($value)."&";
  102. $encoded = substr($encoded, 0, -1);
  103. // construct full url
  104. $url = "{$this->Endpoint}/$path";
  105. // if GET and vars, append them
  106. if($method == "GET")
  107. $url .= (FALSE === strpos($path, '?')?"?":"&").$encoded;
  108. // initialize a new curl object
  109. $curl = curl_init($url);
  110. curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
  111. curl_setopt($curl, CURLOPT_RETURNTRANSFER, TRUE);
  112. $ci = &get_instance();
  113. if(isset($ci->testing_mode)
  114. && $ci->testing_mode && isset($_REQUEST['Hiccup-Config']))
  115. {
  116. $headers = array("Hiccup-Config: {$_REQUEST['Hiccup-Config']}");
  117. // curl_setopt($curl, CURLOPT_HTTPHEADER, array("Hiccup-Config: ".$config));
  118. curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
  119. }
  120. switch(strtoupper($method)) {
  121. case "GET":
  122. curl_setopt($curl, CURLOPT_HTTPGET, TRUE);
  123. break;
  124. case "POST":
  125. curl_setopt($curl, CURLOPT_POST, TRUE);
  126. curl_setopt($curl, CURLOPT_POSTFIELDS, $encoded);
  127. break;
  128. case "PUT":
  129. // curl_setopt($curl, CURLOPT_PUT, TRUE);
  130. curl_setopt($curl, CURLOPT_POSTFIELDS, $encoded);
  131. curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "PUT");
  132. file_put_contents($tmpfile = tempnam("/tmp", "put_"),
  133. $encoded);
  134. curl_setopt($curl, CURLOPT_INFILE, $fp = fopen($tmpfile,
  135. 'r'));
  136. curl_setopt($curl, CURLOPT_INFILESIZE,
  137. filesize($tmpfile));
  138. break;
  139. case "DELETE":
  140. curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "DELETE");
  141. break;
  142. default:
  143. throw(new TwilioException("Unknown method $method"));
  144. break;
  145. }
  146. // send credentials
  147. curl_setopt($curl, CURLOPT_USERPWD,
  148. $pwd = "{$this->AccountSid}:{$this->AuthToken}");
  149. // do the request. If FALSE, then an exception occurred
  150. if(FALSE === ($result = curl_exec($curl)))
  151. throw(new TwilioException(
  152. "Curl failed with error " . curl_error($curl)));
  153. // get result code
  154. $responseCode = curl_getinfo($curl, CURLINFO_HTTP_CODE);
  155. // unlink tmpfiles
  156. if($method == 'PUT') {
  157. if($fp)
  158. fclose($fp);
  159. if(strlen($tmpfile))
  160. @unlink($tmpfile);
  161. if(is_file($tmpfile))
  162. error_log("Failed to delete cache: $tmpfile");
  163. }
  164. return new TwilioRestResponse($url, $result, $responseCode);
  165. }
  166. }
  167. // Twiml Response Helpers
  168. // ========================================================================
  169. /*
  170. * Verb: Base class for all TwiML verbs used in creating Responses
  171. * Throws a TwilioException if an non-supported attribute or
  172. * attribute value is added to the verb. All methods in Verb are protected
  173. * or private
  174. */
  175. class Verb {
  176. private $tag;
  177. private $body;
  178. private $attr;
  179. private $children;
  180. /*
  181. * __construct
  182. * $body : Verb contents
  183. * $body : Verb attributes
  184. */
  185. function __construct($body=NULL, $attr = array()) {
  186. if (is_array($body)) {
  187. $attr = $body;
  188. $body = NULL;
  189. }
  190. $this->tag = get_class($this);
  191. $this->body = self::encode($body);
  192. $this->attr = array();
  193. $this->children = array();
  194. self::addAttributes($attr);
  195. }
  196. private function encode($t)
  197. {
  198. return htmlspecialchars($t);
  199. }
  200. /*
  201. * addAttributes
  202. * $attr : A key/value array of attributes to be added
  203. * $valid : A key/value array containging the accepted attributes
  204. * for this verb
  205. * Throws an exception if an invlaid attribute is found
  206. */
  207. private function addAttributes($attr) {
  208. foreach ($attr as $key => $value) {
  209. if(in_array($key, $this->valid))
  210. $this->attr[$key] = self::encode($value);
  211. else
  212. throw new TwilioException($key . ', ' . $value .
  213. " is not a supported attribute pair");
  214. }
  215. }
  216. /*
  217. * append
  218. * Nests other verbs inside self.
  219. */
  220. function append($verb) {
  221. if(is_null($verb))
  222. return $verb;
  223. else if(is_null($this->nesting))
  224. throw new TwilioException($this->tag ." doesn't support nesting");
  225. else if(!is_object($verb))
  226. throw new TwilioException($verb->tag . " is not an object");
  227. else if(!in_array(get_class($verb), $this->nesting))
  228. throw new TwilioException($verb->tag . " is not an allowed verb here");
  229. else {
  230. $this->children[] = $verb;
  231. return $verb;
  232. }
  233. }
  234. /*
  235. * set
  236. * $attr : An attribute to be added
  237. * $valid : The attrbute value for this verb
  238. * No error checking here
  239. */
  240. function set($key, $value){
  241. $this->attr[$key] = self::encode($value);
  242. }
  243. /* Convenience Methods */
  244. function addSay($body=NULL, $attr = array()){
  245. return self::append(new Say($body, $attr));
  246. }
  247. function addPlay($body=NULL, $attr = array()){
  248. return self::append(new Play($body, $attr));
  249. }
  250. function addDial($body=NULL, $attr = array()){
  251. return self::append(new Dial($body, $attr));
  252. }
  253. function addNumber($body=NULL, $attr = array()){
  254. return self::append(new Number($body, $attr));
  255. }
  256. function addClient($body=NULL, $attr = array()){
  257. return self::append(new Client($body, $attr));
  258. }
  259. function addGather($attr = array()){
  260. return self::append(new Gather($attr));
  261. }
  262. function addRecord($attr = array()){
  263. return self::append(new Record(NULL, $attr));
  264. }
  265. function addHangup(){
  266. return self::append(new Hangup());
  267. }
  268. function addRedirect($body=NULL, $attr = array()){
  269. return self::append(new Redirect($body, $attr));
  270. }
  271. function addPause($attr = array()){
  272. return self::append(new Pause($attr));
  273. }
  274. function addConference($body=NULL, $attr = array()){
  275. return self::append(new Conference($body, $attr));
  276. }
  277. function addSms($body=NULL, $attr = array()){
  278. return self::append(new Sms($body, $attr));
  279. }
  280. /*
  281. * write
  282. * Output the XML for this verb and all it's children
  283. * $parent: This verb's parent verb
  284. * $writeself : If FALSE, Verb will not output itself,
  285. * only its children
  286. */
  287. protected function write($parent, $writeself=TRUE){
  288. if($writeself) {
  289. $elem = $parent->addChild($this->tag, $this->body);
  290. foreach($this->attr as $key => $value)
  291. $elem->addAttribute($key, $value);
  292. foreach($this->children as $child)
  293. $child->write($elem);
  294. } else {
  295. foreach($this->children as $child)
  296. $child->write($parent);
  297. }
  298. }
  299. }
  300. class Response extends Verb {
  301. private $xml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><Response></Response>";
  302. protected $nesting = array('Say', 'Play', 'Gather', 'Record',
  303. 'Dial', 'Redirect', 'Pause', 'Hangup', 'Sms');
  304. function __construct(){
  305. parent::__construct(NULL);
  306. }
  307. function Respond($sendHeader = true) {
  308. // if headers haven't already been sent we need to persist
  309. // the session before sending content
  310. if (!headers_sent()) {
  311. $ci = &get_instance();
  312. if(is_object($ci) && isset($ci->session) && is_object($ci->session)) {
  313. $ci->session->persist();
  314. }
  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. $simplexml = new SimpleXMLElement($this->xml);
  331. $this->write($simplexml, FALSE);
  332. if($encode)
  333. return urlencode($simplexml->asXML());
  334. else
  335. return $simplexml->asXML();
  336. }
  337. function setXml($xml) {
  338. $this->xml = $xml;
  339. }
  340. }
  341. class Say extends Verb {
  342. protected $valid = array('voice','language','loop');
  343. }
  344. class Play extends Verb {
  345. protected $valid = array('loop');
  346. }
  347. class Record extends Verb {
  348. protected $valid = array('action','method','timeout','finishOnKey',
  349. 'maxLength','transcribe','transcribeCallback');
  350. }
  351. class Dial extends Verb {
  352. protected $valid = array('action','method','timeout','hangupOnStar',
  353. 'timeLimit','callerId');
  354. protected $nesting = array('Number','Conference', 'Client');
  355. }
  356. class Redirect extends Verb {
  357. protected $valid = array('method');
  358. }
  359. class Pause extends Verb {
  360. protected $valid = array('length');
  361. function __construct($attr = array()) {
  362. parent::__construct(NULL, $attr);
  363. }
  364. }
  365. class Hangup extends Verb {
  366. function __construct() {
  367. parent::__construct(NULL, array());
  368. }
  369. }
  370. class Client extends Verb {
  371. function __construct($body) {
  372. parent::__construct($body, array());
  373. }
  374. }
  375. class Gather extends Verb {
  376. protected $valid = array('action','method','timeout','finishOnKey',
  377. 'numDigits');
  378. protected $nesting = array('Say', 'Play', 'Pause');
  379. function __construct($attr = array()){
  380. parent::__construct(NULL, $attr);
  381. }
  382. }
  383. class Number extends Verb {
  384. protected $valid = array('url','sendDigits');
  385. }
  386. class Conference extends Verb {
  387. protected $valid = array('muted','beep','startConferenceOnEnter',
  388. 'endConferenceOnExit','waitUrl','waitMethod');
  389. }
  390. class Sms extends Verb {
  391. protected $valid = array('to', 'from', 'action', 'method', 'statusCallback');
  392. }
  393. // Twilio Utility function and Request Validation
  394. // ========================================================================
  395. class TwilioUtils {
  396. protected $AccountSid;
  397. protected $AuthToken;
  398. public $CallSid;
  399. public $Caller;
  400. public $Called;
  401. public $CallStatus;
  402. public $DialStatus;
  403. public $Digits;
  404. public $Duration;
  405. public $RecordingDuration;
  406. public $CallDuration;
  407. public $DialCallStatus;
  408. public $DialCallDuration;
  409. public $RecordingUrl;
  410. public $TranscriptionText;
  411. public $SmsSid;
  412. public $To;
  413. public $SmsMessageSid;
  414. public $From;
  415. public $Body;
  416. public $DigitNumbers = FALSE;
  417. function __construct($id, $token) {
  418. $this->AuthToken = $token;
  419. $this->AccountSid = $id;
  420. foreach(array('CallSid', 'Caller', 'Called', 'CallStatus', 'DialStatus', 'Digits', 'Duration', 'RecordingUrl', 'TranscriptionText', 'SmsSid', 'To', 'SmsMessageSid', 'From', 'CallDuration', 'RecordingDuration', 'DialCallStatus', 'DialCallDuration') as $field)
  421. {
  422. $this->$field = (isset($_REQUEST[$field]) ? $_REQUEST[$field] : FALSE);
  423. }
  424. if($this->Digits) {
  425. $trimmed = str_replace(array('#', '*'), '', $this->Digits);
  426. if(strlen($trimmed) > 0) $this->DigitNumbers = $trimmed;
  427. }
  428. }
  429. public function validateRequest($expected_signature, $url, $data = array()) {
  430. // sort the array by keys
  431. ksort($data);
  432. // append them to the data string in order
  433. // with no delimiters
  434. foreach($data AS $key=>$value)
  435. $url .= "$key$value";
  436. // This function calculates the HMAC hash of the data with the key
  437. // passed in
  438. // Note: hash_hmac requires PHP 5 >= 5.1.2 or PECL hash:1.1-1.5
  439. // Or http://pear.php.net/package/Crypt_HMAC/
  440. $calculated_signature = base64_encode(hash_hmac("sha1",$url, $this->AuthToken, true));
  441. return $calculated_signature == $expected_signature;
  442. }
  443. }
  444. ?>