PageRenderTime 63ms CodeModel.GetById 30ms RepoModel.GetById 0ms app.codeStats 0ms

/convert/system/helpers/typography_helper.php

https://github.com/usagi-project/mynets1
PHP | 545 lines | 342 code | 62 blank | 141 comment | 38 complexity | 8abe3f0613879d05ad9ceef0e4e275b2 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) 2006, 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. * CodeIgniter Typography Helpers
  18. *
  19. * @package CodeIgniter
  20. * @subpackage Helpers
  21. * @category Helpers
  22. * @author ExpressionEngine Dev Team
  23. * @link http://codeigniter.com/user_guide/helpers/typography_helper.html
  24. */
  25. // ------------------------------------------------------------------------
  26. /**
  27. * Convert newlines to HTML line breaks except within PRE tags
  28. *
  29. * @access public
  30. * @param string
  31. * @return string
  32. */
  33. if (! function_exists('nl2br_except_pre'))
  34. {
  35. function nl2br_except_pre($str)
  36. {
  37. $ex = explode("pre>",$str);
  38. $ct = count($ex);
  39. $newstr = "";
  40. for ($i = 0; $i < $ct; $i++)
  41. {
  42. if (($i % 2) == 0)
  43. {
  44. $newstr .= nl2br($ex[$i]);
  45. }
  46. else
  47. {
  48. $newstr .= $ex[$i];
  49. }
  50. if ($ct - 1 != $i)
  51. $newstr .= "pre>";
  52. }
  53. return $newstr;
  54. }
  55. }
  56. // ------------------------------------------------------------------------
  57. /**
  58. * Auto Typography Wrapper Function
  59. *
  60. *
  61. * @access public
  62. * @param string
  63. * @return string
  64. */
  65. if (! function_exists('auto_typography'))
  66. {
  67. function auto_typography($str)
  68. {
  69. $TYPE = new Auto_typography();
  70. return $TYPE->convert($str);
  71. }
  72. }
  73. // ------------------------------------------------------------------------
  74. /**
  75. * Auto Typography Class
  76. *
  77. *
  78. * @access private
  79. * @category Helpers
  80. * @author ExpressionEngine Dev Team
  81. * @link http://codeigniter.com/user_guide/helpers/
  82. */
  83. class Auto_typography {
  84. // Block level elements that should not be wrapped inside <p> tags
  85. var $block_elements = 'div|blockquote|pre|code|h\d|script|ol|ul';
  86. // Elements that should not have <p> and <br /> tags within them.
  87. var $skip_elements = 'pre|ol|ul';
  88. // Tags we want the parser to completely ignore when splitting the string.
  89. var $ignore_elements = 'a|b|i|em|strong|span|img|li';
  90. /**
  91. * Main Processing Function
  92. *
  93. */
  94. function convert($str)
  95. {
  96. if ($str == '')
  97. {
  98. return '';
  99. }
  100. $str = ' '.$str.' ';
  101. // Standardize Newlines to make matching easier
  102. $str = preg_replace("/(\r\n|\r)/", "\n", $str);
  103. /*
  104. * Reduce line breaks
  105. *
  106. * If there are more than two consecutive line
  107. * breaks we'll compress them down to a maximum
  108. * of two since there's no benefit to more.
  109. *
  110. */
  111. $str = preg_replace("/\n\n+/", "\n\n", $str);
  112. /*
  113. * Convert quotes within tags to temporary marker
  114. *
  115. * We don't want quotes converted within
  116. * tags so we'll temporarily convert them to
  117. * {@DQ} and {@SQ}
  118. *
  119. */
  120. if (preg_match_all("#\<.+?>#si", $str, $matches))
  121. {
  122. for ($i = 0; $i < count($matches['0']); $i++)
  123. {
  124. $str = str_replace($matches['0'][$i],
  125. str_replace(array("'",'"'), array('{@SQ}', '{@DQ}'), $matches['0'][$i]),
  126. $str);
  127. }
  128. }
  129. /*
  130. * Add closing/opening paragraph tags before/after "block" elements
  131. *
  132. * Since block elements (like <blockquotes>, <pre>, etc.) do not get
  133. * wrapped in paragraph tags we will add a closing </p> tag just before
  134. * each block element starts and an opening <p> tag right after the block element
  135. * ends. Later on we'll do some further clean up.
  136. *
  137. */
  138. $str = preg_replace("#(<)(".$this->block_elements.")(.*?>)#", "</p>\\1\\2\\3", $str);
  139. $str = preg_replace("#(</)(".$this->block_elements.")(.*?>)#", "\\1\\2\\3<p>", $str);
  140. /*
  141. * Convert "ignore" tags to temporary marker
  142. *
  143. * The parser splits out the string at every tag
  144. * it encounters. Certain inline tags, like image
  145. * tags, links, span tags, etc. will be adversely
  146. * affected if they are split out so we'll convert
  147. * the opening < temporarily to: {@TAG}
  148. *
  149. */
  150. $str = preg_replace("#<(/*)(".$this->ignore_elements.")#i", "{@TAG}\\1\\2", $str);
  151. /*
  152. * Split the string at every tag
  153. *
  154. * This creates an array with this prototype:
  155. *
  156. * [array]
  157. * {
  158. * [0] = <opening tag>
  159. * [1] = Content contained between the tags
  160. * [2] = <closing tag>
  161. * Etc...
  162. * }
  163. *
  164. */
  165. $chunks = preg_split('/(<(?:[^<>]+(?:"[^"]*"|\'[^\']*\')?)+>)/', $str, -1, PREG_SPLIT_DELIM_CAPTURE|PREG_SPLIT_NO_EMPTY);
  166. /*
  167. * Build our finalized string
  168. *
  169. * We'll cycle through the array, skipping tags,
  170. * and processing the contained text
  171. *
  172. */
  173. $str = '';
  174. $process = TRUE;
  175. foreach ($chunks as $chunk)
  176. {
  177. /*
  178. * Are we dealing with a tag?
  179. *
  180. * If so, we'll skip the processing for this cycle.
  181. * Well also set the "process" flag which allows us
  182. * to skip <pre> tags and a few other things.
  183. *
  184. */
  185. if (preg_match("#<(/*)(".$this->block_elements.").*?\>#", $chunk, $match))
  186. {
  187. if (preg_match("#".$this->skip_elements."#", $match['2']))
  188. {
  189. $process = ($match['1'] == '/') ? TRUE : FALSE;
  190. }
  191. $str .= $chunk;
  192. continue;
  193. }
  194. if ($process == FALSE)
  195. {
  196. $str .= $chunk;
  197. continue;
  198. }
  199. // Convert Newlines into <p> and <br /> tags
  200. $str .= $this->format_newlines($chunk);
  201. }
  202. // FINAL CLEAN UP
  203. // IMPORTANT: DO NOT ALTER THE ORDER OF THE ITEMS BELOW!
  204. /*
  205. * Clean up paragraph tags before/after "block" elements
  206. *
  207. * Earlier we added <p></p> tags before/after block level elements.
  208. * Then, we added paragraph tags around double line breaks. This
  209. * potentially created incorrectly formatted paragraphs so we'll
  210. * clean it up here.
  211. *
  212. */
  213. $str = preg_replace("#<p>({@TAG}.*?)(".$this->block_elements.")(.*?>)#", "\\1\\2\\3", $str);
  214. $str = preg_replace("#({@TAG}/.*?)(".$this->block_elements.")(.*?>)</p>#", "\\1\\2\\3", $str);
  215. // Convert Quotes and other characters
  216. $str = $this->format_characters($str);
  217. // Fix an artifact that happens during the paragraph replacement
  218. $str = preg_replace('#(<p>\n*</p>)#', '', $str);
  219. // If the user submitted their own paragraph tags with class data
  220. // in them we will retain them instead of using our tags.
  221. $str = preg_replace('#(<p.*?>)<p>#', "\\1", $str);
  222. // Final clean up
  223. $str = str_replace(
  224. array(
  225. '</p></p>',
  226. '</p><p>',
  227. '<p> ',
  228. ' </p>',
  229. '{@TAG}',
  230. '{@DQ}',
  231. '{@SQ}',
  232. '<p></p>'
  233. ),
  234. array(
  235. '</p>',
  236. '<p>',
  237. '<p>',
  238. '</p>',
  239. '<',
  240. '"',
  241. "'",
  242. ''
  243. ),
  244. $str
  245. );
  246. return $str;
  247. }
  248. // --------------------------------------------------------------------
  249. /**
  250. * Format Characters
  251. *
  252. * This function mainly converts double and single quotes
  253. * to entities, but since these are directional, it does
  254. * it based on some rules. It also converts em-dashes
  255. * and a couple other things.
  256. */
  257. function format_characters($str)
  258. {
  259. $table = array(
  260. ' "' => " &#8220;",
  261. '" ' => "&#8221; ",
  262. " '" => " &#8216;",
  263. "' " => "&#8217; ",
  264. '>"' => ">&#8220;",
  265. '"<' => "&#8221;<",
  266. ">'" => ">&#8216;",
  267. "'<" => "&#8217;<",
  268. "\"." => "&#8221;.",
  269. "\"," => "&#8221;,",
  270. "\";" => "&#8221;;",
  271. "\":" => "&#8221;:",
  272. "\"!" => "&#8221;!",
  273. "\"?" => "&#8221;?",
  274. ". " => ".&nbsp; ",
  275. "? " => "?&nbsp; ",
  276. "! " => "!&nbsp; ",
  277. ": " => ":&nbsp; ",
  278. );
  279. // These deal with quotes within quotes, like: "'hi here'"
  280. $start = 0;
  281. $space = array("\n", "\t", " ");
  282. while(TRUE)
  283. {
  284. $current = strpos(substr($str, $start), "\"'");
  285. if ($current === FALSE) break;
  286. $one_before = substr($str, $start+$current-1, 1);
  287. $one_after = substr($str, $start+$current+2, 1);
  288. if ( ! in_array($one_after, $space, TRUE) && $one_after != "<")
  289. {
  290. $str = str_replace( $one_before."\"'".$one_after,
  291. $one_before."&#8220;&#8216;".$one_after,
  292. $str);
  293. }
  294. elseif ( ! in_array($one_before, $space, TRUE) && (in_array($one_after, $space, TRUE) OR $one_after == '<'))
  295. {
  296. $str = str_replace( $one_before."\"'".$one_after,
  297. $one_before."&#8221;&#8217;".$one_after,
  298. $str);
  299. }
  300. $start = $start+$current+2;
  301. }
  302. $start = 0;
  303. while(TRUE)
  304. {
  305. $current = strpos(substr($str, $start), "'\"");
  306. if ($current === FALSE) break;
  307. $one_before = substr($str, $start+$current-1, 1);
  308. $one_after = substr($str, $start+$current+2, 1);
  309. if ( in_array($one_before, $space, TRUE) && ! in_array($one_after, $space, TRUE) && $one_after != "<")
  310. {
  311. $str = str_replace( $one_before."'\"".$one_after,
  312. $one_before."&#8216;&#8220;".$one_after,
  313. $str);
  314. }
  315. elseif ( ! in_array($one_before, $space, TRUE) && $one_before != ">")
  316. {
  317. $str = str_replace( $one_before."'\"".$one_after,
  318. $one_before."&#8217;&#8221;".$one_after,
  319. $str);
  320. }
  321. $start = $start+$current+2;
  322. }
  323. // Are there quotes within a word, as in: ("something")
  324. if (preg_match_all("/(.)\"(\S+?)\"(.)/", $str, $matches))
  325. {
  326. for ($i=0, $s=sizeof($matches['0']); $i < $s; ++$i)
  327. {
  328. if ( ! in_array($matches['1'][$i], $space, TRUE) && ! in_array($matches['3'][$i], $space, TRUE))
  329. {
  330. $str = str_replace( $matches['0'][$i],
  331. $matches['1'][$i]."&#8220;".$matches['2'][$i]."&#8221;".$matches['3'][$i],
  332. $str);
  333. }
  334. }
  335. }
  336. if (preg_match_all("/(.)\'(\S+?)\'(.)/", $str, $matches))
  337. {
  338. for ($i=0, $s=sizeof($matches['0']); $i < $s; ++$i)
  339. {
  340. if ( ! in_array($matches['1'][$i], $space, TRUE) && ! in_array($matches['3'][$i], $space, TRUE))
  341. {
  342. $str = str_replace( $matches['0'][$i],
  343. $matches['1'][$i]."&#8216;".$matches['2'][$i]."&#8217;".$matches['3'][$i],
  344. $str);
  345. }
  346. }
  347. }
  348. // How about one apostrophe, as in Rick's
  349. $start = 0;
  350. while(TRUE)
  351. {
  352. $current = strpos(substr($str, $start), "'");
  353. if ($current === FALSE) break;
  354. $one_before = substr($str, $start+$current-1, 1);
  355. $one_after = substr($str, $start+$current+1, 1);
  356. if ( ! in_array($one_before, $space, TRUE) && ! in_array($one_after, $space, TRUE))
  357. {
  358. $str = str_replace( $one_before."'".$one_after,
  359. $one_before."&#8217;".$one_after,
  360. $str);
  361. }
  362. $start = $start+$current+2;
  363. }
  364. // Em-dashes
  365. $start = 0;
  366. while(TRUE)
  367. {
  368. $current = strpos(substr($str, $start), "--");
  369. if ($current === FALSE) break;
  370. $one_before = substr($str, $start+$current-1, 1);
  371. $one_after = substr($str, $start+$current+2, 1);
  372. $two_before = substr($str, $start+$current-2, 1);
  373. $two_after = substr($str, $start+$current+3, 1);
  374. if (( ! in_array($one_before, $space, TRUE) && ! in_array($one_after, $space, TRUE))
  375. OR
  376. ( ! in_array($two_before, $space, TRUE) && ! in_array($two_after, $space, TRUE) && $one_before == ' ' && $one_after == ' ')
  377. )
  378. {
  379. $str = str_replace( $two_before.$one_before."--".$one_after.$two_after,
  380. $two_before.trim($one_before)."&#8212;".trim($one_after).$two_after,
  381. $str);
  382. }
  383. $start = $start+$current+2;
  384. }
  385. // Ellipsis
  386. $str = preg_replace("#(\w)\.\.\.(\s|<br />|</p>)#", "\\1&#8230;\\2", $str);
  387. $str = preg_replace("#(\s|<br />|</p>)\.\.\.(\w)#", "\\1&#8230;\\2", $str);
  388. // Run the translation array we defined above
  389. $str = str_replace(array_keys($table), array_values($table), $str);
  390. // If there are any stray double quotes we'll catch them here
  391. $start = 0;
  392. while(TRUE)
  393. {
  394. $current = strpos(substr($str, $start), '"');
  395. if ($current === FALSE) break;
  396. $one_before = substr($str, $start+$current-1, 1);
  397. $one_after = substr($str, $start+$current+1, 1);
  398. if ( ! in_array($one_after, $space, TRUE))
  399. {
  400. $str = str_replace( $one_before.'"'.$one_after,
  401. $one_before."&#8220;".$one_after,
  402. $str);
  403. }
  404. elseif( ! in_array($one_before, $space, TRUE))
  405. {
  406. $str = str_replace( $one_before."'".$one_after,
  407. $one_before."&#8221;".$one_after,
  408. $str);
  409. }
  410. $start = $start+$current+2;
  411. }
  412. $start = 0;
  413. while(TRUE)
  414. {
  415. $current = strpos(substr($str, $start), "'");
  416. if ($current === FALSE) break;
  417. $one_before = substr($str, $start+$current-1, 1);
  418. $one_after = substr($str, $start+$current+1, 1);
  419. if ( ! in_array($one_after, $space, TRUE))
  420. {
  421. $str = str_replace( $one_before."'".$one_after,
  422. $one_before."&#8216;".$one_after,
  423. $str);
  424. }
  425. elseif( ! in_array($one_before, $space, TRUE))
  426. {
  427. $str = str_replace( $one_before."'".$one_after,
  428. $one_before."&#8217;".$one_after,
  429. $str);
  430. }
  431. $start = $start+$current+2;
  432. }
  433. return $str;
  434. }
  435. // --------------------------------------------------------------------
  436. /**
  437. * Format Newlines
  438. *
  439. * Converts newline characters into either <p> tags or <br />
  440. *
  441. */
  442. function format_newlines($str)
  443. {
  444. if ($str == '')
  445. {
  446. return $str;
  447. }
  448. if (strpos($str, "\n") === FALSE)
  449. {
  450. return '<p>'.$str.'</p>';
  451. }
  452. $str = str_replace("\n\n", "</p>\n\n<p>", $str);
  453. $str = preg_replace("/([^\n])(\n)([^\n])/", "\\1<br />\\2\\3", $str);
  454. return '<p>'.$str.'</p>';
  455. }
  456. }
  457. ?>