PageRenderTime 83ms CodeModel.GetById 25ms RepoModel.GetById 1ms app.codeStats 1ms

/public/min/lib/HTTP/Encoder.php

https://github.com/gudoy/PHPGasus-v0
PHP | 341 lines | 141 code | 16 blank | 184 comment | 34 complexity | 446967a1f64ae3e7c71655b05f763fce MD5 | raw file
  1. <?php
  2. /**
  3. * Class HTTP_Encoder
  4. * @package Minify
  5. * @subpackage HTTP
  6. */
  7. /**
  8. * Encode and send gzipped/deflated content
  9. *
  10. * The "Vary: Accept-Encoding" header is sent. If the client allows encoding,
  11. * Content-Encoding and Content-Length are added.
  12. *
  13. * <code>
  14. * // Send a CSS file, compressed if possible
  15. * $he = new HTTP_Encoder(array(
  16. * 'content' => file_get_contents($cssFile)
  17. * ,'type' => 'text/css'
  18. * ));
  19. * $he->encode();
  20. * $he->sendAll();
  21. * </code>
  22. *
  23. * <code>
  24. * // Shortcut to encoding output
  25. * header('Content-Type: text/css'); // needed if not HTML
  26. * HTTP_Encoder::output($css);
  27. * </code>
  28. *
  29. * <code>
  30. * // Just sniff for the accepted encoding
  31. * $encoding = HTTP_Encoder::getAcceptedEncoding();
  32. * </code>
  33. *
  34. * For more control over headers, use getHeaders() and getData() and send your
  35. * own output.
  36. *
  37. * Note: If you don't need header mgmt, use PHP's native gzencode, gzdeflate,
  38. * and gzcompress functions for gzip, deflate, and compress-encoding
  39. * respectively.
  40. *
  41. * @package Minify
  42. * @subpackage HTTP
  43. * @author Stephen Clay <steve@mrclay.org>
  44. */
  45. class HTTP_Encoder {
  46. /**
  47. * Should the encoder allow HTTP encoding to IE6?
  48. *
  49. * If you have many IE6 users and the bandwidth savings is worth troubling
  50. * some of them, set this to true.
  51. *
  52. * By default, encoding is only offered to IE7+. When this is true,
  53. * getAcceptedEncoding() will return an encoding for IE6 if its user agent
  54. * string contains "SV1". This has been documented in many places as "safe",
  55. * but there seem to be remaining, intermittent encoding bugs in patched
  56. * IE6 on the wild web.
  57. *
  58. * @var bool
  59. */
  60. public static $encodeToIe6 = true;
  61. /**
  62. * Default compression level for zlib operations
  63. *
  64. * This level is used if encode() is not given a $compressionLevel
  65. *
  66. * @var int
  67. */
  68. public static $compressionLevel = 6;
  69. /**
  70. * Get an HTTP Encoder object
  71. *
  72. * @param array $spec options
  73. *
  74. * 'content': (string required) content to be encoded
  75. *
  76. * 'type': (string) if set, the Content-Type header will have this value.
  77. *
  78. * 'method: (string) only set this if you are forcing a particular encoding
  79. * method. If not set, the best method will be chosen by getAcceptedEncoding()
  80. * The available methods are 'gzip', 'deflate', 'compress', and '' (no
  81. * encoding)
  82. *
  83. * @return null
  84. */
  85. public function __construct($spec)
  86. {
  87. $this->_useMbStrlen = (function_exists('mb_strlen')
  88. && (ini_get('mbstring.func_overload') !== '')
  89. && ((int)ini_get('mbstring.func_overload') & 2));
  90. $this->_content = $spec['content'];
  91. $this->_headers['Content-Length'] = $this->_useMbStrlen
  92. ? (string)mb_strlen($this->_content, '8bit')
  93. : (string)strlen($this->_content);
  94. if (isset($spec['type'])) {
  95. $this->_headers['Content-Type'] = $spec['type'];
  96. }
  97. if (isset($spec['method'])
  98. && in_array($spec['method'], array('gzip', 'deflate', 'compress', '')))
  99. {
  100. $this->_encodeMethod = array($spec['method'], $spec['method']);
  101. } else {
  102. $this->_encodeMethod = self::getAcceptedEncoding();
  103. }
  104. }
  105. /**
  106. * Get content in current form
  107. *
  108. * Call after encode() for encoded content.
  109. *
  110. * return string
  111. */
  112. public function getContent()
  113. {
  114. return $this->_content;
  115. }
  116. /**
  117. * Get array of output headers to be sent
  118. *
  119. * E.g.
  120. * <code>
  121. * array(
  122. * 'Content-Length' => '615'
  123. * ,'Content-Encoding' => 'x-gzip'
  124. * ,'Vary' => 'Accept-Encoding'
  125. * )
  126. * </code>
  127. *
  128. * @return array
  129. */
  130. public function getHeaders()
  131. {
  132. return $this->_headers;
  133. }
  134. /**
  135. * Send output headers
  136. *
  137. * You must call this before headers are sent and it probably cannot be
  138. * used in conjunction with zlib output buffering / mod_gzip. Errors are
  139. * not handled purposefully.
  140. *
  141. * @see getHeaders()
  142. *
  143. * @return null
  144. */
  145. public function sendHeaders()
  146. {
  147. foreach ($this->_headers as $name => $val) {
  148. header($name . ': ' . $val);
  149. }
  150. }
  151. /**
  152. * Send output headers and content
  153. *
  154. * A shortcut for sendHeaders() and echo getContent()
  155. *
  156. * You must call this before headers are sent and it probably cannot be
  157. * used in conjunction with zlib output buffering / mod_gzip. Errors are
  158. * not handled purposefully.
  159. *
  160. * @return null
  161. */
  162. public function sendAll()
  163. {
  164. $this->sendHeaders();
  165. echo $this->_content;
  166. }
  167. /**
  168. * Determine the client's best encoding method from the HTTP Accept-Encoding
  169. * header.
  170. *
  171. * If no Accept-Encoding header is set, or the browser is IE before v6 SP2,
  172. * this will return ('', ''), the "identity" encoding.
  173. *
  174. * A syntax-aware scan is done of the Accept-Encoding, so the method must
  175. * be non 0. The methods are favored in order of gzip, deflate, then
  176. * compress. Deflate is always smallest and generally faster, but is
  177. * rarely sent by servers, so client support could be buggier.
  178. *
  179. * @param bool $allowCompress allow the older compress encoding
  180. *
  181. * @param bool $allowDeflate allow the more recent deflate encoding
  182. *
  183. * @return array two values, 1st is the actual encoding method, 2nd is the
  184. * alias of that method to use in the Content-Encoding header (some browsers
  185. * call gzip "x-gzip" etc.)
  186. */
  187. public static function getAcceptedEncoding($allowCompress = true, $allowDeflate = true)
  188. {
  189. // @link http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html
  190. if (! isset($_SERVER['HTTP_ACCEPT_ENCODING'])
  191. || self::isBuggyIe())
  192. {
  193. return array('', '');
  194. }
  195. $ae = $_SERVER['HTTP_ACCEPT_ENCODING'];
  196. // gzip checks (quick)
  197. if (0 === strpos($ae, 'gzip,') // most browsers
  198. || 0 === strpos($ae, 'deflate, gzip,') // opera
  199. ) {
  200. return array('gzip', 'gzip');
  201. }
  202. // gzip checks (slow)
  203. if (preg_match(
  204. '@(?:^|,)\\s*((?:x-)?gzip)\\s*(?:$|,|;\\s*q=(?:0\\.|1))@'
  205. ,$ae
  206. ,$m)) {
  207. return array('gzip', $m[1]);
  208. }
  209. if ($allowDeflate) {
  210. // deflate checks
  211. $aeRev = strrev($ae);
  212. if (0 === strpos($aeRev, 'etalfed ,') // ie, webkit
  213. || 0 === strpos($aeRev, 'etalfed,') // gecko
  214. || 0 === strpos($ae, 'deflate,') // opera
  215. // slow parsing
  216. || preg_match(
  217. '@(?:^|,)\\s*deflate\\s*(?:$|,|;\\s*q=(?:0\\.|1))@', $ae)) {
  218. return array('deflate', 'deflate');
  219. }
  220. }
  221. if ($allowCompress && preg_match(
  222. '@(?:^|,)\\s*((?:x-)?compress)\\s*(?:$|,|;\\s*q=(?:0\\.|1))@'
  223. ,$ae
  224. ,$m)) {
  225. return array('compress', $m[1]);
  226. }
  227. return array('', '');
  228. }
  229. /**
  230. * Encode (compress) the content
  231. *
  232. * If the encode method is '' (none) or compression level is 0, or the 'zlib'
  233. * extension isn't loaded, we return false.
  234. *
  235. * Then the appropriate gz_* function is called to compress the content. If
  236. * this fails, false is returned.
  237. *
  238. * The header "Vary: Accept-Encoding" is added. If encoding is successful,
  239. * the Content-Length header is updated, and Content-Encoding is also added.
  240. *
  241. * @param int $compressionLevel given to zlib functions. If not given, the
  242. * class default will be used.
  243. *
  244. * @return bool success true if the content was actually compressed
  245. */
  246. public function encode($compressionLevel = null)
  247. {
  248. if (! self::isBuggyIe()) {
  249. $this->_headers['Vary'] = 'Accept-Encoding';
  250. }
  251. if (null === $compressionLevel) {
  252. $compressionLevel = self::$compressionLevel;
  253. }
  254. if ('' === $this->_encodeMethod[0]
  255. || ($compressionLevel == 0)
  256. || !extension_loaded('zlib'))
  257. {
  258. return false;
  259. }
  260. if ($this->_encodeMethod[0] === 'deflate') {
  261. $encoded = gzdeflate($this->_content, $compressionLevel);
  262. } elseif ($this->_encodeMethod[0] === 'gzip') {
  263. $encoded = gzencode($this->_content, $compressionLevel);
  264. } else {
  265. $encoded = gzcompress($this->_content, $compressionLevel);
  266. }
  267. if (false === $encoded) {
  268. return false;
  269. }
  270. $this->_headers['Content-Length'] = $this->_useMbStrlen
  271. ? (string)mb_strlen($encoded, '8bit')
  272. : (string)strlen($encoded);
  273. $this->_headers['Content-Encoding'] = $this->_encodeMethod[1];
  274. $this->_content = $encoded;
  275. return true;
  276. }
  277. /**
  278. * Encode and send appropriate headers and content
  279. *
  280. * This is a convenience method for common use of the class
  281. *
  282. * @param string $content
  283. *
  284. * @param int $compressionLevel given to zlib functions. If not given, the
  285. * class default will be used.
  286. *
  287. * @return bool success true if the content was actually compressed
  288. */
  289. public static function output($content, $compressionLevel = null)
  290. {
  291. if (null === $compressionLevel) {
  292. $compressionLevel = self::$compressionLevel;
  293. }
  294. $he = new HTTP_Encoder(array('content' => $content));
  295. $ret = $he->encode($compressionLevel);
  296. $he->sendAll();
  297. return $ret;
  298. }
  299. /**
  300. * Is the browser an IE version earlier than 6 SP2?
  301. *
  302. * @return bool
  303. */
  304. public static function isBuggyIe()
  305. {
  306. if (empty($_SERVER['HTTP_USER_AGENT'])) {
  307. return false;
  308. }
  309. $ua = $_SERVER['HTTP_USER_AGENT'];
  310. // quick escape for non-IEs
  311. if (0 !== strpos($ua, 'Mozilla/4.0 (compatible; MSIE ')
  312. || false !== strpos($ua, 'Opera')) {
  313. return false;
  314. }
  315. // no regex = faaast
  316. $version = (float)substr($ua, 30);
  317. return self::$encodeToIe6
  318. ? ($version < 6 || ($version == 6 && false === strpos($ua, 'SV1')))
  319. : ($version < 7);
  320. }
  321. protected $_content = '';
  322. protected $_headers = array();
  323. protected $_encodeMethod = array('', '');
  324. protected $_useMbStrlen = false;
  325. }