Add height parameter to makeImg
[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
51 *
52 * Can be overloaded by defining a hook_makeLink function
53 */
9cac5c87 54function makeLink($params)
55{
d5588318 56 if (function_exists('hook_makeLink')
57 && $res = hook_makeLink($params)) {
58 return $res;
59 }
0eb1e7ef 60 $proto = empty($_SERVER['HTTPS']) ? 'http://' : 'https://';
9cac5c87 61 $host = $_SERVER['HTTP_HOST'];
62 $file = $_SERVER['PHP_SELF'];
63
d5588318 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;
0eb1e7ef 77}
78
79/** Format a link to be use in a link
80 * @ref makeLink
81 */
82function makeHREF($params, $text = null)
83{
d5588318 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>';
9cac5c87 93}
94
d7632010 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 */
4ccaaeb7 102function makeImg($img, $alt, $height = null, $width = null)
d7632010 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 }
4ccaaeb7 112 if (!is_null($height)) {
113 $height = ' height="' . $height . '"';
114 }
115
d7632010 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
4ccaaeb7 121 return '<img src="' . $url . '"' . $height . $width . ' alt="' . $alt . '" />';
d7632010 122}
123
8f6f50fb 124/********************************************************************************
125 * HTML STUFF
126 * Taken from php.net
127 */
128
5d133234 129/**
8f6f50fb 130 * @return string
131 * @param string
132 * @desc Strip forbidden tags and delegate tag-source check to removeEvilAttributes()
133 */
134function removeEvilTags($source)
135{
73ab762c 136 $allowedTags = '<h1><b><i><a><ul><li><pre><hr><blockquote><img><br><font><p><small><big><sup><sub><code><em>';
76032c26 137 $source = preg_replace('|</div>|i', '<br />', $source);
8f6f50fb 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 */
147function 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
5d133234 154/** Convert html to plain text
155 */
156function htmlToPlainText($res)
157{
76032c26 158 $res = trim(html_entity_decode(strip_tags($res, '<div><br><p>')));
159 $res = preg_replace("@</?(br|p|div)[^>]*>@i", "\n", $res);
e27ae1a3 160 if (!is_utf8($res)) {
161 $res = utf8_encode($res);
162 }
5d133234 163 return $res;
164}
165
166/********************************************************************************
167 * RICHTEXT STUFF
168 */
169
170/** Convert richtext to html
171 */
172function 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
73d5bf46 203/********************************************************************************
204 * HEADER STUFF
205 */
206
dd7d1c59 207function _headerdecode($charset, $c, $str) {
67d2dcfc 208 $s = ($c == 'Q' || $c == 'q') ? quoted_printable_decode($str) : base64_decode($str);
dd7d1c59 209 $s = iconv($charset, 'iso-8859-15', $s);
210 return str_replace('_', ' ', $s);
211}
212
213function headerDecode($value) {
67d2dcfc 214 $val = preg_replace('/(=\?[^?]*\?[BQbq]\?[^?]*\?=) (=\?[^?]*\?[BQbq]\?[^?]*\?=)/', '\1\2', $value);
215 return preg_replace('/=\?([^?]*)\?([BQbq])\?([^?]*)\?=/e', '_headerdecode("\1", "\2", "\3")', $val);
dd7d1c59 216}
217
9cf3f056
PHM
218function headerEncode($value, $trim = 0) {
219 if ($trim) {
d752880f
PHM
220 if (strlen($value) > $trim) {
221 $value = substr($value, 0, $trim) . "[...]";
222 }
9cf3f056
PHM
223 }
224 return "=?UTF-8?B?".base64_encode($value)."?=";
225}
226
e2cae7e3 227function header_translate($hdr) {
d4c19591 228 switch ($hdr) {
0a65ec9d 229 case 'from': return _b_('De');
230 case 'subject': return _b_('Sujet');
231 case 'newsgroups': return _b_('Forums');
d4c19591 232 case 'followup-to': return _b_('Suivi-ŕ');
0a65ec9d 233 case 'date': return _b_('Date');
234 case 'organization': return _b_('Organisation');
235 case 'references': return _b_('Références');
d4c19591 236 case 'x-face': return _b_('Image');
e2cae7e3 237 default:
559be3d6 238 if (function_exists('hook_headerTranslate')
239 && $res = hook_headerTranslate($hdr)) {
240 return $res;
2dbc0167 241 }
e2cae7e3 242 return $hdr;
243 }
244}
245
2dbc0167 246function 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) {
0eb1e7ef 257 $res .= makeHREF(Array('group' => $g), $g) . ', ';
2dbc0167 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);
58d1740e 271 $par_ok = Array();
2dbc0167 272
273 while ($p) {
58d1740e 274 $par_ok[]=$p;
2dbc0167 275 $p = $banana->spool->overview[$p]->parent;
276 }
58d1740e 277 foreach (array_reverse($par_ok) as $p) {
4840f22b 278 $rsl .= makeHREF(Array('group' => $banana->spool->group), $ndx) . ' ';
2dbc0167 279 $ndx++;
280 }
281 return $rsl;
282
283 case "x-face":
09a8b2b0 284 return '<img src="xface.php?face='.urlencode(base64_encode($_text)).'" alt="x-face" />';
2dbc0167 285
286 default:
559be3d6 287 if (function_exists('hook_formatDisplayHeader')
288 && $res = hook_formatDisplayHeader($_header, $_text))
289 {
290 return $res;
2dbc0167 291 }
292 return htmlentities($_text);
293 }
294}
295
73d5bf46 296/********************************************************************************
297 * FORMATTING STUFF
298 */
299
e2cae7e3 300function formatDate($_text) {
301 return strftime("%A %d %B %Y, %H:%M (fuseau serveur)", strtotime($_text));
302}
303
304function 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) {
0a65ec9d 311 $format = _b_('hier')." %H:%M";
e2cae7e3 312 } elseif ($today < 7 + $dday) {
1248ebac 313 $format = '%a %H:%M';
e2cae7e3 314 } else {
315 $format = '%a %e %b';
316 }
317 return strftime($format, $stamp);
318}
319
dd7d1c59 320function 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
f78f34d2 339function displayshortcuts($first = -1) {
41cf00eb 340 global $banana;
8d99c683 341 extract($banana->state);
342
559be3d6 343 $res = '<div class="banana_scuts">';
0eb1e7ef 344 $res .= '[' . makeHREF(Array(), _b_('Liste des forums')) . '] ';
8d99c683 345 if (is_null($group)) {
0eb1e7ef 346 return $res.'[' . makeHREF(Array('subscribe' => 1), _b_('Abonnements')) . ']</div>';
8d99c683 347 }
348
0eb1e7ef 349 $res .= '[' . makeHREF(Array('group' => $group), $group) . '] ';
8d99c683 350
351 if (is_null($artid)) {
0eb1e7ef 352 $res .= '[' . makeHREF(Array('group' => $group,
d5588318 353 'action' => 'new'),
354 _b_('Nouveau message'))
355 . '] ';
8d99c683 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 {
0eb1e7ef 363 $fmt = '[' . makeHREF(Array('group' => $group,
d5588318 364 'first' => $ndx),
365 '%0' . $n . 'u-%0' . $n . 'u')
366 . '] ';
f78f34d2 367 }
8d99c683 368 $res .= sprintf($fmt, $ndx, min($ndx+$banana->tmax-1,sizeof($banana->spool->overview)));
f78f34d2 369 }
8d99c683 370 }
371 } else {
0eb1e7ef 372 $res .= '[' . makeHREF(Array('group' => $group,
d5588318 373 'artid' => $artid,
374 'action' => 'new'),
375 _b_('Répondre'))
376 . '] ';
940ae667 377 if ($banana->post && $banana->post->checkcancel()) {
0eb1e7ef 378 $res .= '[' . makeHREF(Array('group' => $group,
d5588318 379 'artid' => $artid,
380 'action' => 'cancel'),
381 _b_('Annuler ce message'))
382 . '] ';
8d99c683 383 }
f78f34d2 384 }
8d99c683 385 return $res.'</div>';
f78f34d2 386}
387
388/********************************************************************************
389 * FORMATTING STUFF : BODY
390 */
391
28fb1083 392function 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) {
9ee36ea4 400 $result = split("\n", $text);
28fb1083 401 }
402 return $result;
403}
404
e04e6059 405function wrap($text, $_prefix="", $_force=false)
cced14b6 406{
dd7d1c59 407 $parts = preg_split("/\n-- ?\n/", $text);
276debfc 408 if (count($parts) >1) {
409 $sign = "\n-- \n" . array_pop($parts);
410 $text = join("\n-- \n", $parts);
3ee590a9 411 } else {
276debfc 412 $sign = '';
3ee590a9 413 }
2dbc0167 414
415 global $banana;
e04e6059 416 $url = $banana->url_regexp;
2dbc0167 417 $length = $banana->wrap;
e04e6059 418 $max = $length + ($length/10);
419 $splits = split("\n", $text);
28fb1083 420 $result = array();
421 $next = array();
422 $format = false;
e04e6059 423 foreach ($splits as $line) {
424 if ($_force || strlen($line) > $max) {
28fb1083 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);
e04e6059 451 }
28fb1083 452 } else {
453 array_push($next, $line);
e04e6059 454 }
455 }
28fb1083 456 if ($format) {
457 $result = array_merge($result, autoformat(join("\n", $next)));
458 } else {
459 $result = array_merge($result, $next);
ee4709c7 460 }
3ee590a9 461
f8e23519 462 return $_prefix.join("\n$_prefix", $result).($_prefix ? '' : $sign);
3ee590a9 463}
464
e04e6059 465function 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
4c921acf 475function cleanurl($url)
476{
477 $url = str_replace('@', '%40', $url);
478 return '<a href="'.$url.'" title="'.$url.'">'.cutlink($url).'</a>';
479}
480
e04e6059 481function formatbody($_text, $format='plain', $flowed=false)
8f6f50fb 482{
483 if ($format == 'html') {
76032c26 484 $res = '<br/>'.html_entity_decode(to_entities(removeEvilTags($_text))).'<br/>';
5d133234 485 } else if ($format == 'richtext') {
09f71105 486 $res = '<br/>'.html_entity_decode(to_entities(richtextToHtml($_text))).'<br/>';
8f6f50fb 487 } else {
e04e6059 488 $res = "\n\n" . to_entities(wrap($_text, "", $flowed))."\n\n";
03851c08 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 }
d5588318 495 }
8f6f50fb 496
09f71105 497 if ($format != 'html') {
498 global $banana;
499 $url = $banana->url_regexp;
500 $res = preg_replace("/(&lt;|&gt;|&quot;)/", " \\1 ", $res);
4c921acf 501 $res = preg_replace("!$url!ie", "'\\1'.cleanurl('\\2').'\\3'", $res);
09f71105 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 }
e04e6059 509
8f6f50fb 510 if ($format == 'html') {
9c192e03 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);
f5eb6c66 515 } else {
9ee36ea4 516 while (preg_match("@(^|<pre>|\n)&gt;@i", $res)) {
b7a8ff33 517 $res = preg_replace("@(^|<pre>|\n)((&gt;[^\n]*\n)+)@ie",
9ee36ea4 518 "'\\1</pre><blockquote><pre>'"
d5588318 519 .".stripslashes(preg_replace('@(^|<pre>|\n)&gt;[ \\t\\r]*@i', '\\1', '\\2'))"
520 .".'</pre></blockquote><pre>'",
521 $res);
73afa785 522 }
d5588318 523 $res = preg_replace("@<pre>-- ?\n@", "<pre>\n-- \n", $res);
f5eb6c66 524 $parts = preg_split("/\n-- ?\n/", $res);
8f6f50fb 525 }
526
dd7d1c59 527 if (count($parts) > 1) {
f5eb6c66 528 $sign = array_pop($parts);
529 if ($format == 'html') {
530 $res = join('<br/>-- <br/>', $parts);
73afa785 531 $sign = '<hr style="width: 100%; margin: 1em 0em; " />'.$sign.'<br/>';
f5eb6c66 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;
dd7d1c59 537 } else {
538 return $res;
539 }
cced14b6 540}
541
d5588318 542// vim:set et sw=4 sts=4 ts=4
3ee590a9 543?>