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