Place formatting before html conversion of the article in order to avoid // matching...
[banana.git] / banana / misc.inc.php
index 04bd09c..ece2883 100644 (file)
@@ -30,6 +30,67 @@ function textFormat_translate($format)
     }
 }
 
+/** Redirect to the page with the given parameter
+ * @ref makeLink
+ */
+function redirect($params)
+{
+       header('Location: ' . makeLink($params));
+}
+
+/** Make a link using the given parameters
+ * @param ARRAY params, the parameters with
+ *       key => value
+ * Known key are:
+ *  - group       = group name
+ *  - artid/first = article id the the group
+ *  - subscribe   = to show the subscription page
+ *  - action      = action to do (new, cancel, view)
+ *  - part        = to show the given MIME part of the article
+ *  - pj          = to get the given attachment
+ *
+ * Can be overloaded by defining a hook_makeLink function
+ */
+function makeLink($params)
+{
+       if (function_exists('hook_makeLink')
+                       && $res = hook_makeLink($params)) {
+               return $res;
+       }
+    $proto = empty($_SERVER['HTTPS']) ? 'http://' : 'https://';
+    $host  = $_SERVER['HTTP_HOST'];
+    $file  = $_SERVER['PHP_SELF'];
+
+       if (count($params) != 0) {
+               $get = '?';
+               foreach ($params as $key=>$value) {
+                       if (strlen($get) != 1) {
+                               $get .= '&';
+                       }
+                       $get .= $key . '=' . $value;
+               }
+       } else {
+               $get = '';
+       }
+
+       return $proto . $host . $file . $get;
+}
+
+/** Format a link to be use in a link
+ * @ref makeLink
+ */
+function makeHREF($params, $text = null)
+{
+       $link = makeLink($params);
+       if (is_null($text)) {
+               $text = $link;
+       }
+       if ($params['action'] == 'view') {
+               $target = ' target="_blank"';
+       }
+       return '<a href="' . htmlentities($link) . $target . '">' . $text . '</a>';
+}
+
 /********************************************************************************
  * HTML STUFF
  * Taken from php.net
@@ -42,7 +103,8 @@ function textFormat_translate($format)
  */
 function removeEvilTags($source)
 {
-    $allowedTags = '<h1><b><i><a><ul><li><pre><hr><blockquote><img><br><font><p><small><big><sup><sub><code>';
+    $allowedTags = '<h1><b><i><a><ul><li><pre><hr><blockquote><img><br><font><p><small><big><sup><sub><code><em>';
+    $source = preg_replace('|</div>|i', '<br />', $source);
     $source = strip_tags($source, $allowedTags);
     return preg_replace('/<(.*?)>/ie', "'<'.removeEvilAttributes('\\1').'>'", $source);
 }
