Typography.php 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424
  1. <?php
  2. /**
  3. * CodeIgniter
  4. *
  5. * An open source application development framework for PHP
  6. *
  7. * This content is released under the MIT License (MIT)
  8. *
  9. * Copyright (c) 2014 - 2017, British Columbia Institute of Technology
  10. *
  11. * Permission is hereby granted, free of charge, to any person obtaining a copy
  12. * of this software and associated documentation files (the "Software"), to deal
  13. * in the Software without restriction, including without limitation the rights
  14. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  15. * copies of the Software, and to permit persons to whom the Software is
  16. * furnished to do so, subject to the following conditions:
  17. *
  18. * The above copyright notice and this permission notice shall be included in
  19. * all copies or substantial portions of the Software.
  20. *
  21. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  22. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  23. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  24. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  25. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  26. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  27. * THE SOFTWARE.
  28. *
  29. * @package CodeIgniter
  30. * @author EllisLab Dev Team
  31. * @copyright Copyright (c) 2008 - 2014, EllisLab, Inc. (https://ellislab.com/)
  32. * @copyright Copyright (c) 2014 - 2017, British Columbia Institute of Technology (http://bcit.ca/)
  33. * @license http://opensource.org/licenses/MIT MIT License
  34. * @link https://codeigniter.com
  35. * @since Version 1.0.0
  36. * @filesource
  37. */
  38. defined('BASEPATH') OR exit('No direct script access allowed');
  39. /**
  40. * Typography Class
  41. *
  42. * @package CodeIgniter
  43. * @subpackage Libraries
  44. * @category Helpers
  45. * @author EllisLab Dev Team
  46. * @link https://codeigniter.com/user_guide/libraries/typography.html
  47. */
  48. class CI_Typography {
  49. /**
  50. * Block level elements that should not be wrapped inside <p> tags
  51. *
  52. * @var string
  53. */
  54. public $block_elements = 'address|blockquote|div|dl|fieldset|form|h\d|hr|noscript|object|ol|p|pre|script|table|ul';
  55. /**
  56. * Elements that should not have <p> and <br /> tags within them.
  57. *
  58. * @var string
  59. */
  60. public $skip_elements = 'p|pre|ol|ul|dl|object|table|h\d';
  61. /**
  62. * Tags we want the parser to completely ignore when splitting the string.
  63. *
  64. * @var string
  65. */
  66. public $inline_elements = 'a|abbr|acronym|b|bdo|big|br|button|cite|code|del|dfn|em|i|img|ins|input|label|map|kbd|q|samp|select|small|span|strong|sub|sup|textarea|tt|var';
  67. /**
  68. * array of block level elements that require inner content to be within another block level element
  69. *
  70. * @var array
  71. */
  72. public $inner_block_required = array('blockquote');
  73. /**
  74. * the last block element parsed
  75. *
  76. * @var string
  77. */
  78. public $last_block_element = '';
  79. /**
  80. * whether or not to protect quotes within { curly braces }
  81. *
  82. * @var bool
  83. */
  84. public $protect_braced_quotes = FALSE;
  85. /**
  86. * Auto Typography
  87. *
  88. * This function converts text, making it typographically correct:
  89. * - Converts double spaces into paragraphs.
  90. * - Converts single line breaks into <br /> tags
  91. * - Converts single and double quotes into correctly facing curly quote entities.
  92. * - Converts three dots into ellipsis.
  93. * - Converts double dashes into em-dashes.
  94. * - Converts two spaces into entities
  95. *
  96. * @param string
  97. * @param bool whether to reduce more then two consecutive newlines to two
  98. * @return string
  99. */
  100. public function auto_typography($str, $reduce_linebreaks = FALSE)
  101. {
  102. if ($str === '')
  103. {
  104. return '';
  105. }
  106. // Standardize Newlines to make matching easier
  107. if (strpos($str, "\r") !== FALSE)
  108. {
  109. $str = str_replace(array("\r\n", "\r"), "\n", $str);
  110. }
  111. // Reduce line breaks. If there are more than two consecutive linebreaks
  112. // we'll compress them down to a maximum of two since there's no benefit to more.
  113. if ($reduce_linebreaks === TRUE)
  114. {
  115. $str = preg_replace("/\n\n+/", "\n\n", $str);
  116. }
  117. // HTML comment tags don't conform to patterns of normal tags, so pull them out separately, only if needed
  118. $html_comments = array();
  119. if (strpos($str, '<!--') !== FALSE && preg_match_all('#(<!\-\-.*?\-\->)#s', $str, $matches))
  120. {
  121. for ($i = 0, $total = count($matches[0]); $i < $total; $i++)
  122. {
  123. $html_comments[] = $matches[0][$i];
  124. $str = str_replace($matches[0][$i], '{@HC'.$i.'}', $str);
  125. }
  126. }
  127. // match and yank <pre> tags if they exist. It's cheaper to do this separately since most content will
  128. // not contain <pre> tags, and it keeps the PCRE patterns below simpler and faster
  129. if (strpos($str, '<pre') !== FALSE)
  130. {
  131. $str = preg_replace_callback('#<pre.*?>.*?</pre>#si', array($this, '_protect_characters'), $str);
  132. }
  133. // Convert quotes within tags to temporary markers.
  134. $str = preg_replace_callback('#<.+?>#si', array($this, '_protect_characters'), $str);
  135. // Do the same with braces if necessary
  136. if ($this->protect_braced_quotes === TRUE)
  137. {
  138. $str = preg_replace_callback('#\{.+?\}#si', array($this, '_protect_characters'), $str);
  139. }
  140. // Convert "ignore" tags to temporary marker. The parser splits out the string at every tag
  141. // it encounters. Certain inline tags, like image tags, links, span tags, etc. will be
  142. // adversely affected if they are split out so we'll convert the opening bracket < temporarily to: {@TAG}
  143. $str = preg_replace('#<(/*)('.$this->inline_elements.')([ >])#i', '{@TAG}\\1\\2\\3', $str);
  144. /* Split the string at every tag. This expression creates an array with this prototype:
  145. *
  146. * [array]
  147. * {
  148. * [0] = <opening tag>
  149. * [1] = Content...
  150. * [2] = <closing tag>
  151. * Etc...
  152. * }
  153. */
  154. $chunks = preg_split('/(<(?:[^<>]+(?:"[^"]*"|\'[^\']*\')?)+>)/', $str, -1, PREG_SPLIT_DELIM_CAPTURE|PREG_SPLIT_NO_EMPTY);
  155. // Build our finalized string. We cycle through the array, skipping tags, and processing the contained text
  156. $str = '';
  157. $process = TRUE;
  158. for ($i = 0, $c = count($chunks) - 1; $i <= $c; $i++)
  159. {
  160. // Are we dealing with a tag? If so, we'll skip the processing for this cycle.
  161. // Well also set the "process" flag which allows us to skip <pre> tags and a few other things.
  162. if (preg_match('#<(/*)('.$this->block_elements.').*?>#', $chunks[$i], $match))
  163. {
  164. if (preg_match('#'.$this->skip_elements.'#', $match[2]))
  165. {
  166. $process = ($match[1] === '/');
  167. }
  168. if ($match[1] === '')
  169. {
  170. $this->last_block_element = $match[2];
  171. }
  172. $str .= $chunks[$i];
  173. continue;
  174. }
  175. if ($process === FALSE)
  176. {
  177. $str .= $chunks[$i];
  178. continue;
  179. }
  180. // Force a newline to make sure end tags get processed by _format_newlines()
  181. if ($i === $c)
  182. {
  183. $chunks[$i] .= "\n";
  184. }
  185. // Convert Newlines into <p> and <br /> tags
  186. $str .= $this->_format_newlines($chunks[$i]);
  187. }
  188. // No opening block level tag? Add it if needed.
  189. if ( ! preg_match('/^\s*<(?:'.$this->block_elements.')/i', $str))
  190. {
  191. $str = preg_replace('/^(.*?)<('.$this->block_elements.')/i', '<p>$1</p><$2', $str);
  192. }
  193. // Convert quotes, elipsis, em-dashes, non-breaking spaces, and ampersands
  194. $str = $this->format_characters($str);
  195. // restore HTML comments
  196. for ($i = 0, $total = count($html_comments); $i < $total; $i++)
  197. {
  198. // remove surrounding paragraph tags, but only if there's an opening paragraph tag
  199. // otherwise HTML comments at the ends of paragraphs will have the closing tag removed
  200. // if '<p>{@HC1}' then replace <p>{@HC1}</p> with the comment, else replace only {@HC1} with the comment
  201. $str = preg_replace('#(?(?=<p>\{@HC'.$i.'\})<p>\{@HC'.$i.'\}(\s*</p>)|\{@HC'.$i.'\})#s', $html_comments[$i], $str);
  202. }
  203. // Final clean up
  204. $table = array(
  205. // If the user submitted their own paragraph tags within the text
  206. // we will retain them instead of using our tags.
  207. '/(<p[^>*?]>)<p>/' => '$1', // <?php BBEdit syntax coloring bug fix
  208. // Reduce multiple instances of opening/closing paragraph tags to a single one
  209. '#(</p>)+#' => '</p>',
  210. '/(<p>\W*<p>)+/' => '<p>',
  211. // Clean up stray paragraph tags that appear before block level elements
  212. '#<p></p><('.$this->block_elements.')#' => '<$1',
  213. // Clean up stray non-breaking spaces preceding block elements
  214. '#(&nbsp;\s*)+<('.$this->block_elements.')#' => ' <$2',
  215. // Replace the temporary markers we added earlier
  216. '/\{@TAG\}/' => '<',
  217. '/\{@DQ\}/' => '"',
  218. '/\{@SQ\}/' => "'",
  219. '/\{@DD\}/' => '--',
  220. '/\{@NBS\}/' => ' ',
  221. // An unintended consequence of the _format_newlines function is that
  222. // some of the newlines get truncated, resulting in <p> tags
  223. // starting immediately after <block> tags on the same line.
  224. // This forces a newline after such occurrences, which looks much nicer.
  225. "/><p>\n/" => ">\n<p>",
  226. // Similarly, there might be cases where a closing </block> will follow
  227. // a closing </p> tag, so we'll correct it by adding a newline in between
  228. '#</p></#' => "</p>\n</"
  229. );
  230. // Do we need to reduce empty lines?
  231. if ($reduce_linebreaks === TRUE)
  232. {
  233. $table['#<p>\n*</p>#'] = '';
  234. }
  235. else
  236. {
  237. // If we have empty paragraph tags we add a non-breaking space
  238. // otherwise most browsers won't treat them as true paragraphs
  239. $table['#<p></p>#'] = '<p>&nbsp;</p>';
  240. }
  241. return preg_replace(array_keys($table), $table, $str);
  242. }
  243. // --------------------------------------------------------------------
  244. /**
  245. * Format Characters
  246. *
  247. * This function mainly converts double and single quotes
  248. * to curly entities, but it also converts em-dashes,
  249. * double spaces, and ampersands
  250. *
  251. * @param string
  252. * @return string
  253. */
  254. public function format_characters($str)
  255. {
  256. static $table;
  257. if ( ! isset($table))
  258. {
  259. $table = array(
  260. // nested smart quotes, opening and closing
  261. // note that rules for grammar (English) allow only for two levels deep
  262. // and that single quotes are _supposed_ to always be on the outside
  263. // but we'll accommodate both
  264. // Note that in all cases, whitespace is the primary determining factor
  265. // on which direction to curl, with non-word characters like punctuation
  266. // being a secondary factor only after whitespace is addressed.
  267. '/\'"(\s|$)/' => '&#8217;&#8221;$1',
  268. '/(^|\s|<p>)\'"/' => '$1&#8216;&#8220;',
  269. '/\'"(\W)/' => '&#8217;&#8221;$1',
  270. '/(\W)\'"/' => '$1&#8216;&#8220;',
  271. '/"\'(\s|$)/' => '&#8221;&#8217;$1',
  272. '/(^|\s|<p>)"\'/' => '$1&#8220;&#8216;',
  273. '/"\'(\W)/' => '&#8221;&#8217;$1',
  274. '/(\W)"\'/' => '$1&#8220;&#8216;',
  275. // single quote smart quotes
  276. '/\'(\s|$)/' => '&#8217;$1',
  277. '/(^|\s|<p>)\'/' => '$1&#8216;',
  278. '/\'(\W)/' => '&#8217;$1',
  279. '/(\W)\'/' => '$1&#8216;',
  280. // double quote smart quotes
  281. '/"(\s|$)/' => '&#8221;$1',
  282. '/(^|\s|<p>)"/' => '$1&#8220;',
  283. '/"(\W)/' => '&#8221;$1',
  284. '/(\W)"/' => '$1&#8220;',
  285. // apostrophes
  286. "/(\w)'(\w)/" => '$1&#8217;$2',
  287. // Em dash and ellipses dots
  288. '/\s?\-\-\s?/' => '&#8212;',
  289. '/(\w)\.{3}/' => '$1&#8230;',
  290. // double space after sentences
  291. '/(\W) /' => '$1&nbsp; ',
  292. // ampersands, if not a character entity
  293. '/&(?!#?[a-zA-Z0-9]{2,};)/' => '&amp;'
  294. );
  295. }
  296. return preg_replace(array_keys($table), $table, $str);
  297. }
  298. // --------------------------------------------------------------------
  299. /**
  300. * Format Newlines
  301. *
  302. * Converts newline characters into either <p> tags or <br />
  303. *
  304. * @param string
  305. * @return string
  306. */
  307. protected function _format_newlines($str)
  308. {
  309. if ($str === '' OR (strpos($str, "\n") === FALSE && ! in_array($this->last_block_element, $this->inner_block_required)))
  310. {
  311. return $str;
  312. }
  313. // Convert two consecutive newlines to paragraphs
  314. $str = str_replace("\n\n", "</p>\n\n<p>", $str);
  315. // Convert single spaces to <br /> tags
  316. $str = preg_replace("/([^\n])(\n)([^\n])/", '\\1<br />\\2\\3', $str);
  317. // Wrap the whole enchilada in enclosing paragraphs
  318. if ($str !== "\n")
  319. {
  320. // We trim off the right-side new line so that the closing </p> tag
  321. // will be positioned immediately following the string, matching
  322. // the behavior of the opening <p> tag
  323. $str = '<p>'.rtrim($str).'</p>';
  324. }
  325. // Remove empty paragraphs if they are on the first line, as this
  326. // is a potential unintended consequence of the previous code
  327. return preg_replace('/<p><\/p>(.*)/', '\\1', $str, 1);
  328. }
  329. // ------------------------------------------------------------------------
  330. /**
  331. * Protect Characters
  332. *
  333. * Protects special characters from being formatted later
  334. * We don't want quotes converted within tags so we'll temporarily convert them to {@DQ} and {@SQ}
  335. * and we don't want double dashes converted to emdash entities, so they are marked with {@DD}
  336. * likewise double spaces are converted to {@NBS} to prevent entity conversion
  337. *
  338. * @param array
  339. * @return string
  340. */
  341. protected function _protect_characters($match)
  342. {
  343. return str_replace(array("'",'"','--',' '), array('{@SQ}', '{@DQ}', '{@DD}', '{@NBS}'), $match[0]);
  344. }
  345. // --------------------------------------------------------------------
  346. /**
  347. * Convert newlines to HTML line breaks except within PRE tags
  348. *
  349. * @param string
  350. * @return string
  351. */
  352. public function nl2br_except_pre($str)
  353. {
  354. $newstr = '';
  355. for ($ex = explode('pre>', $str), $ct = count($ex), $i = 0; $i < $ct; $i++)
  356. {
  357. $newstr .= (($i % 2) === 0) ? nl2br($ex[$i]) : $ex[$i];
  358. if ($ct - 1 !== $i)
  359. {
  360. $newstr .= 'pre>';
  361. }
  362. }
  363. return $newstr;
  364. }
  365. }