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