HttpStream.php 2.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. <?php
  2. /**
  3. * HTTP Stream version of the TinyHttp Client used to connect to Twilio
  4. * services.
  5. */
  6. class Services_Twilio_HttpStreamException extends ErrorException {}
  7. class Services_Twilio_HttpStream {
  8. private $auth_header = null;
  9. private $uri = null;
  10. private $debug = false;
  11. private static $default_options = array(
  12. "http" => array(
  13. "headers" => "",
  14. "timeout" => 60,
  15. "follow_location" => true,
  16. "ignore_errors" => true,
  17. ),
  18. "ssl" => array(),
  19. );
  20. private $options = array();
  21. public function __construct($uri = '', $kwargs = array()) {
  22. $this->uri = $uri;
  23. if (isset($kwargs['debug'])) {
  24. $this->debug = true;
  25. }
  26. if (isset($kwargs['http_options'])) {
  27. $this->options = $kwargs['http_options'] + self::$default_options;
  28. } else {
  29. $this->options = self::$default_options;
  30. }
  31. }
  32. public function __call($name, $args) {
  33. list($res, $req_headers, $req_body) = $args + array(0, array(), '');
  34. $request_options = $this->options;
  35. $url = $this->uri . $res;
  36. if (isset($req_body) && strlen($req_body) > 0) {
  37. $request_options['http']['content'] = $req_body;
  38. }
  39. foreach($req_headers as $key => $value) {
  40. $request_options['http']['header'] .= sprintf("%s: %s\r\n", $key, $value);
  41. }
  42. if (isset($this->auth_header)) {
  43. $request_options['http']['header'] .= $this->auth_header;
  44. }
  45. $request_options['http']['method'] = strtoupper($name);
  46. $request_options['http']['ignore_errors'] = true;
  47. if ($this->debug) {
  48. error_log(var_export($request_options, true));
  49. }
  50. $ctx = stream_context_create($request_options);
  51. $result = file_get_contents($url, false, $ctx);
  52. if (false === $result) {
  53. throw new Services_Twilio_HttpStreamException(
  54. "Unable to connect to service");
  55. }
  56. $status_header = array_shift($http_response_header);
  57. if (1 !== preg_match('#HTTP/\d+\.\d+ (\d+)#', $status_header, $matches)) {
  58. throw new Services_Twilio_HttpStreamException(
  59. "Unable to detect the status code in the HTTP result.");
  60. }
  61. $status_code = intval($matches[1]);
  62. $response_headers = array();
  63. foreach($http_response_header as $header) {
  64. list($key, $val) = explode(":", $header);
  65. $response_headers[trim($key)] = trim($val);
  66. }
  67. return array($status_code, $response_headers, $result);
  68. }
  69. public function authenticate($user, $pass) {
  70. if (isset($user) && isset($pass)) {
  71. $this->auth_header = sprintf("Authorization: Basic %s",
  72. base64_encode(sprintf("%s:%s", $user, $pass)));
  73. } else {
  74. $this->auth_header = null;
  75. }
  76. }
  77. }