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