Response.php 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456
  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. protected $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 = $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($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 string $name
  287. * @param string $value
  288. * @param int $maxage
  289. * @param string $path
  290. * @param string $domain
  291. * @param bool $secure
  292. * @param bool $http_only
  293. * @return $this
  294. */
  295. public function cookie($name, $value = '', $max_age = 0, $path = '', $domain = '', $secure = false, $http_only = false)
  296. {
  297. $this->_header['Set-Cookie'][] = $name . '=' . \rawurlencode($value)
  298. . (empty($domain) ? '' : '; Domain=' . $domain)
  299. . (empty($max_age) ? '' : '; Max-Age=' . $max_age)
  300. . (empty($path) ? '' : '; Path=' . $path)
  301. . (!$secure ? '' : '; Secure')
  302. . (!$http_only ? '' : '; HttpOnly');
  303. return $this;
  304. }
  305. /**
  306. * Create header for file.
  307. *
  308. * @param array $file_info
  309. * @return string
  310. */
  311. protected function createHeadForFile($file_info)
  312. {
  313. $file = $file_info['file'];
  314. $reason = $this->_reason ? $this->_reason : static::$_phrases[$this->_status];
  315. $head = "HTTP/{$this->_version} {$this->_status} $reason\r\n";
  316. $headers = $this->_header;
  317. if (!isset($headers['Server'])) {
  318. $head .= "Server: workerman\r\n";
  319. }
  320. foreach ($headers as $name => $value) {
  321. if (\is_array($value)) {
  322. foreach ($value as $item) {
  323. $head .= "$name: $item\r\n";
  324. }
  325. continue;
  326. }
  327. $head .= "$name: $value\r\n";
  328. }
  329. if (!isset($headers['Connection'])) {
  330. $head .= "Connection: keep-alive\r\n";
  331. }
  332. $file_info = \pathinfo($file);
  333. $extension = isset($file_info['extension']) ? $file_info['extension'] : '';
  334. $base_name = isset($file_info['basename']) ? $file_info['basename'] : 'unknown';
  335. if (!isset($headers['Content-Type'])) {
  336. if (isset(self::$_mimeTypeMap[$extension])) {
  337. $head .= "Content-Type: " . self::$_mimeTypeMap[$extension] . "\r\n";
  338. } else {
  339. $head .= "Content-Type: application/octet-stream\r\n";
  340. }
  341. }
  342. if (!isset($headers['Content-Disposition']) && !isset(self::$_mimeTypeMap[$extension])) {
  343. $head .= "Content-Disposition: attachment; filename=\"$base_name\"\r\n";
  344. }
  345. if (!isset($headers['Last-Modified'])) {
  346. if ($mtime = \filemtime($file)) {
  347. $head .= 'Last-Modified: '.\date('D, d M Y H:i:s', $mtime) . ' ' . \date_default_timezone_get() ."\r\n";
  348. }
  349. }
  350. return "{$head}\r\n";
  351. }
  352. /**
  353. * __toString.
  354. *
  355. * @return string
  356. */
  357. public function __toString()
  358. {
  359. if (isset($this->file)) {
  360. return $this->createHeadForFile($this->file);
  361. }
  362. $reason = $this->_reason ? $this->_reason : static::$_phrases[$this->_status];
  363. $body_len = \strlen($this->_body);
  364. if (empty($this->_header)) {
  365. 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}";
  366. }
  367. $head = "HTTP/{$this->_version} {$this->_status} $reason\r\n";
  368. $headers = $this->_header;
  369. if (!isset($headers['Server'])) {
  370. $head .= "Server: workerman\r\n";
  371. }
  372. foreach ($headers as $name => $value) {
  373. if (\is_array($value)) {
  374. foreach ($value as $item) {
  375. $head .= "$name: $item\r\n";
  376. }
  377. continue;
  378. }
  379. $head .= "$name: $value\r\n";
  380. }
  381. if (!isset($headers['Connection'])) {
  382. $head .= "Connection: keep-alive\r\n";
  383. }
  384. if (!isset($headers['Content-Type'])) {
  385. $head .= "Content-Type: text/html;charset=utf-8\r\n";
  386. } else if ($headers['Content-Type'] === 'text/event-stream') {
  387. return $head . $this->_body;
  388. }
  389. if (!isset($headers['Transfer-Encoding'])) {
  390. $head .= "Content-Length: $body_len\r\n\r\n";
  391. } else {
  392. return "$head\r\n".dechex($body_len)."\r\n{$this->_body}\r\n";
  393. }
  394. // The whole http package
  395. return $head . $this->_body;
  396. }
  397. /**
  398. * Init mime map.
  399. *
  400. * @return void
  401. */
  402. public static function initMimeTypeMap()
  403. {
  404. $mime_file = __DIR__ . '/mime.types';
  405. $items = \file($mime_file, \FILE_IGNORE_NEW_LINES | \FILE_SKIP_EMPTY_LINES);
  406. foreach ($items as $content) {
  407. if (\preg_match("/\s*(\S+)\s+(\S.+)/", $content, $match)) {
  408. $mime_type = $match[1];
  409. $extension_var = $match[2];
  410. $extension_array = \explode(' ', \substr($extension_var, 0, -1));
  411. foreach ($extension_array as $file_extension) {
  412. static::$_mimeTypeMap[$file_extension] = $mime_type;
  413. }
  414. }
  415. }
  416. }
  417. }
  418. Response::init();