Response.php 10.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375
  1. <?php
  2. /**
  3. * This file is part of workerman.
  4. *
  5. * Licensed under The MIT License
  6. * For full copyright and license information, please see the MIT-LICENSE.txt
  7. * Redistributions of files must retain the above copyright notice.
  8. *
  9. * @author walkor<walkor@workerman.net>
  10. * @copyright walkor<walkor@workerman.net>
  11. * @link http://www.workerman.net/
  12. * @license http://www.opensource.org/licenses/mit-license.php MIT License
  13. */
  14. namespace Workerman\Protocols\Http;
  15. /**
  16. * Class Response
  17. * @package Workerman\Protocols\Http
  18. */
  19. class Response
  20. {
  21. /**
  22. * Header data.
  23. *
  24. * @var array
  25. */
  26. protected $_header = null;
  27. /**
  28. * Http status.
  29. *
  30. * @var int
  31. */
  32. protected $_status = null;
  33. /**
  34. * Http reason.
  35. *
  36. * @var string
  37. */
  38. protected $_reason = null;
  39. /**
  40. * Http version.
  41. *
  42. * @var string
  43. */
  44. protected $_version = '1.1';
  45. /**
  46. * Http body.
  47. *
  48. * @var string
  49. */
  50. protected $_body = null;
  51. /**
  52. * Mine type map.
  53. * @var array
  54. */
  55. protected static $_mimeTypeMap = null;
  56. /**
  57. * Phrases.
  58. *
  59. * @var array
  60. */
  61. protected static $_phrases = array(
  62. 100 => 'Continue',
  63. 101 => 'Switching Protocols',
  64. 102 => 'Processing',
  65. 200 => 'OK',
  66. 201 => 'Created',
  67. 202 => 'Accepted',
  68. 203 => 'Non-Authoritative Information',
  69. 204 => 'No Content',
  70. 205 => 'Reset Content',
  71. 206 => 'Partial Content',
  72. 207 => 'Multi-status',
  73. 208 => 'Already Reported',
  74. 300 => 'Multiple Choices',
  75. 301 => 'Moved Permanently',
  76. 302 => 'Found',
  77. 303 => 'See Other',
  78. 304 => 'Not Modified',
  79. 305 => 'Use Proxy',
  80. 306 => 'Switch Proxy',
  81. 307 => 'Temporary Redirect',
  82. 400 => 'Bad Request',
  83. 401 => 'Unauthorized',
  84. 402 => 'Payment Required',
  85. 403 => 'Forbidden',
  86. 404 => 'Not Found',
  87. 405 => 'Method Not Allowed',
  88. 406 => 'Not Acceptable',
  89. 407 => 'Proxy Authentication Required',
  90. 408 => 'Request Time-out',
  91. 409 => 'Conflict',
  92. 410 => 'Gone',
  93. 411 => 'Length Required',
  94. 412 => 'Precondition Failed',
  95. 413 => 'Request Entity Too Large',
  96. 414 => 'Request-URI Too Large',
  97. 415 => 'Unsupported Media Type',
  98. 416 => 'Requested range not satisfiable',
  99. 417 => 'Expectation Failed',
  100. 418 => 'I\'m a teapot',
  101. 422 => 'Unprocessable Entity',
  102. 423 => 'Locked',
  103. 424 => 'Failed Dependency',
  104. 425 => 'Unordered Collection',
  105. 426 => 'Upgrade Required',
  106. 428 => 'Precondition Required',
  107. 429 => 'Too Many Requests',
  108. 431 => 'Request Header Fields Too Large',
  109. 451 => 'Unavailable For Legal Reasons',
  110. 500 => 'Internal Server Error',
  111. 501 => 'Not Implemented',
  112. 502 => 'Bad Gateway',
  113. 503 => 'Service Unavailable',
  114. 504 => 'Gateway Time-out',
  115. 505 => 'HTTP Version not supported',
  116. 506 => 'Variant Also Negotiates',
  117. 507 => 'Insufficient Storage',
  118. 508 => 'Loop Detected',
  119. 511 => 'Network Authentication Required',
  120. );
  121. /**
  122. * Init.
  123. *
  124. * @return void
  125. */
  126. public static function init() {
  127. static::initMimeTypeMap();
  128. }
  129. /**
  130. * Response constructor.
  131. *
  132. * @param int $status
  133. * @param array $headers
  134. * @param string $body
  135. */
  136. public function __construct(
  137. $status = 200,
  138. array $headers = array(),
  139. $body = ''
  140. ) {
  141. $this->_status = $status;
  142. $this->_header = $headers;
  143. $this->_body = $body;
  144. }
  145. /**
  146. * Set header.
  147. *
  148. * @param $name
  149. * @param $value
  150. * @return $this
  151. */
  152. public function header($name, $value) {
  153. $this->_header[$name] = $value;
  154. return $this;
  155. }
  156. /**
  157. * Set headers.
  158. *
  159. * @param $headers
  160. * @return $this
  161. */
  162. public function withHeaders($headers) {
  163. $this->_header = \array_merge($this->_header, $headers);
  164. return $this;
  165. }
  166. /**
  167. * Set status.
  168. *
  169. * @param $code
  170. * @param null $reason_phrase
  171. * @return $this
  172. */
  173. public function withStatus($code, $reason_phrase = null) {
  174. $this->_status = $code;
  175. $this->_reason = $reason_phrase;
  176. return $this;
  177. }
  178. /**
  179. * Set protocol version.
  180. *
  181. * @param $version
  182. * @return $this
  183. */
  184. public function withProtocolVersion($version) {
  185. $this->_version = $version;
  186. return $this;
  187. }
  188. /**
  189. * Set http body.
  190. *
  191. * @param $body
  192. * @return $this
  193. */
  194. public function withBody($body) {
  195. $this->_body = $body;
  196. return $this;
  197. }
  198. /**
  199. * Set file.
  200. *
  201. * @param $file
  202. * @return $this
  203. */
  204. public function withFile($file) {
  205. if (!\is_file($file)) {
  206. return $this->withStatus(404)->withBody('<h3>404 Not Found</h3>');
  207. }
  208. $this->file = $file;
  209. return $this;
  210. }
  211. /**
  212. * Set cookie.
  213. *
  214. * @param $name
  215. * @param string $value
  216. * @param int $maxage
  217. * @param string $path
  218. * @param string $domain
  219. * @param bool $secure
  220. * @param bool $http_only
  221. * @return $this
  222. */
  223. public function cookie($name, $value = '', $max_age = 0, $path = '', $domain = '', $secure = false, $http_only = false)
  224. {
  225. $this->_header['Set-Cookie'][] = $name . '=' . \rawurlencode($value)
  226. . (empty($domain) ? '' : '; Domain=' . $domain)
  227. . (empty($max_age) ? '' : '; Max-Age=' . $max_age)
  228. . (empty($path) ? '' : '; Path=' . $path)
  229. . (!$secure ? '' : '; Secure')
  230. . (!$http_only ? '' : '; HttpOnly');
  231. return $this;
  232. }
  233. /**
  234. * Create header for file.
  235. *
  236. * @param $file
  237. * @return string
  238. */
  239. protected function createHeadForFile($file)
  240. {
  241. $reason = $this->_reason ? $this->_reason : static::$_phrases[$this->_status];
  242. $head = "HTTP/{$this->_version} {$this->_status} $reason\r\n";
  243. $headers = $this->_header;
  244. if (!isset($headers['Server'])) {
  245. $head .= "Server: workerman\r\n";
  246. }
  247. foreach ($headers as $name => $value) {
  248. if (\is_array($value)) {
  249. foreach ($value as $item) {
  250. $head .= "$name: $item\r\n";
  251. }
  252. continue;
  253. }
  254. $head .= "$name: $value\r\n";
  255. }
  256. if (!isset($headers['Connection'])) {
  257. $head .= "Connection: keep-alive\r\n";
  258. }
  259. $file_info = \pathinfo($file);
  260. $extension = isset($file_info['extension']) ? $file_info['extension'] : '';
  261. $base_name = isset($file_info['basename']) ? $file_info['basename'] : 'unknown';
  262. if (!isset($headers['Content-Type'])) {
  263. if (isset(self::$_mimeTypeMap[$extension])) {
  264. $head .= "Content-Type: " . self::$_mimeTypeMap[$extension] . "\r\n";
  265. } else {
  266. $head .= "Content-Type: application/octet-stream\r\n";
  267. }
  268. }
  269. if (!isset($headers['Content-Disposition']) && !isset(self::$_mimeTypeMap[$extension])) {
  270. $head .= "Content-Disposition: attachment; filename=\"$base_name\"\r\n";
  271. }
  272. if (!isset($headers['Last-Modified'])) {
  273. if ($mtime = \filemtime($file)) {
  274. $head .= 'Last-Modified: '.\date('D, d M Y H:i:s', $mtime) . ' ' . \date_default_timezone_get() ."\r\n";
  275. }
  276. }
  277. return "{$head}\r\n";
  278. }
  279. /**
  280. * __toString.
  281. *
  282. * @return string
  283. */
  284. public function __toString()
  285. {
  286. if (isset($this->file)) {
  287. return $this->createHeadForFile($this->file);
  288. }
  289. $reason = $this->_reason ? $this->_reason : static::$_phrases[$this->_status];
  290. $body_len = \strlen($this->_body);
  291. if (empty($this->_header)) {
  292. return "HTTP/{$this->_version} {$this->_status} $reason\r\nServer: workerman\r\nContent-Type: text/html;charset=utf-8\r\nContent-Length: $body_len\r\nConnection: keep-alive\r\n\r\n{$this->_body}";
  293. }
  294. $head = "HTTP/{$this->_version} {$this->_status} $reason\r\n";
  295. $headers = $this->_header;
  296. if (!isset($headers['Server'])) {
  297. $head .= "Server: workerman\r\n";
  298. }
  299. foreach ($headers as $name => $value) {
  300. if (\is_array($value)) {
  301. foreach ($value as $item) {
  302. $head .= "$name: $item\r\n";
  303. }
  304. continue;
  305. }
  306. $head .= "$name: $value\r\n";
  307. }
  308. if (!isset($headers['Connection'])) {
  309. $head .= "Connection: keep-alive\r\n";
  310. }
  311. if (!isset($headers['Content-Type'])) {
  312. $head .= "Content-Type: text/html;charset=utf-8\r\n";
  313. } else if ($headers['Content-Type'] === 'text/event-stream') {
  314. return $head . $this->_body;
  315. }
  316. if (!isset($headers['Transfer-Encoding'])) {
  317. $head .= "Content-Length: $body_len\r\n\r\n";
  318. } else {
  319. return "$head\r\n".dechex($body_len)."\r\n{$this->_body}\r\n";
  320. }
  321. // The whole http package
  322. return $head . $this->_body;
  323. }
  324. /**
  325. * Init mime map.
  326. *
  327. * @return void
  328. */
  329. public static function initMimeTypeMap()
  330. {
  331. $mime_file = __DIR__ . '/mime.types';
  332. $items = \file($mime_file, \FILE_IGNORE_NEW_LINES | \FILE_SKIP_EMPTY_LINES);
  333. foreach ($items as $content) {
  334. if (\preg_match("/\s*(\S+)\s+(\S.+)/", $content, $match)) {
  335. $mime_type = $match[1];
  336. $extension_var = $match[2];
  337. $extension_array = \explode(' ', \substr($extension_var, 0, -1));
  338. foreach ($extension_array as $file_extension) {
  339. static::$_mimeTypeMap[$file_extension] = $mime_type;
  340. }
  341. }
  342. }
  343. }
  344. }
  345. Response::init();