TypographyHelper.php 12 KB

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