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, $height = null
, $width = null
)
104 if (function_exists('hook_makeImg')
105 && $res = hook_makeImg($img, $alt, $height, $width)) {
109 if (!is_null($width)) {
110 $width = ' width="' . $width . '"';
112 if (!is_null($height)) {
113 $height = ' height="' . $height . '"';
116 $proto = empty($_SERVER['HTTPS']) ?
'http://' : 'https://';
117 $host = $_SERVER['HTTP_HOST'];
118 $file = dirname($_SERVER['PHP_SELF']) . '/img/' . $img . '.gif';
119 $url = $proto . $host . $file;
121 return '<img src="' . $url . '"' . $height . $width . ' alt="' . $alt . '" />';
124 /********************************************************************************
132 * @desc Strip forbidden tags and delegate tag-source check to removeEvilAttributes()
134 function removeEvilTags($source)
136 $allowedTags = '<h1><b><i><a><ul><li><pre><hr><blockquote><img><br><font><p><small><big><sup><sub><code><em>';
137 $source = preg_replace('|</div>|i', '<br />', $source);
138 $source = strip_tags($source, $allowedTags);
139 return preg_replace('/<(.*?)>/ie', "'<'.removeEvilAttributes('\\1').'>'", $source);
145 * @desc Strip forbidden attributes from a tag
147 function removeEvilAttributes($tagSource)
149 $stripAttrib = 'javascript:|onclick|ondblclick|onmousedown|onmouseup|onmouseover|'.
150 'onmousemove|onmouseout|onkeypress|onkeydown|onkeyup';
151 return stripslashes(preg_replace("/$stripAttrib/i", '', $tagSource));
154 /** Convert html to plain text
156 function htmlToPlainText($res)
158 $res = trim(html_entity_decode(strip_tags($res, '<div><br><p>')));
159 $res = preg_replace("@</?(br|p|div)[^>]*>@i", "\n", $res);
160 if (!is_utf8($res)) {
161 $res = utf8_encode($res);
166 /********************************************************************************
170 /** Convert richtext to html
172 function richtextToHtml($source)
174 $tags = Array('bold' => 'b',
176 'smaller' => 'small',
179 'subscript' => 'sub',
180 'superscript' => 'sup',
181 'excerpt' => 'blockquote',
186 // clean unsupported tags
187 $protectedTags = '<signature><lt><comment><'.join('><', array_keys($tags)).'>';
188 $source = strip_tags($source, $protectedTags);
190 // convert richtext tags to html
191 foreach (array_keys($tags) as $tag) {
192 $source = preg_replace('@(</?)'.$tag.'([^>]*>)@i', '\1'.$tags[$tag].'\2', $source);
195 // some special cases
196 $source = preg_replace('@<signature>@i', '<br>-- <br>', $source);
197 $source = preg_replace('@</signature>@i', '', $source);
198 $source = preg_replace('@<lt>@i', '<', $source);
199 $source = preg_replace('@<comment[^>]*>((?:[^<]|<(?!/comment>))*)</comment>@i', '<!-- \1 -->', $source);
200 return removeEvilAttributes($source);
203 /********************************************************************************
207 function _headerdecode($charset, $c, $str) {
208 $s = ($c == 'Q' ||
$c == 'q') ?
quoted_printable_decode($str) : base64_decode($str);
209 $s = iconv($charset, 'iso-8859-15', $s);
210 return str_replace('_', ' ', $s);
213 function headerDecode($value) {
214 $val = preg_replace('/(=\?[^?]*\?[BQbq]\?[^?]*\?=) (=\?[^?]*\?[BQbq]\?[^?]*\?=)/', '\1\2', $value);
215 return preg_replace('/=\?([^?]*)\?([BQbq])\?([^?]*)\?=/e', '_headerdecode("\1", "\2", "\3")', $val);
218 function headerEncode($value, $trim = 0) {
220 if (strlen($value) > $trim) {
221 $value = substr($value, 0, $trim) . "[...]";
224 return "=?UTF-8?B?".base64_encode($value)."?=";
227 function header_translate($hdr) {
229 case 'from': return _b_('De');
230 case 'subject': return _b_('Sujet');
231 case 'newsgroups': return _b_('Forums');
232 case 'followup-to': return _b_('Suivi-Ă ');
233 case 'date': return _b_('Date');
234 case 'organization': return _b_('Organisation');
235 case 'references': return _b_('Références');
236 case 'x-face': return _b_('Image');
238 if (function_exists('hook_headerTranslate')
239 && $res = hook_headerTranslate($hdr)) {
246 function formatDisplayHeader($_header,$_text) {
250 return formatDate($_text);
255 $groups = preg_split("/[\t ]*,[\t ]*/",$_text);
256 foreach ($groups as $g) {
257 $res .= makeHREF(Array('group' => $g), $g) . ', ';
259 return substr($res,0, -2);
262 return formatFrom($_text);
267 $text = str_replace("><","> <",$_text);
268 $text = preg_split("/[ \t]/",strtr($text,$banana->spool
->ids
));
269 $parents = preg_grep("/^\d+$/",$text);
270 $p = array_pop($parents);
275 $p = $banana->spool
->overview
[$p]->parent
;
277 foreach (array_reverse($par_ok) as $p) {
278 $rsl .= makeHREF(Array('group' => $banana->spool
->group
), $ndx) . ' ';
284 return '<img src="xface.php?face='.urlencode(base64_encode($_text)).'" alt="x-face" />';
287 if (function_exists('hook_formatDisplayHeader')
288 && $res = hook_formatDisplayHeader($_header, $_text))
292 return htmlentities($_text);
296 /********************************************************************************
300 function formatDate($_text) {
301 return strftime("%A %d %B %Y, %H:%M (fuseau serveur)", strtotime($_text));
304 function fancyDate($stamp) {
305 $today = intval(time() / (24*3600));
306 $dday = intval($stamp / (24*3600));
308 if ($today == $dday) {
310 } elseif ($today == 1 +
$dday) {
311 $format = _b_('hier')." %H:%M";
312 } elseif ($today < 7 +
$dday) {
313 $format = '%a %H:%M';
315 $format = '%a %e %b';
317 return strftime($format, $stamp);
320 function formatFrom($text) {
321 # From: mark@cbosgd.ATT.COM
322 # From: mark@cbosgd.ATT.COM (Mark Horton)
323 # From: Mark Horton <mark@cbosgd.ATT.COM>
324 $mailto = '<a href="mailto:';
326 $result = htmlentities($text);
327 if (preg_match("/^([^ ]+)@([^ ]+)$/",$text,$regs)) {
328 $result="$mailto{$regs[1]}@{$regs[2]}\">".htmlentities($regs[1]."@".$regs[2])."</a>";
330 if (preg_match("/^([^ ]+)@([^ ]+) \((.*)\)$/",$text,$regs)) {
331 $result="$mailto{$regs[1]}@{$regs[2]}\">".htmlentities($regs[3])."</a>";
333 if (preg_match("/^\"?([^<>\"]+)\"? +<(.+)@(.+)>$/",$text,$regs)) {
334 $result="$mailto{$regs[2]}@{$regs[3]}\">".htmlentities($regs[1])."</a>";
336 return preg_replace("/\\\(\(|\))/","\\1",$result);
339 function displayshortcuts($first = -1) {
341 extract($banana->state
);
343 $res = '<div class="banana_scuts">';
344 $res .= '[' . makeHREF(Array(), _b_('Liste des forums')) . '] ';
345 if (is_null($group)) {
346 return $res.'[' . makeHREF(Array('subscribe' => 1), _b_('Abonnements')) . ']</div>';
349 $res .= '[' . makeHREF(Array('group' => $group), $group) . '] ';
351 if (is_null($artid)) {
352 $res .= '[' . makeHREF(Array('group' => $group,
354 _b_('Nouveau message'))
356 if (sizeof($banana->spool
->overview
)>$banana->tmax
) {
358 $n = intval(log(count($banana->spool
->overview
), 10))+
1;
359 for ($ndx=1; $ndx <= sizeof($banana->spool
->overview
); $ndx +
= $banana->tmax
) {
361 $fmt = "[%0{$n}u-%0{$n}u] ";
363 $fmt = '[' . makeHREF(Array('group' => $group,
365 '%0' . $n . 'u-%0' . $n . 'u')
368 $res .= sprintf($fmt, $ndx, min($ndx+
$banana->tmax
-1,sizeof($banana->spool
->overview
)));
372 $res .= '[' . makeHREF(Array('group' => $group,
377 if ($banana->post
&& $banana->post
->checkcancel()) {
378 $res .= '[' . makeHREF(Array('group' => $group,
380 'action' => 'cancel'),
381 _b_('Annuler ce message'))
385 return $res.'</div>';
388 /********************************************************************************
389 * FORMATTING STUFF : BODY
392 function autoformat($text)
395 $length = $banana->wrap
;
397 $cmd = "echo ".escapeshellarg($text)." | perl -MText::Autoformat -e 'autoformat {left=>1, right=>$length, all=>1 };'";
398 exec($cmd, $result, $ret);
400 $result = split("\n", $text);
405 function wrap($text, $_prefix="", $_force=false
)
407 $parts = preg_split("/\n-- ?\n/", $text);
408 if (count($parts) >1) {
409 $sign = "\n-- \n" . array_pop($parts);
410 $text = join("\n-- \n", $parts);
416 $url = $banana->url_regexp
;
417 $length = $banana->wrap
;
418 $max = $length +
($length/10);
419 $splits = split("\n", $text);
423 foreach ($splits as $line) {
424 if ($_force ||
strlen($line) > $max) {
425 if (preg_match("!^(.*)($url)(.*)!i", $line, $matches) && strlen($matches[2]) > $length && strlen($matches) < 900) {
426 if (strlen($matches[1]) != 0) {
427 array_push($next, rtrim($matches[1]));
428 if (strlen($matches[1]) > $max) {
434 $result = array_merge($result, autoformat(join("\n", $next)));
436 $result = array_merge($result, $next);
440 array_push($result, $matches[2]);
442 if (strlen($matches[6]) != 0) {
443 array_push($next, ltrim($matches[6]));
444 if (strlen($matches[6]) > $max) {
450 array_push($next, $line);
453 array_push($next, $line);
457 $result = array_merge($result, autoformat(join("\n", $next)));
459 $result = array_merge($result, $next);
462 return $_prefix.join("\n$_prefix", $result).($_prefix ?
'' : $sign);
465 function cutlink($link)
469 if (strlen($link) > $banana->wrap
) {
470 $link = substr($link, 0, $banana->wrap
- 3)."...";
475 function cleanurl($url)
477 $url = str_replace('@', '%40', $url);
478 return '<a href="'.$url.'" title="'.$url.'">'.cutlink($url).'</a>';
481 function formatbody($_text, $format='plain', $flowed=false
)
483 if ($format == 'html') {
484 $res = '<br/>'.html_entity_decode(to_entities(removeEvilTags($_text))).'<br/>';
485 } else if ($format == 'richtext') {
486 $res = '<br/>'.html_entity_decode(to_entities(richtextToHtml($_text))).'<br/>';
488 $res = "\n\n" . to_entities(wrap($_text, "", $flowed))."\n\n";
489 $formatting = Array('\*' => 'strong',
492 foreach ($formatting as $limit=>$mark) {
493 $res = preg_replace('@' . $limit . '([^\s]+)' . $limit . '@', "<$mark>\\1</$mark>", $res);
497 if ($format != 'html') {
499 $url = $banana->url_regexp
;
500 $res = preg_replace("/(<|>|")/", " \\1 ", $res);
501 $res = preg_replace("!$url!ie", "'\\1'.cleanurl('\\2').'\\3'", $res);
502 $res = preg_replace('/(["\[])?(?:mailto:)?([a-z0-9.\-+_]+@[a-z0-9.\-+_]+)(["\]])?/i', '\1<a href="mailto:\2">\2</a>\3', $res);
503 $res = preg_replace("/ (<|>|") /", "\\1", $res);
505 if ($format == 'richtext') {
510 if ($format == 'html') {
511 $res = preg_replace("@(</p>)\n?-- ?\n?(<p[^>]*>|<br[^>]*>)@", "\\1<br/>-- \\2", $res);
512 $res = preg_replace("@<br[^>]*>\n?-- ?\n?(<p[^>]*>)@", "<br/>-- <br/>\\2", $res);
513 $res = preg_replace("@(<pre[^>]*>)\n?-- ?\n@", "<br/>-- <br/>\\1", $res);
514 $parts = preg_split("@(:?<p[^>]*>\n?-- ?\n?</p>|<br[^>]*>\n?-- ?\n?<br[^>]*>)@", $res);
516 while (preg_match("@(^|<pre>|\n)>@i", $res)) {
517 $res = preg_replace("@(^|<pre>|\n)((>[^\n]*\n)+)@ie",
518 "'\\1</pre><blockquote><pre>'"
519 .".stripslashes(preg_replace('@(^|<pre>|\n)>[ \\t\\r]*@i', '\\1', '\\2'))"
520 .".'</pre></blockquote><pre>'",
523 $res = preg_replace("@<pre>-- ?\n@", "<pre>\n-- \n", $res);
524 $parts = preg_split("/\n-- ?\n/", $res);
527 if (count($parts) > 1) {
528 $sign = array_pop($parts);
529 if ($format == 'html') {
530 $res = join('<br/>-- <br/>', $parts);
531 $sign = '<hr style="width: 100%; margin: 1em 0em; " />'.$sign.'<br/>';
533 $res = join('\n-- \n', $parts);
534 $sign = '</pre><hr style="width: 100%; margin: 1em 0em; " /><pre>'.$sign;
542 // vim:set et sw=4 sts=4 ts=4