Fixes deprecated features in PHP 5.3.x.
[banana.git] / banana / message.func.inc.php
CommitLineData
7027794f 1<?php
2/********************************************************************************
3 * * banana/message.func.inc.php : function to display messages
4 * * ------------------------
5 * *
6 * * This file is part of the banana distribution
7 * * Copyright: See COPYING files that comes with this distribution
8 * ********************************************************************************/
9
10require_once dirname(__FILE__) . '/mimepart.inc.php';
11require_once dirname(__FILE__) . '/banana.inc.php';
12
13// {{{ Plain Text Functions
14
15function banana_isFlowed($line)
16{
17 return ctype_space(substr($line, -1)) && $line != '-- ';
18}
19
20function banana_removeQuotes($line, &$quote_level, $strict = true)
21{
22 $quote_level = 0;
23 if (empty($line)) {
24 return '';
25 }
26 while ($line{0} == '>') {
27 $line = substr($line, 1);
28 if (!$strict && ctype_space($line{0})) {
29 $line = substr($line, 1);
30 }
31 $quote_level++;
32 }
33 if (ctype_space($line{0})) {
34 $line = substr($line, 1);
35 }
36 return $line;
37}
38
39function banana_quote($line, $level, $mark = '>')
40{
41 $lines = explode("\n", $line);
b18124be 42 $quote = str_repeat($mark, $level);
7027794f 43 foreach ($lines as &$line) {
b18124be 44 $line = $quote . $line;
7027794f 45 }
46 return implode("\n", $lines);
47}
48
49function banana_unflowed($text)
50{
51 $lines = explode("\n", $text);
52 $text = '';
53 while (!is_null($line = array_shift($lines))) {
54 $level = 0;
55 $line = banana_removeQuotes($line, $level);
56 while (banana_isFlowed($line)) {
57 $lvl = 0;
b18124be 58 if (empty($lines)) {
7027794f 59 break;
60 }
b18124be 61 $nl = $lines[0];
7027794f 62 $nl = banana_removeQuotes($nl, $lvl);
b18124be 63 if ($lvl == $level) {
64 $line .= $nl;
65 array_shift($lines);
66 } else {
67 break;
68 }
7027794f 69 }
70 $text .= banana_quote($line, $level) . "\n";
71 }
72 return $text;
73}
74
bffb37b4 75function banana_wordwrap($text, $quote_level = 0)
7027794f 76{
77 if ($quote_level > 0) {
e9360b11 78 $length = Banana::$msgshow_wrap - $quote_level - 1;
7027794f 79 return banana_quote(wordwrap($text, $length), $quote_level);
7027794f 80 }
e9360b11 81 return wordwrap($text, Banana::$msgshow_wrap);
7027794f 82}
83
84function banana_catchFormats($text)
85{
a719cdaf 86 $formatting = Array('em' => array('\B\/\b', '\b\/\B'),
87 'u' => array('\b_', '_\b'),
88 'strong' => array('\B\*\b', '\b\*\B'));
e9360b11 89 $url = Banana::$msgshow_url;
598a1c53 90 preg_match_all("/$url/ui", $text, $urls);
9bd9df1e
FB
91 $urls = $urls[0];
92 $replace = $urls;
93 rsort($replace);
94 $text = str_replace($replace, "&&&urls&&&", $text);
a719cdaf 95 foreach ($formatting as $mark=>$limit) {
96 list($ll, $lr) = $limit;
97 $text = preg_replace('/' . $ll . '(\w+?)' . $lr . '/us',
7027794f 98 "<$mark>\\1</$mark>", $text);
99 }
9bd9df1e 100 return preg_replace('/&&&urls&&&/e', 'array_shift($urls)', $text);
7027794f 101}
102
168e9acb 103/** Build a flowed text from plain text
104 */
105function banana_flow($text)
106{
107 $lines = explode("\n", $text);
108 $text = '';
109 while (!is_null($line = array_shift($lines))) {
110 if ($line != '-- ') {
0954b1a7 111 $level = 0;
112 $line = banana_removeQuotes($line, $level);
113 $text .= rtrim(str_replace("\n", " \n", banana_wordwrap($line, $level))) . "\n";
168e9acb 114 } else {
115 $text .= $line . "\n";
116 }
117 }
118 return $text;
119}
120
7027794f 121// {{{ URL Catcher tools
122
123function banana__cutlink($link)
124{
125 $link = banana_html_entity_decode($link, ENT_QUOTES);
e9360b11 126 if (strlen($link) > Banana::$msgshow_wrap) {
127 $link = substr($link, 0, Banana::$msgshow_wrap - 3) . "...";
7027794f 128 }
129 return banana_htmlentities($link, ENT_QUOTES);
130}
131
132function banana__cleanURL($url)
133{
134 $url = str_replace('@', '%40', $url);
135 if (strpos($url, '://') === false) {
136 $url = 'http://' . $url;
137 }
138 return '<a href="'.$url.'" title="'.$url.'">' . banana__cutlink($url) . '</a>';
139}
140
141function banana__catchMailLink($email)
142{
143 $mid = '<' . $email . '>';
144 if (isset(Banana::$spool->ids[$mid])) {
145 return Banana::$page->makeLink(Array('group' => Banana::$group,
4769d001 146 'artid' => Banana::$spool->ids[$mid]->id,
7027794f 147 'text' => $email));
148 } elseif (strpos($email, '$') !== false) {
149 return $email;
150 }
151 return '<a href="mailto:' . $email . '">' . $email . '</a>';
152}
153
154// }}}
155
156function banana_catchURLs($text)
157{
e9360b11 158 $url = Banana::$msgshow_url;
7027794f 159
160 $res = preg_replace("/&(lt|gt|quot);/", " &\\1; ", $text);
598a1c53 161 $res = preg_replace("/$url/uie", "'\\1'.banana__cleanurl('\\2').'\\3'", $res);
7027794f 162 $res = preg_replace('/(["\[])?(?:mailto:|news:)?([a-z0-9.\-+_\$]+@([\-.+_]?[a-z0-9])+)(["\]])?/ie',
163 "'\\1' . banana__catchMailLink('\\2') . '\\4'",
164 $res);
165 $res = preg_replace("/ &(lt|gt|quot); /", "&\\1;", $res);
166 return $res;
167}
168
169// {{{ Quotes catcher functions
170
171function banana__replaceQuotes($text, $regexp)
172{
173 return stripslashes(preg_replace("@(^|<pre>|\n)$regexp@i", '\1', $text));
174}
175
176// }}}
177
178function banana_catchQuotes($res, $strict = true)
179{
180 if ($strict) {
181 $regexp = "&gt;";
182 } else {
183 $regexp = "&gt; *";
184 }
185 while (preg_match("/(^|<pre>|\n)$regexp/i", $res)) {
186 $res = preg_replace("/(^|<pre>|\n)(($regexp.*(?:\n|$))+)/ie",
187 "'\\1</pre><blockquote><pre>'"
188 ." . banana__replaceQuotes('\\2', '$regexp')"
189 ." . '</pre></blockquote><pre>'",
190 $res);
191 }
192 return $res;
193}
194
195function banana_catchSignature($res)
196{
197 $res = preg_replace("@<pre>-- ?\n@", "<pre>\n-- \n", $res);
198 $parts = preg_split("/\n-- ?\n/", $res);
199 $sign = '</pre><hr style="width: 100%; margin: 1em 0em; " /><pre>';
200 return join($sign, $parts);
201}
202
203function banana_plainTextToHtml($text, $strict = true)
204{
205 $text = banana_htmlentities($text);
206 $text = banana_catchFormats($text);
207 $text = banana_catchURLs($text);
208 $text = banana_catchQuotes($text, $strict);
209 $text = banana_catchSignature($text);
a09d81f4 210 return '<pre>' . $text . '</pre>';
7027794f 211}
212
213function banana_wrap($text, $base_level = 0, $strict = true)
214{
215 $lines = explode("\n", $text);
216 $text = '';
217 $buffer = array();
218 $level = 0;
219 while (!is_null($line = array_shift($lines))) {
220 $lvl = 0;
221 $line = banana_removeQuotes($line, $lvl, $strict);
b18124be 222 if($lvl != $level) {
223 if (!empty($buffer)) {
224 $text .= banana_wordwrap(implode("\n", $buffer), $level + $base_level) . "\n";
225 $buffer = array();
226 }
7027794f 227 $level = $lvl;
7027794f 228 }
229 $buffer[] = $line;
230 }
231 if (!empty($buffer)) {
232 $text .= banana_wordwrap(implode("\n", $buffer), $level + $base_level);
233 }
234 return $text;
235}
236
8a30c7d6 237function banana_formatPlainText(BananaMimePart $part, $base_level = 0)
7027794f 238{
239 $text = $part->getText();
240 if ($part->isFlowed()) {
241 $text = banana_unflowed($text);
242 }
243 $text = banana_wrap($text, $base_level, $part->isFlowed());
244 return banana_plainTextToHtml($text, $part->isFlowed());
245}
246
8a30c7d6 247function banana_quotePlainText(BananaMimePart $part)
7027794f 248{
249 $text = $part->getText();
250 if ($part->isFlowed()) {
251 $text = banana_unflowed($text);
252 }
4dd4ff0a 253 return banana_quote($text, 1);
7027794f 254}
255
256// }}}
257// {{{ HTML Functions
258
259function banana_htmlentities($text, $quote = ENT_COMPAT)
260{
261 return htmlentities($text, $quote, 'UTF-8');
262}
263
264function banana_html_entity_decode($text, $quote = ENT_COMPAT)
265{
266 return html_entity_decode($text, $quote, 'UTF-8');
267}
268
269function banana_removeEvilAttributes($tagSource)
270{
271 $stripAttrib = 'javascript:|onclick|ondblclick|onmousedown|onmouseup|onmouseover|'.
272 'onmousemove|onmouseout|onkeypress|onkeydown|onkeyup';
273 return stripslashes(preg_replace("/$stripAttrib/i", '', $tagSource));
9c118ac9 274}
275
276function banana_cleanStyles($tag, $attributes)
277{
278 static $td_style, $conv, $size_conv;
279 if (!isset($td_style)) {
280 $conv = array('style' => 'style', 'width' => 'width', 'height' => 'height', 'border' => 'border-size',
281 'size' => 'font-size', 'align' => 'text-align', 'valign' => 'vertical-align', 'face' => 'font',
282 'bgcolor' => 'background-color', 'color' => 'color', 'style' => 'style',
283 'cellpadding' => 'padding', 'cellspacing' => 'border-spacing');
284 $size_conv = array(1 => 'xx-small', 2 => 'x-small', 3 => 'small', 4 => 'medium', 5 => 'large',
285 6 => 'x-large', 7 => 'xx-large',
286 '-2' => 'xx-small', '-1' => 'x-small', '+1' => 'medium', '+2' => 'large',
287 '+3' => 'x-large', '+4' => 'xx-large');
288 $td_style = array();
289 }
290 if ($tag == 'table') {
291 array_unshift($td_style, '');
292 }
293 if ($tag == '/table') {
294 array_shift($td_style);
295 }
296 if ($tag{0} == '/') {
297 return '';
298 }
299 if ($tag == 'td') {
300 $style = $td_style[0];
301 } else {
302 $style = '';
303 }
b61ff999 304 $attributes = str_replace(array("\n", "\r"), ' ', stripslashes($attributes));
305 $attributes = str_replace(array('= "', '= \''), array('="', '=\''), $attributes);
9c118ac9 306 foreach ($conv as $att=>$stl) {
36335e0f 307 $pattern = '/\b' . preg_quote($att, '/') . '=([\'"])?(.+?)(?(1)\1|(?:$| ))/i';
9c118ac9 308 if (preg_match($pattern, $attributes, $matches)) {
309 $attributes = preg_replace($pattern, '', $attributes);
36335e0f 310 $val = $matches[2];
9c118ac9 311 if ($att == 'cellspacing' && strpos($style, 'border-collapse') === false) {
b61ff999 312 $style = "border-collapse: separate; border-spacing: $val $val; " . $style;
9c118ac9 313 } elseif ($att == 'cellpadding' && $tag == 'table') {
314 $td_style[0] = "$stl: {$val}px; ";
315 } elseif ($att == 'style') {
316 $val = rtrim($val, ' ;');
317 $style .= "$val; ";
318 } elseif ($att == 'size') {
319 $val = $size_conv[$val];
b61ff999 320 $style = "$stl: $val; " . $style;
9c118ac9 321 } elseif (is_numeric($val)) {
b61ff999 322 $style = "$stl: {$val}px; " . $style;
9c118ac9 323 } else {
b61ff999 324 $style = "$stl: $val; " . $style;
9c118ac9 325 }
326 }
327 }
328 if (!empty($style)) {
329 $style = 'style="' . $style . '" ';
330 }
331 return ' ' . $style . trim($attributes);
332}
e67c2c1c 333
19fc7e1d 334function banana__filterCss($text)
335{
336 $text = preg_replace("/(,[\s\n\r]*)/s", '\1 .banana .message .body .html ', $text);
337 return '.banana .message .body .html ' . $text;
338}
339
e67c2c1c 340function banana_filterCss($css)
341{
19fc7e1d 342 preg_match_all("/(^|\n|,\s*)\s*([\#\.@\w][^;\{\}\<]*?[\{])/s", $css, $matches);
343 $css = preg_replace("/(^|\n)\s*([\#\.@\w][^;\{\}\<]*?)([\{])/se", '"\1" . banana__filterCss("\2") . "\3"', $css);
e67c2c1c 344 $css = preg_replace('/ body\b/i', '', $css);
345 if (!Banana::$msgshow_externalimages) {
19fc7e1d 346 if (preg_match('!url\([^:\)]+:(//|\\\).*?\)!i', $css)) {
347 $css = preg_replace('!url\([^:\)]+:(//|\\\).*?\)!i', 'url(invalid-image.png)', $css);
e67c2c1c 348 Banana::$msgshow_hasextimages = true;
349 }
350 }
351 return $css;
352}
7027794f 353
354/**
355 * @return string
356 * @param string
357 * @desc Strip forbidden tags and delegate tag-source check to removeEvilAttributes()
358 */
d69a4629 359function banana_cleanHtml($source, $to_xhtml = false)
7027794f 360{
ba77e884 361 if (function_exists('tidy_repair_string')) {
eeedb24a 362 $tidy_config = array('drop-empty-paras' => true,
363 'drop-proprietary-attributes' => true,
364 'hide-comments' => true,
365 'logical-emphasis' => true,
366 'output-xhtml' => true,
367 'replace-color' => true,
368 'join-classes' => false,
369 'clean' => false,
370 'show-body-only' => false,
371 'alt-text' => '[ inserted by TIDY ]',
372 'wrap' => 120);
373 if (function_exists('tidy_setopt')) { // Tidy 1.0
374 foreach ($tidy_config as $field=>$value) {
375 tidy_setopt($field, $value);
376 }
377 tidy_set_encoding('utf8');
378 $source = tidy_repair_string($source);
a09d81f4 379
eeedb24a 380 } else { // Tidy 2.0
381 $source = tidy_repair_string($source, $tidy_config, 'utf8');
7027794f 382 }
9c118ac9 383 }
384
385 // To XHTML
d69a4629 386 if ($to_xhtml) {
387 // catch inline CSS
388 $css = null;
389 if (preg_match('/<head.*?>(.*?)<\/head>/is', $source, $matches)) {
390 $source = preg_replace('/<head.*?>.*?<\/head>/is', '', $source);
19fc7e1d 391 preg_match_all('/<style(?:.*?type="text\/css".*?)?>(.*?)<\/style>/is', $matches[1], $matches);
d69a4629 392 foreach ($matches[1] as &$match) {
393 $css .= $match;
394 }
e67c2c1c 395 $css = banana_filterCss($css);
d69a4629 396 Banana::$page->addCssInline($css);
9c118ac9 397 }
9c118ac9 398
d69a4629 399 // clean DTD
400 $source = str_replace('<font', '<span', $source);
401 $source = preg_replace('/<u\b/', '<span style="text-decoration: underline"', $source);
402 $source = preg_replace('/<\/(font|u)>/', '</span>', $source);
403 $source = str_replace('<body', $css ? '<div class="html"' : '<div class="html default"', $source);
404 $source = str_replace('</body>', '</div>', $source);
405 }
9c118ac9 406 $allowedTags = '<h1><h2><h3><b><i><a><ul><li><pre><hr><blockquote><img><br><div><span>'
407 . '<p><small><big><sup><sub><code><em><strong><table><tr><td><th>';
408 $source = strip_tags($source, $allowedTags);
409
410 // Use inlined style instead of old html attributes
d69a4629 411 if ($to_xhtml) {
b61ff999 412 $source = preg_replace('/<(\/?\w+)(.*?)(\/?>)/muise', "'<\\1' . banana_cleanStyles('\\1', '\\2') . '\\3'", $source);
d69a4629 413 }
9c118ac9 414 return preg_replace('/<(.*?)>/ie', "'<'.banana_removeEvilAttributes('\\1').'>'", $source);
7027794f 415}
416
417function banana_catchHtmlSignature($res)
418{
419 $res = preg_replace("@(</p>)\n?-- ?\n?(<p[^>]*>|<br[^>]*>)@", "\\1<br/>-- \\2", $res);
420 $res = preg_replace("@<br[^>]*>\n?-- ?\n?(<p[^>]*>)@", "<br/>-- <br/>\\2", $res);
421 $res = preg_replace("@(<pre[^>]*>)\n?-- ?\n@", "<br/>-- <br/>\\1", $res);
422 $parts = preg_split("@(:?<p[^>]*>\n?-- ?\n?</p>|<br[^>]*>\n?-- ?\n?<br[^>]*>)@", $res);
423 $sign = '<hr style="width: 100%; margin: 1em 0em; " />';
424 return join($sign, $parts);
425}
426
427// {{{ Link to part catcher tools
428
429function banana__linkAttachment($cid)
430{
431 return banana_htmlentities(
432 Banana::$page->makeUrl(Array('group' => Banana::$group,
433 'artid' => Banana::$artid,
434 'part' => $cid)));
435}
436
437// }}}
438
439function banana_hideExternalImages($text)
440{
e67c2c1c 441 if (preg_match("/<img([^>]*?)src=['\"](?!cid).*?['\"](.*?)>/i", $text)) {
442 Banana::$msgshow_hasextimages = true;
443 return preg_replace("/<img([^>]*?)src=['\"](?!cid).*?['\"](.*?)>/i",
444 '<img\1src="invalid"\2>',
445 $text);
446 }
447 return $text;
7027794f 448}
449
450function banana_catchPartLinks($text)
451{
9c118ac9 452 $article = Banana::$page->makeURL(array('group' => Banana::$group, 'artid' => Banana::$artid, 'part' => Banana::$part));
453 $article = banana_htmlentities($article);
454 $text = preg_replace('/cid:([^\'" ]+)/e', "banana__linkAttachment('\\1')", $text);
455 $text = preg_replace('/href="(#.*?)"/i', 'href="' . $article . '\1"', $text);
456 return $text;
7027794f 457}
458
459// {{{ HTML to Plain Text tools
460
461function banana__convertFormats($res)
462{
463 $table = array('em|i' => '/',
464 'strong|b' => '*',
465 'u' => '_');
466 foreach ($table as $tags=>$format) {
467 $res = preg_replace("!</?($tags)( .*?)?>!is", $format, $res);
468 }
469 return $res;
470}
471
472function banana__convertQuotes($res)
473{
474 return preg_replace('!<blockquote.*?>([^<]*)</blockquote>!ies',
475 "\"\n\" . banana_quote(banana__convertQuotes('\\1' . \"\n\"), 1, '&gt;')",
476 $res);
477}
478
479// }}}
480
481function banana_htmlToPlainText($res)
482{
483 $res = str_replace("\n", '', $res);
484 $res = banana__convertFormats($res);
485 $res = trim(strip_tags($res, '<div><br><p><blockquote>'));
486 $res = preg_replace("@</?(br|p|div).*?>@si", "\n", $res);
487 $res = banana__convertQuotes($res);
488 return banana_html_entity_decode($res);
489}
490
8a30c7d6 491function banana_formatHtml(BananaMimePart $part)
7027794f 492{
493 $text = $part->getText();
494 $text = banana_catchHtmlSignature($text);
57efc445 495 if (!Banana::$msgshow_externalimages) {
496 $text = banana_hideExternalImages($text);
497 }
7027794f 498 $text = banana_catchPartLinks($text);
d69a4629 499 return banana_cleanHtml($text, true);
7027794f 500}
501
8a30c7d6 502function banana_quoteHtml(BananaMimePart $part)
7027794f 503{
504 $text = $part->getText();
505 $text = banana_htmlToPlainText($text);
4dd4ff0a 506 return banana_quote($text, 1);
7027794f 507}
508
509// }}}
510// {{{ Richtext Functions
511
512/** Convert richtext to html
513 */
514function banana_richtextToHtml($source)
515{
516 $tags = Array('bold' => 'b',
517 'italic' => 'i',
518 'smaller' => 'small',
519 'bigger' => 'big',
520 'underline' => 'u',
521 'subscript' => 'sub',
522 'superscript' => 'sup',
523 'excerpt' => 'blockquote',
524 'paragraph' => 'p',
525 'nl' => 'br'
526 );
527
528 // clean unsupported tags
529 $protectedTags = '<signature><lt><comment><'.join('><', array_keys($tags)).'>';
530 $source = strip_tags($source, $protectedTags);
531
532 // convert richtext tags to html
533 foreach (array_keys($tags) as $tag) {
534 $source = preg_replace('@(</?)'.$tag.'([^>]*>)@i', '\1'.$tags[$tag].'\2', $source);
535 }
536
537 // some special cases
538 $source = preg_replace('@<signature>@i', '<br>-- <br>', $source);
539 $source = preg_replace('@</signature>@i', '', $source);
540 $source = preg_replace('@<lt>@i', '&lt;', $source);
541 $source = preg_replace('@<comment[^>]*>((?:[^<]|<(?!/comment>))*)</comment>@i', '<!-- \1 -->', $source);
542 return banana_cleanHtml($source);
543}
544
8a30c7d6 545function banana_formatRichText(BananaMimePart $part)
7027794f 546{
547 $text = $part->getText();
548 $text = banana_richtextToHtml($text);
549 $text = banana_catchHtmlSignature($text);
550 return banana_cleanHtml($text);
551}
552
8a30c7d6 553function banana_quoteRichtText(BananaMimePart $part)
3c3a3ce3 554{
555 $text = $part->getText();
556 $text = banana_richtextToHtml($text);
557 $text = banana_htmlToPlainText($text);
4dd4ff0a 558 return banana_quote($text, 1);
3c3a3ce3 559}
560
7027794f 561// }}}
562
598a1c53 563// vim:set et sw=4 sts=4 ts=4 enc=utf-8:
7027794f 564?>