Typography.php 12 KB

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