Response.php 12 KB

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