blob: 27fa421926e29a466049a55b6f2cb25638f14141 [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
91 // Convert quotes within tags to temporary markers. We don't want quotes converted
92 // within tags so we'll temporarily convert them to {@DQ} and {@SQ}
93 // and we don't want double dashes converted to emdash entities, so they are marked with {@DD}
94 // likewise double spaces are converted to {@NBS} to prevent entity conversion
95 if (preg_match_all("#\<.+?>#si", $str, $matches))
96 {
97 for ($i = 0, $total = count($matches[0]); $i < $total; $i++)
98 {
99 $str = str_replace($matches[0][$i],
100 str_replace(array("'",'"','--',' '), array('{@SQ}', '{@DQ}', '{@DD}', '{@NBS}'), $matches[0][$i]),
101 $str);
102 }
103 }
104
105 if ($this->protect_braced_quotes === TRUE)
106 {
107 if (preg_match_all("#\{.+?}#si", $str, $matches))
108 {
109 for ($i = 0, $total = count($matches[0]); $i < $total; $i++)
110 {
111 $str = str_replace($matches[0][$i],
112 str_replace(array("'",'"'), array('{@SQ}', '{@DQ}'), $matches[0][$i]),
113 $str);
114 }
115 }
116 }
117
118 // Convert "ignore" tags to temporary marker. The parser splits out the string at every tag
119 // it encounters. Certain inline tags, like image tags, links, span tags, etc. will be
120 // adversely affected if they are split out so we'll convert the opening bracket < temporarily to: {@TAG}
121 $str = preg_replace("#<(/*)(".$this->inline_elements.")([ >])#i", "{@TAG}\\1\\2\\3", $str);
122
123 // Split the string at every tag. This expression creates an array with this prototype:
124 //
125 // [array]
126 // {
127 // [0] = <opening tag>
128 // [1] = Content...
129 // [2] = <closing tag>
130 // Etc...
131 // }
132 $chunks = preg_split('/(<(?:[^<>]+(?:"[^"]*"|\'[^\']*\')?)+>)/', $str, -1, PREG_SPLIT_DELIM_CAPTURE|PREG_SPLIT_NO_EMPTY);
133
134 // Build our finalized string. We cycle through the array, skipping tags, and processing the contained text
135 $str = '';
136 $process = TRUE;
137 $paragraph = FALSE;
138 foreach ($chunks as $chunk)
139 {
140 // Are we dealing with a tag? If so, we'll skip the processing for this cycle.
141 // Well also set the "process" flag which allows us to skip <pre> tags and a few other things.
Derek Jonesd5738d92008-11-14 16:53:34 +0000142 if (preg_match("#<(/*)(".$this->block_elements.").*?\>#", $chunk, $match))
Derek Allard2067d1a2008-11-13 22:59:24 +0000143 {
144 if (preg_match("#".$this->skip_elements."#", $match[2]))
145 {
146 $process = ($match[1] == '/') ? TRUE : FALSE;
147 }
148
Derek Jonesd5738d92008-11-14 16:53:34 +0000149 if ($match[1] == '')
150 {
151 $this->last_block_element = $match[2];
152 }
153
Derek Allard2067d1a2008-11-13 22:59:24 +0000154 $str .= $chunk;
155 continue;
156 }
Derek Jonesd5738d92008-11-14 16:53:34 +0000157
Derek Allard2067d1a2008-11-13 22:59:24 +0000158 if ($process == FALSE)
159 {
160 $str .= $chunk;
161 continue;
162 }
Derek Jonesd5738d92008-11-14 16:53:34 +0000163
Derek Allard2067d1a2008-11-13 22:59:24 +0000164 // Convert Newlines into <p> and <br /> tags
Derek Jonesd5738d92008-11-14 16:53:34 +0000165 $str .= $this->_format_newlines($chunk);
Derek Allard2067d1a2008-11-13 22:59:24 +0000166 }
167
168 // is the whole of the content inside a block level element?
169 if ( ! preg_match("/^<(?:".$this->block_elements.")/i", $str, $match))
170 {
171 $str = "<p>{$str}</p>";
172 }
Derek Allard2067d1a2008-11-13 22:59:24 +0000173
Derek Jonesd5738d92008-11-14 16:53:34 +0000174 // Convert quotes, elipsis, and em-dashes
175 $str = $this->format_characters($str);
176
Derek Allard2067d1a2008-11-13 22:59:24 +0000177 // Final clean up
178 $table = array(
179
180 // If the user submitted their own paragraph tags within the text
181 // we will retain them instead of using our tags.
Derek Jonesd5738d92008-11-14 16:53:34 +0000182 '/(<p[^>*?]>)<p>/' => '$1', // <?php BBEdit syntax coloring bug fix
Derek Allard2067d1a2008-11-13 22:59:24 +0000183
184 // Reduce multiple instances of opening/closing paragraph tags to a single one
185 '#(</p>)+#' => '</p>',
186 '/(<p>\W*<p>)+/' => '<p>',
187
188 // Clean up stray paragraph tags that appear before block level elements
189 '#<p></p><('.$this->block_elements.')#' => '<$1',
Derek Allard2067d1a2008-11-13 22:59:24 +0000190
191 // Clean up stray non-breaking spaces preceeding block elements
192 '#[&nbsp; ]+<('.$this->block_elements.')#' => ' <$1',
Derek Jonesd5738d92008-11-14 16:53:34 +0000193
Derek Allard2067d1a2008-11-13 22:59:24 +0000194 // Replace the temporary markers we added earlier
195 '/\{@TAG\}/' => '<',
196 '/\{@DQ\}/' => '"',
197 '/\{@SQ\}/' => "'",
198 '/\{@DD\}/' => '--',
199 '/\{@NBS\}/' => ' '
200
201 );
Derek Jonesd5738d92008-11-14 16:53:34 +0000202
Derek Allard2067d1a2008-11-13 22:59:24 +0000203 // Do we need to reduce empty lines?
204 if ($reduce_linebreaks === TRUE)
205 {
206 $table['#<p>\n*</p>#'] = '';
207 }
208 else
209 {
210 // If we have empty paragraph tags we add a non-breaking space
211 // otherwise most browsers won't treat them as true paragraphs
212 $table['#<p></p>#'] = '<p>&nbsp;</p>';
213 }
214
215 return preg_replace(array_keys($table), $table, $str);
216
217 }
218
219 // --------------------------------------------------------------------
220
221 /**
Derek Allard2067d1a2008-11-13 22:59:24 +0000222 * Format Characters
223 *
224 * This function mainly converts double and single quotes
225 * to curly entities, but it also converts em-dashes,
226 * double spaces, and ampersands
227 *
228 * @access public
229 * @param string
230 * @return string
231 */
232 function format_characters($str)
233 {
234 static $table;
235
236 if ( ! isset($table))
237 {
Derek Jonesb859df82008-11-18 15:24:20 +0000238 $table = array(
Derek Allard2067d1a2008-11-13 22:59:24 +0000239 // nested smart quotes, opening and closing
240 // note that rules for grammar (English) allow only for two levels deep
241 // and that single quotes are _supposed_ to always be on the outside
242 // but we'll accommodate both
Derek Jonesb859df82008-11-18 15:24:20 +0000243 // Note that in all cases, whitespace is the primary determining factor
244 // on which direction to curl, with non-word characters like punctuation
245 // being a secondary factor only after whitespace is addressed.
246 '/\'"(\s|$)/' => '&#8217;&#8221;$1',
247 '/(^|\s)\'"/' => '$1&#8216;&#8220;',
248 '/\'"(\W)/' => '&#8217;&#8221;$1',
249 '/(\W)\'"/' => '$1&#8216;&#8220;',
250 '/"\'(\s|$)/' => '&#8221;&#8217;$1',
251 '/(^|\s)"\'/' => '$1&#8220;&#8216;',
252 '/"\'(\W)/' => '&#8221;&#8217;$1',
253 '/(\W)"\'/' => '$1&#8220;&#8216;',
Derek Allard2067d1a2008-11-13 22:59:24 +0000254
255 // single quote smart quotes
Derek Jonesb859df82008-11-18 15:24:20 +0000256 '/\'(\s|$)/' => '&#8217;$1',
257 '/(^|\s)\'/' => '$1&#8216;',
258 '/\'(\W)/' => '&#8217;$1',
259 '/(\W)\'/' => '$1&#8216;',
Derek Allard2067d1a2008-11-13 22:59:24 +0000260
261 // double quote smart quotes
Derek Jonesb859df82008-11-18 15:24:20 +0000262 '/"(\s|$)/' => '&#8221;$1',
263 '/(^|\s)"/' => '$1&#8220;',
264 '/"(\W)/' => '&#8221;$1',
265 '/(\W)"/' => '$1&#8220;',
266
Derek Allard2067d1a2008-11-13 22:59:24 +0000267 // apostrophes
Derek Jonesb859df82008-11-18 15:24:20 +0000268 "/(\w)'(\w)/" => '$1&#8217;$2',
Derek Allard2067d1a2008-11-13 22:59:24 +0000269
270 // Em dash and ellipses dots
271 '/\s?\-\-\s?/' => '&#8212;',
272 '/(\w)\.{3}/' => '$1&#8230;',
273
274 // double space after sentences
275 '/(\W) /' => '$1&nbsp; ',
276
277 // ampersands, if not a character entity
278 '/&(?!#?[a-zA-Z0-9]{2,};)/' => '&amp;'
Derek Jonesb859df82008-11-18 15:24:20 +0000279 );
280 }
Derek Allard2067d1a2008-11-13 22:59:24 +0000281
282 return preg_replace(array_keys($table), $table, $str);
283 }
284
285 // --------------------------------------------------------------------
286
287 /**
288 * Format Newlines
289 *
290 * Converts newline characters into either <p> tags or <br />
291 *
292 * @access public
293 * @param string
294 * @return string
295 */
296 function _format_newlines($str)
297 {
298 if ($str == '')
299 {
300 return $str;
301 }
Derek Jonesd5738d92008-11-14 16:53:34 +0000302
303 if (strpos($str, "\n") === FALSE && ! in_array($this->last_block_element, $this->inner_block_required))
Derek Allard2067d1a2008-11-13 22:59:24 +0000304 {
305 return $str;
306 }
307
308 // Convert two consecutive newlines to paragraphs
309 $str = str_replace("\n\n", "</p>\n\n<p>", $str);
310
311 // Convert single spaces to <br /> tags
312 $str = preg_replace("/([^\n])(\n)([^\n])/", "\\1<br />\\2\\3", $str);
313
314 // Wrap the whole enchilada in enclosing paragraphs
315 if ($str != "\n")
316 {
317 $str = '<p>'.$str.'</p>';
318 }
319
320 // Remove empty paragraphs if they are on the first line, as this
321 // is a potential unintended consequence of the previous code
322 $str = preg_replace("/<p><\/p>(.*)/", "\\1", $str, 1);
323
324 return $str;
325 }
326
327 // ------------------------------------------------------------------------
328
329 /**
330 * Convert newlines to HTML line breaks except within PRE tags
331 *
332 * @access public
333 * @param string
334 * @return string
335 */
336 function nl2br_except_pre($str)
337 {
338 $ex = explode("pre>",$str);
339 $ct = count($ex);
340
341 $newstr = "";
342 for ($i = 0; $i < $ct; $i++)
343 {
344 if (($i % 2) == 0)
345 {
346 $newstr .= nl2br($ex[$i]);
347 }
348 else
349 {
350 $newstr .= $ex[$i];
351 }
352
353 if ($ct - 1 != $i)
354 $newstr .= "pre>";
355 }
356
357 return $newstr;
358 }
359
360}
361// END Typography Class
362
363/* End of file Typography.php */
Rick Ellis4c938ae2008-09-10 22:58:38 +0000364/* Location: ./system/libraries/Typography.php */