TypographyHelper.php 14 KB

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