1
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
5
* An open source application development framework for PHP 5.1.6 or newer
8
* @author ExpressionEngine Dev Team
9
* @copyright Copyright (c) 2008 - 2011, EllisLab, Inc.
10
* @license http://codeigniter.com/user_guide/license.html
11
* @link http://codeigniter.com
16
// ------------------------------------------------------------------------
24
* @author ExpressionEngine Dev Team
25
* @link http://codeigniter.com/user_guide/helpers/
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';
32
// Elements that should not have <p> and <br /> tags within them.
33
var $skip_elements = 'p|pre|ol|ul|dl|object|table|h\d';
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';
38
// array of block level elements that require inner content to be within another block level element
39
var $inner_block_required = array('blockquote');
41
// the last block element parsed
42
var $last_block_element = '';
44
// whether or not to protect quotes within { curly braces }
45
var $protect_braced_quotes = FALSE;
50
* This function converts text, making it typographically correct:
51
* - Converts double spaces into paragraphs.
52
* - Converts single line breaks into <br /> tags
53
* - Converts single and double quotes into correctly facing curly quote entities.
54
* - Converts three dots into ellipsis.
55
* - Converts double dashes into em-dashes.
56
* - Converts two spaces into entities
60
* @param bool whether to reduce more then two consecutive newlines to two
63
function auto_typography($str, $reduce_linebreaks = FALSE)
70
// Standardize Newlines to make matching easier
71
if (strpos($str, "\r") !== FALSE)
73
$str = str_replace(array("\r\n", "\r"), "\n", $str);
76
// Reduce line breaks. If there are more than two consecutive linebreaks
77
// we'll compress them down to a maximum of two since there's no benefit to more.
78
if ($reduce_linebreaks === TRUE)
80
$str = preg_replace("/\n\n+/", "\n\n", $str);
83
// HTML comment tags don't conform to patterns of normal tags, so pull them out separately, only if needed
84
$html_comments = array();
85
if (strpos($str, '<!--') !== FALSE)
87
if (preg_match_all("#(<!\-\-.*?\-\->)#s", $str, $matches))
89
for ($i = 0, $total = count($matches[0]); $i < $total; $i++)
91
$html_comments[] = $matches[0][$i];
92
$str = str_replace($matches[0][$i], '{@HC'.$i.'}', $str);
97
// match and yank <pre> tags if they exist. It's cheaper to do this separately since most content will
98
// not contain <pre> tags, and it keeps the PCRE patterns below simpler and faster
99
if (strpos($str, '<pre') !== FALSE)
101
$str = preg_replace_callback("#<pre.*?>.*?</pre>#si", array($this, '_protect_characters'), $str);
104
// Convert quotes within tags to temporary markers.
105
$str = preg_replace_callback("#<.+?>#si", array($this, '_protect_characters'), $str);
107
// Do the same with braces if necessary
108
if ($this->protect_braced_quotes === TRUE)
110
$str = preg_replace_callback("#\{.+?\}#si", array($this, '_protect_characters'), $str);
113
// Convert "ignore" tags to temporary marker. The parser splits out the string at every tag
114
// it encounters. Certain inline tags, like image tags, links, span tags, etc. will be
115
// adversely affected if they are split out so we'll convert the opening bracket < temporarily to: {@TAG}
116
$str = preg_replace("#<(/*)(".$this->inline_elements.")([ >])#i", "{@TAG}\\1\\2\\3", $str);
118
// Split the string at every tag. This expression creates an array with this prototype:
122
// [0] = <opening tag>
124
// [2] = <closing tag>
127
$chunks = preg_split('/(<(?:[^<>]+(?:"[^"]*"|\'[^\']*\')?)+>)/', $str, -1, PREG_SPLIT_DELIM_CAPTURE|PREG_SPLIT_NO_EMPTY);
129
// Build our finalized string. We cycle through the array, skipping tags, and processing the contained text
134
$total_chunks = count($chunks);
136
foreach ($chunks as $chunk)
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.
142
if (preg_match("#<(/*)(".$this->block_elements.").*?>#", $chunk, $match))
144
if (preg_match("#".$this->skip_elements."#", $match[2]))
146
$process = ($match[1] == '/') ? TRUE : FALSE;
151
$this->last_block_element = $match[2];
158
if ($process == FALSE)
164
// Force a newline to make sure end tags get processed by _format_newlines()
165
if ($current_chunk == $total_chunks)
170
// Convert Newlines into <p> and <br /> tags
171
$str .= $this->_format_newlines($chunk);
174
// No opening block level tag? Add it if needed.
175
if ( ! preg_match("/^\s*<(?:".$this->block_elements.")/i", $str))
177
$str = preg_replace("/^(.*?)<(".$this->block_elements.")/i", '<p>$1</p><$2', $str);
180
// Convert quotes, elipsis, em-dashes, non-breaking spaces, and ampersands
181
$str = $this->format_characters($str);
183
// restore HTML comments
184
for ($i = 0, $total = count($html_comments); $i < $total; $i++)
186
// remove surrounding paragraph tags, but only if there's an opening paragraph tag
187
// otherwise HTML comments at the ends of paragraphs will have the closing tag removed
188
// if '<p>{@HC1}' then replace <p>{@HC1}</p> with the comment, else replace only {@HC1} with the comment
189
$str = preg_replace('#(?(?=<p>\{@HC'.$i.'\})<p>\{@HC'.$i.'\}(\s*</p>)|\{@HC'.$i.'\})#s', $html_comments[$i], $str);
195
// If the user submitted their own paragraph tags within the text
196
// we will retain them instead of using our tags.
197
'/(<p[^>*?]>)<p>/' => '$1', // <?php BBEdit syntax coloring bug fix
199
// Reduce multiple instances of opening/closing paragraph tags to a single one
200
'#(</p>)+#' => '</p>',
201
'/(<p>\W*<p>)+/' => '<p>',
203
// Clean up stray paragraph tags that appear before block level elements
204
'#<p></p><('.$this->block_elements.')#' => '<$1',
206
// Clean up stray non-breaking spaces preceeding block elements
207
'#( \s*)+<('.$this->block_elements.')#' => ' <$2',
209
// Replace the temporary markers we added earlier
216
// An unintended consequence of the _format_newlines function is that
217
// some of the newlines get truncated, resulting in <p> tags
218
// starting immediately after <block> tags on the same line.
219
// This forces a newline after such occurrences, which looks much nicer.
220
"/><p>\n/" => ">\n<p>",
222
// Similarly, there might be cases where a closing </block> will follow
223
// a closing </p> tag, so we'll correct it by adding a newline in between
224
"#</p></#" => "</p>\n</"
227
// Do we need to reduce empty lines?
228
if ($reduce_linebreaks === TRUE)
230
$table['#<p>\n*</p>#'] = '';
234
// If we have empty paragraph tags we add a non-breaking space
235
// otherwise most browsers won't treat them as true paragraphs
236
$table['#<p></p>#'] = '<p> </p>';
239
return preg_replace(array_keys($table), $table, $str);
243
// --------------------------------------------------------------------
248
* This function mainly converts double and single quotes
249
* to curly entities, but it also converts em-dashes,
250
* double spaces, and ampersands
256
function format_characters($str)
260
if ( ! isset($table))
263
// nested smart quotes, opening and closing
264
// note that rules for grammar (English) allow only for two levels deep
265
// and that single quotes are _supposed_ to always be on the outside
266
// but we'll accommodate both
267
// Note that in all cases, whitespace is the primary determining factor
268
// on which direction to curl, with non-word characters like punctuation
269
// being a secondary factor only after whitespace is addressed.
270
'/\'"(\s|$)/' => '’”$1',
271
'/(^|\s|<p>)\'"/' => '$1‘“',
272
'/\'"(\W)/' => '’”$1',
273
'/(\W)\'"/' => '$1‘“',
274
'/"\'(\s|$)/' => '”’$1',
275
'/(^|\s|<p>)"\'/' => '$1“‘',
276
'/"\'(\W)/' => '”’$1',
277
'/(\W)"\'/' => '$1“‘',
279
// single quote smart quotes
280
'/\'(\s|$)/' => '’$1',
281
'/(^|\s|<p>)\'/' => '$1‘',
282
'/\'(\W)/' => '’$1',
283
'/(\W)\'/' => '$1‘',
285
// double quote smart quotes
286
'/"(\s|$)/' => '”$1',
287
'/(^|\s|<p>)"/' => '$1“',
288
'/"(\W)/' => '”$1',
289
'/(\W)"/' => '$1“',
292
"/(\w)'(\w)/" => '$1’$2',
294
// Em dash and ellipses dots
295
'/\s?\-\-\s?/' => '—',
296
'/(\w)\.{3}/' => '$1…',
298
// double space after sentences
299
'/(\W) /' => '$1 ',
301
// ampersands, if not a character entity
302
'/&(?!#?[a-zA-Z0-9]{2,};)/' => '&'
306
return preg_replace(array_keys($table), $table, $str);
309
// --------------------------------------------------------------------
314
* Converts newline characters into either <p> tags or <br />
320
function _format_newlines($str)
327
if (strpos($str, "\n") === FALSE && ! in_array($this->last_block_element, $this->inner_block_required))
332
// Convert two consecutive newlines to paragraphs
333
$str = str_replace("\n\n", "</p>\n\n<p>", $str);
335
// Convert single spaces to <br /> tags
336
$str = preg_replace("/([^\n])(\n)([^\n])/", "\\1<br />\\2\\3", $str);
338
// Wrap the whole enchilada in enclosing paragraphs
341
// We trim off the right-side new line so that the closing </p> tag
342
// will be positioned immediately following the string, matching
343
// the behavior of the opening <p> tag
344
$str = '<p>'.rtrim($str).'</p>';
347
// Remove empty paragraphs if they are on the first line, as this
348
// is a potential unintended consequence of the previous code
349
$str = preg_replace("/<p><\/p>(.*)/", "\\1", $str, 1);
354
// ------------------------------------------------------------------------
359
* Protects special characters from being formatted later
360
* We don't want quotes converted within tags so we'll temporarily convert them to {@DQ} and {@SQ}
361
* and we don't want double dashes converted to emdash entities, so they are marked with {@DD}
362
* likewise double spaces are converted to {@NBS} to prevent entity conversion
368
function _protect_characters($match)
370
return str_replace(array("'",'"','--',' '), array('{@SQ}', '{@DQ}', '{@DD}', '{@NBS}'), $match[0]);
373
// --------------------------------------------------------------------
376
* Convert newlines to HTML line breaks except within PRE tags
382
function nl2br_except_pre($str)
384
$ex = explode("pre>",$str);
388
for ($i = 0; $i < $ct; $i++)
392
$newstr .= nl2br($ex[$i]);
407
// END Typography Class
409
/* End of file Typography.php */
410
/* Location: ./system/libraries/Typography.php */
b'\\ No newline at end of file'