2 /********************************************************************************
3 * include/misc.inc.php : Misc functions
4 * -------------------------
6 * This file is part of the banana distribution
7 * Copyright: See COPYING files that comes with this distribution
8 ********************************************************************************/
10 /********************************************************************************
14 function _b_($str) { return utf8_decode(dgettext('banana', utf8_encode($str))); }
16 function to_entities($str) {
17 require_once dirname(__FILE__
).'/utf8.php';
18 return utf8entities(htmlentities($str, ENT_NOQUOTES
, 'UTF-8'));
21 function is_utf8($s) { return iconv('utf-8', 'utf-8', $s) == $s; }
23 function textFormat_translate($format)
25 switch (strtolower($format)) {
26 case 'plain': return _b_('Texte brut');
27 case 'richtext': return _b_('Texte enrichi');
28 case 'html': return _b_('HTML');
29 default: return $format;
33 function redirect($params)
35 header('Location: ' . makeLink($params));
38 function makeLink($params)
40 $proto = empty($_SERVER['HTTPS']) ?
'http://' : 'http://';
41 $host = $_SERVER['HTTP_HOST'];
42 $file = $_SERVER['PHP_SELF'];
44 return $proto . $host . $file . '?' . $params;
47 /********************************************************************************
55 * @desc Strip forbidden tags and delegate tag-source check to removeEvilAttributes()
57 function removeEvilTags($source)
59 $allowedTags = '<h1><b><i><a><ul><li><pre><hr><blockquote><img><br><font><p><small><big><sup><sub><code><em>';
60 $source = preg_replace('|</div>|i', '<br />', $source);
61 $source = strip_tags($source, $allowedTags);
62 return preg_replace('/<(.*?)>/ie', "'<'.removeEvilAttributes('\\1').'>'", $source);
68 * @desc Strip forbidden attributes from a tag
70 function removeEvilAttributes($tagSource)
72 $stripAttrib = 'javascript:|onclick|ondblclick|onmousedown|onmouseup|onmouseover|'.
73 'onmousemove|onmouseout|onkeypress|onkeydown|onkeyup';
74 return stripslashes(preg_replace("/$stripAttrib/i", '', $tagSource));
77 /** Convert html to plain text
79 function htmlToPlainText($res)
81 $res = trim(html_entity_decode(strip_tags($res, '<div><br><p>')));
82 $res = preg_replace("@</?(br|p|div)[^>]*>@i", "\n", $res);
84 $res = utf8_encode($res);
89 /********************************************************************************
93 /** Convert richtext to html
95 function richtextToHtml($source)
97 $tags = Array('bold' => 'b',
102 'subscript' => 'sub',
103 'superscript' => 'sup',
104 'excerpt' => 'blockquote',
109 // clean unsupported tags
110 $protectedTags = '<signature><lt><comment><'.join('><', array_keys($tags)).'>';
111 $source = strip_tags($source, $protectedTags);
113 // convert richtext tags to html
114 foreach (array_keys($tags) as $tag) {
115 $source = preg_replace('@(</?)'.$tag.'([^>]*>)@i', '\1'.$tags[$tag].'\2', $source);
118 // some special cases
119 $source = preg_replace('@<signature>@i', '<br>-- <br>', $source);
120 $source = preg_replace('@</signature>@i', '', $source);
121 $source = preg_replace('@<lt>@i', '<', $source);
122 $source = preg_replace('@<comment[^>]*>((?:[^<]|<(?!/comment>))*)</comment>@i', '<!-- \1 -->', $source);
123 return removeEvilAttributes($source);
126 /********************************************************************************
130 function _headerdecode($charset, $c, $str) {
131 $s = ($c == 'Q' ||
$c == 'q') ?
quoted_printable_decode($str) : base64_decode($str);
132 $s = iconv($charset, 'iso-8859-15', $s);
133 return str_replace('_', ' ', $s);
136 function headerDecode($value) {
137 $val = preg_replace('/(=\?[^?]*\?[BQbq]\?[^?]*\?=) (=\?[^?]*\?[BQbq]\?[^?]*\?=)/', '\1\2', $value);
138 return preg_replace('/=\?([^?]*)\?([BQbq])\?([^?]*)\?=/e', '_headerdecode("\1", "\2", "\3")', $val);
141 function headerEncode($value, $trim = 0) {
143 if (strlen($value) > $trim) {
144 $value = substr($value, 0, $trim) . "[...]";
147 return "=?UTF-8?B?".base64_encode($value)."?=";
150 function header_translate($hdr) {
152 case 'from': return _b_('De');
153 case 'subject': return _b_('Sujet');
154 case 'newsgroups': return _b_('Forums');
155 case 'followup-to': return _b_('Suivi-à');
156 case 'date': return _b_('Date');
157 case 'organization': return _b_('Organisation');
158 case 'references': return _b_('Références');
159 case 'x-face': return _b_('Image');
161 if (function_exists('hook_headerTranslate')
162 && $res = hook_headerTranslate($hdr)) {
169 function formatDisplayHeader($_header,$_text) {
173 return formatDate($_text);
178 $groups = preg_split("/[\t ]*,[\t ]*/",$_text);
179 foreach ($groups as $g) {
180 $res.="<a href='?group=$g'>$g</a>, ";
182 return substr($res,0, -2);
185 return formatFrom($_text);
190 $text = str_replace("><","> <",$_text);
191 $text = preg_split("/[ \t]/",strtr($text,$banana->spool
->ids
));
192 $parents = preg_grep("/^\d+$/",$text);
193 $p = array_pop($parents);
198 $p = $banana->spool
->overview
[$p]->parent
;
200 foreach (array_reverse($par_ok) as $p) {
201 $rsl .= "<a href=\"?group={$banana->spool->group}&artid=$p\">$ndx</a> ";
207 return '<img src="xface.php?face='.urlencode(base64_encode($_text)).'" alt="x-face" />';
210 if (function_exists('hook_formatDisplayHeader')
211 && $res = hook_formatDisplayHeader($_header, $_text))
215 return htmlentities($_text);
219 /********************************************************************************
223 function formatDate($_text) {
224 return strftime("%A %d %B %Y, %H:%M (fuseau serveur)", strtotime($_text));
227 function fancyDate($stamp) {
228 $today = intval(time() / (24*3600));
229 $dday = intval($stamp / (24*3600));
231 if ($today == $dday) {
233 } elseif ($today == 1 +
$dday) {
234 $format = _b_('hier')." %H:%M";
235 } elseif ($today < 7 +
$dday) {
236 $format = '%a %H:%M';
238 $format = '%a %e %b';
240 return strftime($format, $stamp);
243 function formatFrom($text) {
244 # From: mark@cbosgd.ATT.COM
245 # From: mark@cbosgd.ATT.COM (Mark Horton)
246 # From: Mark Horton <mark@cbosgd.ATT.COM>
247 $mailto = '<a href="mailto:';
249 $result = htmlentities($text);
250 if (preg_match("/^([^ ]+)@([^ ]+)$/",$text,$regs)) {
251 $result="$mailto{$regs[1]}@{$regs[2]}\">".htmlentities($regs[1]."@".$regs[2])."</a>";
253 if (preg_match("/^([^ ]+)@([^ ]+) \((.*)\)$/",$text,$regs)) {
254 $result="$mailto{$regs[1]}@{$regs[2]}\">".htmlentities($regs[3])."</a>";
256 if (preg_match("/^\"?([^<>\"]+)\"? +<(.+)@(.+)>$/",$text,$regs)) {
257 $result="$mailto{$regs[2]}@{$regs[3]}\">".htmlentities($regs[1])."</a>";
259 return preg_replace("/\\\(\(|\))/","\\1",$result);
262 function displayshortcuts($first = -1) {
264 extract($banana->state
);
266 $res = '<div class="banana_scuts">';
267 $res .= '[<a href="?">'._b_('Liste des forums').'</a>] ';
268 if (is_null($group)) {
269 return $res.'[<a href="?subscribe=1">'._b_('Abonnements').'</a>]</div>';
272 $res .= "[<a href=\"?group=$group\">$group</a>] ";
274 if (is_null($artid)) {
275 $res .= "[<a href=\"?group=$group&action=new\">"._b_('Nouveau message')."</a>] ";
276 if (sizeof($banana->spool
->overview
)>$banana->tmax
) {
278 $n = intval(log(count($banana->spool
->overview
), 10))+
1;
279 for ($ndx=1; $ndx <= sizeof($banana->spool
->overview
); $ndx +
= $banana->tmax
) {
281 $fmt = "[%0{$n}u-%0{$n}u] ";
283 $fmt = "[<a href=\"?group=$group&first=$ndx\">%0{$n}u-%0{$n}u</a>] ";
285 $res .= sprintf($fmt, $ndx, min($ndx+
$banana->tmax
-1,sizeof($banana->spool
->overview
)));
289 $res .= "[<a href=\"?group=$group&artid=$artid&action=new\">"
290 ._b_('Répondre')."</a>] ";
291 if ($banana->post
&& $banana->post
->checkcancel()) {
292 $res .= "[<a href=\"?group=$group&artid=$artid&action=cancel\">"
293 ._b_('Annuler ce message')."</a>] ";
296 return $res.'</div>';
299 /********************************************************************************
300 * FORMATTING STUFF : BODY
303 function autoformat($text)
306 $length = $banana->wrap
;
308 $cmd = "echo ".escapeshellarg($text)." | perl -MText::Autoformat -e 'autoformat {left=>1, right=>$length, all=>1 };'";
309 exec($cmd, $result, $ret);
311 $result = split("\n", $text);
316 function wrap($text, $_prefix="", $_force=false
)
318 $parts = preg_split("/\n-- ?\n/", $text);
319 if (count($parts) >1) {
320 $sign = "\n-- \n" . array_pop($parts);
321 $text = join("\n-- \n", $parts);
327 $url = $banana->url_regexp
;
328 $length = $banana->wrap
;
329 $max = $length +
($length/10);
330 $splits = split("\n", $text);
334 foreach ($splits as $line) {
335 if ($_force ||
strlen($line) > $max) {
336 if (preg_match("!^(.*)($url)(.*)!i", $line, $matches) && strlen($matches[2]) > $length && strlen($matches) < 900) {
337 if (strlen($matches[1]) != 0) {
338 array_push($next, rtrim($matches[1]));
339 if (strlen($matches[1]) > $max) {
345 $result = array_merge($result, autoformat(join("\n", $next)));
347 $result = array_merge($result, $next);
351 array_push($result, $matches[2]);
353 if (strlen($matches[6]) != 0) {
354 array_push($next, ltrim($matches[6]));
355 if (strlen($matches[6]) > $max) {
361 array_push($next, $line);
364 array_push($next, $line);
368 $result = array_merge($result, autoformat(join("\n", $next)));
370 $result = array_merge($result, $next);
373 return $_prefix.join("\n$_prefix", $result).($_prefix ?
'' : $sign);
376 function cutlink($link)
380 if (strlen($link) > $banana->wrap
) {
381 $link = substr($link, 0, $banana->wrap
- 3)."...";
386 function cleanurl($url)
388 $url = str_replace('@', '%40', $url);
389 return '<a href="'.$url.'" title="'.$url.'">'.cutlink($url).'</a>';
392 function formatbody($_text, $format='plain', $flowed=false
)
394 if ($format == 'html') {
395 $res = '<br/>'.html_entity_decode(to_entities(removeEvilTags($_text))).'<br/>';
396 } else if ($format == 'richtext') {
397 $res = '<br/>'.html_entity_decode(to_entities(richtextToHtml($_text))).'<br/>';
399 $res = "\n\n" . to_entities(wrap($_text, "", $flowed))."\n\n";
402 if ($format != 'html') {
404 $url = $banana->url_regexp
;
405 $res = preg_replace("/(<|>|")/", " \\1 ", $res);
406 $res = preg_replace("!$url!ie", "'\\1'.cleanurl('\\2').'\\3'", $res);
407 $res = preg_replace('/(["\[])?(?:mailto:)?([a-z0-9.\-+_]+@[a-z0-9.\-+_]+)(["\]])?/i', '\1<a href="mailto:\2">\2</a>\3', $res);
408 $res = preg_replace("/ (<|>|") /", "\\1", $res);
410 if ($format == 'richtext') {
415 if ($format == 'html') {
416 $res = preg_replace("@(</p>)\n?-- ?\n?(<p[^>]*>|<br[^>]*>)@", "\\1<br/>-- \\2", $res);
417 $res = preg_replace("@<br[^>]*>\n?-- ?\n?(<p[^>]*>)@", "<br/>-- <br/>\\2", $res);
418 $res = preg_replace("@(<pre[^>]*>)\n?-- ?\n@", "<br/>-- <br/>\\1", $res);
419 $parts = preg_split("@(:?<p[^>]*>\n?-- ?\n?</p>|<br[^>]*>\n?-- ?\n?<br[^>]*>)@", $res);
421 while (preg_match("@(^|<pre>|\n)>@i", $res)) {
422 $res = preg_replace("@(^|<pre>|\n)((>[^\n]*\n)+)@ie",
423 "'\\1</pre><blockquote><pre>'"
424 .".stripslashes(preg_replace('@(^|<pre>|\n)>[ \\t\\r]*@i', '\\1', '\\2'))"
425 .".'</pre></blockquote><pre>'",
428 $res = preg_replace("@<pre>-- ?\n@", "<pre>\n-- \n", $res);
429 $parts = preg_split("/\n-- ?\n/", $res);
432 if (count($parts) > 1) {
433 $sign = array_pop($parts);
434 if ($format == 'html') {
435 $res = join('<br/>-- <br/>', $parts);
436 $sign = '<hr style="width: 100%; margin: 1em 0em; " />'.$sign.'<br/>';
438 $res = join('\n-- \n', $parts);
439 $sign = '</pre><hr style="width: 100%; margin: 1em 0em; " /><pre>'.$sign;