d680293cd6c390228870f766255045c6116dcb41
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=' . urlencode(base64_encode($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
, $popup = null
, $class = null
)
88 $link = makeLink($params);
92 if (!is_null($popup)) {
93 $popup = ' title="' . $popup . '"';
95 if (!is_null($class)) {
96 $class = ' class="' . $class . '"';
99 if (isset($params['action']) && $params['action'] == 'view') {
100 $target = ' target="_blank"';
102 return '<a href="' . htmlentities($link) .'"' . $target . $popup . $class . '>' . $text . '</a>';
105 /** Format tree images links
106 * @param img STRING Image name (without extension)
107 * @param alt STRING alternative string
108 * @param width INT to force width of the image (null if not defined)
110 * This function can be overloaded by defining hook_makeImg()
112 function makeImg($img, $alt, $height = null
, $width = null
)
114 if (function_exists('hook_makeImg')
115 && $res = hook_makeImg($img, $alt, $height, $width)) {
119 if (!is_null($width)) {
120 $width = ' width="' . $width . '"';
122 if (!is_null($height)) {
123 $height = ' height="' . $height . '"';
126 $proto = empty($_SERVER['HTTPS']) ?
'http://' : 'https://';
127 $host = $_SERVER['HTTP_HOST'];
128 $file = dirname($_SERVER['PHP_SELF']) . '/img/' . $img;
129 $url = $proto . $host . $file;
131 return '<img src="' . $url . '"' . $height . $width . ' alt="' . $alt . '" />';
134 /** Make a link using an image
136 function makeImgLink($params, $img, $alt, $height = null
, $width = null
, $class = null
)
138 return makeHREF($params,
139 makeImg($img, ' [' . $alt . ']', $height, $width),
144 /********************************************************************************
152 * @desc Strip forbidden tags and delegate tag-source check to removeEvilAttributes()
154 function removeEvilTags($source)
156 $allowedTags = '<h1><b><i><a><ul><li><pre><hr><blockquote><img><br><font><p><small><big><sup><sub><code><em>';
157 $source = preg_replace('|</div>|i', '<br />', $source);
158 $source = strip_tags($source, $allowedTags);
159 return preg_replace('/<(.*?)>/ie', "'<'.removeEvilAttributes('\\1').'>'", $source);
165 * @desc Strip forbidden attributes from a tag
167 function removeEvilAttributes($tagSource)
169 $stripAttrib = 'javascript:|onclick|ondblclick|onmousedown|onmouseup|onmouseover|'.
170 'onmousemove|onmouseout|onkeypress|onkeydown|onkeyup';
171 return stripslashes(preg_replace("/$stripAttrib/i", '', $tagSource));
174 /** Convert html to plain text
176 function htmlToPlainText($res)
178 $res = trim(html_entity_decode(strip_tags($res, '<div><br><p>')));
179 $res = preg_replace("@</?(br|p|div)[^>]*>@i", "\n", $res);
180 if (!is_utf8($res)) {
181 $res = utf8_encode($res);
186 /** Match **, // and __ to format plain text
188 function formatPlainText($text)
190 $formatting = Array('\*' => 'strong',
193 foreach ($formatting as $limit=>$mark) {
194 $text = preg_replace('@(^|\W)' . $limit . '(\w+)' . $limit . '(\W|$)@'
195 ,'\1<' . $mark . '>\2</' . $mark . '>\3'
201 /********************************************************************************
205 /** Convert richtext to html
207 function richtextToHtml($source)
209 $tags = Array('bold' => 'b',
211 'smaller' => 'small',
214 'subscript' => 'sub',
215 'superscript' => 'sup',
216 'excerpt' => 'blockquote',
221 // clean unsupported tags
222 $protectedTags = '<signature><lt><comment><'.join('><', array_keys($tags)).'>';
223 $source = strip_tags($source, $protectedTags);
225 // convert richtext tags to html
226 foreach (array_keys($tags) as $tag) {
227 $source = preg_replace('@(</?)'.$tag.'([^>]*>)@i', '\1'.$tags[$tag].'\2', $source);
230 // some special cases
231 $source = preg_replace('@<signature>@i', '<br>-- <br>', $source);
232 $source = preg_replace('@</signature>@i', '', $source);
233 $source = preg_replace('@<lt>@i', '<', $source);
234 $source = preg_replace('@<comment[^>]*>((?:[^<]|<(?!/comment>))*)</comment>@i', '<!-- \1 -->', $source);
235 return removeEvilAttributes($source);
238 /********************************************************************************
242 function _headerdecode($charset, $c, $str) {
243 $s = ($c == 'Q' ||
$c == 'q') ?
quoted_printable_decode($str) : base64_decode($str);
244 $s = iconv($charset, 'iso-8859-15', $s);
245 return str_replace('_', ' ', $s);
248 function headerDecode($value) {
249 $val = preg_replace('/(=\?[^?]*\?[BQbq]\?[^?]*\?=) (=\?[^?]*\?[BQbq]\?[^?]*\?=)/', '\1\2', $value);
250 return preg_replace('/=\?([^?]*)\?([BQbq])\?([^?]*)\?=/e', '_headerdecode("\1", "\2", "\3")', $val);
253 function headerEncode($value, $trim = 0) {
255 if (strlen($value) > $trim) {
256 $value = substr($value, 0, $trim) . "[...]";
259 return "=?UTF-8?B?".base64_encode($value)."?=";
262 function header_translate($hdr) {
264 case 'from': return _b_('De');
265 case 'subject': return _b_('Sujet');
266 case 'newsgroups': return _b_('Forums');
267 case 'followup-to': return _b_('Suivi-Ă ');
268 case 'date': return _b_('Date');
269 case 'organization': return _b_('Organisation');
270 case 'references': return _b_('Références');
271 case 'x-face': return _b_('Image');
273 if (function_exists('hook_headerTranslate')
274 && $res = hook_headerTranslate($hdr)) {
281 function formatDisplayHeader($_header,$_text) {
283 if (function_exists('hook_formatDisplayHeader')
284 && $res = hook_formatDisplayHeader($_header, $_text)) {
290 return formatDate($_text);
295 $groups = preg_split("/[\t ]*,[\t ]*/",$_text);
296 foreach ($groups as $g) {
297 $res .= makeHREF(Array('group' => $g), $g) . ', ';
299 return substr($res,0, -2);
302 return formatFrom($_text);
307 $text = str_replace("><","> <",$_text);
308 $text = preg_split("/[ \t]/",strtr($text,$banana->spool
->ids
));
309 $parents = preg_grep("/^\d+$/",$text);
310 $p = array_pop($parents);
315 $p = $banana->spool
->overview
[$p]->parent
;
317 foreach (array_reverse($par_ok) as $p) {
318 $rsl .= makeHREF(Array('group' => $banana->spool
->group
,
326 return '<img src="' . makeLink(Array('xface' => headerDecode($_text))) .'" alt="x-face" />';
330 if (function_exists('hook_getSubject')) {
331 $link = hook_getSubject($_text);
333 return formatPlainText($_text) . $link;
336 return htmlentities($_text);
340 /********************************************************************************
344 function formatDate($_text) {
345 return strftime("%A %d %B %Y, %H:%M (fuseau serveur)", strtotime($_text));
348 function fancyDate($stamp) {
349 $today = intval(time() / (24*3600));
350 $dday = intval($stamp / (24*3600));
352 if ($today == $dday) {
354 } elseif ($today == 1 +
$dday) {
355 $format = _b_('hier')." %H:%M";
356 } elseif ($today < 7 +
$dday) {
357 $format = '%a %H:%M';
359 $format = '%a %e %b';
361 return strftime($format, $stamp);
364 function formatFrom($text) {
365 # From: mark@cbosgd.ATT.COM
366 # From: mark@cbosgd.ATT.COM (Mark Horton)
367 # From: Mark Horton <mark@cbosgd.ATT.COM>
368 $mailto = '<a href="mailto:';
370 $result = htmlentities($text);
371 if (preg_match("/^([^ ]+)@([^ ]+)$/",$text,$regs)) {
372 $result="$mailto{$regs[1]}@{$regs[2]}\">".htmlentities($regs[1]."@".$regs[2])."</a>";
374 if (preg_match("/^([^ ]+)@([^ ]+) \((.*)\)$/",$text,$regs)) {
375 $result="$mailto{$regs[1]}@{$regs[2]}\">".htmlentities($regs[3])."</a>";
377 if (preg_match("/^\"?([^<>\"]+)\"? +<(.+)@(.+)>$/",$text,$regs)) {
378 $result="$mailto{$regs[2]}@{$regs[3]}\">".htmlentities($regs[1])."</a>";
380 return preg_replace("/\\\(\(|\))/","\\1",$result);
383 function displayShortcuts($first = -1)
386 extract($banana->state
);
388 $res = '<div class="banana_scuts">';
389 $res .= '<span class="title"> Profil :</span> ' . makeHREF(Array('subscribe' => 1), _b_('Abonnements'));
390 if (function_exists('hook_shortcuts') && $cstm = hook_shortcuts()) {
391 $res .= ' . ' . $cstm;
395 $res .= '<span class="title">Navigation :</span> '
396 . (is_null($group) ?
'Les forums' : makeHREF(Array(), _b_('Les forums')));
398 if (!is_null($group)) {
399 $res .= ' > ' . makeHREF(Array('group' => $group), $group);
400 if (is_null($artid)) {
401 if (sizeof($banana->spool
->overview
)>$banana->tmax
) {
402 $res .= ' > Pages<br />';
403 $n = intval(log(count($banana->spool
->overview
), 10))+
1;
405 for ($ndx = 1 ; $ndx <= sizeof($banana->spool
->overview
) ; $ndx +
= $banana->tmax
) {
409 $fmt = makeHREF(Array('group' => $group,
412 '%0' . $n . 'u-%0' . $n . 'u')
416 $res .= sprintf($fmt, $ndx, min($ndx+
$banana->tmax
-1,sizeof($banana->spool
->overview
)));
419 if (!is_null($action)) {
420 if ($action == 'new') {
421 $res .= ' > Nouveau Message';
425 if (!is_null($action)) {
426 $res .= ' > ' . makeHREF(Array('group' => $group,
430 if ($action == 'new') {
432 } elseif ($action == 'cancel') {
436 $res .= ' > Message';
440 return $res.'</div>';
443 /********************************************************************************
444 * FORMATTING STUFF : BODY
447 function autoformat($text, $part = false
)
450 $length = $banana->wrap
;
456 $cmd = "echo ".escapeshellarg($text)." | perl -MText::Autoformat -e 'autoformat {left=>1, right=>$length$all };'";
457 exec($cmd, $result, $ret);
459 $result = split("\n", $text);
464 function wrap($text, $_prefix="", $_force=false
)
466 $parts = preg_split("/\n-- ?\n/", $text);
467 if (count($parts) >1) {
468 $sign = "\n-- \n" . array_pop($parts);
469 $text = join("\n-- \n", $parts);
475 $url = $banana->url_regexp
;
476 $length = $banana->wrap
;
477 $max = $length +
($length/10);
478 $splits = split("\n", $text);
482 foreach ($splits as $line) {
483 if ($_force ||
strlen($line) > $max) {
484 if (preg_match("!^(.*)($url)(.*)!i", $line, $matches)
485 && strlen($matches[2]) > $length && strlen($matches) < 900) {
486 if (strlen($matches[1]) != 0) {
487 array_push($next, rtrim($matches[1]));
488 if (strlen($matches[1]) > $max) {
494 $result = array_merge($result, autoformat(join("\n", $next)));
496 $result = array_merge($result, $next);
500 array_push($result, $matches[2]);
502 if (strlen($matches[6]) != 0) {
503 array_push($next, ltrim($matches[6]));
504 if (strlen($matches[6]) > $max) {
509 if (strlen($line) > 2 * $max) {
510 $next = array_merge($next, autoformat($line, true
));
513 array_push($next, $line);
517 array_push($next, $line);
521 $result = array_merge($result, autoformat(join("\n", $next)));
523 $result = array_merge($result, $next);
526 return $_prefix.join("\n$_prefix", $result).($_prefix ?
'' : $sign);
529 function cutlink($link)
533 if (strlen($link) > $banana->wrap
) {
534 $link = substr($link, 0, $banana->wrap
- 3)."...";
539 function cleanurl($url)
541 $url = str_replace('@', '%40', $url);
542 return '<a href="'.$url.'" title="'.$url.'">'.cutlink($url).'</a>';
545 function formatbody($_text, $format='plain', $flowed=false
)
547 if ($format == 'html') {
548 $res = '<br/>'.html_entity_decode(to_entities(removeEvilTags($_text))).'<br/>';
549 } else if ($format == 'richtext') {
550 $res = '<br/>'.html_entity_decode(to_entities(richtextToHtml($_text))).'<br/>';
552 $res = "\n" . to_entities(wrap($_text, "", $flowed)) . "\n";
553 $res = formatPlainText($res);
556 if ($format != 'html') {
558 $url = $banana->url_regexp
;
559 $res = preg_replace("/(<|>|")/", " \\1 ", $res);
560 $res = preg_replace("!$url!ie", "'\\1'.cleanurl('\\2').'\\3'", $res);
561 $res = preg_replace('/(["\[])?(?:mailto:)?([a-z0-9.\-+_]+@[a-z0-9.\-+_]+)(["\]])?/i', '\1<a href="mailto:\2">\2</a>\3', $res);
562 $res = preg_replace("/ (<|>|") /", "\\1", $res);
564 if ($format == 'richtext') {
569 if ($format == 'html') {
570 $res = preg_replace("@(</p>)\n?-- ?\n?(<p[^>]*>|<br[^>]*>)@", "\\1<br/>-- \\2", $res);
571 $res = preg_replace("@<br[^>]*>\n?-- ?\n?(<p[^>]*>)@", "<br/>-- <br/>\\2", $res);
572 $res = preg_replace("@(<pre[^>]*>)\n?-- ?\n@", "<br/>-- <br/>\\1", $res);
573 $parts = preg_split("@(:?<p[^>]*>\n?-- ?\n?</p>|<br[^>]*>\n?-- ?\n?<br[^>]*>)@", $res);
574 $sign = '<hr style="width: 100%; margin: 1em 0em; " />';
577 while (preg_match("@(^|<pre>|\n)>@i", $res)) {
578 $res = preg_replace("@(^|<pre>|\n)((>[^\n]*\n)+)@ie",
579 "'\\1</pre><blockquote><pre>'"
580 .".stripslashes(preg_replace('@(^|<pre>|\n)>[ \\t\\r]*@i', '\\1', '\\2'))"
581 .".'</pre></blockquote><pre>'",
584 $res = preg_replace("@<pre>-- ?\n@", "<pre>\n-- \n", $res);
585 $parts = preg_split("/\n-- ?\n/", $res);
586 $sign = '</pre><hr style="width: 100%; margin: 1em 0em; " /><pre>';
590 return join($sign, $parts) . $end;
593 // vim:set et sw=4 sts=4 ts=4