blob: 3875bd5c4161f6dcd5fb3bf909f7ba4b705841e1 [file] [log] [blame]
Derek Allard2067d1a2008-11-13 22:59:24 +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
9 * @copyright Copyright (c) 2008, 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
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
30 var $block_elements = 'address|blockquote|div|dl|fieldset|form|h\d|hr|noscript|object|ol|p|pre|script|table|ul';
31
32 // Elements that should not have <p> and <br /> tags within them.
33 var $skip_elements = 'p|pre|ol|ul|dl|object|table';
34
35 // Tags we want the parser to completely ignore when splitting the string.
36 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';
Derek Jonesd5738d92008-11-14 16:53:34 +000037
38 // array of block level elements that require inner content to be within another block level element
39 var $inner_block_required = array('blockquote');
40
41 // the last block element parsed
42 var $last_block_element = '';
43
Derek Allard2067d1a2008-11-13 22:59:24 +000044 // whether or not to protect quotes within { curly braces }
45 var $protect_braced_quotes = FALSE;
46
47 /**
48 * Nothing to do here...
49 *
50 */
51 function CI_Typography()
52 {
53 }
54
55 /**
56 * Auto Typography
57 *
58 * This function converts text, making it typographically correct:
59 * - Converts double spaces into paragraphs.
60 * - Converts single line breaks into <br /> tags
61 * - Converts single and double quotes into correctly facing curly quote entities.
62 * - Converts three dots into ellipsis.
63 * - Converts double dashes into em-dashes.
64 * - Converts two spaces into entities
65 *
66 * @access public
67 * @param string
68 * @param bool whether to reduce more then two consecutive newlines to two
69 * @return string
70 */
71 function auto_typography($str, $reduce_linebreaks = FALSE)
72 {
73 if ($str == '')
74 {
75 return '';
76 }
77
78 // Standardize Newlines to make matching easier
79 if (strpos($str, "\r") !== FALSE)
80 {
81 $str = str_replace(array("\r\n", "\r"), "\n", $str);
82 }
83
84 // Reduce line breaks. If there are more than two consecutive linebreaks
85 // we'll compress them down to a maximum of two since there's no benefit to more.
86 if ($reduce_linebreaks === TRUE)
87 {
88 $str = preg_replace("/\n\n+/", "\n\n", $str);
Derek Jonesd5738d92008-11-14 16:53:34 +000089 }
Derek Allard2067d1a2008-11-13 22:59:24 +000090
Derek Jonesa633ec22008-12-11 14:31:33 +000091 // HTML comment tags don't conform to patterns of normal tags, so pull them out separately, only if needed
92 $html_comments = array();
93 if (strpos($str, '<!--') !== FALSE)
94 {
95 if (preg_match_all("#(<!\-\-.*?\-\->)#s", $str, $matches))
96 {
97 for ($i = 0, $total = count($matches[0]); $i < $total; $i++)
98 {
99 $html_comments[] = $matches[0][$i];
100 $str = str_replace($matches[0][$i], '{@HC'.$i.'}', $str);
101 }
102 }
103 }
Derek Jones7deecfb2008-12-11 15:38:01 +0000104
105 // match and yank <pre> tags if they exist. It's cheaper to do this separately since most content will
106 // not contain <pre> tags, and it keeps the PCRE patterns below simpler and faster
107 if (strpos($str, '<pre') !== FALSE)
Derek Allard2067d1a2008-11-13 22:59:24 +0000108 {
Derek Jones7deecfb2008-12-11 15:38:01 +0000109 $str = preg_replace_callback("#<pre.*?>.*?</pre>#si", array($this, '_protect_characters'), $str);
Derek Allard2067d1a2008-11-13 22:59:24 +0000110 }
111
Derek Jones7deecfb2008-12-11 15:38:01 +0000112 // Convert quotes within tags to temporary markers.
113 $str = preg_replace_callback("#<.+?>#si", array($this, '_protect_characters'), $str);
114
115 // Do the same with braces if necessary
Derek Allard2067d1a2008-11-13 22:59:24 +0000116 if ($this->protect_braced_quotes === TRUE)
117 {
Derek Jones7deecfb2008-12-11 15:38:01 +0000118 $str = preg_replace_callback("#\{.+?\}#si", array($this, '_protect_characters'), $str);
Derek Allard2067d1a2008-11-13 22:59:24 +0000119 }
Derek Jonesa633ec22008-12-11 14:31:33 +0000120
Derek Allard2067d1a2008-11-13 22:59:24 +0000121 // Convert "ignore" tags to temporary marker. The parser splits out the string at every tag
122 // it encounters. Certain inline tags, like image tags, links, span tags, etc. will be
123 // adversely affected if they are split out so we'll convert the opening bracket < temporarily to: {@TAG}
124 $str = preg_replace("#<(/*)(".$this->inline_elements.")([ >])#i", "{@TAG}\\1\\2\\3", $str);
125
126 // Split the string at every tag. This expression creates an array with this prototype:
127 //
128 // [array]
129 // {
130 // [0] = <opening tag>
131 // [1] = Content...
132 // [2] = <closing tag>
133 // Etc...
134 // }
135 $chunks = preg_split('/(<(?:[^<>]+(?:"[^"]*"|\'[^\']*\')?)+>)/', $str, -1, PREG_SPLIT_DELIM_CAPTURE|PREG_SPLIT_NO_EMPTY);
136
137 // Build our finalized string. We cycle through the array, skipping tags, and processing the contained text
138 $str = '';
139 $process = TRUE;
140 $paragraph = FALSE;
141 foreach ($chunks as $chunk)
142 {
143 // Are we dealing with a tag? If so, we'll skip the processing for this cycle.
144 // Well also set the "process" flag which allows us to skip <pre> tags and a few other things.
Derek Jones7deecfb2008-12-11 15:38:01 +0000145 if (preg_match("#<(/*)(".$this->block_elements.").*?>#", $chunk, $match))
Derek Allard2067d1a2008-11-13 22:59:24 +0000146 {
147 if (preg_match("#".$this->skip_elements."#", $match[2]))
148 {
149 $process = ($match[1] == '/') ? TRUE : FALSE;
150 }
151
Derek Jonesd5738d92008-11-14 16:53:34 +0000152 if ($match[1] == '')
153 {
154 $this->last_block_element = $match[2];
155 }
156
Derek Allard2067d1a2008-11-13 22:59:24 +0000157 $str .= $chunk;
158 continue;
159 }
Derek Jonesd5738d92008-11-14 16:53:34 +0000160
Derek Allard2067d1a2008-11-13 22:59:24 +0000161 if ($process == FALSE)
162 {
Derek Jones7deecfb2008-12-11 15:38:01 +0000163 $str .= $chunk;
Derek Allard2067d1a2008-11-13 22:59:24 +0000164 continue;
165 }
Derek Jonesd5738d92008-11-14 16:53:34 +0000166
Derek Allard2067d1a2008-11-13 22:59:24 +0000167 // Convert Newlines into <p> and <br /> tags
Derek Jones7deecfb2008-12-11 15:38:01 +0000168 $str .= $this->_format_newlines($chunk);
Derek Allard2067d1a2008-11-13 22:59:24 +0000169 }
170
171 // is the whole of the content inside a block level element?
Derek Jonesa633ec22008-12-11 14:31:33 +0000172 if ( ! preg_match("/^\s*<(?:".$this->block_elements.")/i", $str, $match))
Derek Allard2067d1a2008-11-13 22:59:24 +0000173 {
174 $str = "<p>{$str}</p>";
175 }
Derek Jonesa633ec22008-12-11 14:31:33 +0000176
Derek Jones7deecfb2008-12-11 15:38:01 +0000177 // Convert quotes, elipsis, em-dashes, non-breaking spaces, and ampersands
178 $str = $this->format_characters($str);
179
Derek Jonesa633ec22008-12-11 14:31:33 +0000180 // restore HTML comments
181 for ($i = 0, $total = count($html_comments); $i < $total; $i++)
182 {
Derek Jones4777fb82008-12-11 17:55:42 +0000183 // remove surrounding paragraph tags, but only if there's an opening paragraph tag
184 // otherwise HTML comments at the ends of paragraphs will have the closing tag removed
185 // if '<p>{@HC1}' then replace <p>{@HC1}</p> with the comment, else replace only {@HC1} with the comment
186 $str = preg_replace('#(?(?=<p>\{@HC'.$i.'\})<p>\{@HC'.$i.'\}(\s*</p>)|\{@HC'.$i.'\})#s', $html_comments[$i], $str);
Derek Jonesa633ec22008-12-11 14:31:33 +0000187 }
Derek Jones4777fb82008-12-11 17:55:42 +0000188
Derek Allard2067d1a2008-11-13 22:59:24 +0000189 // Final clean up
190 $table = array(
191
192 // If the user submitted their own paragraph tags within the text
193 // we will retain them instead of using our tags.
Derek Jonesd5738d92008-11-14 16:53:34 +0000194 '/(<p[^>*?]>)<p>/' => '$1', // <?php BBEdit syntax coloring bug fix
Derek Allard2067d1a2008-11-13 22:59:24 +0000195
196 // Reduce multiple instances of opening/closing paragraph tags to a single one
197 '#(</p>)+#' => '</p>',
198 '/(<p>\W*<p>)+/' => '<p>',
199
200 // Clean up stray paragraph tags that appear before block level elements
201 '#<p></p><('.$this->block_elements.')#' => '<$1',
Derek Jonesffa4c842008-12-11 16:37:04 +0000202
Derek Allard2067d1a2008-11-13 22:59:24 +0000203 // Clean up stray non-breaking spaces preceeding block elements
Derek Jonesffa4c842008-12-11 16:37:04 +0000204 '#(&nbsp;\s*)+<('.$this->block_elements.')#' => ' <$2',
Derek Jonesd5738d92008-11-14 16:53:34 +0000205
Derek Allard2067d1a2008-11-13 22:59:24 +0000206 // Replace the temporary markers we added earlier
207 '/\{@TAG\}/' => '<',
208 '/\{@DQ\}/' => '"',
209 '/\{@SQ\}/' => "'",
210 '/\{@DD\}/' => '--',
211 '/\{@NBS\}/' => ' '
212
213 );
Derek Jonesa633ec22008-12-11 14:31:33 +0000214
Derek Allard2067d1a2008-11-13 22:59:24 +0000215 // Do we need to reduce empty lines?
216 if ($reduce_linebreaks === TRUE)
217 {
218 $table['#<p>\n*</p>#'] = '';
219 }
220 else
221 {
222 // If we have empty paragraph tags we add a non-breaking space
223 // otherwise most browsers won't treat them as true paragraphs
224 $table['#<p></p>#'] = '<p>&nbsp;</p>';
225 }
226
227 return preg_replace(array_keys($table), $table, $str);
228
229 }
230
231 // --------------------------------------------------------------------
232
233 /**
Derek Allard2067d1a2008-11-13 22:59:24 +0000234 * Format Characters
235 *
236 * This function mainly converts double and single quotes
237 * to curly entities, but it also converts em-dashes,
238 * double spaces, and ampersands
239 *
240 * @access public
241 * @param string
242 * @return string
243 */
244 function format_characters($str)
245 {
246 static $table;
247
248 if ( ! isset($table))
249 {
Derek Jonesb859df82008-11-18 15:24:20 +0000250 $table = array(
Derek Allard2067d1a2008-11-13 22:59:24 +0000251 // nested smart quotes, opening and closing
252 // note that rules for grammar (English) allow only for two levels deep
253 // and that single quotes are _supposed_ to always be on the outside
254 // but we'll accommodate both
Derek Jonesb859df82008-11-18 15:24:20 +0000255 // Note that in all cases, whitespace is the primary determining factor
256 // on which direction to curl, with non-word characters like punctuation
257 // being a secondary factor only after whitespace is addressed.
258 '/\'"(\s|$)/' => '&#8217;&#8221;$1',
259 '/(^|\s)\'"/' => '$1&#8216;&#8220;',
260 '/\'"(\W)/' => '&#8217;&#8221;$1',
261 '/(\W)\'"/' => '$1&#8216;&#8220;',
262 '/"\'(\s|$)/' => '&#8221;&#8217;$1',
263 '/(^|\s)"\'/' => '$1&#8220;&#8216;',
264 '/"\'(\W)/' => '&#8221;&#8217;$1',
265 '/(\W)"\'/' => '$1&#8220;&#8216;',
Derek Allard2067d1a2008-11-13 22:59:24 +0000266
267 // single quote smart quotes
Derek Jonesb859df82008-11-18 15:24:20 +0000268 '/\'(\s|$)/' => '&#8217;$1',
269 '/(^|\s)\'/' => '$1&#8216;',
270 '/\'(\W)/' => '&#8217;$1',
271 '/(\W)\'/' => '$1&#8216;',
Derek Allard2067d1a2008-11-13 22:59:24 +0000272
273 // double quote smart quotes
Derek Jonesb859df82008-11-18 15:24:20 +0000274 '/"(\s|$)/' => '&#8221;$1',
275 '/(^|\s)"/' => '$1&#8220;',
276 '/"(\W)/' => '&#8221;$1',
277 '/(\W)"/' => '$1&#8220;',
278
Derek Allard2067d1a2008-11-13 22:59:24 +0000279 // apostrophes
Derek Jonesb859df82008-11-18 15:24:20 +0000280 "/(\w)'(\w)/" => '$1&#8217;$2',
Derek Allard2067d1a2008-11-13 22:59:24 +0000281
282 // Em dash and ellipses dots
283 '/\s?\-\-\s?/' => '&#8212;',
284 '/(\w)\.{3}/' => '$1&#8230;',
285
286 // double space after sentences
287 '/(\W) /' => '$1&nbsp; ',
288
289 // ampersands, if not a character entity
290 '/&(?!#?[a-zA-Z0-9]{2,};)/' => '&amp;'
Derek Jonesb859df82008-11-18 15:24:20 +0000291 );
292 }
Derek Allard2067d1a2008-11-13 22:59:24 +0000293
294 return preg_replace(array_keys($table), $table, $str);
295 }
296
297 // --------------------------------------------------------------------
298
299 /**
300 * Format Newlines
301 *
302 * Converts newline characters into either <p> tags or <br />
303 *
304 * @access public
305 * @param string
306 * @return string
307 */
308 function _format_newlines($str)
309 {
310 if ($str == '')
311 {
312 return $str;
313 }
Derek Jonesd5738d92008-11-14 16:53:34 +0000314
315 if (strpos($str, "\n") === FALSE && ! in_array($this->last_block_element, $this->inner_block_required))
Derek Allard2067d1a2008-11-13 22:59:24 +0000316 {
317 return $str;
318 }
319
320 // Convert two consecutive newlines to paragraphs
321 $str = str_replace("\n\n", "</p>\n\n<p>", $str);
322
323 // Convert single spaces to <br /> tags
324 $str = preg_replace("/([^\n])(\n)([^\n])/", "\\1<br />\\2\\3", $str);
325
326 // Wrap the whole enchilada in enclosing paragraphs
327 if ($str != "\n")
328 {
329 $str = '<p>'.$str.'</p>';
330 }
331
332 // Remove empty paragraphs if they are on the first line, as this
333 // is a potential unintended consequence of the previous code
334 $str = preg_replace("/<p><\/p>(.*)/", "\\1", $str, 1);
335
336 return $str;
337 }
338
339 // ------------------------------------------------------------------------
340
341 /**
Derek Jones7deecfb2008-12-11 15:38:01 +0000342 * Protect Characters
343 *
344 * Protects special characters from being formatted later
345 * We don't want quotes converted within tags so we'll temporarily convert them to {@DQ} and {@SQ}
346 * and we don't want double dashes converted to emdash entities, so they are marked with {@DD}
347 * likewise double spaces are converted to {@NBS} to prevent entity conversion
348 *
349 * @access public
350 * @param array
351 * @return string
352 */
353 function _protect_characters($match)
354 {
355 return str_replace(array("'",'"','--',' '), array('{@SQ}', '{@DQ}', '{@DD}', '{@NBS}'), $match[0]);
356 }
357
358 // --------------------------------------------------------------------
359
360 /**
Derek Allard2067d1a2008-11-13 22:59:24 +0000361 * Convert newlines to HTML line breaks except within PRE tags
362 *
363 * @access public
364 * @param string
365 * @return string
366 */
367 function nl2br_except_pre($str)
368 {
369 $ex = explode("pre>",$str);
370 $ct = count($ex);
371
372 $newstr = "";
373 for ($i = 0; $i < $ct; $i++)
374 {
375 if (($i % 2) == 0)
376 {
377 $newstr .= nl2br($ex[$i]);
378 }
379 else
380 {
381 $newstr .= $ex[$i];
382 }
383
384 if ($ct - 1 != $i)
385 $newstr .= "pre>";
386 }
387
388 return $newstr;
389 }
390
391}
392// END Typography Class
393
394/* End of file Typography.php */
Rick Ellis4c938ae2008-09-10 22:58:38 +0000395/* Location: ./system/libraries/Typography.php */