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
51 * - xface = to make a link to an xface
53 * Can be overloaded by defining a hook_makeLink function
55 function makeLink($params)
57 if (function_exists('hook_makeLink')
58 && $res = hook_makeLink($params)) {
61 $proto = empty($_SERVER['HTTPS']) ?
'http://' : 'https://';
62 $host = $_SERVER['HTTP_HOST'];
63 $file = $_SERVER['PHP_SELF'];
65 if (isset($params['xface'])) {
66 $file = dirname($file) . '/xface.php';
67 $get = 'face=' . $params['xface'];
68 } else if (count($params) != 0) {
70 foreach ($params as $key=>$value) {
71 if (strlen($get) != 1) {
74 $get .= $key . '=' . $value;
80 return $proto . $host . $file . $get;
83 /** Format a link to be use in a link
86 function makeHREF($params, $text = null
)
88 $link = makeLink($params);
93 if (isset($params['action']) && $params['action'] == 'view') {
94 $target = ' target="_blank"';
96 return '<a href="' . htmlentities($link) . $target . '">' . $text . '</a>';
99 /** Format tree images links
100 * @param img STRING Image name (without extension)
101 * @param alt STRING alternative string
102 * @param width INT to force width of the image (null if not defined)
104 * This function can be overloaded by defining hook_makeImg()
106 function makeImg($img, $alt, $height = null
, $width = null
)
108 if (function_exists('hook_makeImg')
109 && $res = hook_makeImg($img, $alt, $height, $width)) {
113 if (!is_null($width)) {
114 $width = ' width="' . $width . '"';
116 if (!is_null($height)) {
117 $height = ' height="' . $height . '"';
120 $proto = empty($_SERVER['HTTPS']) ?
'http://' : 'https://';
121 $host = $_SERVER['HTTP_HOST'];
122 $file = dirname($_SERVER['PHP_SELF']) . '/img/' . $img . '.gif';
123 $url = $proto . $host . $file;
125 return '<img src="' . $url . '"' . $height . $width . ' alt="' . $alt . '" />';
128 /********************************************************************************
136 * @desc Strip forbidden tags and delegate tag-source check to removeEvilAttributes()
138 function removeEvilTags($source)
140 $allowedTags = '<h1><b><i><a><ul><li><pre><hr><blockquote><img><br><font><p><small><big><sup><sub><code><em>';
141 $source = preg_replace('|</div>|i', '<br />', $source);
142 $source = strip_tags($source, $allowedTags);
143 return preg_replace('/<(.*?)>/ie', "'<'.removeEvilAttributes('\\1').'>'", $source);
149 * @desc Strip forbidden attributes from a tag
151 function removeEvilAttributes($tagSource)
153 $stripAttrib = 'javascript:|onclick|ondblclick|onmousedown|onmouseup|onmouseover|'.
154 'onmousemove|onmouseout|onkeypress|onkeydown|onkeyup';
155 return stripslashes(preg_replace("/$stripAttrib/i", '', $tagSource));
158 /** Convert html to plain text
160 function htmlToPlainText($res)
162 $res = trim(html_entity_decode(strip_tags($res, '<div><br><p>')));
163 $res = preg_replace("@</?(br|p|div)[^>]*>@i", "\n", $res);
164 if (!is_utf8($res)) {
165 $res = utf8_encode($res);
170 /********************************************************************************
174 /** Convert richtext to html
176 function richtextToHtml($source)
178 $tags = Array('bold' => 'b',
180 'smaller' => 'small',
183 'subscript' => 'sub',
184 'superscript' => 'sup',
185 'excerpt' => 'blockquote',
190 // clean unsupported tags
191 $protectedTags = '<signature><lt><comment><'.join('><', array_keys($tags)).'>';
192 $source = strip_tags($source, $protectedTags);
194 // convert richtext tags to html
195 foreach (array_keys($tags) as $tag) {
196 $source = preg_replace('@(</?)'.$tag.'([^>]*>)@i', '\1'.$tags[$tag].'\2', $source);
199 // some special cases
200 $source = preg_replace('@<signature>@i', '<br>-- <br>', $source);
201 $source = preg_replace('@</signature>@i', '', $source);
202 $source = preg_replace('@<lt>@i', '<', $source);
203 $source = preg_replace('@<comment[^>]*>((?:[^<]|<(?!/comment>))*)</comment>@i', '<!-- \1 -->', $source);
204 return removeEvilAttributes($source);
207 /********************************************************************************
211 function _headerdecode($charset, $c, $str) {
212 $s = ($c == 'Q' ||
$c == 'q') ?
quoted_printable_decode($str) : base64_decode($str);
213 $s = iconv($charset, 'iso-8859-15', $s);
214 return str_replace('_', ' ', $s);
217 function headerDecode($value) {
218 $val = preg_replace('/(=\?[^?]*\?[BQbq]\?[^?]*\?=) (=\?[^?]*\?[BQbq]\?[^?]*\?=)/', '\1\2', $value);
219 return preg_replace('/=\?([^?]*)\?([BQbq])\?([^?]*)\?=/e', '_headerdecode("\1", "\2", "\3")', $val);
222 function headerEncode($value, $trim = 0) {
224 if (strlen($value) > $trim) {
225 $value = substr($value, 0, $trim) . "[...]";
228 return "=?UTF-8?B?".base64_encode($value)."?=";
231 function header_translate($hdr) {
233 case 'from': return _b_('De');
234 case 'subject': return _b_('Sujet');
235 case 'newsgroups': return _b_('Forums');
236 case 'followup-to': return _b_('Suivi-Ă ');
237 case 'date': return _b_('Date');
238 case 'organization': return _b_('Organisation');
239 case 'references': return _b_('Références');
240 case 'x-face': return _b_('Image');
242 if (function_exists('hook_headerTranslate')
243 && $res = hook_headerTranslate($hdr)) {
250 function formatDisplayHeader($_header,$_text) {
254 return formatDate($_text);
259 $groups = preg_split("/[\t ]*,[\t ]*/",$_text);
260 foreach ($groups as $g) {
261 $res .= makeHREF(Array('group' => $g), $g) . ', ';
263 return substr($res,0, -2);
266 return formatFrom($_text);
271 $text = str_replace("><","> <",$_text);
272 $text = preg_split("/[ \t]/",strtr($text,$banana->spool
->ids
));
273 $parents = preg_grep("/^\d+$/",$text);
274 $p = array_pop($parents);
279 $p = $banana->spool
->overview
[$p]->parent
;
281 foreach (array_reverse($par_ok) as $p) {
282 $rsl .= makeHREF(Array('group' => $banana->spool
->group
), $ndx) . ' ';
288 return '<img src="' . makeLink(Array('xface' => urlencode(base64_encode($_text)))) .'" alt="x-face" />';
291 if (function_exists('hook_formatDisplayHeader')
292 && $res = hook_formatDisplayHeader($_header, $_text))
296 return htmlentities($_text);
300 /********************************************************************************
304 function formatDate($_text) {
305 return strftime("%A %d %B %Y, %H:%M (fuseau serveur)", strtotime($_text));
308 function fancyDate($stamp) {
309 $today = intval(time() / (24*3600));
310 $dday = intval($stamp / (24*3600));
312 if ($today == $dday) {
314 } elseif ($today == 1 +
$dday) {
315 $format = _b_('hier')." %H:%M";
316 } elseif ($today < 7 +
$dday) {
317 $format = '%a %H:%M';
319 $format = '%a %e %b';
321 return strftime($format, $stamp);
324 function formatFrom($text) {
325 # From: mark@cbosgd.ATT.COM
326 # From: mark@cbosgd.ATT.COM (Mark Horton)
327 # From: Mark Horton <mark@cbosgd.ATT.COM>
328 $mailto = '<a href="mailto:';
330 $result = htmlentities($text);
331 if (preg_match("/^([^ ]+)@([^ ]+)$/",$text,$regs)) {
332 $result="$mailto{$regs[1]}@{$regs[2]}\">".htmlentities($regs[1]."@".$regs[2])."</a>";
334 if (preg_match("/^([^ ]+)@([^ ]+) \((.*)\)$/",$text,$regs)) {
335 $result="$mailto{$regs[1]}@{$regs[2]}\">".htmlentities($regs[3])."</a>";
337 if (preg_match("/^\"?([^<>\"]+)\"? +<(.+)@(.+)>$/",$text,$regs)) {
338 $result="$mailto{$regs[2]}@{$regs[3]}\">".htmlentities($regs[1])."</a>";
340 return preg_replace("/\\\(\(|\))/","\\1",$result);
343 function displayshortcuts($first = -1) {
345 extract($banana->state
);
347 $res = '<div class="banana_scuts">';
348 $res .= '[' . makeHREF(Array(), _b_('Liste des forums')) . '] ';
349 if (is_null($group)) {
350 return $res.'[' . makeHREF(Array('subscribe' => 1), _b_('Abonnements')) . ']</div>';
353 $res .= '[' . makeHREF(Array('group' => $group), $group) . '] ';
355 if (is_null($artid)) {
356 $res .= '[' . makeHREF(Array('group' => $group,
358 _b_('Nouveau message'))
360 if (sizeof($banana->spool
->overview
)>$banana->tmax
) {
362 $n = intval(log(count($banana->spool
->overview
), 10))+
1;
363 for ($ndx=1; $ndx <= sizeof($banana->spool
->overview
); $ndx +
= $banana->tmax
) {
365 $fmt = "[%0{$n}u-%0{$n}u] ";
367 $fmt = '[' . makeHREF(Array('group' => $group,
369 '%0' . $n . 'u-%0' . $n . 'u')
372 $res .= sprintf($fmt, $ndx, min($ndx+
$banana->tmax
-1,sizeof($banana->spool
->overview
)));
376 $res .= '[' . makeHREF(Array('group' => $group,
381 if ($banana->post
&& $banana->post
->checkcancel()) {
382 $res .= '[' . makeHREF(Array('group' => $group,
384 'action' => 'cancel'),
385 _b_('Annuler ce message'))
389 return $res.'</div>';
392 /********************************************************************************
393 * FORMATTING STUFF : BODY
396 function autoformat($text)
399 $length = $banana->wrap
;
401 $cmd = "echo ".escapeshellarg($text)." | perl -MText::Autoformat -e 'autoformat {left=>1, right=>$length, all=>1 };'";
402 exec($cmd, $result, $ret);
404 $result = split("\n", $text);
409 function wrap($text, $_prefix="", $_force=false
)
411 $parts = preg_split("/\n-- ?\n/", $text);
412 if (count($parts) >1) {
413 $sign = "\n-- \n" . array_pop($parts);
414 $text = join("\n-- \n", $parts);
420 $url = $banana->url_regexp
;
421 $length = $banana->wrap
;
422 $max = $length +
($length/10);
423 $splits = split("\n", $text);
427 foreach ($splits as $line) {
428 if ($_force ||
strlen($line) > $max) {
429 if (preg_match("!^(.*)($url)(.*)!i", $line, $matches) && strlen($matches[2]) > $length && strlen($matches) < 900) {
430 if (strlen($matches[1]) != 0) {
431 array_push($next, rtrim($matches[1]));
432 if (strlen($matches[1]) > $max) {
438 $result = array_merge($result, autoformat(join("\n", $next)));
440 $result = array_merge($result, $next);
444 array_push($result, $matches[2]);
446 if (strlen($matches[6]) != 0) {
447 array_push($next, ltrim($matches[6]));
448 if (strlen($matches[6]) > $max) {
454 array_push($next, $line);
457 array_push($next, $line);
461 $result = array_merge($result, autoformat(join("\n", $next)));
463 $result = array_merge($result, $next);
466 return $_prefix.join("\n$_prefix", $result).($_prefix ?
'' : $sign);
469 function cutlink($link)
473 if (strlen($link) > $banana->wrap
) {
474 $link = substr($link, 0, $banana->wrap
- 3)."...";
479 function cleanurl($url)
481 $url = str_replace('@', '%40', $url);
482 return '<a href="'.$url.'" title="'.$url.'">'.cutlink($url).'</a>';
485 function formatbody($_text, $format='plain', $flowed=false
)
487 if ($format == 'html') {
488 $res = '<br/>'.html_entity_decode(to_entities(removeEvilTags($_text))).'<br/>';
489 } else if ($format == 'richtext') {
490 $res = '<br/>'.html_entity_decode(to_entities(richtextToHtml($_text))).'<br/>';
492 $res = "\n\n" . to_entities(wrap($_text, "", $flowed))."\n\n";
493 $formatting = Array('\*' => 'strong',
496 foreach ($formatting as $limit=>$mark) {
497 $res = preg_replace('@' . $limit . '([^\s]+)' . $limit . '@', "<$mark>\\1</$mark>", $res);
501 if ($format != 'html') {
503 $url = $banana->url_regexp
;
504 $res = preg_replace("/(<|>|")/", " \\1 ", $res);
505 $res = preg_replace("!$url!ie", "'\\1'.cleanurl('\\2').'\\3'", $res);
506 $res = preg_replace('/(["\[])?(?:mailto:)?([a-z0-9.\-+_]+@[a-z0-9.\-+_]+)(["\]])?/i', '\1<a href="mailto:\2">\2</a>\3', $res);
507 $res = preg_replace("/ (<|>|") /", "\\1", $res);
509 if ($format == 'richtext') {
514 if ($format == 'html') {
515 $res = preg_replace("@(</p>)\n?-- ?\n?(<p[^>]*>|<br[^>]*>)@", "\\1<br/>-- \\2", $res);
516 $res = preg_replace("@<br[^>]*>\n?-- ?\n?(<p[^>]*>)@", "<br/>-- <br/>\\2", $res);
517 $res = preg_replace("@(<pre[^>]*>)\n?-- ?\n@", "<br/>-- <br/>\\1", $res);
518 $parts = preg_split("@(:?<p[^>]*>\n?-- ?\n?</p>|<br[^>]*>\n?-- ?\n?<br[^>]*>)@", $res);
520 while (preg_match("@(^|<pre>|\n)>@i", $res)) {
521 $res = preg_replace("@(^|<pre>|\n)((>[^\n]*\n)+)@ie",
522 "'\\1</pre><blockquote><pre>'"
523 .".stripslashes(preg_replace('@(^|<pre>|\n)>[ \\t\\r]*@i', '\\1', '\\2'))"
524 .".'</pre></blockquote><pre>'",
527 $res = preg_replace("@<pre>-- ?\n@", "<pre>\n-- \n", $res);
528 $parts = preg_split("/\n-- ?\n/", $res);
531 if (count($parts) > 1) {
532 $sign = array_pop($parts);
533 if ($format == 'html') {
534 $res = join('<br/>-- <br/>', $parts);
535 $sign = '<hr style="width: 100%; margin: 1em 0em; " />'.$sign.'<br/>';
537 $res = join('\n-- \n', $parts);
538 $sign = '</pre><hr style="width: 100%; margin: 1em 0em; " /><pre>'.$sign;
546 // vim:set et sw=4 sts=4 ts=4