TypographyHelper.php 14 KB

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