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 /** Redirect to the page with the given parameter
36 function redirectInBanana($params)
38 header('Location: ' . makeLink($params));
41 /** Make a link using the given parameters
42 * @param ARRAY params, the parameters with
45 * - group = group name
46 * - artid/first = article id the the group
47 * - subscribe = to show the subscription page
48 * - action = action to do (new, cancel, view)
49 * - part = to show the given MIME part of the article
50 * - pj = to get the given attachment
52 * Can be overloaded by defining a hook_makeLink function
54 function makeLink($params)
56 if (function_exists('hook_makeLink')
57 && $res = hook_makeLink($params)) {
60 $proto = empty($_SERVER['HTTPS']) ?
'http://' : 'https://';
61 $host = $_SERVER['HTTP_HOST'];
62 $file = $_SERVER['PHP_SELF'];
64 if (count($params) != 0) {
66 foreach ($params as $key=>$value) {
67 if (strlen($get) != 1) {
70 $get .= $key . '=' . $value;
76 return $proto . $host . $file . $get;
79 /** Format a link to be use in a link
82 function makeHREF($params, $text = null
)
84 $link = makeLink($params);
89 if (isset($params['action']) && $params['action'] == 'view') {
90 $target = ' target="_blank"';
92 return '<a href="' . htmlentities($link) . $target . '">' . $text . '</a>';
95 /** Format tree images links
96 * @param img STRING Image name (without extension)
97 * @param alt STRING alternative string
98 * @param width INT to force width of the image (null if not defined)
100 * This function can be overloaded by defining hook_makeImg()
102 function makeImg($img, $alt, $width = null
)
104 if (function_exists('hook_makeImg')
105 && $res = hook_makeImg($img, $alt, $width)) {
109 if (!is_null($width)) {
110 $width = ' width="' . $width . '"';
113 $proto = empty($_SERVER['HTTPS']) ?
'http://' : 'https://';
114 $host = $_SERVER['HTTP_HOST'];
115 $file = dirname($_SERVER['PHP_SELF']) . '/img/' . $img . '.gif';
116 $url = $proto . $host . $file;
118 return '<img src="' . $url . '"' . $width . ' alt="' . $alt . '" />';
121 /********************************************************************************
129 * @desc Strip forbidden tags and delegate tag-source check to removeEvilAttributes()
131 function removeEvilTags($source)
133 $allowedTags = '<h1><b><i><a><ul><li><pre><hr><blockquote><img><br><font><p><small><big><sup><sub><code><em>';
134 $source = preg_replace('|</div>|i', '<br />', $source);
135 $source = strip_tags($source, $allowedTags);
136 return preg_replace('/<(.*?)>/ie', "'<'.removeEvilAttributes('\\1').'>'", $source);
142 * @desc Strip forbidden attributes from a tag
144 function removeEvilAttributes($tagSource)
146 $stripAttrib = 'javascript:|onclick|ondblclick|onmousedown|onmouseup|onmouseover|'.
147 'onmousemove|onmouseout|onkeypress|onkeydown|onkeyup';
148 return stripslashes(preg_replace("/$stripAttrib/i", '', $tagSource));
151 /** Convert html to plain text
153 function htmlToPlainText($res)
155 $res = trim(html_entity_decode(strip_tags($res, '<div><br><p>')));
156 $res = preg_replace("@</?(br|p|div)[^>]*>@i", "\n", $res);
157 if (!is_utf8($res)) {
158 $res = utf8_encode($res);
163 /********************************************************************************
167 /** Convert richtext to html
169 function richtextToHtml($source)
171 $tags = Array('bold' => 'b',
173 'smaller' => 'small',
176 'subscript' => 'sub',
177 'superscript' => 'sup',
178 'excerpt' => 'blockquote',
183 // clean unsupported tags
184 $protectedTags = '<signature><lt><comment><'.join('><', array_keys($tags)).'>';
185 $source = strip_tags($source, $protectedTags);
187 // convert richtext tags to html
188 foreach (array_keys($tags) as $tag) {
189 $source = preg_replace('@(</?)'.$tag.'([^>]*>)@i', '\1'.$tags[$tag].'\2', $source);
192 // some special cases
193 $source = preg_replace('@<signature>@i', '<br>-- <br>', $source);
194 $source = preg_replace('@</signature>@i', '', $source);
195 $source = preg_replace('@<lt>@i', '<', $source);
196 $source = preg_replace('@<comment[^>]*>((?:[^<]|<(?!/comment>))*)</comment>@i', '<!-- \1 -->', $source);
197 return removeEvilAttributes($source);
200 /********************************************************************************
204 function _headerdecode($charset, $c, $str) {
205 $s = ($c == 'Q' ||
$c == 'q') ?
quoted_printable_decode($str) : base64_decode($str);
206 $s = iconv($charset, 'iso-8859-15', $s);
207 return str_replace('_', ' ', $s);
210 function headerDecode($value) {
211 $val = preg_replace('/(=\?[^?]*\?[BQbq]\?[^?]*\?=) (=\?[^?]*\?[BQbq]\?[^?]*\?=)/', '\1\2', $value);
212 return preg_replace('/=\?([^?]*)\?([BQbq])\?([^?]*)\?=/e', '_headerdecode("\1", "\2", "\3")', $val);
215 function headerEncode($value, $trim = 0) {
217 if (strlen($value) > $trim) {
218 $value = substr($value, 0, $trim) . "[...]";
221 return "=?UTF-8?B?".base64_encode($value)."?=";
224 function header_translate($hdr) {
226 case 'from': return _b_('De');
227 case 'subject': return _b_('Sujet');
228 case 'newsgroups': return _b_('Forums');
229 case 'followup-to': return _b_('Suivi-Ã ');
230 case 'date': return _b_('Date');
231 case 'organization': return _b_('Organisation');
232 case 'references': return _b_('Références');
233 case 'x-face': return _b_('Image');
235 if (function_exists('hook_headerTranslate')
236 && $res = hook_headerTranslate($hdr)) {
243 function formatDisplayHeader($_header,$_text) {
247 return formatDate($_text);
252 $groups = preg_split("/[\t ]*,[\t ]*/",$_text);
253 foreach ($groups as $g) {
254 $res .= makeHREF(Array('group' => $g), $g) . ', ';
256 return substr($res,0, -2);
259 return formatFrom($_text);
264 $text = str_replace("><","> <",$_text);
265 $text = preg_split("/[ \t]/",strtr($text,$banana->spool
->ids
));
266 $parents = preg_grep("/^\d+$/",$text);
267 $p = array_pop($parents);
272 $p = $banana->spool
->overview
[$p]->parent
;
274 foreach (array_reverse($par_ok) as $p) {
275 $rsl .= makeHREF(Array('group' => $banana->spool
->group
), $ndx) . ' ';
281 return '<img src="xface.php?face='.urlencode(base64_encode($_text)).'" alt="x-face" />';
284 if (function_exists('hook_formatDisplayHeader')
285 && $res = hook_formatDisplayHeader($_header, $_text))
289 return htmlentities($_text);
293 /********************************************************************************
297 function formatDate($_text) {
298 return strftime("%A %d %B %Y, %H:%M (fuseau serveur)", strtotime($_text));
301 function fancyDate($stamp) {
302 $today = intval(time() / (24*3600));
303 $dday = intval($stamp / (24*3600));
305 if ($today == $dday) {
307 } elseif ($today == 1 +
$dday) {
308 $format = _b_('hier')." %H:%M";
309 } elseif ($today < 7 +
$dday) {
310 $format = '%a %H:%M';
312 $format = '%a %e %b';
314 return strftime($format, $stamp);
317 function formatFrom($text) {
318 # From: mark@cbosgd.ATT.COM
319 # From: mark@cbosgd.ATT.COM (Mark Horton)
320 # From: Mark Horton <mark@cbosgd.ATT.COM>
321 $mailto = '<a href="mailto:';
323 $result = htmlentities($text);
324 if (preg_match("/^([^ ]+)@([^ ]+)$/",$text,$regs)) {
325 $result="$mailto{$regs[1]}@{$regs[2]}\">".htmlentities($regs[1]."@".$regs[2])."</a>";
327 if (preg_match("/^([^ ]+)@([^ ]+) \((.*)\)$/",$text,$regs)) {
328 $result="$mailto{$regs[1]}@{$regs[2]}\">".htmlentities($regs[3])."</a>";
330 if (preg_match("/^\"?([^<>\"]+)\"? +<(.+)@(.+)>$/",$text,$regs)) {
331 $result="$mailto{$regs[2]}@{$regs[3]}\">".htmlentities($regs[1])."</a>";
333 return preg_replace("/\\\(\(|\))/","\\1",$result);
336 function displayshortcuts($first = -1) {
338 extract($banana->state
);
340 $res = '<div class="banana_scuts">';
341 $res .= '[' . makeHREF(Array(), _b_('Liste des forums')) . '] ';
342 if (is_null($group)) {
343 return $res.'[' . makeHREF(Array('subscribe' => 1), _b_('Abonnements')) . ']</div>';
346 $res .= '[' . makeHREF(Array('group' => $group), $group) . '] ';
348 if (is_null($artid)) {
349 $res .= '[' . makeHREF(Array('group' => $group,
351 _b_('Nouveau message'))
353 if (sizeof($banana->spool
->overview
)>$banana->tmax
) {
355 $n = intval(log(count($banana->spool
->overview
), 10))+
1;
356 for ($ndx=1; $ndx <= sizeof($banana->spool
->overview
); $ndx +
= $banana->tmax
) {
358 $fmt = "[%0{$n}u-%0{$n}u] ";
360 $fmt = '[' . makeHREF(Array('group' => $group,
362 '%0' . $n . 'u-%0' . $n . 'u')
365 $res .= sprintf($fmt, $ndx, min($ndx+
$banana->tmax
-1,sizeof($banana->spool
->overview
)));
369 $res .= '[' . makeHREF(Array('group' => $group,
374 if ($banana->post
&& $banana->post
->checkcancel()) {
375 $res .= '[' . makeHREF(Array('group' => $group,
377 'action' => 'cancel'),
378 _b_('Annuler ce message'))
382 return $res.'</div>';
385 /********************************************************************************
386 * FORMATTING STUFF : BODY
389 function autoformat($text)
392 $length = $banana->wrap
;
394 $cmd = "echo ".escapeshellarg($text)." | perl -MText::Autoformat -e 'autoformat {left=>1, right=>$length, all=>1 };'";
395 exec($cmd, $result, $ret);
397 $result = split("\n", $text);
402 function wrap($text, $_prefix="", $_force=false
)
404 $parts = preg_split("/\n-- ?\n/", $text);
405 if (count($parts) >1) {
406 $sign = "\n-- \n" . array_pop($parts);
407 $text = join("\n-- \n", $parts);
413 $url = $banana->url_regexp
;
414 $length = $banana->wrap
;
415 $max = $length +
($length/10);
416 $splits = split("\n", $text);
420 foreach ($splits as $line) {
421 if ($_force ||
strlen($line) > $max) {
422 if (preg_match("!^(.*)($url)(.*)!i", $line, $matches) && strlen($matches[2]) > $length && strlen($matches) < 900) {
423 if (strlen($matches[1]) != 0) {
424 array_push($next, rtrim($matches[1]));
425 if (strlen($matches[1]) > $max) {
431 $result = array_merge($result, autoformat(join("\n", $next)));
433 $result = array_merge($result, $next);
437 array_push($result, $matches[2]);
439 if (strlen($matches[6]) != 0) {
440 array_push($next, ltrim($matches[6]));
441 if (strlen($matches[6]) > $max) {
447 array_push($next, $line);
450 array_push($next, $line);
454 $result = array_merge($result, autoformat(join("\n", $next)));
456 $result = array_merge($result, $next);
459 return $_prefix.join("\n$_prefix", $result).($_prefix ?
'' : $sign);
462 function cutlink($link)
466 if (strlen($link) > $banana->wrap
) {
467 $link = substr($link, 0, $banana->wrap
- 3)."...";
472 function cleanurl($url)
474 $url = str_replace('@', '%40', $url);
475 return '<a href="'.$url.'" title="'.$url.'">'.cutlink($url).'</a>';
478 function formatbody($_text, $format='plain', $flowed=false
)
480 if ($format == 'html') {
481 $res = '<br/>'.html_entity_decode(to_entities(removeEvilTags($_text))).'<br/>';
482 } else if ($format == 'richtext') {
483 $res = '<br/>'.html_entity_decode(to_entities(richtextToHtml($_text))).'<br/>';
485 $res = "\n\n" . to_entities(wrap($_text, "", $flowed))."\n\n";
486 $formatting = Array('\*' => 'strong',
489 foreach ($formatting as $limit=>$mark) {
490 $res = preg_replace('@' . $limit . '([^\s]+)' . $limit . '@', "<$mark>\\1</$mark>", $res);
494 if ($format != 'html') {
496 $url = $banana->url_regexp
;
497 $res = preg_replace("/(<|>|")/", " \\1 ", $res);
498 $res = preg_replace("!$url!ie", "'\\1'.cleanurl('\\2').'\\3'", $res);
499 $res = preg_replace('/(["\[])?(?:mailto:)?([a-z0-9.\-+_]+@[a-z0-9.\-+_]+)(["\]])?/i', '\1<a href="mailto:\2">\2</a>\3', $res);
500 $res = preg_replace("/ (<|>|") /", "\\1", $res);
502 if ($format == 'richtext') {
507 if ($format == 'html') {
508 $res = preg_replace("@(</p>)\n?-- ?\n?(<p[^>]*>|<br[^>]*>)@", "\\1<br/>-- \\2", $res);
509 $res = preg_replace("@<br[^>]*>\n?-- ?\n?(<p[^>]*>)@", "<br/>-- <br/>\\2", $res);
510 $res = preg_replace("@(<pre[^>]*>)\n?-- ?\n@", "<br/>-- <br/>\\1", $res);
511 $parts = preg_split("@(:?<p[^>]*>\n?-- ?\n?</p>|<br[^>]*>\n?-- ?\n?<br[^>]*>)@", $res);
513 while (preg_match("@(^|<pre>|\n)>@i", $res)) {
514 $res = preg_replace("@(^|<pre>|\n)((>[^\n]*\n)+)@ie",
515 "'\\1</pre><blockquote><pre>'"
516 .".stripslashes(preg_replace('@(^|<pre>|\n)>[ \\t\\r]*@i', '\\1', '\\2'))"
517 .".'</pre></blockquote><pre>'",
520 $res = preg_replace("@<pre>-- ?\n@", "<pre>\n-- \n", $res);
521 $parts = preg_split("/\n-- ?\n/", $res);
524 if (count($parts) > 1) {
525 $sign = array_pop($parts);
526 if ($format == 'html') {
527 $res = join('<br/>-- <br/>', $parts);
528 $sign = '<hr style="width: 100%; margin: 1em 0em; " />'.$sign.'<br/>';
530 $res = join('\n-- \n', $parts);
531 $sign = '</pre><hr style="width: 100%; margin: 1em 0em; " /><pre>'.$sign;
539 // vim:set et sw=4 sts=4 ts=4