TypographyHelper.php 14 KB

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