Response.php 13 KB

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