@@ -63,8 +125,8 @@ function removeEvilAttributes($tagSource)
  */
 function htmlToPlainText($res)
 {
-    $res = trim(html_entity_decode(strip_tags($res, '<br>')));
-    $res = preg_replace("@<br[^>]>@i", "\n", $res);
+    $res = trim(html_entity_decode(strip_tags($res, '<div><br><p>')));
+    $res = preg_replace("@</?(br|p|div)[^>]*>@i", "\n", $res);
     if (!is_utf8($res)) {
         $res = utf8_encode($res);
     }   
@@ -113,14 +175,14 @@ function richtextToHtml($source)
  */
 
 function _headerdecode($charset, $c, $str) {
-    $s = ($c == 'Q') ? quoted_printable_decode($str) : base64_decode($str);
+    $s = ($c == 'Q' || $c == 'q') ? quoted_printable_decode($str) : base64_decode($str);
     $s = iconv($charset, 'iso-8859-15', $s);
     return str_replace('_', ' ', $s);
 }
  
 function headerDecode($value) {
-    $val = preg_replace('/(=\?[^?]*\?[BQ]\?[^?]*\?=) (=\?[^?]*\?[BQ]\?[^?]*\?=)/', '\1\2', $value);
-    return preg_replace('/=\?([^?]*)\?([BQ])\?([^?]*)\?=/e', '_headerdecode("\1", "\2", "\3")', $val);
+    $val = preg_replace('/(=\?[^?]*\?[BQbq]\?[^?]*\?=) (=\?[^?]*\?[BQbq]\?[^?]*\?=)/', '\1\2', $value);
+    return preg_replace('/=\?([^?]*)\?([BQbq])\?([^?]*)\?=/e', '_headerdecode("\1", "\2", "\3")', $val);
 }
 
 function headerEncode($value, $trim = 0) {
@@ -162,7 +224,7 @@ function formatDisplayHeader($_header,$_text) {
             $res = "";
             $groups = preg_split("/[\t ]*,[\t ]*/",$_text);
             foreach ($groups as $g) {
-                $res.="<a href='?group=$g'>$g</a>, ";
+                $res .= makeHREF(Array('group' => $g), $g) . ', ';
             }
             return substr($res,0, -2);
 
@@ -183,13 +245,13 @@ function formatDisplayHeader($_header,$_text) {
                 $p = $banana->spool->overview[$p]->parent;
             }
             foreach (array_reverse($par_ok) as $p) {
-                $rsl .= "<a href=\"?group={$banana->spool->group}&amp;artid=$p\">$ndx</a> ";
+                $rsl .= makeHREF(Array('group' => $banana->spool->group), $ndx);
                 $ndx++;
             }
             return $rsl;
 
         case "x-face":
-            return '<img src="xface.php?face='.base64_encode($_text).'"  alt="x-face" />';
+            return '<img src="xface.php?face='.urlencode(base64_encode($_text)).'"  alt="x-face" />';
         
         default:
             if (function_exists('hook_formatDisplayHeader')
@@ -249,15 +311,18 @@ function displayshortcuts($first = -1) {
     extract($banana->state);
 
     $res  = '<div class="banana_scuts">';
-    $res .= '[<a href="?">'._b_('Liste des forums').'</a>] ';
+    $res .= '[' . makeHREF(Array(), _b_('Liste des forums')) . '] ';
     if (is_null($group)) {
-        return $res.'[<a href="?subscribe=1">'._b_('Abonnements').'</a>]</div>';
+        return $res.'[' . makeHREF(Array('subscribe' => 1), _b_('Abonnements')) . ']</div>';
     }
    
-    $res .= "[<a href=\"?group=$group\">$group</a>] ";
+    $res .= '[' . makeHREF(Array('group' => $group), $group) . '] ';
 
     if (is_null($artid)) {
-        $res .= "[<a href=\"?group=$group&amp;action=new\">"._b_('Nouveau message')."</a>] ";
+        $res .= '[' . makeHREF(Array('group'  => $group,
+                                                                        'action' => 'new'),
+                                                          _b_('Nouveau message'))
+                         . '] ';
         if (sizeof($banana->spool->overview)>$banana->tmax) {
             $res .= '<br />';
             $n = intval(log(count($banana->spool->overview), 10))+1;
@@ -265,17 +330,26 @@ function displayshortcuts($first = -1) {
                 if ($first==$ndx) {
                     $fmt = "[%0{$n}u-%0{$n}u] ";
                 } else {
-                    $fmt = "[<a href=\"?group=$group&amp;first=$ndx\">%0{$n}u-%0{$n}u</a>] ";
+                    $fmt = '[' . makeHREF(Array('group' => $group,
+                                                                   'first' => $ndx),
+                                                                                 '%0' . $n . 'u-%0' . $n . 'u')
+                                                . '] ';
                 }
                 $res .= sprintf($fmt, $ndx, min($ndx+$banana->tmax-1,sizeof($banana->spool->overview)));
             }
         }
     } else {
-        $res .= "[<a href=\"?group=$group&amp;artid=$artid&amp;action=new\">"
-            ._b_('Répondre')."</a>] ";
-        if ($banana->post->checkcancel()) {
-            $res .= "[<a href=\"?group=$group&amp;artid=$artid&amp;action=cancel\">"
-                ._b_('Annuler ce message')."</a>] ";
+        $res .= '[' . makeHREF(Array('group'  => $group,
+                                            'artid'  => $artid,
+                                                                        'action' => 'new'),
+                                                          _b_('Répondre'))
+                         . '] ';
+        if ($banana->post && $banana->post->checkcancel()) {
+            $res .= '[' . makeHREF(Array('group'  => $group,
+                                                    'artid'  => $artid,
+                                                                                'action' => 'cancel'), 
+                                                                  _b_('Annuler ce message'))
+                                 . '] ';
         }
     }
     return $res.'</div>';
@@ -285,7 +359,20 @@ function displayshortcuts($first = -1) {
  *  FORMATTING STUFF : BODY
  */
 
-function wrap($text, $_prefix="")
+function autoformat($text)
+{
+    global $banana;
+    $length = $banana->wrap;
+        
+    $cmd = "echo ".escapeshellarg($text)." | perl -MText::Autoformat -e 'autoformat {left=>1, right=>$length, all=>1 };'";
+    exec($cmd, $result, $ret);
+    if ($ret != 0) {
+        $result = split("\n", $text);
+    }
+    return $result;
+}                                
+
+function wrap($text, $_prefix="", $_force=false)
 {
     $parts = preg_split("/\n-- ?\n/", $text);
     if (count($parts)  >1) {
@@ -293,36 +380,117 @@ function wrap($text, $_prefix="")
         $text = join("\n-- \n", $parts);
     } else {
         $sign = '';
-        $text = $text;
     }
    
     global $banana;
+    $url    = $banana->url_regexp;
     $length = $banana->wrap;
-    $cmd = "echo ".escapeshellarg($text)." | perl -MText::Autoformat -e 'autoformat {left=>1, right=>$length, all=>1 };'";
-    exec($cmd, $result);
+    $max    = $length + ($length/10);
+    $splits = split("\n", $text);
+    $result = array();
+    $next   = array();
+    $format = false;
+    foreach ($splits as $line) {
+        if ($_force || strlen($line) > $max) {
+            if (preg_match("!^(.*)($url)(.*)!i", $line, $matches) && strlen($matches[2]) > $length && strlen($matches) < 900) {
+                if (strlen($matches[1]) != 0) {
+                    array_push($next, rtrim($matches[1]));
+                    if (strlen($matches[1]) > $max) {
+                        $format = true;
+                    }
+                }
+                    
+                if ($format) {
+                    $result = array_merge($result, autoformat(join("\n", $next)));
+                } else {
+                    $result = array_merge($result, $next);
+                }
+                $format = false;
+                $next   = array();
+                array_push($result, $matches[2]);
+                    
+                if (strlen($matches[6]) != 0) {
+                    array_push($next, ltrim($matches[6]));
+                    if (strlen($matches[6]) > $max) {
+                        $format = true;
+                    }
+                }
+            } else {
+                $format = true;
+                array_push($next, $line);
+            }
+        } else {
+            array_push($next, $line);
+        }
+    }
+    if ($format) {
+        $result = array_merge($result, autoformat(join("\n", $next)));
+    } else {
+        $result = array_merge($result, $next);
+    }
 
     return $_prefix.join("\n$_prefix", $result).($_prefix ? '' : $sign);
 }
 
-function formatbody($_text, $format='plain')
+function cutlink($link)
+{
+    global $banana;
+    
+    if (strlen($link) > $banana->wrap) {
+        $link = substr($link, 0, $banana->wrap - 3)."...";
+    }
+    return $link;
+}
+
+function cleanurl($url)
+{
+    $url = str_replace('@', '%40', $url);
+    return '<a href="'.$url.'" title="'.$url.'">'.cutlink($url).'</a>';
+}
+
+function formatbody($_text, $format='plain', $flowed=false)
 {
     if ($format == 'html') {
-        $res = '<br/>'.removeEvilTags($_text).'<br/>';
+        $res = '<br/>'.html_entity_decode(to_entities(removeEvilTags($_text))).'<br/>';
     } else if ($format == 'richtext') {
-        $res = '<br/>'.richtextToHtml($_text).'<br/>';
-        $format = 'html';
+        $res = '<br/>'.html_entity_decode(to_entities(richtextToHtml($_text))).'<br/>';
     } else {
-        $res  = "\n\n" . to_entities(wrap($_text, ""))."\n\n";
+        $res  = "\n\n" . to_entities(wrap($_text, "", $flowed))."\n\n";
+        $formatting = Array('\*' => 'strong',
+                            '_' => 'u',
+                            '/' => 'em');
+        foreach ($formatting as $limit=>$mark) {
+            $res = preg_replace('@' . $limit . '([^\s]+)' . $limit . '@', "<$mark>\\1</$mark>", $res);
+        }
+       }
+
+    if ($format != 'html') {
+        global $banana;
+        $url  = $banana->url_regexp;
+        $res  = preg_replace("/(&lt;|&gt;|&quot;)/", " \\1 ", $res);
+        $res  = preg_replace("!$url!ie", "'\\1'.cleanurl('\\2').'\\3'", $res);
+        $res  = preg_replace('/(["\[])?(?:mailto:)?([a-z0-9.\-+_]+@[a-z0-9.\-+_]+)(["\]])?/i', '\1<a href="mailto:\2">\2</a>\3', $res);
+        $res  = preg_replace("/ (&lt;|&gt;|&quot;) /", "\\1", $res);
+
+        if ($format == 'richtext') {
+            $format = 'html';
+        }
     }
-    $res  = preg_replace("/(&lt;|&gt;|&quot;)/", " \\1 ", $res);
-    $res  = preg_replace('/(["\[])?((https?|ftp|news):\/\/[a-z@0-9.~%$£µ&i#\-+=_\/\?]*)(["\]])?/i', "\\1<a href=\"\\2\">\\2</a>\\4", $res);
-    $res  = preg_replace("/ (&lt;|&gt;|&quot;) /", "\\1", $res);
-
     if ($format == 'html') {
-        $res = preg_replace("@(</p>)\n?-- \n?(<p[^>]*>|<br>)@", "\\1<br>-- \\2", $res);
-        $res = preg_replace("@<br>\n?-- \n?(<p[^>]*>)@", "<br>-- <br>\\2", $res);
-        $parts = preg_split("@(:?<p[^>]*>\n?-- \n?</p>|<br[^>]*>\n?-- \n?<br>)@", $res);
+        $res = preg_replace("@(</p>)\n?-- ?\n?(<p[^>]*>|<br[^>]*>)@", "\\1<br/>-- \\2", $res);
+        $res = preg_replace("@<br[^>]*>\n?-- ?\n?(<p[^>]*>)@", "<br/>-- <br/>\\2", $res);
+        $res = preg_replace("@(<pre[^>]*>)\n?-- ?\n@", "<br/>-- <br/>\\1", $res);
+        $parts = preg_split("@(:?<p[^>]*>\n?-- ?\n?</p>|<br[^>]*>\n?-- ?\n?<br[^>]*>)@", $res);
     } else {
+        while (preg_match("@(^|<pre>|\n)&gt;@i", $res)) {
+            $res  = preg_replace("@(^|<pre>|\n)((&gt;[^\n]*\n)+)@ie",
+                "'\\1</pre><blockquote><pre>'"
+                   .".stripslashes(preg_replace('@(^|<pre>|\n)&gt;[ \\t\\r]*@i', '\\1', '\\2'))"
+                   .".'</pre></blockquote><pre>'",
+                   $res);
+        }
+               $res = preg_replace("@<pre>-- ?\n@", "<pre>\n-- \n", $res);
         $parts = preg_split("/\n-- ?\n/", $res);
     }
 
@@ -330,7 +498,7 @@ function formatbody($_text, $format='plain')
         $sign  = array_pop($parts);
         if ($format == 'html') {
             $res  = join('<br/>-- <br/>', $parts);
-            $sign = '<hr style="width: 100%; margin: 1em 0em; " />'.$sign;
+            $sign = '<hr style="width: 100%; margin: 1em 0em; " />'.$sign.'<br/>';
         } else {
             $res  = join('\n-- \n', $parts);
             $sign = '</pre><hr style="width: 100%; margin: 1em 0em; " /><pre>'.$sign;