blob: 0fa7d6611ea141c7ef6ea20d5a8ce8360e915cdb [file] [log] [blame]
Rick Ellis4c938ae2008-09-10 22:58:38 +00001<?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
Rick Ellis08e38122008-09-12 06:21:25 +00009 * @copyright Copyright (c) 2008, EllisLab, Inc.
Rick Ellis4c938ae2008-09-10 22:58:38 +000010 * @license http://codeigniter.com/user_guide/license.html
11 * @link http://codeigniter.com
12 * @since Version 1.0
13 * @filesource
14 */
15
16// ------------------------------------------------------------------------
17
18/**
19 * Typography Class
20 *
21 *
22 * @access private
23 * @category Helpers
24 * @author ExpressionEngine Dev Team
25 * @link http://codeigniter.com/user_guide/helpers/
26 */
27class CI_Typography {
28
29 // Block level elements that should not be wrapped inside <p> tags
Derek Jonesfa5c4102008-09-30 00:47:54 +000030 var $block_elements = 'address|blockquote|div|dl|fieldset|form|h\d|hr|noscript|object|ol|p|pre|script|table|ul';
Rick Ellis4c938ae2008-09-10 22:58:38 +000031
32 // Elements that should not have <p> and <br /> tags within them.
Derek Jonesfa5c4102008-09-30 00:47:54 +000033 var $skip_elements = 'p|pre|ol|ul|dl|object|table';
Rick Ellis4c938ae2008-09-10 22:58:38 +000034
35 // Tags we want the parser to completely ignore when splitting the string.
Rick Ellis4b84a422008-11-05 01:21:21 +000036 var $inline_elements = 'a|abbr|acronym|b|bdo|br|button|cite|code|del|dfn|em|i|img|ins|input|label|map|kbd|samp|select|span|strong|sub|sup|textarea|var|big|small|q';
Rick Ellis4c938ae2008-09-10 22:58:38 +000037
Derek Jonesd95ebca2008-10-01 23:57:38 +000038 // whether or not to protect quotes within { curly braces }
39 var $protect_braced_quotes = FALSE;
40
Rick Ellis4c938ae2008-09-10 22:58:38 +000041 /**
Rick Ellis142f8ed2008-09-12 06:14:52 +000042 * Nothing to do here...
43 *
44 */
45 function CI_Typography()
46 {
47 }
48
49 /**
Rick Ellis08e38122008-09-12 06:21:25 +000050 * Auto Typography
Rick Ellis4c938ae2008-09-10 22:58:38 +000051 *
Rick Ellis08e38122008-09-12 06:21:25 +000052 * This function converts text, making it typographically correct:
53 * - Converts double spaces into paragraphs.
54 * - Converts single line breaks into <br /> tags
55 * - Converts single and double quotes into correctly facing curly quote entities.
56 * - Converts three dots into ellipsis.
57 * - Converts double dashes into em-dashes.
58 * - Converts two spaces into entities
Rick Ellis3bc791f2008-09-12 23:15:52 +000059 *
60 * @access public
61 * @param string
Rick Ellis3bc791f2008-09-12 23:15:52 +000062 * @param bool whether to reduce more then two consecutive newlines to two
63 * @return string
Rick Ellis4c938ae2008-09-10 22:58:38 +000064 */
Rick Ellisac91bd72008-10-26 21:52:41 +000065 function auto_typography($str, $reduce_linebreaks = FALSE)
Rick Ellis4c938ae2008-09-10 22:58:38 +000066 {
67 if ($str == '')
68 {
69 return '';
70 }
Rick Ellis3bc791f2008-09-12 23:15:52 +000071
Rick Ellis4c938ae2008-09-10 22:58:38 +000072 // Standardize Newlines to make matching easier
73 if (strpos($str, "\r") !== FALSE)
74 {
75 $str = str_replace(array("\r\n", "\r"), "\n", $str);
76 }
Rick Ellis16e3c8c2008-09-11 20:12:26 +000077
78 // Reduce line breaks. If there are more than two consecutive linebreaks
79 // we'll compress them down to a maximum of two since there's no benefit to more.
Rick Ellis3bc791f2008-09-12 23:15:52 +000080 if ($reduce_linebreaks === TRUE)
Rick Ellis16e3c8c2008-09-11 20:12:26 +000081 {
82 $str = preg_replace("/\n\n+/", "\n\n", $str);
Rick Ellisac91bd72008-10-26 21:52:41 +000083 }
Rick Ellis18bd8b52008-09-10 23:40:35 +000084
Rick Ellis339fab72008-09-12 06:04:39 +000085 // Convert quotes within tags to temporary markers. We don't want quotes converted
86 // within tags so we'll temporarily convert them to {@DQ} and {@SQ}
Derek Jones0d37ed82008-10-29 22:09:27 +000087 // and we don't want double dashes converted to emdash entities, so they are marked with {@DD}
Derek Jonescc13d492008-11-04 19:20:36 +000088 // likewise double spaces are converted to {@NBS} to prevent entity conversion
Rick Ellis4c938ae2008-09-10 22:58:38 +000089 if (preg_match_all("#\<.+?>#si", $str, $matches))
90 {
Derek Jonesc349c512008-10-27 16:29:19 +000091 for ($i = 0, $total = count($matches[0]); $i < $total; $i++)
Rick Ellis4c938ae2008-09-10 22:58:38 +000092 {
Derek Jonesc349c512008-10-27 16:29:19 +000093 $str = str_replace($matches[0][$i],
Derek Jonescc13d492008-11-04 19:20:36 +000094 str_replace(array("'",'"','--',' '), array('{@SQ}', '{@DQ}', '{@DD}', '{@NBS}'), $matches[0][$i]),
Rick Ellis4c938ae2008-09-10 22:58:38 +000095 $str);
96 }
97 }
Derek Jonesc349c512008-10-27 16:29:19 +000098
Derek Jonesd95ebca2008-10-01 23:57:38 +000099 if ($this->protect_braced_quotes === TRUE)
100 {
101 if (preg_match_all("#\{.+?}#si", $str, $matches))
102 {
Derek Jonesc349c512008-10-27 16:29:19 +0000103 for ($i = 0, $total = count($matches[0]); $i < $total; $i++)
Derek Jonesd95ebca2008-10-01 23:57:38 +0000104 {
Derek Jonesc349c512008-10-27 16:29:19 +0000105 $str = str_replace($matches[0][$i],
106 str_replace(array("'",'"'), array('{@SQ}', '{@DQ}'), $matches[0][$i]),
Derek Jonesd95ebca2008-10-01 23:57:38 +0000107 $str);
108 }
109 }
110 }
Derek Jones0d37ed82008-10-29 22:09:27 +0000111
Rick Ellis16e3c8c2008-09-11 20:12:26 +0000112 // Convert "ignore" tags to temporary marker. The parser splits out the string at every tag
113 // it encounters. Certain inline tags, like image tags, links, span tags, etc. will be
Rick Ellis339fab72008-09-12 06:04:39 +0000114 // adversely affected if they are split out so we'll convert the opening bracket < temporarily to: {@TAG}
Derek Jonesf2b7f622008-09-27 00:10:37 +0000115 $str = preg_replace("#<(/*)(".$this->inline_elements.")([ >])#i", "{@TAG}\\1\\2\\3", $str);
Rick Ellis16e3c8c2008-09-11 20:12:26 +0000116
117 // Split the string at every tag. This expression creates an array with this prototype:
118 //
119 // [array]
120 // {
121 // [0] = <opening tag>
122 // [1] = Content...
123 // [2] = <closing tag>
124 // Etc...
125 // }
Rick Ellis4c938ae2008-09-10 22:58:38 +0000126 $chunks = preg_split('/(<(?:[^<>]+(?:"[^"]*"|\'[^\']*\')?)+>)/', $str, -1, PREG_SPLIT_DELIM_CAPTURE|PREG_SPLIT_NO_EMPTY);
127
Rick Ellis16e3c8c2008-09-11 20:12:26 +0000128 // Build our finalized string. We cycle through the array, skipping tags, and processing the contained text
Rick Ellis4c938ae2008-09-10 22:58:38 +0000129 $str = '';
130 $process = TRUE;
Rick Ellis3ef59b72008-09-11 21:35:39 +0000131 $paragraph = FALSE;
Rick Ellis4c938ae2008-09-10 22:58:38 +0000132 foreach ($chunks as $chunk)
133 {
Rick Ellis16e3c8c2008-09-11 20:12:26 +0000134 // Are we dealing with a tag? If so, we'll skip the processing for this cycle.
135 // Well also set the "process" flag which allows us to skip <pre> tags and a few other things.
Rick Ellis4c938ae2008-09-10 22:58:38 +0000136 if (preg_match("#<(/*)(".$this->block_elements.").*?\>#", $chunk, $match))
137 {
Rick Ellis3ef59b72008-09-11 21:35:39 +0000138 if (preg_match("#".$this->skip_elements."#", $match[2]))
Rick Ellis4c938ae2008-09-10 22:58:38 +0000139 {
Derek Jones99765872008-09-24 17:19:44 +0000140 $process = ($match[1] == '/') ? TRUE : FALSE;
Rick Ellis4c938ae2008-09-10 22:58:38 +0000141 }
Rick Ellis3ef59b72008-09-11 21:35:39 +0000142
Rick Ellis4c938ae2008-09-10 22:58:38 +0000143 $str .= $chunk;
144 continue;
145 }
Rick Ellis4b84a422008-11-05 01:21:21 +0000146 elseif (preg_match('/<(\/?)([a-z]*).*?>/s', $chunk, $tagmatch))
147 {
148 if ($tagmatch[1] == '/' && $tagmatch[2] == $this->last_tag)
149 {
150 $process = FALSE;
151 }
152 else
153 {
154 $process = TRUE;
155 $this->last_tag = $tagmatch[2];
156 }
157 }
Rick Ellis8ca943f2008-10-01 01:37:59 +0000158
Rick Ellis4c938ae2008-09-10 22:58:38 +0000159 if ($process == FALSE)
160 {
161 $str .= $chunk;
162 continue;
163 }
164
165 // Convert Newlines into <p> and <br /> tags
Rick Ellis4b84a422008-11-05 01:21:21 +0000166 $str .= $this->format_characters($this->_format_newlines($chunk));
Rick Ellis4c938ae2008-09-10 22:58:38 +0000167 }
168
Derek Jonese07ba012008-09-25 22:14:01 +0000169 // is the whole of the content inside a block level element?
170 if ( ! preg_match("/^<(?:".$this->block_elements.")/i", $str, $match))
171 {
172 $str = "<p>{$str}</p>";
173 }
174
Derek Jonesc349c512008-10-27 16:29:19 +0000175
Rick Ellis4b84a422008-11-05 01:21:21 +0000176 // some special linebreak cleanup
177 $str = preg_replace_callback('#<(?!/|'.$this->block_elements.')([^>]*)><p>(.*?)</p><(\w*)#si', array($this, '_linebreak_cleanup'), $str);
178
179 // and cleanup empty paragraph tags sitting between two closing tags
180 $str = preg_replace('#(</\w+>)<p>(\s*)</p>(</\w+>)#si', '$1$2$3', $str);
181
Rick Ellis4c938ae2008-09-10 22:58:38 +0000182 // Final clean up
Rick Ellis16e3c8c2008-09-11 20:12:26 +0000183 $table = array(
Rick Ellis4c938ae2008-09-10 22:58:38 +0000184
Rick Ellis16e3c8c2008-09-11 20:12:26 +0000185 // If the user submitted their own paragraph tags within the text
186 // we will retain them instead of using our tags.
Rick Ellis4b84a422008-11-05 01:21:21 +0000187 '/(<p[^>*?]>)<p>/' => '$1', // <?php BBEdit syntax coloring bug fix
Rick Ellis16e3c8c2008-09-11 20:12:26 +0000188
Rick Ellis25319a32008-09-11 20:13:25 +0000189 // Reduce multiple instances of opening/closing paragraph tags to a single one
Rick Ellis9da2ee92008-09-23 20:39:50 +0000190 '#(</p>)+#' => '</p>',
Rick Ellis16e3c8c2008-09-11 20:12:26 +0000191 '/(<p><p>)+/' => '<p>',
Rick Ellis4b84a422008-11-05 01:21:21 +0000192 '/(<p>\W+<p>)+/' => '<p>',
Rick Ellis16e3c8c2008-09-11 20:12:26 +0000193
194 // Clean up stray paragraph tags that appear before block level elements
Rick Ellis339fab72008-09-12 06:04:39 +0000195 '#<p></p><('.$this->block_elements.')#' => '<$1',
Rick Ellis4b84a422008-11-05 01:21:21 +0000196
197 // Clean up open paragraph tags that appear before block level elements
198 '#<p>(\W)<('.$this->block_elements.')#' => '<p></p>$1<$2',
199
200 // Clean up stray non-breaking spaces preceeding block elements
201 '#[&nbsp; ]+<('.$this->block_elements.')#' => ' <$1',
Rick Ellis16e3c8c2008-09-11 20:12:26 +0000202
203 // Replace the temporary markers we added earlier
204 '/\{@TAG\}/' => '<',
205 '/\{@DQ\}/' => '"',
Derek Jones0d37ed82008-10-29 22:09:27 +0000206 '/\{@SQ\}/' => "'",
Derek Jonescc13d492008-11-04 19:20:36 +0000207 '/\{@DD\}/' => '--',
208 '/\{@NBS\}/' => ' '
Rick Ellis16e3c8c2008-09-11 20:12:26 +0000209
210 );
Rick Ellis4b84a422008-11-05 01:21:21 +0000211
Rick Ellis339fab72008-09-12 06:04:39 +0000212 // Do we need to reduce empty lines?
Rick Ellis3bc791f2008-09-12 23:15:52 +0000213 if ($reduce_linebreaks === TRUE)
Rick Ellis339fab72008-09-12 06:04:39 +0000214 {
215 $table['#<p>\n*</p>#'] = '';
216 }
217 else
218 {
219 // If we have empty paragraph tags we add a non-breaking space
220 // otherwise most browsers won't treat them as true paragraphs
221 $table['#<p></p>#'] = '<p>&nbsp;</p>';
222 }
223
Rick Ellis16e3c8c2008-09-11 20:12:26 +0000224 return preg_replace(array_keys($table), $table, $str);
225
Rick Ellis4c938ae2008-09-10 22:58:38 +0000226 }
227
228 // --------------------------------------------------------------------
Rick Ellis4b84a422008-11-05 01:21:21 +0000229
230 /**
231 * Linebreak Cleanup
232 *
233 * Removes paragraph and line break tags inserted inbetween
234 * inline content and a new opening block level element
235 *
236 * @access private
237 * @param array
238 * @return string
239 */
240 function _linebreak_cleanup($match)
241 {
242 if (in_array($match[3], explode('|', $this->block_elements)))
243 {
244 return "<{$match[1]}>".str_replace('<br />', '', $match[2])."<{$match[3]}";
245 }
246 else
247 {
248 return $match[0];
249 }
250 }
Rick Ellis4c938ae2008-09-10 22:58:38 +0000251
Rick Ellis4b84a422008-11-05 01:21:21 +0000252 // --------------------------------------------------------------------
253
Rick Ellis4c938ae2008-09-10 22:58:38 +0000254 /**
255 * Format Characters
256 *
257 * This function mainly converts double and single quotes
Derek Jonesab504b82008-09-11 17:04:30 +0000258 * to curly entities, but it also converts em-dashes,
259 * double spaces, and ampersands
Rick Ellis3bc791f2008-09-12 23:15:52 +0000260 *
261 * @access public
262 * @param string
263 * @return string
Rick Ellis4c938ae2008-09-10 22:58:38 +0000264 */
265 function format_characters($str)
Derek Jonesab504b82008-09-11 17:04:30 +0000266 {
267 static $table;
268
269 if ( ! isset($table))
270 {
271 $table = array(
272 // nested smart quotes, opening and closing
273 // note that rules for grammar (English) allow only for two levels deep
274 // and that single quotes are _supposed_ to always be on the outside
275 // but we'll accommodate both
276 '/(^|\W|\s)\'"/' => '$1&#8216;&#8220;',
277 '/\'"(\s|\W|$)/' => '&#8217;&#8221;$1',
278 '/(^|\W|\s)"\'/' => '$1&#8220;&#8216;',
279 '/"\'(\s|\W|$)/' => '&#8221;&#8217;$1',
Rick Ellis4c938ae2008-09-10 22:58:38 +0000280
Derek Jonesab504b82008-09-11 17:04:30 +0000281 // single quote smart quotes
282 '/\'(\s|\W|$)/' => '&#8217;$1',
283 '/(^|\W|\s)\'/' => '$1&#8216;',
Rick Ellis4c938ae2008-09-10 22:58:38 +0000284
Derek Jonesab504b82008-09-11 17:04:30 +0000285 // double quote smart quotes
286 '/"(\s|\W|$)/' => '&#8221;$1',
287 '/(^|\W|\s)"/' => '$1&#8220;',
Rick Ellis4c938ae2008-09-10 22:58:38 +0000288
Derek Jonesab504b82008-09-11 17:04:30 +0000289 // apostrophes
290 "/(\w)'(\w)/" => '$1&#8217;$2',
291
292 // Em dash and ellipses dots
293 '/\s?\-\-\s?/' => '&#8212;',
Derek Jones92490682008-09-24 20:44:34 +0000294 '/(\w)\.{3}/' => '$1&#8230;',
Derek Jonesab504b82008-09-11 17:04:30 +0000295
296 // double space after sentences
Derek Jones50500a22008-09-11 18:21:18 +0000297 '/(\W) /' => '$1&nbsp; ',
Derek Jonesab504b82008-09-11 17:04:30 +0000298
299 // ampersands, if not a character entity
300 '/&(?!#?[a-zA-Z0-9]{2,};)/' => '&amp;'
301 );
302 }
303
304 return preg_replace(array_keys($table), $table, $str);
Rick Ellis4c938ae2008-09-10 22:58:38 +0000305 }
306
307 // --------------------------------------------------------------------
308
309 /**
310 * Format Newlines
311 *
312 * Converts newline characters into either <p> tags or <br />
313 *
Rick Ellis0de7f252008-09-12 23:22:33 +0000314 * @access public
315 * @param string
316 * @return string
Rick Ellis4c938ae2008-09-10 22:58:38 +0000317 */
Rick Ellis3bc791f2008-09-12 23:15:52 +0000318 function _format_newlines($str)
Rick Ellis4c938ae2008-09-10 22:58:38 +0000319 {
320 if ($str == '')
321 {
322 return $str;
323 }
324
325 if (strpos($str, "\n") === FALSE)
326 {
Rick Ellis16e3c8c2008-09-11 20:12:26 +0000327 return $str;
Rick Ellis4c938ae2008-09-10 22:58:38 +0000328 }
Rick Ellis9da2ee92008-09-23 20:39:50 +0000329
330 // Convert two consecutive newlines to paragraphs
331 $str = str_replace("\n\n", "</p>\n\n<p>", $str);
332
333 // Convert single spaces to <br /> tags
Rick Ellis4c938ae2008-09-10 22:58:38 +0000334 $str = preg_replace("/([^\n])(\n)([^\n])/", "\\1<br />\\2\\3", $str);
335
Rick Ellis9da2ee92008-09-23 20:39:50 +0000336 // Wrap the whole enchilada in enclosing paragraphs
Rick Ellisc95c7e92008-10-22 20:17:21 +0000337 if ($str != "\n")
338 {
339 $str = '<p>'.$str.'</p>';
340 }
Rick Ellis9da2ee92008-09-23 20:39:50 +0000341
342 // Remove empty paragraphs if they are on the first line, as this
343 // is a potential unintended consequence of the previous code
344 $str = preg_replace("/<p><\/p>(.*)/", "\\1", $str, 1);
345
346 return $str;
Rick Ellis18bd8b52008-09-10 23:40:35 +0000347 }
348
Rick Ellis9907df42008-09-12 07:22:21 +0000349 // ------------------------------------------------------------------------
350
351 /**
352 * Convert newlines to HTML line breaks except within PRE tags
353 *
354 * @access public
355 * @param string
356 * @return string
357 */
358 function nl2br_except_pre($str)
359 {
360 $ex = explode("pre>",$str);
361 $ct = count($ex);
362
363 $newstr = "";
364 for ($i = 0; $i < $ct; $i++)
365 {
366 if (($i % 2) == 0)
367 {
368 $newstr .= nl2br($ex[$i]);
369 }
370 else
371 {
372 $newstr .= $ex[$i];
373 }
374
375 if ($ct - 1 != $i)
376 $newstr .= "pre>";
377 }
378
379 return $newstr;
380 }
381
Rick Ellis4c938ae2008-09-10 22:58:38 +0000382}
383// END Typography Class
384
385/* End of file Typography.php */
386/* Location: ./system/libraries/Typography.php */