Response.php 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458
  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
  66. */
  67. protected static $_phrases = array(
  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. static::initMimeTypeMap();
  134. }
  135. /**
  136. * Response constructor.
  137. *
  138. * @param int $status
  139. * @param array $headers
  140. * @param string $body
  141. */
  142. public function __construct(
  143. $status = 200,
  144. $headers = array(),
  145. $body = ''
  146. ) {
  147. $this->_status = $status;
  148. $this->_header = $headers;
  149. $this->_body = (string)$body;
  150. }
  151. /**
  152. * Set header.
  153. *
  154. * @param string $name
  155. * @param string $value
  156. * @return $this
  157. */
  158. public function header($name, $value) {
  159. $this->_header[$name] = $value;
  160. return $this;
  161. }
  162. /**
  163. * Set header.
  164. *
  165. * @param string $name
  166. * @param string $value
  167. * @return Response
  168. */
  169. public function withHeader($name, $value) {
  170. return $this->header($name, $value);
  171. }
  172. /**
  173. * Set headers.
  174. *
  175. * @param array $headers
  176. * @return $this
  177. */
  178. public function withHeaders($headers) {
  179. $this->_header = \array_merge_recursive($this->_header, $headers);
  180. return $this;
  181. }
  182. /**
  183. * Remove header.
  184. *
  185. * @param string $name
  186. * @return $this
  187. */
  188. public function withoutHeader($name) {
  189. unset($this->_header[$name]);
  190. return $this;
  191. }
  192. /**
  193. * Get header.
  194. *
  195. * @param string $name
  196. * @return null|array|string
  197. */
  198. public function getHeader($name) {
  199. if (!isset($this->_header[$name])) {
  200. return null;
  201. }
  202. return $this->_header[$name];
  203. }
  204. /**
  205. * Get headers.
  206. *
  207. * @return array
  208. */
  209. public function getHeaders() {
  210. return $this->_header;
  211. }
  212. /**
  213. * Set status.
  214. *
  215. * @param int $code
  216. * @param string|null $reason_phrase
  217. * @return $this
  218. */
  219. public function withStatus($code, $reason_phrase = null) {
  220. $this->_status = $code;
  221. $this->_reason = $reason_phrase;
  222. return $this;
  223. }
  224. /**
  225. * Get status code.
  226. *
  227. * @return int
  228. */
  229. public function getStatusCode() {
  230. return $this->_status;
  231. }
  232. /**
  233. * Get reason phrase.
  234. *
  235. * @return string
  236. */
  237. public function getReasonPhrase() {
  238. return $this->_reason;
  239. }
  240. /**
  241. * Set protocol version.
  242. *
  243. * @param int $version
  244. * @return $this
  245. */
  246. public function withProtocolVersion($version) {
  247. $this->_version = $version;
  248. return $this;
  249. }
  250. /**
  251. * Set http body.
  252. *
  253. * @param string $body
  254. * @return $this
  255. */
  256. public function withBody($body) {
  257. $this->_body = $body;
  258. return $this;
  259. }
  260. /**
  261. * Get http raw body.
  262. *
  263. * @return string
  264. */
  265. public function rawBody() {
  266. return $this->_body;
  267. }
  268. /**
  269. * Send file.
  270. *
  271. * @param string $file
  272. * @param int $offset
  273. * @param int $length
  274. * @return $this
  275. */
  276. public function withFile($file, $offset = 0, $length = 0) {
  277. if (!\is_file($file)) {
  278. return $this->withStatus(404)->withBody('<h3>404 Not Found</h3>');
  279. }
  280. $this->file = array('file' => $file, 'offset' => $offset, 'length' => $length);
  281. return $this;
  282. }
  283. /**
  284. * Set cookie.
  285. *
  286. * @param $name
  287. * @param string $value
  288. * @param int $max_age
  289. * @param string $path
  290. * @param string $domain
  291. * @param bool $secure
  292. * @param bool $http_only
  293. * @param bool $same_site
  294. * @return $this
  295. */
  296. public function cookie($name, $value = '', $max_age = 0, $path = '', $domain = '', $secure = false, $http_only = false, $same_site = false)
  297. {
  298. $this->_header['Set-Cookie'][] = $name . '=' . \rawurlencode($value)
  299. . (empty($domain) ? '' : '; Domain=' . $domain)
  300. . (empty($max_age) ? '' : '; Max-Age=' . $max_age)
  301. . (empty($path) ? '' : '; Path=' . $path)
  302. . (!$secure ? '' : '; Secure')
  303. . (!$http_only ? '' : '; HttpOnly')
  304. . (empty($same_site ) ? '' : '; SameSite=' . $same_site);
  305. return $this;
  306. }
  307. /**
  308. * Create header for file.
  309. *
  310. * @param array $file_info
  311. * @return string
  312. */
  313. protected function createHeadForFile($file_info)
  314. {
  315. $file = $file_info['file'];
  316. $reason = $this->_reason ? $this->_reason : static::$_phrases[$this->_status];
  317. $head = "HTTP/{$this->_version} {$this->_status} $reason\r\n";
  318. $headers = $this->_header;
  319. if (!isset($headers['Server'])) {
  320. $head .= "Server: workerman\r\n";
  321. }
  322. foreach ($headers as $name => $value) {
  323. if (\is_array($value)) {
  324. foreach ($value as $item) {
  325. $head .= "$name: $item\r\n";
  326. }
  327. continue;
  328. }
  329. $head .= "$name: $value\r\n";
  330. }
  331. if (!isset($headers['Connection'])) {
  332. $head .= "Connection: keep-alive\r\n";
  333. }
  334. $file_info = \pathinfo($file);
  335. $extension = isset($file_info['extension']) ? $file_info['extension'] : '';
  336. $base_name = isset($file_info['basename']) ? $file_info['basename'] : 'unknown';
  337. if (!isset($headers['Content-Type'])) {
  338. if (isset(self::$_mimeTypeMap[$extension])) {
  339. $head .= "Content-Type: " . self::$_mimeTypeMap[$extension] . "\r\n";
  340. } else {
  341. $head .= "Content-Type: application/octet-stream\r\n";
  342. }
  343. }
  344. if (!isset($headers['Content-Disposition']) && !isset(self::$_mimeTypeMap[$extension])) {
  345. $head .= "Content-Disposition: attachment; filename=\"$base_name\"\r\n";
  346. }
  347. if (!isset($headers['Last-Modified'])) {
  348. if ($mtime = \filemtime($file)) {
  349. $head .= 'Last-Modified: '. \gmdate('D, d M Y H:i:s', $mtime) . ' GMT' . "\r\n";
  350. }
  351. }
  352. return "{$head}\r\n";
  353. }
  354. /**
  355. * __toString.
  356. *
  357. * @return string
  358. */
  359. public function __toString()
  360. {
  361. if (isset($this->file)) {
  362. return $this->createHeadForFile($this->file);
  363. }
  364. $reason = $this->_reason ? $this->_reason : static::$_phrases[$this->_status];
  365. $body_len = \strlen($this->_body);
  366. if (empty($this->_header)) {
  367. 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}";
  368. }
  369. $head = "HTTP/{$this->_version} {$this->_status} $reason\r\n";
  370. $headers = $this->_header;
  371. if (!isset($headers['Server'])) {
  372. $head .= "Server: workerman\r\n";
  373. }
  374. foreach ($headers as $name => $value) {
  375. if (\is_array($value)) {
  376. foreach ($value as $item) {
  377. $head .= "$name: $item\r\n";
  378. }
  379. continue;
  380. }
  381. $head .= "$name: $value\r\n";
  382. }
  383. if (!isset($headers['Connection'])) {
  384. $head .= "Connection: keep-alive\r\n";
  385. }
  386. if (!isset($headers['Content-Type'])) {
  387. $head .= "Content-Type: text/html;charset=utf-8\r\n";
  388. } else if ($headers['Content-Type'] === 'text/event-stream') {
  389. return $head . $this->_body;
  390. }
  391. if (!isset($headers['Transfer-Encoding'])) {
  392. $head .= "Content-Length: $body_len\r\n\r\n";
  393. } else {
  394. return "$head\r\n".dechex($body_len)."\r\n{$this->_body}\r\n";
  395. }
  396. // The whole http package
  397. return $head . $this->_body;
  398. }
  399. /**
  400. * Init mime map.
  401. *
  402. * @return void
  403. */
  404. public static function initMimeTypeMap()
  405. {
  406. $mime_file = __DIR__ . '/mime.types';
  407. $items = \file($mime_file, \FILE_IGNORE_NEW_LINES | \FILE_SKIP_EMPTY_LINES);
  408. foreach ($items as $content) {
  409. if (\preg_match("/\s*(\S+)\s+(\S.+)/", $content, $match)) {
  410. $mime_type = $match[1];
  411. $extension_var = $match[2];
  412. $extension_array = \explode(' ', \substr($extension_var, 0, -1));
  413. foreach ($extension_array as $file_extension) {
  414. static::$_mimeTypeMap[$file_extension] = $mime_type;
  415. }
  416. }
  417. }
  418. }
  419. }
  420. Response::init();