Response.php 11 KB

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