PageRenderTime 46ms CodeModel.GetById 18ms RepoModel.GetById 0ms app.codeStats 0ms

/manager/min/lib/Minify/HTML.php

https://gitlab.com/haque.mdmanzurul/modx-improve-carolyn
PHP | 246 lines | 136 code | 34 blank | 76 comment | 6 complexity | 39e239cf9174dca6d5aeb0f4a8f8bec6 MD5 | raw file
  1. <?php
  2. /**
  3. * Class Minify_HTML
  4. * @package Minify
  5. */
  6. /**
  7. * Compress HTML
  8. *
  9. * This is a heavy regex-based removal of whitespace, unnecessary comments and
  10. * tokens. IE conditional comments are preserved. There are also options to have
  11. * STYLE and SCRIPT blocks compressed by callback functions.
  12. *
  13. * A test suite is available.
  14. *
  15. * @package Minify
  16. * @author Stephen Clay <steve@mrclay.org>
  17. */
  18. class Minify_HTML {
  19. /**
  20. * "Minify" an HTML page
  21. *
  22. * @param string $html
  23. *
  24. * @param array $options
  25. *
  26. * 'cssMinifier' : (optional) callback function to process content of STYLE
  27. * elements.
  28. *
  29. * 'jsMinifier' : (optional) callback function to process content of SCRIPT
  30. * elements. Note: the type attribute is ignored.
  31. *
  32. * 'xhtml' : (optional boolean) should content be treated as XHTML1.0? If
  33. * unset, minify will sniff for an XHTML doctype.
  34. *
  35. * @return string
  36. */
  37. public static function minify($html, $options = array()) {
  38. $min = new Minify_HTML($html, $options);
  39. return $min->process();
  40. }
  41. /**
  42. * Create a minifier object
  43. *
  44. * @param string $html
  45. *
  46. * @param array $options
  47. *
  48. * 'cssMinifier' : (optional) callback function to process content of STYLE
  49. * elements.
  50. *
  51. * 'jsMinifier' : (optional) callback function to process content of SCRIPT
  52. * elements. Note: the type attribute is ignored.
  53. *
  54. * 'xhtml' : (optional boolean) should content be treated as XHTML1.0? If
  55. * unset, minify will sniff for an XHTML doctype.
  56. *
  57. * @return null
  58. */
  59. public function __construct($html, $options = array())
  60. {
  61. $this->_html = str_replace("\r\n", "\n", trim($html));
  62. if (isset($options['xhtml'])) {
  63. $this->_isXhtml = (bool)$options['xhtml'];
  64. }
  65. if (isset($options['cssMinifier'])) {
  66. $this->_cssMinifier = $options['cssMinifier'];
  67. }
  68. if (isset($options['jsMinifier'])) {
  69. $this->_jsMinifier = $options['jsMinifier'];
  70. }
  71. }
  72. /**
  73. * Minify the markeup given in the constructor
  74. *
  75. * @return string
  76. */
  77. public function process()
  78. {
  79. if ($this->_isXhtml === null) {
  80. $this->_isXhtml = (false !== strpos($this->_html, '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML'));
  81. }
  82. $this->_replacementHash = 'MINIFYHTML' . md5($_SERVER['REQUEST_TIME']);
  83. $this->_placeholders = array();
  84. // replace SCRIPTs (and minify) with placeholders
  85. $this->_html = preg_replace_callback(
  86. '/(\\s*)<script(\\b[^>]*?>)([\\s\\S]*?)<\\/script>(\\s*)/i'
  87. ,array($this, '_removeScriptCB')
  88. ,$this->_html);
  89. // replace STYLEs (and minify) with placeholders
  90. $this->_html = preg_replace_callback(
  91. '/\\s*<style(\\b[^>]*>)([\\s\\S]*?)<\\/style>\\s*/i'
  92. ,array($this, '_removeStyleCB')
  93. ,$this->_html);
  94. // remove HTML comments (not containing IE conditional comments).
  95. $this->_html = preg_replace_callback(
  96. '/<!--([\\s\\S]*?)-->/'
  97. ,array($this, '_commentCB')
  98. ,$this->_html);
  99. // replace PREs with placeholders
  100. $this->_html = preg_replace_callback('/\\s*<pre(\\b[^>]*?>[\\s\\S]*?<\\/pre>)\\s*/i'
  101. ,array($this, '_removePreCB')
  102. ,$this->_html);
  103. // replace TEXTAREAs with placeholders
  104. $this->_html = preg_replace_callback(
  105. '/\\s*<textarea(\\b[^>]*?>[\\s\\S]*?<\\/textarea>)\\s*/i'
  106. ,array($this, '_removeTextareaCB')
  107. ,$this->_html);
  108. // trim each line.
  109. // @todo take into account attribute values that span multiple lines.
  110. $this->_html = preg_replace('/^\\s+|\\s+$/m', '', $this->_html);
  111. // remove ws around block/undisplayed elements
  112. $this->_html = preg_replace('/\\s+(<\\/?(?:area|base(?:font)?|blockquote|body'
  113. .'|caption|center|cite|col(?:group)?|dd|dir|div|dl|dt|fieldset|form'
  114. .'|frame(?:set)?|h[1-6]|head|hr|html|legend|li|link|map|menu|meta'
  115. .'|ol|opt(?:group|ion)|p|param|t(?:able|body|head|d|h||r|foot|itle)'
  116. .'|ul)\\b[^>]*>)/i', '$1', $this->_html);
  117. // remove ws outside of all elements
  118. $this->_html = preg_replace(
  119. '/>(\\s(?:\\s*))?([^<]+)(\\s(?:\s*))?</'
  120. ,'>$1$2$3<'
  121. ,$this->_html);
  122. // use newlines before 1st attribute in open tags (to limit line lengths)
  123. $this->_html = preg_replace('/(<[a-z\\-]+)\\s+([^>]+>)/i', "$1\n$2", $this->_html);
  124. // fill placeholders
  125. $this->_html = str_replace(
  126. array_keys($this->_placeholders)
  127. ,array_values($this->_placeholders)
  128. ,$this->_html
  129. );
  130. // issue 229: multi-pass to catch scripts that didn't get replaced in textareas
  131. $this->_html = str_replace(
  132. array_keys($this->_placeholders)
  133. ,array_values($this->_placeholders)
  134. ,$this->_html
  135. );
  136. return $this->_html;
  137. }
  138. protected function _commentCB($m)
  139. {
  140. return (0 === strpos($m[1], '[') || false !== strpos($m[1], '<!['))
  141. ? $m[0]
  142. : '';
  143. }
  144. protected function _reservePlace($content)
  145. {
  146. $placeholder = '%' . $this->_replacementHash . count($this->_placeholders) . '%';
  147. $this->_placeholders[$placeholder] = $content;
  148. return $placeholder;
  149. }
  150. protected $_isXhtml = null;
  151. protected $_replacementHash = null;
  152. protected $_placeholders = array();
  153. protected $_cssMinifier = null;
  154. protected $_jsMinifier = null;
  155. protected function _removePreCB($m)
  156. {
  157. return $this->_reservePlace("<pre{$m[1]}");
  158. }
  159. protected function _removeTextareaCB($m)
  160. {
  161. return $this->_reservePlace("<textarea{$m[1]}");
  162. }
  163. protected function _removeStyleCB($m)
  164. {
  165. $openStyle = "<style{$m[1]}";
  166. $css = $m[2];
  167. // remove HTML comments
  168. $css = preg_replace('/(?:^\\s*<!--|-->\\s*$)/', '', $css);
  169. // remove CDATA section markers
  170. $css = $this->_removeCdata($css);
  171. // minify
  172. $minifier = $this->_cssMinifier
  173. ? $this->_cssMinifier
  174. : 'trim';
  175. $css = call_user_func($minifier, $css);
  176. return $this->_reservePlace($this->_needsCdata($css)
  177. ? "{$openStyle}/*<![CDATA[*/{$css}/*]]>*/</style>"
  178. : "{$openStyle}{$css}</style>"
  179. );
  180. }
  181. protected function _removeScriptCB($m)
  182. {
  183. $openScript = "<script{$m[2]}";
  184. $js = $m[3];
  185. // whitespace surrounding? preserve at least one space
  186. $ws1 = ($m[1] === '') ? '' : ' ';
  187. $ws2 = ($m[4] === '') ? '' : ' ';
  188. // remove HTML comments (and ending "//" if present)
  189. $js = preg_replace('/(?:^\\s*<!--\\s*|\\s*(?:\\/\\/)?\\s*-->\\s*$)/', '', $js);
  190. // remove CDATA section markers
  191. $js = $this->_removeCdata($js);
  192. // minify
  193. $minifier = $this->_jsMinifier
  194. ? $this->_jsMinifier
  195. : 'trim';
  196. $js = call_user_func($minifier, $js);
  197. return $this->_reservePlace($this->_needsCdata($js)
  198. ? "{$ws1}{$openScript}/*<![CDATA[*/{$js}/*]]>*/</script>{$ws2}"
  199. : "{$ws1}{$openScript}{$js}</script>{$ws2}"
  200. );
  201. }
  202. protected function _removeCdata($str)
  203. {
  204. return (false !== strpos($str, '<![CDATA['))
  205. ? str_replace(array('<![CDATA[', ']]>'), '', $str)
  206. : $str;
  207. }
  208. protected function _needsCdata($str)
  209. {
  210. return ($this->_isXhtml && preg_match('/(?:[<&]|\\-\\-|\\]\\]>)/', $str));
  211. }
  212. }