Use icons to represent actions
[banana.git] / banana / misc.inc.php
CommitLineData
78cd27b3 1<?php
2/********************************************************************************
3 * include/misc.inc.php : Misc functions
4 * -------------------------
5 *
6 * This file is part of the banana distribution
7 * Copyright: See COPYING files that comes with this distribution
8 ********************************************************************************/
9
10/********************************************************************************
11 * MISC
12 */
13
14function _b_($str) { return utf8_decode(dgettext('banana', utf8_encode($str))); }
15
16function to_entities($str) {
39816f8b 17 require_once dirname(__FILE__).'/utf8.php';
78cd27b3 18 return utf8entities(htmlentities($str, ENT_NOQUOTES, 'UTF-8'));
19}
20
21function is_utf8($s) { return iconv('utf-8', 'utf-8', $s) == $s; }
22
1f75b135 23function textFormat_translate($format)
24{
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;
30 }
31}
32
8e519bd8 33/** Redirect to the page with the given parameter
34 * @ref makeLink
35 */
41b90d00 36function redirectInBanana($params)
fe8cbf1d 37{
f6df9eb2 38 header('Location: ' . makeLink($params));
fe8cbf1d 39}
40
8e519bd8 41/** Make a link using the given parameters
42 * @param ARRAY params, the parameters with
43 * key => value
44 * Known key are:
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
78f61fa3 51 * - xface = to make a link to an xface
8e519bd8 52 *
53 * Can be overloaded by defining a hook_makeLink function
54 */
fe8cbf1d 55function makeLink($params)
56{
f6df9eb2 57 if (function_exists('hook_makeLink')
58 && $res = hook_makeLink($params)) {
59 return $res;
60 }
8e519bd8 61 $proto = empty($_SERVER['HTTPS']) ? 'http://' : 'https://';
fe8cbf1d 62 $host = $_SERVER['HTTP_HOST'];
63 $file = $_SERVER['PHP_SELF'];
64
78f61fa3 65 if (isset($params['xface'])) {
66 $file = dirname($file) . '/xface.php';
5b1eaebd 67 $get = 'face=' . urlencode(base64_encode($params['xface']));
78f61fa3 68 } else if (count($params) != 0) {
f6df9eb2 69 $get = '?';
70 foreach ($params as $key=>$value) {
71 if (strlen($get) != 1) {
72 $get .= '&';
73 }
74 $get .= $key . '=' . $value;
75 }
76 } else {
77 $get = '';
78 }
79
80 return $proto . $host . $file . $get;
8e519bd8 81}
82
83/** Format a link to be use in a link
84 * @ref makeLink
85 */
2ba32e89 86function makeHREF($params, $text = null, $popup = null, $class = null)
8e519bd8 87{
f6df9eb2 88 $link = makeLink($params);
89 if (is_null($text)) {
90 $text = $link;
91 }
f0dc6af4 92 if (!is_null($popup)) {
93 $popup = ' title="' . $popup . '"';
94 }
2ba32e89 95 if (!is_null($class)) {
96 $class = ' class="' . $class . '"';
97 }
f6df9eb2 98 $target = null;
99 if (isset($params['action']) && $params['action'] == 'view') {
100 $target = ' target="_blank"';
101 }
2ba32e89 102 return '<a href="' . htmlentities($link) . $target . '"' . $popup . $class . '>' . $text . '</a>';
fe8cbf1d 103}
104
c14c86f4 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)
109 *
110 * This function can be overloaded by defining hook_makeImg()
111 */
5e200c3e 112function makeImg($img, $alt, $height = null, $width = null)
c14c86f4 113{
114 if (function_exists('hook_makeImg')
f944d187 115 && $res = hook_makeImg($img, $alt, $height, $width)) {
c14c86f4 116 return $res;
117 }
118
119 if (!is_null($width)) {
120 $width = ' width="' . $width . '"';
121 }
5e200c3e 122 if (!is_null($height)) {
123 $height = ' height="' . $height . '"';
124 }
125
c14c86f4 126 $proto = empty($_SERVER['HTTPS']) ? 'http://' : 'https://';
127 $host = $_SERVER['HTTP_HOST'];
2ba32e89 128 $file = dirname($_SERVER['PHP_SELF']) . '/img/' . $img;
c14c86f4 129 $url = $proto . $host . $file;
130
5e200c3e 131 return '<img src="' . $url . '"' . $height . $width . ' alt="' . $alt . '" />';
c14c86f4 132}
133
2ba32e89 134/** Make a link using an image
135 */
136function makeImgLink($params, $img, $alt, $height = null, $width = null, $class = null)
137{
138 return makeHREF($params,
139 makeImg($img, ' [' . $alt . ']', $height, $width),
140 $alt,
141 $class);
142}
143
1f75b135 144/********************************************************************************
145 * HTML STUFF
146 * Taken from php.net
147 */
148
aef14768 149/**
1f75b135 150 * @return string
151 * @param string
152 * @desc Strip forbidden tags and delegate tag-source check to removeEvilAttributes()
153 */
154function removeEvilTags($source)
155{
f12fdb59 156 $allowedTags = '<h1><b><i><a><ul><li><pre><hr><blockquote><img><br><font><p><small><big><sup><sub><code><em>';
16b17ba5 157 $source = preg_replace('|</div>|i', '<br />', $source);
1f75b135 158 $source = strip_tags($source, $allowedTags);
159 return preg_replace('/<(.*?)>/ie', "'<'.removeEvilAttributes('\\1').'>'", $source);
160}
161
162/**
163 * @return string
164 * @param string
165 * @desc Strip forbidden attributes from a tag
166 */
167function removeEvilAttributes($tagSource)
168{
169 $stripAttrib = 'javascript:|onclick|ondblclick|onmousedown|onmouseup|onmouseover|'.
170 'onmousemove|onmouseout|onkeypress|onkeydown|onkeyup';
171 return stripslashes(preg_replace("/$stripAttrib/i", '', $tagSource));
172}
173
aef14768 174/** Convert html to plain text
175 */
176function htmlToPlainText($res)
177{
16b17ba5 178 $res = trim(html_entity_decode(strip_tags($res, '<div><br><p>')));
179 $res = preg_replace("@</?(br|p|div)[^>]*>@i", "\n", $res);
4cc80c9a 180 if (!is_utf8($res)) {
181 $res = utf8_encode($res);
182 }
aef14768 183 return $res;
184}
185
820ce67b 186/** Match **, // and __ to format plain text
187 */
188function formatPlainText($text)
189{
190 $formatting = Array('\*' => 'strong',
191 '_' => 'u',
192 '/' => 'em');
193 foreach ($formatting as $limit=>$mark) {
194 $text = preg_replace('@(^|\W)' . $limit . '(\w+)' . $limit . '(\W|$)@'
195 ,'\1<' . $mark . '>\2</' . $mark . '>\3'
196 , $text);
197 }
198 return $text;
199}
200
aef14768 201/********************************************************************************
202 * RICHTEXT STUFF
203 */
204
205/** Convert richtext to html
206 */
207function richtextToHtml($source)
208{
209 $tags = Array('bold' => 'b',
210 'italic' => 'i',
211 'smaller' => 'small',
212 'bigger' => 'big',
213 'underline' => 'u',
214 'subscript' => 'sub',
215 'superscript' => 'sup',
216 'excerpt' => 'blockquote',
217 'paragraph' => 'p',
218 'nl' => 'br'
219 );
220
221 // clean unsupported tags
222 $protectedTags = '<signature><lt><comment><'.join('><', array_keys($tags)).'>';
223 $source = strip_tags($source, $protectedTags);
224
225 // convert richtext tags to html
226 foreach (array_keys($tags) as $tag) {
227 $source = preg_replace('@(</?)'.$tag.'([^>]*>)@i', '\1'.$tags[$tag].'\2', $source);
228 }
229
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', '&lt;', $source);
234 $source = preg_replace('@<comment[^>]*>((?:[^<]|<(?!/comment>))*)</comment>@i', '<!-- \1 -->', $source);
235 return removeEvilAttributes($source);
236}
237
78cd27b3 238/********************************************************************************
239 * HEADER STUFF
240 */
241
242function _headerdecode($charset, $c, $str) {
eeae3e3e 243 $s = ($c == 'Q' || $c == 'q') ? quoted_printable_decode($str) : base64_decode($str);
78cd27b3 244 $s = iconv($charset, 'iso-8859-15', $s);
245 return str_replace('_', ' ', $s);
246}
247
248function headerDecode($value) {
eeae3e3e 249 $val = preg_replace('/(=\?[^?]*\?[BQbq]\?[^?]*\?=) (=\?[^?]*\?[BQbq]\?[^?]*\?=)/', '\1\2', $value);
250 return preg_replace('/=\?([^?]*)\?([BQbq])\?([^?]*)\?=/e', '_headerdecode("\1", "\2", "\3")', $val);
78cd27b3 251}
252
253function headerEncode($value, $trim = 0) {
254 if ($trim) {
255 if (strlen($value) > $trim) {
256 $value = substr($value, 0, $trim) . "[...]";
257 }
258 }
259 return "=?UTF-8?B?".base64_encode($value)."?=";
260}
261
262function header_translate($hdr) {
263 switch ($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');
272 default:
273 if (function_exists('hook_headerTranslate')
274 && $res = hook_headerTranslate($hdr)) {
275 return $res;
276 }
277 return $hdr;
278 }
279}
280
281function formatDisplayHeader($_header,$_text) {
282 global $banana;
820ce67b 283 if (function_exists('hook_formatDisplayHeader')
284 && $res = hook_formatDisplayHeader($_header, $_text)) {
285 return $res;
286 }
287
78cd27b3 288 switch ($_header) {
289 case "date":
290 return formatDate($_text);
291
292 case "followup-to":
293 case "newsgroups":
294 $res = "";
295 $groups = preg_split("/[\t ]*,[\t ]*/",$_text);
296 foreach ($groups as $g) {
8e519bd8 297 $res .= makeHREF(Array('group' => $g), $g) . ', ';
78cd27b3 298 }
299 return substr($res,0, -2);
300
301 case "from":
302 return formatFrom($_text);
303
304 case "references":
305 $rsl = "";
306 $ndx = 1;
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);
311 $par_ok = Array();
312
313 while ($p) {
314 $par_ok[]=$p;
315 $p = $banana->spool->overview[$p]->parent;
316 }
317 foreach (array_reverse($par_ok) as $p) {
1146dd8a 318 $rsl .= makeHREF(Array('group' => $banana->spool->group), $ndx) . ' ';
78cd27b3 319 $ndx++;
320 }
321 return $rsl;
322
323 case "x-face":
5b1eaebd 324 return '<img src="' . makeLink(Array('xface' => headerDecode($_text))) .'" alt="x-face" />';
820ce67b 325
326 case "subject":
0cae4790 327 $link = null;
328 if (function_exists('hook_getSubject')) {
329 $link = hook_getSubject($_text);
330 }
331 return formatPlainText($_text) . $link;
820ce67b 332
78cd27b3 333 default:
78cd27b3 334 return htmlentities($_text);
335 }
336}
337
338/********************************************************************************
339 * FORMATTING STUFF
340 */
341
342function formatDate($_text) {
343 return strftime("%A %d %B %Y, %H:%M (fuseau serveur)", strtotime($_text));
344}
345
346function fancyDate($stamp) {
347 $today = intval(time() / (24*3600));
348 $dday = intval($stamp / (24*3600));
349
350 if ($today == $dday) {
351 $format = "%H:%M";
352 } elseif ($today == 1 + $dday) {
353 $format = _b_('hier')." %H:%M";
354 } elseif ($today < 7 + $dday) {
355 $format = '%a %H:%M';
356 } else {
357 $format = '%a %e %b';
358 }
359 return strftime($format, $stamp);
360}
361
362function formatFrom($text) {
363# From: mark@cbosgd.ATT.COM
364# From: mark@cbosgd.ATT.COM (Mark Horton)
365# From: Mark Horton <mark@cbosgd.ATT.COM>
366 $mailto = '<a href="&#109;&#97;&#105;&#108;&#116;&#111;&#58;';
367
368 $result = htmlentities($text);
369 if (preg_match("/^([^ ]+)@([^ ]+)$/",$text,$regs)) {
370 $result="$mailto{$regs[1]}&#64;{$regs[2]}\">".htmlentities($regs[1]."&#64;".$regs[2])."</a>";
371 }
372 if (preg_match("/^([^ ]+)@([^ ]+) \((.*)\)$/",$text,$regs)) {
373 $result="$mailto{$regs[1]}&#64;{$regs[2]}\">".htmlentities($regs[3])."</a>";
374 }
375 if (preg_match("/^\"?([^<>\"]+)\"? +<(.+)@(.+)>$/",$text,$regs)) {
376 $result="$mailto{$regs[2]}&#64;{$regs[3]}\">".htmlentities($regs[1])."</a>";
377 }
378 return preg_replace("/\\\(\(|\))/","\\1",$result);
379}
380
2ba32e89 381function displayShortcuts($first = -1)
382{
78cd27b3 383 global $banana;
384 extract($banana->state);
2ba32e89 385
78cd27b3 386 $res = '<div class="banana_scuts">';
2ba32e89 387 $res .= '<span class="title"> Profil :</span> ' . makeHREF(Array('subscribe' => 1), _b_('Abonnements'));
388 if (function_exists('hook_shortcuts') && $cstm = hook_shortcuts()) {
389 $res .= ' . ' . $cstm;
78cd27b3 390 }
2ba32e89 391 $res .= '<br />';
392
393 $res .= '<span class="title">Navigation :</span> '
394 . (is_null($group) ? 'Les forums' : makeHREF(Array(), _b_('Les forums')));
395
396 if (!is_null($group)) {
397 $res .= ' > ' . makeHREF(Array('group' => $group), $group);
398 if (is_null($artid)) {
399 if (sizeof($banana->spool->overview)>$banana->tmax) {
400 $res .= ' > Pages<br />';
401 $n = intval(log(count($banana->spool->overview), 10))+1;
402 $i = 1;
403 for ($ndx = 1 ; $ndx <= sizeof($banana->spool->overview) ; $ndx += $banana->tmax) {
404 if ($first==$ndx) {
405 $fmt = $i . ' ';
406 } else {
407 $fmt = makeHREF(Array('group' => $group,
408 'first' => $ndx),
409 $i,
410 '%0' . $n . 'u-%0' . $n . 'u')
411 . ' ';
412 }
413 $i++;
414 $res .= sprintf($fmt, $ndx, min($ndx+$banana->tmax-1,sizeof($banana->spool->overview)));
78cd27b3 415 }
78cd27b3 416 }
2ba32e89 417 } else {
418 $res .= ' > Message';
78cd27b3 419 }
420 }
421 return $res.'</div>';
422}
423
424/********************************************************************************
425 * FORMATTING STUFF : BODY
426 */
427
9bd35988 428function autoformat($text)
429{
430 global $banana;
431 $length = $banana->wrap;
432
433 $cmd = "echo ".escapeshellarg($text)." | perl -MText::Autoformat -e 'autoformat {left=>1, right=>$length, all=>1 };'";
434 exec($cmd, $result, $ret);
435 if ($ret != 0) {
ebd93a2d 436 $result = split("\n", $text);
9bd35988 437 }
438 return $result;
439}
440
87514711 441function wrap($text, $_prefix="", $_force=false)
78cd27b3 442{
443 $parts = preg_split("/\n-- ?\n/", $text);
444 if (count($parts) >1) {
445 $sign = "\n-- \n" . array_pop($parts);
446 $text = join("\n-- \n", $parts);
447 } else {
448 $sign = '';
78cd27b3 449 }
450
451 global $banana;
87514711 452 $url = $banana->url_regexp;
78cd27b3 453 $length = $banana->wrap;
87514711 454 $max = $length + ($length/10);
455 $splits = split("\n", $text);
9bd35988 456 $result = array();
457 $next = array();
458 $format = false;
87514711 459 foreach ($splits as $line) {
460 if ($_force || strlen($line) > $max) {
9bd35988 461 if (preg_match("!^(.*)($url)(.*)!i", $line, $matches) && strlen($matches[2]) > $length && strlen($matches) < 900) {
462 if (strlen($matches[1]) != 0) {
463 array_push($next, rtrim($matches[1]));
464 if (strlen($matches[1]) > $max) {
465 $format = true;
466 }
467 }
468
469 if ($format) {
470 $result = array_merge($result, autoformat(join("\n", $next)));
471 } else {
472 $result = array_merge($result, $next);
473 }
474 $format = false;
475 $next = array();
476 array_push($result, $matches[2]);
477
478 if (strlen($matches[6]) != 0) {
479 array_push($next, ltrim($matches[6]));
480 if (strlen($matches[6]) > $max) {
481 $format = true;
482 }
483 }
484 } else {
485 $format = true;
486 array_push($next, $line);
87514711 487 }
9bd35988 488 } else {
489 array_push($next, $line);
87514711 490 }
491 }
9bd35988 492 if ($format) {
493 $result = array_merge($result, autoformat(join("\n", $next)));
494 } else {
495 $result = array_merge($result, $next);
a4c1ad46 496 }
78cd27b3 497
498 return $_prefix.join("\n$_prefix", $result).($_prefix ? '' : $sign);
499}
500
87514711 501function cutlink($link)
502{
503 global $banana;
504
505 if (strlen($link) > $banana->wrap) {
506 $link = substr($link, 0, $banana->wrap - 3)."...";
507 }
508 return $link;
509}
510
e7241984 511function cleanurl($url)
512{
513 $url = str_replace('@', '%40', $url);
514 return '<a href="'.$url.'" title="'.$url.'">'.cutlink($url).'</a>';
515}
516
87514711 517function formatbody($_text, $format='plain', $flowed=false)
1f75b135 518{
519 if ($format == 'html') {
16b17ba5 520 $res = '<br/>'.html_entity_decode(to_entities(removeEvilTags($_text))).'<br/>';
aef14768 521 } else if ($format == 'richtext') {
d67abd9d 522 $res = '<br/>'.html_entity_decode(to_entities(richtextToHtml($_text))).'<br/>';
1f75b135 523 } else {
87514711 524 $res = "\n\n" . to_entities(wrap($_text, "", $flowed))."\n\n";
820ce67b 525 $res = formatPlainText($res);
f6df9eb2 526 }
1f75b135 527
d67abd9d 528 if ($format != 'html') {
529 global $banana;
530 $url = $banana->url_regexp;
531 $res = preg_replace("/(&lt;|&gt;|&quot;)/", " \\1 ", $res);
e7241984 532 $res = preg_replace("!$url!ie", "'\\1'.cleanurl('\\2').'\\3'", $res);
d67abd9d 533 $res = preg_replace('/(["\[])?(?:mailto:)?([a-z0-9.\-+_]+@[a-z0-9.\-+_]+)(["\]])?/i', '\1<a href="mailto:\2">\2</a>\3', $res);
534 $res = preg_replace("/ (&lt;|&gt;|&quot;) /", "\\1", $res);
535
536 if ($format == 'richtext') {
537 $format = 'html';
538 }
539 }
87514711 540
1f75b135 541 if ($format == 'html') {
19e26ef7 542 $res = preg_replace("@(</p>)\n?-- ?\n?(<p[^>]*>|<br[^>]*>)@", "\\1<br/>-- \\2", $res);
543 $res = preg_replace("@<br[^>]*>\n?-- ?\n?(<p[^>]*>)@", "<br/>-- <br/>\\2", $res);
544 $res = preg_replace("@(<pre[^>]*>)\n?-- ?\n@", "<br/>-- <br/>\\1", $res);
545 $parts = preg_split("@(:?<p[^>]*>\n?-- ?\n?</p>|<br[^>]*>\n?-- ?\n?<br[^>]*>)@", $res);
11102461 546 } else {
ebd93a2d 547 while (preg_match("@(^|<pre>|\n)&gt;@i", $res)) {
6c7c1730 548 $res = preg_replace("@(^|<pre>|\n)((&gt;[^\n]*\n)+)@ie",
ebd93a2d 549 "'\\1</pre><blockquote><pre>'"
f6df9eb2 550 .".stripslashes(preg_replace('@(^|<pre>|\n)&gt;[ \\t\\r]*@i', '\\1', '\\2'))"
551 .".'</pre></blockquote><pre>'",
552 $res);
cfaab21d 553 }
f6df9eb2 554 $res = preg_replace("@<pre>-- ?\n@", "<pre>\n-- \n", $res);
11102461 555 $parts = preg_split("/\n-- ?\n/", $res);
1f75b135 556 }
557
78cd27b3 558 if (count($parts) > 1) {
11102461 559 $sign = array_pop($parts);
560 if ($format == 'html') {
561 $res = join('<br/>-- <br/>', $parts);
cfaab21d 562 $sign = '<hr style="width: 100%; margin: 1em 0em; " />'.$sign.'<br/>';
11102461 563 } else {
564 $res = join('\n-- \n', $parts);
565 $sign = '</pre><hr style="width: 100%; margin: 1em 0em; " /><pre>'.$sign;
566 }
567 return $res.$sign;
78cd27b3 568 } else {
569 return $res;
570 }
571}
572
f6df9eb2 573// vim:set et sw=4 sts=4 ts=4
78cd27b3 574?>