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