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