TypographyHelper.php 12 KB

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