PageRenderTime 52ms CodeModel.GetById 24ms RepoModel.GetById 0ms app.codeStats 0ms

/system/libraries/Typography.php

https://gitlab.com/ablu/invertika-backup-web
PHP | 406 lines | 207 code | 57 blank | 142 comment | 28 complexity | d4d8b9c32c00deb92658329ae5673e3b MD5 | raw file
  1. <?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
  2. /**
  3. * CodeIgniter
  4. *
  5. * An open source application development framework for PHP 4.3.2 or newer
  6. *
  7. * @package CodeIgniter
  8. * @author ExpressionEngine Dev Team
  9. * @copyright Copyright (c) 2008 - 2010, 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. * Nothing to do here...
  40. *
  41. */
  42. function CI_Typography()
  43. {
  44. }
  45. /**
  46. * Auto Typography
  47. *
  48. * This function converts text, making it typographically correct:
  49. * - Converts double spaces into paragraphs.
  50. * - Converts single line breaks into <br /> tags
  51. * - Converts single and double quotes into correctly facing curly quote entities.
  52. * - Converts three dots into ellipsis.
  53. * - Converts double dashes into em-dashes.
  54. * - Converts two spaces into entities
  55. *
  56. * @access public
  57. * @param string
  58. * @param bool whether to reduce more then two consecutive newlines to two
  59. * @return string
  60. */
  61. function auto_typography($str, $reduce_linebreaks = FALSE)
  62. {
  63. if ($str == '')
  64. {
  65. return '';
  66. }
  67. // Standardize Newlines to make matching easier
  68. if (strpos($str, "\r") !== FALSE)
  69. {
  70. $str = str_replace(array("\r\n", "\r"), "\n", $str);
  71. }
  72. // Reduce line breaks. If there are more than two consecutive linebreaks
  73. // we'll compress them down to a maximum of two since there's no benefit to more.
  74. if ($reduce_linebreaks === TRUE)
  75. {
  76. $str = preg_replace("/\n\n+/", "\n\n", $str);
  77. }
  78. // HTML comment tags don't conform to patterns of normal tags, so pull them out separately, only if needed
  79. $html_comments = array();
  80. if (strpos($str, '<!--') !== FALSE)
  81. {
  82. if (preg_match_all("#(<!\-\-.*?\-\->)#s", $str, $matches))
  83. {
  84. for ($i = 0, $total = count($matches[0]); $i < $total; $i++)
  85. {
  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. {
  95. $str = preg_replace_callback("#<pre.*?>.*?</pre>#si", array($this, '_protect_characters'), $str);
  96. }
  97. // Convert quotes within tags to temporary markers.
  98. $str = preg_replace_callback("#<.+?>#si", array($this, '_protect_characters'), $str);
  99. // Do the same with braces if necessary
  100. if ($this->protect_braced_quotes === TRUE)
  101. {
  102. $str = preg_replace_callback("#\{.+?\}#si", array($this, '_protect_characters'), $str);
  103. }
  104. // Convert "ignore" tags to temporary marker. The parser splits out the string at every tag
  105. // it encounters. Certain inline tags, like image tags, links, span tags, etc. will be
  106. // adversely affected if they are split out so we'll convert the opening bracket < temporarily to: {@TAG}
  107. $str = preg_replace("#<(/*)(".$this->inline_elements.")([ >])#i", "{@TAG}\\1\\2\\3", $str);
  108. // Split the string at every tag. This expression creates an array with this prototype:
  109. //
  110. // [array]
  111. // {
  112. // [0] = <opening tag>
  113. // [1] = Content...
  114. // [2] = <closing tag>
  115. // Etc...
  116. // }
  117. $chunks = preg_split('/(<(?:[^<>]+(?:"[^"]*"|\'[^\']*\')?)+>)/', $str, -1, PREG_SPLIT_DELIM_CAPTURE|PREG_SPLIT_NO_EMPTY);
  118. // Build our finalized string. We cycle through the array, skipping tags, and processing the contained text
  119. $str = '';
  120. $process = TRUE;
  121. $paragraph = FALSE;
  122. $current_chunk = 0;
  123. $total_chunks = count($chunks);
  124. foreach ($chunks as $chunk)
  125. {
  126. $current_chunk++;
  127. // Are we dealing with a tag? If so, we'll skip the processing for this cycle.
  128. // Well also set the "process" flag which allows us to skip <pre> tags and a few other things.
  129. if (preg_match("#<(/*)(".$this->block_elements.").*?>#", $chunk, $match))
  130. {
  131. if (preg_match("#".$this->skip_elements."#", $match[2]))
  132. {
  133. $process = ($match[1] == '/') ? TRUE : FALSE;
  134. }
  135. if ($match[1] == '')
  136. {
  137. $this->last_block_element = $match[2];
  138. }
  139. $str .= $chunk;
  140. continue;
  141. }
  142. if ($process == FALSE)
  143. {
  144. $str .= $chunk;
  145. continue;
  146. }
  147. // Force a newline to make sure end tags get processed by _format_newlines()
  148. if ($current_chunk == $total_chunks)
  149. {
  150. $chunk .= "\n";
  151. }
  152. // Convert Newlines into <p> and <br /> tags
  153. $str .= $this->_format_newlines($chunk);
  154. }
  155. // No opening block level tag? Add it if needed.
  156. if ( ! preg_match("/^\s*<(?:".$this->block_elements.")/i", $str))
  157. {
  158. $str = preg_replace("/^(.*?)<(".$this->block_elements.")/i", '<p>$1</p><$2', $str);
  159. }
  160. // Convert quotes, elipsis, em-dashes, non-breaking spaces, and ampersands
  161. $str = $this->format_characters($str);
  162. // restore HTML comments
  163. for ($i = 0, $total = count($html_comments); $i < $total; $i++)
  164. {
  165. // remove surrounding paragraph tags, but only if there's an opening paragraph tag
  166. // otherwise HTML comments at the ends of paragraphs will have the closing tag removed
  167. // if '<p>{@HC1}' then replace <p>{@HC1}</p> with the comment, else replace only {@HC1} with the comment
  168. $str = preg_replace('#(?(?=<p>\{@HC'.$i.'\})<p>\{@HC'.$i.'\}(\s*</p>)|\{@HC'.$i.'\})#s', $html_comments[$i], $str);
  169. }
  170. // Final clean up
  171. $table = array(
  172. // If the user submitted their own paragraph tags within the text
  173. // we will retain them instead of using our tags.
  174. '/(<p[^>*?]>)<p>/' => '$1', // <?php BBEdit syntax coloring bug fix
  175. // Reduce multiple instances of opening/closing paragraph tags to a single one
  176. '#(</p>)+#' => '</p>',
  177. '/(<p>\W*<p>)+/' => '<p>',
  178. // Clean up stray paragraph tags that appear before block level elements
  179. '#<p></p><('.$this->block_elements.')#' => '<$1',
  180. // Clean up stray non-breaking spaces preceeding block elements
  181. '#(&nbsp;\s*)+<('.$this->block_elements.')#' => ' <$2',
  182. // Replace the temporary markers we added earlier
  183. '/\{@TAG\}/' => '<',
  184. '/\{@DQ\}/' => '"',
  185. '/\{@SQ\}/' => "'",
  186. '/\{@DD\}/' => '--',
  187. '/\{@NBS\}/' => ' '
  188. );
  189. // Do we need to reduce empty lines?
  190. if ($reduce_linebreaks === TRUE)
  191. {
  192. $table['#<p>\n*</p>#'] = '';
  193. }
  194. else
  195. {
  196. // If we have empty paragraph tags we add a non-breaking space
  197. // otherwise most browsers won't treat them as true paragraphs
  198. $table['#<p></p>#'] = '<p>&nbsp;</p>';
  199. }
  200. return preg_replace(array_keys($table), $table, $str);
  201. }
  202. // --------------------------------------------------------------------
  203. /**
  204. * Format Characters
  205. *
  206. * This function mainly converts double and single quotes
  207. * to curly entities, but it also converts em-dashes,
  208. * double spaces, and ampersands
  209. *
  210. * @access public
  211. * @param string
  212. * @return string
  213. */
  214. function format_characters($str)
  215. {
  216. static $table;
  217. if ( ! isset($table))
  218. {
  219. $table = array(
  220. // nested smart quotes, opening and closing
  221. // note that rules for grammar (English) allow only for two levels deep
  222. // and that single quotes are _supposed_ to always be on the outside
  223. // but we'll accommodate both
  224. // Note that in all cases, whitespace is the primary determining factor
  225. // on which direction to curl, with non-word characters like punctuation
  226. // being a secondary factor only after whitespace is addressed.
  227. '/\'"(\s|$)/' => '&#8217;&#8221;$1',
  228. '/(^|\s|<p>)\'"/' => '$1&#8216;&#8220;',
  229. '/\'"(\W)/' => '&#8217;&#8221;$1',
  230. '/(\W)\'"/' => '$1&#8216;&#8220;',
  231. '/"\'(\s|$)/' => '&#8221;&#8217;$1',
  232. '/(^|\s|<p>)"\'/' => '$1&#8220;&#8216;',
  233. '/"\'(\W)/' => '&#8221;&#8217;$1',
  234. '/(\W)"\'/' => '$1&#8220;&#8216;',
  235. // single quote smart quotes
  236. '/\'(\s|$)/' => '&#8217;$1',
  237. '/(^|\s|<p>)\'/' => '$1&#8216;',
  238. '/\'(\W)/' => '&#8217;$1',
  239. '/(\W)\'/' => '$1&#8216;',
  240. // double quote smart quotes
  241. '/"(\s|$)/' => '&#8221;$1',
  242. '/(^|\s|<p>)"/' => '$1&#8220;',
  243. '/"(\W)/' => '&#8221;$1',
  244. '/(\W)"/' => '$1&#8220;',
  245. // apostrophes
  246. "/(\w)'(\w)/" => '$1&#8217;$2',
  247. // Em dash and ellipses dots
  248. '/\s?\-\-\s?/' => '&#8212;',
  249. '/(\w)\.{3}/' => '$1&#8230;',
  250. // double space after sentences
  251. '/(\W) /' => '$1&nbsp; ',
  252. // ampersands, if not a character entity
  253. '/&(?!#?[a-zA-Z0-9]{2,};)/' => '&amp;'
  254. );
  255. }
  256. return preg_replace(array_keys($table), $table, $str);
  257. }
  258. // --------------------------------------------------------------------
  259. /**
  260. * Format Newlines
  261. *
  262. * Converts newline characters into either <p> tags or <br />
  263. *
  264. * @access public
  265. * @param string
  266. * @return string
  267. */
  268. function _format_newlines($str)
  269. {
  270. if ($str == '')
  271. {
  272. return $str;
  273. }
  274. if (strpos($str, "\n") === FALSE && ! in_array($this->last_block_element, $this->inner_block_required))
  275. {
  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. {
  285. $str = '<p>'.$str.'</p>';
  286. }
  287. // Remove empty paragraphs if they are on the first line, as this
  288. // is a potential unintended consequence of the previous code
  289. $str = preg_replace("/<p><\/p>(.*)/", "\\1", $str, 1);
  290. return $str;
  291. }
  292. // ------------------------------------------------------------------------
  293. /**
  294. * Protect Characters
  295. *
  296. * Protects special characters from being formatted later
  297. * We don't want quotes converted within tags so we'll temporarily convert them to {@DQ} and {@SQ}
  298. * and we don't want double dashes converted to emdash entities, so they are marked with {@DD}
  299. * likewise double spaces are converted to {@NBS} to prevent entity conversion
  300. *
  301. * @access public
  302. * @param array
  303. * @return string
  304. */
  305. function _protect_characters($match)
  306. {
  307. return str_replace(array("'",'"','--',' '), array('{@SQ}', '{@DQ}', '{@DD}', '{@NBS}'), $match[0]);
  308. }
  309. // --------------------------------------------------------------------
  310. /**
  311. * Convert newlines to HTML line breaks except within PRE tags
  312. *
  313. * @access public
  314. * @param string
  315. * @return string
  316. */
  317. function nl2br_except_pre($str)
  318. {
  319. $ex = explode("pre>",$str);
  320. $ct = count($ex);
  321. $newstr = "";
  322. for ($i = 0; $i < $ct; $i++)
  323. {
  324. if (($i % 2) == 0)
  325. {
  326. $newstr .= nl2br($ex[$i]);
  327. }
  328. else
  329. {
  330. $newstr .= $ex[$i];
  331. }
  332. if ($ct - 1 != $i)
  333. $newstr .= "pre>";
  334. }
  335. return $newstr;
  336. }
  337. }
  338. // END Typography Class
  339. /* End of file Typography.php */
  340. /* Location: ./system/libraries/Typography.php */