Response.php 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378
  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. $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. * Send file.
  200. *
  201. * @param $file
  202. * @param int $offset
  203. * @param int $length
  204. * @return $this
  205. */
  206. public function withFile($file, $offset = 0, $length = 0) {
  207. if (!\is_file($file)) {
  208. return $this->withStatus(404)->withBody('<h3>404 Not Found</h3>');
  209. }
  210. $this->file = array('file' => $file, 'offset' => $offset, 'length' => $length);
  211. return $this;
  212. }
  213. /**
  214. * Set cookie.
  215. *
  216. * @param $name
  217. * @param string $value
  218. * @param int $maxage
  219. * @param string $path
  220. * @param string $domain
  221. * @param bool $secure
  222. * @param bool $http_only
  223. * @return $this
  224. */
  225. public function cookie($name, $value = '', $max_age = 0, $path = '', $domain = '', $secure = false, $http_only = false)
  226. {
  227. $this->_header['Set-Cookie'][] = $name . '=' . \rawurlencode($value)
  228. . (empty($domain) ? '' : '; Domain=' . $domain)
  229. . (empty($max_age) ? '' : '; Max-Age=' . $max_age)
  230. . (empty($path) ? '' : '; Path=' . $path)
  231. . (!$secure ? '' : '; Secure')
  232. . (!$http_only ? '' : '; HttpOnly');
  233. return $this;
  234. }
  235. /**
  236. * Create header for file.
  237. *
  238. * @param $file
  239. * @return string
  240. */
  241. protected function createHeadForFile($file_info)
  242. {
  243. $file = $file_info['file'];
  244. $reason = $this->_reason ? $this->_reason : static::$_phrases[$this->_status];
  245. $head = "HTTP/{$this->_version} {$this->_status} $reason\r\n";
  246. $headers = $this->_header;
  247. if (!isset($headers['Server'])) {
  248. $head .= "Server: workerman\r\n";
  249. }
  250. foreach ($headers as $name => $value) {
  251. if (\is_array($value)) {
  252. foreach ($value as $item) {
  253. $head .= "$name: $item\r\n";
  254. }
  255. continue;
  256. }
  257. $head .= "$name: $value\r\n";
  258. }
  259. if (!isset($headers['Connection'])) {
  260. $head .= "Connection: keep-alive\r\n";
  261. }
  262. $file_info = \pathinfo($file);
  263. $extension = isset($file_info['extension']) ? $file_info['extension'] : '';
  264. $base_name = isset($file_info['basename']) ? $file_info['basename'] : 'unknown';
  265. if (!isset($headers['Content-Type'])) {
  266. if (isset(self::$_mimeTypeMap[$extension])) {
  267. $head .= "Content-Type: " . self::$_mimeTypeMap[$extension] . "\r\n";
  268. } else {
  269. $head .= "Content-Type: application/octet-stream\r\n";
  270. }
  271. }
  272. if (!isset($headers['Content-Disposition']) && !isset(self::$_mimeTypeMap[$extension])) {
  273. $head .= "Content-Disposition: attachment; filename=\"$base_name\"\r\n";
  274. }
  275. if (!isset($headers['Last-Modified'])) {
  276. if ($mtime = \filemtime($file)) {
  277. $head .= 'Last-Modified: '.\date('D, d M Y H:i:s', $mtime) . ' ' . \date_default_timezone_get() ."\r\n";
  278. }
  279. }
  280. return "{$head}\r\n";
  281. }
  282. /**
  283. * __toString.
  284. *
  285. * @return string
  286. */
  287. public function __toString()
  288. {
  289. if (isset($this->file)) {
  290. return $this->createHeadForFile($this->file);
  291. }
  292. $reason = $this->_reason ? $this->_reason : static::$_phrases[$this->_status];
  293. $body_len = \strlen($this->_body);
  294. if (empty($this->_header)) {
  295. 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}";
  296. }
  297. $head = "HTTP/{$this->_version} {$this->_status} $reason\r\n";
  298. $headers = $this->_header;
  299. if (!isset($headers['Server'])) {
  300. $head .= "Server: workerman\r\n";
  301. }
  302. foreach ($headers as $name => $value) {
  303. if (\is_array($value)) {
  304. foreach ($value as $item) {
  305. $head .= "$name: $item\r\n";
  306. }
  307. continue;
  308. }
  309. $head .= "$name: $value\r\n";
  310. }
  311. if (!isset($headers['Connection'])) {
  312. $head .= "Connection: keep-alive\r\n";
  313. }
  314. if (!isset($headers['Content-Type'])) {
  315. $head .= "Content-Type: text/html;charset=utf-8\r\n";
  316. } else if ($headers['Content-Type'] === 'text/event-stream') {
  317. return $head . $this->_body;
  318. }
  319. if (!isset($headers['Transfer-Encoding'])) {
  320. $head .= "Content-Length: $body_len\r\n\r\n";
  321. } else {
  322. return "$head\r\n".dechex($body_len)."\r\n{$this->_body}\r\n";
  323. }
  324. // The whole http package
  325. return $head . $this->_body;
  326. }
  327. /**
  328. * Init mime map.
  329. *
  330. * @return void
  331. */
  332. public static function initMimeTypeMap()
  333. {
  334. $mime_file = __DIR__ . '/mime.types';
  335. $items = \file($mime_file, \FILE_IGNORE_NEW_LINES | \FILE_SKIP_EMPTY_LINES);
  336. foreach ($items as $content) {
  337. if (\preg_match("/\s*(\S+)\s+(\S.+)/", $content, $match)) {
  338. $mime_type = $match[1];
  339. $extension_var = $match[2];
  340. $extension_array = \explode(' ', \substr($extension_var, 0, -1));
  341. foreach ($extension_array as $file_extension) {
  342. static::$_mimeTypeMap[$file_extension] = $mime_type;
  343. }
  344. }
  345. }
  346. }
  347. }
  348. Response::init();