Response.php 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475
  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. * Send file info
  53. *
  54. * @var array
  55. */
  56. public $file = null;
  57. /**
  58. * Mine type map.
  59. * @var array
  60. */
  61. protected static $_mimeTypeMap = null;
  62. /**
  63. * Phrases.
  64. *
  65. * @var array<int,string>
  66. */
  67. const PHRASES = [
  68. 100 => 'Continue',
  69. 101 => 'Switching Protocols',
  70. 102 => 'Processing',
  71. 200 => 'OK',
  72. 201 => 'Created',
  73. 202 => 'Accepted',
  74. 203 => 'Non-Authoritative Information',
  75. 204 => 'No Content',
  76. 205 => 'Reset Content',
  77. 206 => 'Partial Content',
  78. 207 => 'Multi-status',
  79. 208 => 'Already Reported',
  80. 300 => 'Multiple Choices',
  81. 301 => 'Moved Permanently',
  82. 302 => 'Found',
  83. 303 => 'See Other',
  84. 304 => 'Not Modified',
  85. 305 => 'Use Proxy',
  86. 306 => 'Switch Proxy',
  87. 307 => 'Temporary Redirect',
  88. 400 => 'Bad Request',
  89. 401 => 'Unauthorized',
  90. 402 => 'Payment Required',
  91. 403 => 'Forbidden',
  92. 404 => 'Not Found',
  93. 405 => 'Method Not Allowed',
  94. 406 => 'Not Acceptable',
  95. 407 => 'Proxy Authentication Required',
  96. 408 => 'Request Time-out',
  97. 409 => 'Conflict',
  98. 410 => 'Gone',
  99. 411 => 'Length Required',
  100. 412 => 'Precondition Failed',
  101. 413 => 'Request Entity Too Large',
  102. 414 => 'Request-URI Too Large',
  103. 415 => 'Unsupported Media Type',
  104. 416 => 'Requested range not satisfiable',
  105. 417 => 'Expectation Failed',
  106. 418 => 'I\'m a teapot',
  107. 422 => 'Unprocessable Entity',
  108. 423 => 'Locked',
  109. 424 => 'Failed Dependency',
  110. 425 => 'Unordered Collection',
  111. 426 => 'Upgrade Required',
  112. 428 => 'Precondition Required',
  113. 429 => 'Too Many Requests',
  114. 431 => 'Request Header Fields Too Large',
  115. 451 => 'Unavailable For Legal Reasons',
  116. 500 => 'Internal Server Error',
  117. 501 => 'Not Implemented',
  118. 502 => 'Bad Gateway',
  119. 503 => 'Service Unavailable',
  120. 504 => 'Gateway Time-out',
  121. 505 => 'HTTP Version not supported',
  122. 506 => 'Variant Also Negotiates',
  123. 507 => 'Insufficient Storage',
  124. 508 => 'Loop Detected',
  125. 511 => 'Network Authentication Required',
  126. ];
  127. /**
  128. * Init.
  129. *
  130. * @return void
  131. */
  132. public static function init()
  133. {
  134. static::initMimeTypeMap();
  135. }
  136. /**
  137. * Response constructor.
  138. *
  139. * @param int $status
  140. * @param array $headers
  141. * @param string $body
  142. */
  143. public function __construct(
  144. $status = 200,
  145. $headers = [],
  146. $body = ''
  147. )
  148. {
  149. $this->_status = $status;
  150. $this->_header = $headers;
  151. $this->_body = (string)$body;
  152. }
  153. /**
  154. * Set header.
  155. *
  156. * @param string $name
  157. * @param string $value
  158. * @return $this
  159. */
  160. public function header($name, $value)
  161. {
  162. $this->_header[$name] = $value;
  163. return $this;
  164. }
  165. /**
  166. * Set header.
  167. *
  168. * @param string $name
  169. * @param string $value
  170. * @return Response
  171. */
  172. public function withHeader($name, $value)
  173. {
  174. return $this->header($name, $value);
  175. }
  176. /**
  177. * Set headers.
  178. *
  179. * @param array $headers
  180. * @return $this
  181. */
  182. public function withHeaders($headers)
  183. {
  184. $this->_header = \array_merge_recursive($this->_header, $headers);
  185. return $this;
  186. }
  187. /**
  188. * Remove header.
  189. *
  190. * @param string $name
  191. * @return $this
  192. */
  193. public function withoutHeader($name)
  194. {
  195. unset($this->_header[$name]);
  196. return $this;
  197. }
  198. /**
  199. * Get header.
  200. *
  201. * @param string $name
  202. * @return null|array|string
  203. */
  204. public function getHeader($name)
  205. {
  206. if (!isset($this->_header[$name])) {
  207. return null;
  208. }
  209. return $this->_header[$name];
  210. }
  211. /**
  212. * Get headers.
  213. *
  214. * @return array
  215. */
  216. public function getHeaders()
  217. {
  218. return $this->_header;
  219. }
  220. /**
  221. * Set status.
  222. *
  223. * @param int $code
  224. * @param string|null $reason_phrase
  225. * @return $this
  226. */
  227. public function withStatus($code, $reason_phrase = null)
  228. {
  229. $this->_status = $code;
  230. $this->_reason = $reason_phrase;
  231. return $this;
  232. }
  233. /**
  234. * Get status code.
  235. *
  236. * @return int
  237. */
  238. public function getStatusCode()
  239. {
  240. return $this->_status;
  241. }
  242. /**
  243. * Get reason phrase.
  244. *
  245. * @return string
  246. */
  247. public function getReasonPhrase()
  248. {
  249. return $this->_reason;
  250. }
  251. /**
  252. * Set protocol version.
  253. *
  254. * @param int $version
  255. * @return $this
  256. */
  257. public function withProtocolVersion($version)
  258. {
  259. $this->_version = $version;
  260. return $this;
  261. }
  262. /**
  263. * Set http body.
  264. *
  265. * @param string $body
  266. * @return $this
  267. */
  268. public function withBody($body)
  269. {
  270. $this->_body = (string)$body;
  271. return $this;
  272. }
  273. /**
  274. * Get http raw body.
  275. *
  276. * @return string
  277. */
  278. public function rawBody()
  279. {
  280. return $this->_body;
  281. }
  282. /**
  283. * Send file.
  284. *
  285. * @param string $file
  286. * @param int $offset
  287. * @param int $length
  288. * @return $this
  289. */
  290. public function withFile($file, $offset = 0, $length = 0)
  291. {
  292. if (!\is_file($file)) {
  293. return $this->withStatus(404)->withBody('<h3>404 Not Found</h3>');
  294. }
  295. $this->file = ['file' => $file, 'offset' => $offset, 'length' => $length];
  296. return $this;
  297. }
  298. /**
  299. * Set cookie.
  300. *
  301. * @param $name
  302. * @param string $value
  303. * @param int $max_age
  304. * @param string $path
  305. * @param string $domain
  306. * @param bool $secure
  307. * @param bool $http_only
  308. * @param bool $same_site
  309. * @return $this
  310. */
  311. public function cookie($name, $value = '', $max_age = null, $path = '', $domain = '', $secure = false, $http_only = false, $same_site = false)
  312. {
  313. $this->_header['Set-Cookie'][] = $name . '=' . \rawurlencode($value)
  314. . (empty($domain) ? '' : '; Domain=' . $domain)
  315. . ($max_age === null ? '' : '; Max-Age=' . $max_age)
  316. . (empty($path) ? '' : '; Path=' . $path)
  317. . (!$secure ? '' : '; Secure')
  318. . (!$http_only ? '' : '; HttpOnly')
  319. . (empty($same_site) ? '' : '; SameSite=' . $same_site);
  320. return $this;
  321. }
  322. /**
  323. * Create header for file.
  324. *
  325. * @param array $file_info
  326. * @return string
  327. */
  328. protected function createHeadForFile($file_info)
  329. {
  330. $file = $file_info['file'];
  331. $reason = $this->_reason ?: self::PHRASES[$this->_status];
  332. $head = "HTTP/{$this->_version} {$this->_status} $reason\r\n";
  333. $headers = $this->_header;
  334. if (!isset($headers['Server'])) {
  335. $head .= "Server: workerman\r\n";
  336. }
  337. foreach ($headers as $name => $value) {
  338. if (\is_array($value)) {
  339. foreach ($value as $item) {
  340. $head .= "$name: $item\r\n";
  341. }
  342. continue;
  343. }
  344. $head .= "$name: $value\r\n";
  345. }
  346. if (!isset($headers['Connection'])) {
  347. $head .= "Connection: keep-alive\r\n";
  348. }
  349. $file_info = \pathinfo($file);
  350. $extension = isset($file_info['extension']) ? $file_info['extension'] : '';
  351. $base_name = isset($file_info['basename']) ? $file_info['basename'] : 'unknown';
  352. if (!isset($headers['Content-Type'])) {
  353. if (isset(self::$_mimeTypeMap[$extension])) {
  354. $head .= "Content-Type: " . self::$_mimeTypeMap[$extension] . "\r\n";
  355. } else {
  356. $head .= "Content-Type: application/octet-stream\r\n";
  357. }
  358. }
  359. if (!isset($headers['Content-Disposition']) && !isset(self::$_mimeTypeMap[$extension])) {
  360. $head .= "Content-Disposition: attachment; filename=\"$base_name\"\r\n";
  361. }
  362. if (!isset($headers['Last-Modified'])) {
  363. if ($mtime = \filemtime($file)) {
  364. $head .= 'Last-Modified: ' . \gmdate('D, d M Y H:i:s', $mtime) . ' GMT' . "\r\n";
  365. }
  366. }
  367. return "{$head}\r\n";
  368. }
  369. /**
  370. * __toString.
  371. *
  372. * @return string
  373. */
  374. public function __toString()
  375. {
  376. if (isset($this->file)) {
  377. return $this->createHeadForFile($this->file);
  378. }
  379. $reason = $this->_reason ?: self::PHRASES[$this->_status] ?? '';
  380. $body_len = \strlen($this->_body);
  381. if (empty($this->_header)) {
  382. 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}";
  383. }
  384. $head = "HTTP/{$this->_version} {$this->_status} $reason\r\n";
  385. $headers = $this->_header;
  386. if (!isset($headers['Server'])) {
  387. $head .= "Server: workerman\r\n";
  388. }
  389. foreach ($headers as $name => $value) {
  390. if (\is_array($value)) {
  391. foreach ($value as $item) {
  392. $head .= "$name: $item\r\n";
  393. }
  394. continue;
  395. }
  396. $head .= "$name: $value\r\n";
  397. }
  398. if (!isset($headers['Connection'])) {
  399. $head .= "Connection: keep-alive\r\n";
  400. }
  401. if (!isset($headers['Content-Type'])) {
  402. $head .= "Content-Type: text/html;charset=utf-8\r\n";
  403. } else if ($headers['Content-Type'] === 'text/event-stream') {
  404. return $head . $this->_body;
  405. }
  406. if (!isset($headers['Transfer-Encoding'])) {
  407. $head .= "Content-Length: $body_len\r\n\r\n";
  408. } else {
  409. return "$head\r\n" . dechex($body_len) . "\r\n{$this->_body}\r\n";
  410. }
  411. // The whole http package
  412. return $head . $this->_body;
  413. }
  414. /**
  415. * Init mime map.
  416. *
  417. * @return void
  418. */
  419. public static function initMimeTypeMap()
  420. {
  421. $mime_file = __DIR__ . '/mime.types';
  422. $items = \file($mime_file, \FILE_IGNORE_NEW_LINES | \FILE_SKIP_EMPTY_LINES);
  423. foreach ($items as $content) {
  424. if (\preg_match("/\s*(\S+)\s+(\S.+)/", $content, $match)) {
  425. $mime_type = $match[1];
  426. $extension_var = $match[2];
  427. $extension_array = \explode(' ', \substr($extension_var, 0, -1));
  428. foreach ($extension_array as $file_extension) {
  429. static::$_mimeTypeMap[$file_extension] = $mime_type;
  430. }
  431. }
  432. }
  433. }
  434. }
  435. Response::init();