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 redirect($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);
88 if ($params['action'] == 'view') {
89 $target = ' target="_blank"';
91 return '<a href="' . htmlentities($link) . $target . '">' . $text . '</a>';
94 /********************************************************************************
102 * @desc Strip forbidden tags and delegate tag-source check to removeEvilAttributes()
104 function removeEvilTags($source)
106 $allowedTags = '<h1><b><i><a><ul><li><pre><hr><blockquote><img><br><font><p><small><big><sup><sub><code><em>';
107 $source = preg_replace('|</div>|i', '<br />', $source);
108 $source = strip_tags($source, $allowedTags);
109 return preg_replace('/<(.*?)>/ie', "'<'.removeEvilAttributes('\\1').'>'", $source);
115 * @desc Strip forbidden attributes from a tag
117 function removeEvilAttributes($tagSource)
119 $stripAttrib = 'javascript:|onclick|ondblclick|onmousedown|onmouseup|onmouseover|'.
120 'onmousemove|onmouseout|onkeypress|onkeydown|onkeyup';
121 return stripslashes(preg_replace("/$stripAttrib/i", '', $tagSource));
124 /** Convert html to plain text
126 function htmlToPlainText($res)
128 $res = trim(html_entity_decode(strip_tags($res, '<div><br><p>')));
129 $res = preg_replace("@</?(br|p|div)[^>]*>@i", "\n", $res);
130 if (!is_utf8($res)) {
131 $res = utf8_encode($res);
136 /********************************************************************************
140 /** Convert richtext to html
142 function richtextToHtml($source)
144 $tags = Array('bold' => 'b',
146 'smaller' => 'small',
149 'subscript' => 'sub',
150 'superscript' => 'sup',
151 'excerpt' => 'blockquote',
156 // clean unsupported tags
157 $protectedTags = '<signature><lt><comment><'.join('><', array_keys($tags)).'>';
158 $source = strip_tags($source, $protectedTags);
160 // convert richtext tags to html
161 foreach (array_keys($tags) as $tag) {
162 $source = preg_replace('@(</?)'.$tag.'([^>]*>)@i', '\1'.$tags[$tag].'\2', $source);
165 // some special cases
166 $source = preg_replace('@<signature>@i', '<br>-- <br>', $source);
167 $source = preg_replace('@</signature>@i', '', $source);
168 $source = preg_replace('@<lt>@i', '<', $source);
169 $source = preg_replace('@<comment[^>]*>((?:[^<]|<(?!/comment>))*)</comment>@i', '<!-- \1 -->', $source);
170 return removeEvilAttributes($source);
173 /********************************************************************************
177 function _headerdecode($charset, $c, $str) {
178 $s = ($c == 'Q' ||
$c == 'q') ?
quoted_printable_decode($str) : base64_decode($str);
179 $s = iconv($charset, 'iso-8859-15', $s);
180 return str_replace('_', ' ', $s);
183 function headerDecode($value) {
184 $val = preg_replace('/(=\?[^?]*\?[BQbq]\?[^?]*\?=) (=\?[^?]*\?[BQbq]\?[^?]*\?=)/', '\1\2', $value);
185 return preg_replace('/=\?([^?]*)\?([BQbq])\?([^?]*)\?=/e', '_headerdecode("\1", "\2", "\3")', $val);
188 function headerEncode($value, $trim = 0) {
190 if (strlen($value) > $trim) {
191 $value = substr($value, 0, $trim) . "[...]";
194 return "=?UTF-8?B?".base64_encode($value)."?=";
197 function header_translate($hdr) {
199 case 'from': return _b_('De');
200 case 'subject': return _b_('Sujet');
201 case 'newsgroups': return _b_('Forums');
202 case 'followup-to': return _b_('Suivi-Ã ');
203 case 'date': return _b_('Date');
204 case 'organization': return _b_('Organisation');
205 case 'references': return _b_('Références');
206 case 'x-face': return _b_('Image');
208 if (function_exists('hook_headerTranslate')
209 && $res = hook_headerTranslate($hdr)) {
216 function formatDisplayHeader($_header,$_text) {
220 return formatDate($_text);
225 $groups = preg_split("/[\t ]*,[\t ]*/",$_text);
226 foreach ($groups as $g) {
227 $res .= makeHREF(Array('group' => $g), $g) . ', ';
229 return substr($res,0, -2);
232 return formatFrom($_text);
237 $text = str_replace("><","> <",$_text);
238 $text = preg_split("/[ \t]/",strtr($text,$banana->spool
->ids
));
239 $parents = preg_grep("/^\d+$/",$text);
240 $p = array_pop($parents);
245 $p = $banana->spool
->overview
[$p]->parent
;
247 foreach (array_reverse($par_ok) as $p) {
248 $rsl .= makeHREF(Array('group' => $banana->spool
->group
), $ndx);
254 return '<img src="xface.php?face='.urlencode(base64_encode($_text)).'" alt="x-face" />';
257 if (function_exists('hook_formatDisplayHeader')
258 && $res = hook_formatDisplayHeader($_header, $_text))
262 return htmlentities($_text);
266 /********************************************************************************
270 function formatDate($_text) {
271 return strftime("%A %d %B %Y, %H:%M (fuseau serveur)", strtotime($_text));
274 function fancyDate($stamp) {
275 $today = intval(time() / (24*3600));
276 $dday = intval($stamp / (24*3600));
278 if ($today == $dday) {
280 } elseif ($today == 1 +
$dday) {
281 $format = _b_('hier')." %H:%M";
282 } elseif ($today < 7 +
$dday) {
283 $format = '%a %H:%M';
285 $format = '%a %e %b';
287 return strftime($format, $stamp);
290 function formatFrom($text) {
291 # From: mark@cbosgd.ATT.COM
292 # From: mark@cbosgd.ATT.COM (Mark Horton)
293 # From: Mark Horton <mark@cbosgd.ATT.COM>
294 $mailto = '<a href="mailto:';
296 $result = htmlentities($text);
297 if (preg_match("/^([^ ]+)@([^ ]+)$/",$text,$regs)) {
298 $result="$mailto{$regs[1]}@{$regs[2]}\">".htmlentities($regs[1]."@".$regs[2])."</a>";
300 if (preg_match("/^([^ ]+)@([^ ]+) \((.*)\)$/",$text,$regs)) {
301 $result="$mailto{$regs[1]}@{$regs[2]}\">".htmlentities($regs[3])."</a>";
303 if (preg_match("/^\"?([^<>\"]+)\"? +<(.+)@(.+)>$/",$text,$regs)) {
304 $result="$mailto{$regs[2]}@{$regs[3]}\">".htmlentities($regs[1])."</a>";
306 return preg_replace("/\\\(\(|\))/","\\1",$result);
309 function displayshortcuts($first = -1) {
311 extract($banana->state
);
313 $res = '<div class="banana_scuts">';
314 $res .= '[' . makeHREF(Array(), _b_('Liste des forums')) . '] ';
315 if (is_null($group)) {
316 return $res.'[' . makeHREF(Array('subscribe' => 1), _b_('Abonnements')) . ']</div>';
319 $res .= '[' . makeHREF(Array('group' => $group), $group) . '] ';
321 if (is_null($artid)) {
322 $res .= '[' . makeHREF(Array('group' => $group,
324 _b_('Nouveau message'))
326 if (sizeof($banana->spool
->overview
)>$banana->tmax
) {
328 $n = intval(log(count($banana->spool
->overview
), 10))+
1;
329 for ($ndx=1; $ndx <= sizeof($banana->spool
->overview
); $ndx +
= $banana->tmax
) {
331 $fmt = "[%0{$n}u-%0{$n}u] ";
333 $fmt = '[' . makeHREF(Array('group' => $group,
335 '%0' . $n . 'u-%0' . $n . 'u')
338 $res .= sprintf($fmt, $ndx, min($ndx+
$banana->tmax
-1,sizeof($banana->spool
->overview
)));
342 $res .= '[' . makeHREF(Array('group' => $group,
347 if ($banana->post
&& $banana->post
->checkcancel()) {
348 $res .= '[' . makeHREF(Array('group' => $group,
350 'action' => 'cancel'),
351 _b_('Annuler ce message'))
355 return $res.'</div>';
358 /********************************************************************************
359 * FORMATTING STUFF : BODY
362 function autoformat($text)
365 $length = $banana->wrap
;
367 $cmd = "echo ".escapeshellarg($text)." | perl -MText::Autoformat -e 'autoformat {left=>1, right=>$length, all=>1 };'";
368 exec($cmd, $result, $ret);
370 $result = split("\n", $text);
375 function wrap($text, $_prefix="", $_force=false
)
377 $parts = preg_split("/\n-- ?\n/", $text);
378 if (count($parts) >1) {
379 $sign = "\n-- \n" . array_pop($parts);
380 $text = join("\n-- \n", $parts);
386 $url = $banana->url_regexp
;
387 $length = $banana->wrap
;
388 $max = $length +
($length/10);
389 $splits = split("\n", $text);
393 foreach ($splits as $line) {
394 if ($_force ||
strlen($line) > $max) {
395 if (preg_match("!^(.*)($url)(.*)!i", $line, $matches) && strlen($matches[2]) > $length && strlen($matches) < 900) {
396 if (strlen($matches[1]) != 0) {
397 array_push($next, rtrim($matches[1]));
398 if (strlen($matches[1]) > $max) {
404 $result = array_merge($result, autoformat(join("\n", $next)));
406 $result = array_merge($result, $next);
410 array_push($result, $matches[2]);
412 if (strlen($matches[6]) != 0) {
413 array_push($next, ltrim($matches[6]));
414 if (strlen($matches[6]) > $max) {
420 array_push($next, $line);
423 array_push($next, $line);
427 $result = array_merge($result, autoformat(join("\n", $next)));
429 $result = array_merge($result, $next);
432 return $_prefix.join("\n$_prefix", $result).($_prefix ?
'' : $sign);
435 function cutlink($link)
439 if (strlen($link) > $banana->wrap
) {
440 $link = substr($link, 0, $banana->wrap
- 3)."...";
445 function cleanurl($url)
447 $url = str_replace('@', '%40', $url);
448 return '<a href="'.$url.'" title="'.$url.'">'.cutlink($url).'</a>';
451 function formatbody($_text, $format='plain', $flowed=false
)
453 if ($format == 'html') {
454 $res = '<br/>'.html_entity_decode(to_entities(removeEvilTags($_text))).'<br/>';
455 } else if ($format == 'richtext') {
456 $res = '<br/>'.html_entity_decode(to_entities(richtextToHtml($_text))).'<br/>';
458 $res = "\n\n" . to_entities(wrap($_text, "", $flowed))."\n\n";
461 if ($format != 'html') {
463 $url = $banana->url_regexp
;
464 $res = preg_replace("/(<|>|")/", " \\1 ", $res);
465 $res = preg_replace("!$url!ie", "'\\1'.cleanurl('\\2').'\\3'", $res);
466 $res = preg_replace('/(["\[])?(?:mailto:)?([a-z0-9.\-+_]+@[a-z0-9.\-+_]+)(["\]])?/i', '\1<a href="mailto:\2">\2</a>\3', $res);
467 $res = preg_replace("/ (<|>|") /", "\\1", $res);
469 if ($format == 'richtext') {
474 if ($format == 'html') {
475 $res = preg_replace("@(</p>)\n?-- ?\n?(<p[^>]*>|<br[^>]*>)@", "\\1<br/>-- \\2", $res);
476 $res = preg_replace("@<br[^>]*>\n?-- ?\n?(<p[^>]*>)@", "<br/>-- <br/>\\2", $res);
477 $res = preg_replace("@(<pre[^>]*>)\n?-- ?\n@", "<br/>-- <br/>\\1", $res);
478 $parts = preg_split("@(:?<p[^>]*>\n?-- ?\n?</p>|<br[^>]*>\n?-- ?\n?<br[^>]*>)@", $res);
480 while (preg_match("@(^|<pre>|\n)>@i", $res)) {
481 $res = preg_replace("@(^|<pre>|\n)((>[^\n]*\n)+)@ie",
482 "'\\1</pre><blockquote><pre>'"
483 .".stripslashes(preg_replace('@(^|<pre>|\n)>[ \\t\\r]*@i', '\\1', '\\2'))"
484 .".'</pre></blockquote><pre>'",
487 $formatting = Array('\*' => 'strong',
490 foreach ($formatting as $limit=>$mark) {
491 $res = preg_replace('@' . $limit . '([^\s]+)' . $limit . '@', "<$mark>\\1</$mark>", $res);
493 $res = preg_replace("@<pre>-- ?\n@", "<pre>\n-- \n", $res);
494 $parts = preg_split("/\n-- ?\n/", $res);
497 if (count($parts) > 1) {
498 $sign = array_pop($parts);
499 if ($format == 'html') {
500 $res = join('<br/>-- <br/>', $parts);
501 $sign = '<hr style="width: 100%; margin: 1em 0em; " />'.$sign.'<br/>';
503 $res = join('\n-- \n', $parts);
504 $sign = '</pre><hr style="width: 100%; margin: 1em 0em; " /><pre>'.$sign;