PageRenderTime 47ms CodeModel.GetById 20ms RepoModel.GetById 1ms app.codeStats 0ms

/system/libraries/Typography.php

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