blob: bc3baeb5dae14601460e775ea6158978c58e16d0 [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
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
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 = 'div|blockquote|pre|code|h\d|script|ol|ul';
31
32 // Elements that should not have <p> and <br /> tags within them.
33 var $skip_elements = 'pre|ol|ul';
34
35 // Tags we want the parser to completely ignore when splitting the string.
36 var $ignore_elements = 'a|b|i|em|strong|span|img|li';
37
Rick Ellis18bd8b52008-09-10 23:40:35 +000038 // Whether to allow Javascript event handlers to be sumitted inside tags
39 var $allow_js_event_handlers = FALSE;
Rick Ellis4c938ae2008-09-10 22:58:38 +000040
41 /**
42 * Main Processing Function
43 *
44 */
45 function convert($str)
46 {
47 if ($str == '')
48 {
49 return '';
50 }
51
52 $str = ' '.$str.' ';
53
54 // Standardize Newlines to make matching easier
55 if (strpos($str, "\r") !== FALSE)
56 {
57 $str = str_replace(array("\r\n", "\r"), "\n", $str);
58 }
59
60 /*
61 * Reduce line breaks
62 *
63 * If there are more than two consecutive line
64 * breaks we'll compress them down to a maximum
65 * of two since there's no benefit to more.
66 *
67 */
68 $str = preg_replace("/\n\n+/", "\n\n", $str);
69
70 /*
Rick Ellis18bd8b52008-09-10 23:40:35 +000071 * Do we allow JavaScript event handlers?
72 *
73 * If not, we strip them from within all tags
74 */
75 if ($this->allow_js_event_handlers == FALSE)
76 {
77 $event_handlers = array('[^a-z_\-]on\w*','xmlns');
78 $str = preg_replace("#<([^><]+?)(".implode('|', $event_handlers).")(\s*=\s*[^><]*)([><]*)#i", "<\\1\\4", $str);
79 }
80
81 /*
Rick Ellis4c938ae2008-09-10 22:58:38 +000082 * Convert quotes within tags to temporary marker
83 *
84 * We don't want quotes converted within
85 * tags so we'll temporarily convert them to
86 * {@DQ} and {@SQ}
87 *
88 */
89 if (preg_match_all("#\<.+?>#si", $str, $matches))
90 {
91 for ($i = 0; $i < count($matches['0']); $i++)
92 {
93 $str = str_replace($matches['0'][$i],
94 str_replace(array("'",'"'), array('{@SQ}', '{@DQ}'), $matches['0'][$i]),
95 $str);
96 }
97 }
Rick Ellis4c938ae2008-09-10 22:58:38 +000098
Rick Ellis18bd8b52008-09-10 23:40:35 +000099 /*
Rick Ellis4c938ae2008-09-10 22:58:38 +0000100 * Add closing/opening paragraph tags before/after "block" elements
101 *
102 * Since block elements (like <blockquotes>, <pre>, etc.) do not get
103 * wrapped in paragraph tags we will add a closing </p> tag just before
104 * each block element starts and an opening <p> tag right after the block element
105 * ends. Later on we'll do some further clean up.
106 *
107 */
108 $str = preg_replace("#(<)(".$this->block_elements.")(.*?>)#", "</p>\\1\\2\\3", $str);
109 $str = preg_replace("#(</)(".$this->block_elements.")(.*?>)#", "\\1\\2\\3<p>", $str);
110
111 /*
112 * Convert "ignore" tags to temporary marker
113 *
114 * The parser splits out the string at every tag
115 * it encounters. Certain inline tags, like image
116 * tags, links, span tags, etc. will be adversely
117 * affected if they are split out so we'll convert
118 * the opening < temporarily to: {@TAG}
119 *
120 */
121 $str = preg_replace("#<(/*)(".$this->ignore_elements.")#i", "{@TAG}\\1\\2", $str);
122
123 /*
124 * Split the string at every tag
125 *
126 * This creates an array with this prototype:
127 *
128 * [array]
129 * {
130 * [0] = <opening tag>
131 * [1] = Content contained between the tags
132 * [2] = <closing tag>
133 * Etc...
134 * }
135 *
136 */
137 $chunks = preg_split('/(<(?:[^<>]+(?:"[^"]*"|\'[^\']*\')?)+>)/', $str, -1, PREG_SPLIT_DELIM_CAPTURE|PREG_SPLIT_NO_EMPTY);
138
139 /*
140 * Build our finalized string
141 *
142 * We'll cycle through the array, skipping tags,
143 * and processing the contained text
144 *
145 */
146 $str = '';
147 $process = TRUE;
148 foreach ($chunks as $chunk)
149 {
150 /*
151 * Are we dealing with a tag?
152 *
153 * If so, we'll skip the processing for this cycle.
154 * Well also set the "process" flag which allows us
155 * to skip <pre> tags and a few other things.
156 *
157 */
158 if (preg_match("#<(/*)(".$this->block_elements.").*?\>#", $chunk, $match))
159 {
160 if (preg_match("#".$this->skip_elements."#", $match['2']))
161 {
162 $process = ($match['1'] == '/') ? TRUE : FALSE;
163 }
164
165 $str .= $chunk;
166 continue;
167 }
168
169 if ($process == FALSE)
170 {
171 $str .= $chunk;
172 continue;
173 }
174
175 // Convert Newlines into <p> and <br /> tags
176 $str .= $this->format_newlines($chunk);
177 }
178
179 // FINAL CLEAN UP
180 // IMPORTANT: DO NOT ALTER THE ORDER OF THE ITEMS BELOW!
181
182 /*
183 * Clean up paragraph tags before/after "block" elements
184 *
185 * Earlier we added <p></p> tags before/after block level elements.
186 * Then, we added paragraph tags around double line breaks. This
187 * potentially created incorrectly formatted paragraphs so we'll
188 * clean it up here.
189 *
190 */
191 $str = preg_replace("#<p>({@TAG}.*?)(".$this->block_elements.")(.*?>)#", "\\1\\2\\3", $str);
192 $str = preg_replace("#({@TAG}/.*?)(".$this->block_elements.")(.*?>)</p>#", "\\1\\2\\3", $str);
193
194 // Convert Quotes and other characters
195 $str = $this->format_characters($str);
196
197 // Fix an artifact that happens during the paragraph replacement
198 $str = preg_replace('#(<p>\n*</p>)#', '', $str);
199
200 // If the user submitted their own paragraph tags with class data
201 // in them we will retain them instead of using our tags.
Rick Ellis18bd8b52008-09-10 23:40:35 +0000202 $str = preg_replace('#(<p.*?>)<p>#', "\\1", $str); // <?php BBEdit syntax coloring fix
Rick Ellis4c938ae2008-09-10 22:58:38 +0000203
204 // Final clean up
205 $str = str_replace(
206 array(
207 '</p></p>',
208 '</p><p>',
209 '<p> ',
210 ' </p>',
211 '{@TAG}',
212 '{@DQ}',
213 '{@SQ}',
214 '<p></p>'
215 ),
216 array(
217 '</p>',
218 '<p>',
219 '<p>',
220 '</p>',
221 '<',
222 '"',
223 "'",
224 ''
225 ),
226 $str
227 );
228
229 return $str;
230 }
231
232 // --------------------------------------------------------------------
233
234 /**
235 * Format Characters
236 *
237 * This function mainly converts double and single quotes
Derek Jonesab504b82008-09-11 17:04:30 +0000238 * to curly entities, but it also converts em-dashes,
239 * double spaces, and ampersands
Rick Ellis4c938ae2008-09-10 22:58:38 +0000240 */
241 function format_characters($str)
Derek Jonesab504b82008-09-11 17:04:30 +0000242 {
243 static $table;
244
245 if ( ! isset($table))
246 {
247 $table = array(
248 // nested smart quotes, opening and closing
249 // note that rules for grammar (English) allow only for two levels deep
250 // and that single quotes are _supposed_ to always be on the outside
251 // but we'll accommodate both
252 '/(^|\W|\s)\'"/' => '$1&#8216;&#8220;',
253 '/\'"(\s|\W|$)/' => '&#8217;&#8221;$1',
254 '/(^|\W|\s)"\'/' => '$1&#8220;&#8216;',
255 '/"\'(\s|\W|$)/' => '&#8221;&#8217;$1',
Rick Ellis4c938ae2008-09-10 22:58:38 +0000256
Derek Jonesab504b82008-09-11 17:04:30 +0000257 // single quote smart quotes
258 '/\'(\s|\W|$)/' => '&#8217;$1',
259 '/(^|\W|\s)\'/' => '$1&#8216;',
Rick Ellis4c938ae2008-09-10 22:58:38 +0000260
Derek Jonesab504b82008-09-11 17:04:30 +0000261 // double quote smart quotes
262 '/"(\s|\W|$)/' => '&#8221;$1',
263 '/(^|\W|\s)"/' => '$1&#8220;',
Rick Ellis4c938ae2008-09-10 22:58:38 +0000264
Derek Jonesab504b82008-09-11 17:04:30 +0000265 // apostrophes
266 "/(\w)'(\w)/" => '$1&#8217;$2',
267
268 // Em dash and ellipses dots
269 '/\s?\-\-\s?/' => '&#8212;',
270 '/\w\.{3}/' => '&#8230;',
271
272 // double space after sentences
273 '/(\W)\s{2}/' => '$1&nbsp; ',
274
275 // ampersands, if not a character entity
276 '/&(?!#?[a-zA-Z0-9]{2,};)/' => '&amp;'
277 );
278 }
279
280 return preg_replace(array_keys($table), $table, $str);
Rick Ellis4c938ae2008-09-10 22:58:38 +0000281 }
282
283 // --------------------------------------------------------------------
284
285 /**
286 * Format Newlines
287 *
288 * Converts newline characters into either <p> tags or <br />
289 *
290 */
291 function format_newlines($str)
292 {
293 if ($str == '')
294 {
295 return $str;
296 }
297
298 if (strpos($str, "\n") === FALSE)
299 {
300 return '<p>'.$str.'</p>';
301 }
302
303 $str = str_replace("\n\n", "</p>\n\n<p>", $str);
304 $str = preg_replace("/([^\n])(\n)([^\n])/", "\\1<br />\\2\\3", $str);
305
306 return '<p>'.$str.'</p>';
Rick Ellis18bd8b52008-09-10 23:40:35 +0000307 }
308
309 // --------------------------------------------------------------------
310
311 /**
312 * Allow JavaScript Event Handlers?
313 *
314 * For security reasons, by default we disallow JS event handlers
315 *
316 */
317 function allow_js_event_handlers($val = FALSE)
318 {
319 $this->allow_js_event_handlers = ($val === FALSE) ? FALSE : TRUE;
320 }
321
322
Rick Ellis4c938ae2008-09-10 22:58:38 +0000323}
324// END Typography Class
325
326/* End of file Typography.php */
327/* Location: ./system/libraries/Typography.php */