blob: fa1ec19994bea2bb828693dd831e9b36807dae9e [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 }
104
Derek Allard2067d1a2008-11-13 22:59:24 +0000105 // Convert quotes within tags to temporary markers. We don't want quotes converted
106 // within tags so we'll temporarily convert them to {@DQ} and {@SQ}
107 // and we don't want double dashes converted to emdash entities, so they are marked with {@DD}
108 // likewise double spaces are converted to {@NBS} to prevent entity conversion
Derek Jonesa633ec22008-12-11 14:31:33 +0000109 if (preg_match_all("#<.+?>#si", $str, $matches))
Derek Allard2067d1a2008-11-13 22:59:24 +0000110 {
111 for ($i = 0, $total = count($matches[0]); $i < $total; $i++)
112 {
113 $str = str_replace($matches[0][$i],
114 str_replace(array("'",'"','--',' '), array('{@SQ}', '{@DQ}', '{@DD}', '{@NBS}'), $matches[0][$i]),
115 $str);
116 }
117 }
118
119 if ($this->protect_braced_quotes === TRUE)
120 {
Derek Jonesa633ec22008-12-11 14:31:33 +0000121 if (preg_match_all("#\{.+?\}#si", $str, $matches))
Derek Allard2067d1a2008-11-13 22:59:24 +0000122 {
123 for ($i = 0, $total = count($matches[0]); $i < $total; $i++)
124 {
125 $str = str_replace($matches[0][$i],
126 str_replace(array("'",'"'), array('{@SQ}', '{@DQ}'), $matches[0][$i]),
127 $str);
128 }
129 }
130 }
Derek Jonesa633ec22008-12-11 14:31:33 +0000131
Derek Allard2067d1a2008-11-13 22:59:24 +0000132 // Convert "ignore" tags to temporary marker. The parser splits out the string at every tag
133 // it encounters. Certain inline tags, like image tags, links, span tags, etc. will be
134 // adversely affected if they are split out so we'll convert the opening bracket < temporarily to: {@TAG}
135 $str = preg_replace("#<(/*)(".$this->inline_elements.")([ >])#i", "{@TAG}\\1\\2\\3", $str);
136
137 // Split the string at every tag. This expression creates an array with this prototype:
138 //
139 // [array]
140 // {
141 // [0] = <opening tag>
142 // [1] = Content...
143 // [2] = <closing tag>
144 // Etc...
145 // }
146 $chunks = preg_split('/(<(?:[^<>]+(?:"[^"]*"|\'[^\']*\')?)+>)/', $str, -1, PREG_SPLIT_DELIM_CAPTURE|PREG_SPLIT_NO_EMPTY);
147
148 // Build our finalized string. We cycle through the array, skipping tags, and processing the contained text
149 $str = '';
150 $process = TRUE;
151 $paragraph = FALSE;
152 foreach ($chunks as $chunk)
153 {
154 // Are we dealing with a tag? If so, we'll skip the processing for this cycle.
155 // Well also set the "process" flag which allows us to skip <pre> tags and a few other things.
Derek Jonesa633ec22008-12-11 14:31:33 +0000156 if (preg_match("#<(/*)(".$this->block_elements.")[\s.]*?>#", $chunk, $match))
Derek Allard2067d1a2008-11-13 22:59:24 +0000157 {
158 if (preg_match("#".$this->skip_elements."#", $match[2]))
159 {
160 $process = ($match[1] == '/') ? TRUE : FALSE;
161 }
162
Derek Jonesd5738d92008-11-14 16:53:34 +0000163 if ($match[1] == '')
164 {
165 $this->last_block_element = $match[2];
166 }
167
Derek Allard2067d1a2008-11-13 22:59:24 +0000168 $str .= $chunk;
169 continue;
170 }
Derek Jonesd5738d92008-11-14 16:53:34 +0000171
Derek Allard2067d1a2008-11-13 22:59:24 +0000172 if ($process == FALSE)
173 {
Derek Jonesa633ec22008-12-11 14:31:33 +0000174 $str .= ($this->last_block_element == 'pre') ? $chunk : $this->format_characters($chunk);
Derek Allard2067d1a2008-11-13 22:59:24 +0000175 continue;
176 }
Derek Jonesd5738d92008-11-14 16:53:34 +0000177
Derek Allard2067d1a2008-11-13 22:59:24 +0000178 // Convert Newlines into <p> and <br /> tags
Derek Jonesa633ec22008-12-11 14:31:33 +0000179 $str .= $this->format_characters($this->_format_newlines($chunk));
Derek Allard2067d1a2008-11-13 22:59:24 +0000180 }
181
182 // is the whole of the content inside a block level element?
Derek Jonesa633ec22008-12-11 14:31:33 +0000183 if ( ! preg_match("/^\s*<(?:".$this->block_elements.")/i", $str, $match))
Derek Allard2067d1a2008-11-13 22:59:24 +0000184 {
185 $str = "<p>{$str}</p>";
186 }
Derek Jonesa633ec22008-12-11 14:31:33 +0000187
188 // restore HTML comments
189 for ($i = 0, $total = count($html_comments); $i < $total; $i++)
190 {
191 $str = preg_replace('#(?:<p>)?{@HC'.$i.'}(?:\s*</p>)?#s', $html_comments[$i], $str);
192 }
193
Derek Allard2067d1a2008-11-13 22:59:24 +0000194 // Final clean up
195 $table = array(
196
197 // If the user submitted their own paragraph tags within the text
198 // we will retain them instead of using our tags.
Derek Jonesd5738d92008-11-14 16:53:34 +0000199 '/(<p[^>*?]>)<p>/' => '$1', // <?php BBEdit syntax coloring bug fix
Derek Allard2067d1a2008-11-13 22:59:24 +0000200
201 // Reduce multiple instances of opening/closing paragraph tags to a single one
202 '#(</p>)+#' => '</p>',
203 '/(<p>\W*<p>)+/' => '<p>',
204
205 // Clean up stray paragraph tags that appear before block level elements
206 '#<p></p><('.$this->block_elements.')#' => '<$1',
Derek Allard2067d1a2008-11-13 22:59:24 +0000207
208 // Clean up stray non-breaking spaces preceeding block elements
209 '#[&nbsp; ]+<('.$this->block_elements.')#' => ' <$1',
Derek Jonesd5738d92008-11-14 16:53:34 +0000210
Derek Allard2067d1a2008-11-13 22:59:24 +0000211 // Replace the temporary markers we added earlier
212 '/\{@TAG\}/' => '<',
213 '/\{@DQ\}/' => '"',
214 '/\{@SQ\}/' => "'",
215 '/\{@DD\}/' => '--',
216 '/\{@NBS\}/' => ' '
217
218 );
Derek Jonesa633ec22008-12-11 14:31:33 +0000219
Derek Allard2067d1a2008-11-13 22:59:24 +0000220 // Do we need to reduce empty lines?
221 if ($reduce_linebreaks === TRUE)
222 {
223 $table['#<p>\n*</p>#'] = '';
224 }
225 else
226 {
227 // If we have empty paragraph tags we add a non-breaking space
228 // otherwise most browsers won't treat them as true paragraphs
229 $table['#<p></p>#'] = '<p>&nbsp;</p>';
230 }
231
232 return preg_replace(array_keys($table), $table, $str);
233
234 }
235
236 // --------------------------------------------------------------------
237
238 /**
Derek Allard2067d1a2008-11-13 22:59:24 +0000239 * Format Characters
240 *
241 * This function mainly converts double and single quotes
242 * to curly entities, but it also converts em-dashes,
243 * double spaces, and ampersands
244 *
245 * @access public
246 * @param string
247 * @return string
248 */
249 function format_characters($str)
250 {
251 static $table;
252
253 if ( ! isset($table))
254 {
Derek Jonesb859df82008-11-18 15:24:20 +0000255 $table = array(
Derek Allard2067d1a2008-11-13 22:59:24 +0000256 // nested smart quotes, opening and closing
257 // note that rules for grammar (English) allow only for two levels deep
258 // and that single quotes are _supposed_ to always be on the outside
259 // but we'll accommodate both
Derek Jonesb859df82008-11-18 15:24:20 +0000260 // Note that in all cases, whitespace is the primary determining factor
261 // on which direction to curl, with non-word characters like punctuation
262 // being a secondary factor only after whitespace is addressed.
263 '/\'"(\s|$)/' => '&#8217;&#8221;$1',
264 '/(^|\s)\'"/' => '$1&#8216;&#8220;',
265 '/\'"(\W)/' => '&#8217;&#8221;$1',
266 '/(\W)\'"/' => '$1&#8216;&#8220;',
267 '/"\'(\s|$)/' => '&#8221;&#8217;$1',
268 '/(^|\s)"\'/' => '$1&#8220;&#8216;',
269 '/"\'(\W)/' => '&#8221;&#8217;$1',
270 '/(\W)"\'/' => '$1&#8220;&#8216;',
Derek Allard2067d1a2008-11-13 22:59:24 +0000271
272 // single quote smart quotes
Derek Jonesb859df82008-11-18 15:24:20 +0000273 '/\'(\s|$)/' => '&#8217;$1',
274 '/(^|\s)\'/' => '$1&#8216;',
275 '/\'(\W)/' => '&#8217;$1',
276 '/(\W)\'/' => '$1&#8216;',
Derek Allard2067d1a2008-11-13 22:59:24 +0000277
278 // double quote smart quotes
Derek Jonesb859df82008-11-18 15:24:20 +0000279 '/"(\s|$)/' => '&#8221;$1',
280 '/(^|\s)"/' => '$1&#8220;',
281 '/"(\W)/' => '&#8221;$1',
282 '/(\W)"/' => '$1&#8220;',
283
Derek Allard2067d1a2008-11-13 22:59:24 +0000284 // apostrophes
Derek Jonesb859df82008-11-18 15:24:20 +0000285 "/(\w)'(\w)/" => '$1&#8217;$2',
Derek Allard2067d1a2008-11-13 22:59:24 +0000286
287 // Em dash and ellipses dots
288 '/\s?\-\-\s?/' => '&#8212;',
289 '/(\w)\.{3}/' => '$1&#8230;',
290
291 // double space after sentences
292 '/(\W) /' => '$1&nbsp; ',
293
294 // ampersands, if not a character entity
295 '/&(?!#?[a-zA-Z0-9]{2,};)/' => '&amp;'
Derek Jonesb859df82008-11-18 15:24:20 +0000296 );
297 }
Derek Allard2067d1a2008-11-13 22:59:24 +0000298
299 return preg_replace(array_keys($table), $table, $str);
300 }
301
302 // --------------------------------------------------------------------
303
304 /**
305 * Format Newlines
306 *
307 * Converts newline characters into either <p> tags or <br />
308 *
309 * @access public
310 * @param string
311 * @return string
312 */
313 function _format_newlines($str)
314 {
315 if ($str == '')
316 {
317 return $str;
318 }
Derek Jonesd5738d92008-11-14 16:53:34 +0000319
320 if (strpos($str, "\n") === FALSE && ! in_array($this->last_block_element, $this->inner_block_required))
Derek Allard2067d1a2008-11-13 22:59:24 +0000321 {
322 return $str;
323 }
324
325 // Convert two consecutive newlines to paragraphs
326 $str = str_replace("\n\n", "</p>\n\n<p>", $str);
327
328 // Convert single spaces to <br /> tags
329 $str = preg_replace("/([^\n])(\n)([^\n])/", "\\1<br />\\2\\3", $str);
330
331 // Wrap the whole enchilada in enclosing paragraphs
332 if ($str != "\n")
333 {
334 $str = '<p>'.$str.'</p>';
335 }
336
337 // Remove empty paragraphs if they are on the first line, as this
338 // is a potential unintended consequence of the previous code
339 $str = preg_replace("/<p><\/p>(.*)/", "\\1", $str, 1);
340
341 return $str;
342 }
343
344 // ------------------------------------------------------------------------
345
346 /**
347 * Convert newlines to HTML line breaks except within PRE tags
348 *
349 * @access public
350 * @param string
351 * @return string
352 */
353 function nl2br_except_pre($str)
354 {
355 $ex = explode("pre>",$str);
356 $ct = count($ex);
357
358 $newstr = "";
359 for ($i = 0; $i < $ct; $i++)
360 {
361 if (($i % 2) == 0)
362 {
363 $newstr .= nl2br($ex[$i]);
364 }
365 else
366 {
367 $newstr .= $ex[$i];
368 }
369
370 if ($ct - 1 != $i)
371 $newstr .= "pre>";
372 }
373
374 return $newstr;
375 }
376
377}
378// END Typography Class
379
380/* End of file Typography.php */
Rick Ellis4c938ae2008-09-10 22:58:38 +0000381/* Location: ./system/libraries/Typography.php */