Consolidate legacy syntax rules
[geekigeeki.git] / geekigeeki.py
index f89a844037a4d5428b31d86b89cac4ba8bbf984e..651d98db20e984506af833ebf7c810e20a8ae635 100755 (executable)
@@ -30,7 +30,7 @@ import cgi, sys, os, re, errno, stat
 word_re = re.compile(r"^\b((([A-Z][a-z0-9]+){2,}/)*([A-Z][a-z0-9]+){2,})\b$")
 # FIXME: we accept stuff like foo/../bar and we shouldn't
 file_re = re.compile(r"^\b([A-Za-z0-9_\-][A-Za-z0-9_\.\-/]*)\b$")
-img_re = re.compile(r"^.*\.(png|gif|jpg|jpeg|bmp|ico)$", re.IGNORECASE)
+img_re = re.compile(r"^.*\.(png|gif|jpg|jpeg|bmp|ico|ogm|ogg|mkv|mpg|mpeg|mp4|avi|asf|flv|wmv|qt)$", re.IGNORECASE)
 video_re = re.compile(r"^.*\.(ogm|ogg|mkv|mpg|mpeg|mp4|avi|asf|flv|wmv|qt)$", re.IGNORECASE)
 url_re = re.compile(r"^[a-z]{3,8}://[^\s'\"]+\S$")
 link_re = re.compile("(?:\[\[|{{)([^\s\|]+)(?:\s*\|\s*([^\]]+)|)(?:\]\]|}})")
@@ -62,8 +62,11 @@ def get_hostname(addr):
     except Exception:
         return addr
 
+def is_external_url(pathname):
+    return (url_re.match(pathname) or pathname.startswith('/'))
+
 def relative_url(pathname, privileged=False):
-    if not (url_re.match(pathname) or pathname.startswith('/')):
+    if not is_external_url(pathname):
         if privileged:
             url = privileged_path()
         else:
@@ -78,6 +81,13 @@ def permalink(s):
 def emit_header(mime_type="text/html"):
     print "Content-type: " + mime_type + "; charset=utf-8\n"
 
+def sendfile(dest_file, src_file):
+    """Efficiently copy file data between file descriptors"""
+    while 1:
+        data = src_file.read(65536)
+        if not data: break
+        dest_file.write(data)
+
 def send_guru(msg_text, msg_type):
     if not msg_text: return
     print '<pre id="guru" onclick="this.style.display = \'none\'" class="' + msg_type + '">'
@@ -87,28 +97,10 @@ def send_guru(msg_text, msg_type):
     if msg_type == 'error':
         print '\n      Guru Meditation #DEADBEEF.ABADC0DE'
     print '</pre>'
-    # FIXME: This little JS snippet is harder to pass than ACID 3.0 
-    print """
-    <script language="JavaScript" type="text/javascript">
-        var guru = document.getElementById('guru');
-        // Firefox 2.0 doesn't take border-color, but returns border-top-color fine
-        var color = document.defaultView.getComputedStyle(guru,null).getPropertyValue('border-top-color');
-
-        function guruOn() {
-            guru.style.setProperty('border-color', color, '');
-            setTimeout('guruOff()', 1000);
-        }
-        function guruOff() {
-            guru.style.setProperty('border-color', '#000000', '');
-            setTimeout('guruOn()', 1000);
-        }
-        // Safari 2.0 returns this rgba crap
-        // Konqueror 3.5.6 doesn't seem to support computed properties
-        if (color && color != 'rgba(0, 0, 0, 0)') {
-            //window.alert("enabled! color='" + color + "'");
-            guruOn();
-        }
-    </script>"""
+    try:
+        sendfile(sys.stdout, open('gurumeditation.js', 'rb'))
+    except IOError, err:
+        pass
 
 def send_title(name, text="Limbo", msg_text=None, msg_type='error', writable=False):
     global title_done
@@ -187,17 +179,26 @@ def send_httperror(status="403 Not Found", query=""):
     send_title(None, msg_text=("%s: on query '%s'" % (status, query)))
     send_footer()
 
-def link_tag(params, text=None, ss_class=None, privileged=False):
+def link_tag(params, text=None, link_class=None, privileged=False):
     if text is None:
         text = params # default
-    classattr = ''
-    if ss_class:
-        classattr += 'class="%s" ' % ss_class
-        # Prevent crawlers from following links potentially added by spammers or to generated pages
-        if ss_class == 'external' or ss_class == 'navlink':
-            classattr += 'rel="nofollow" '
-    elif url_re.match(params):
-        classattr += 'rel="nofollow" '
+    elif img_re.match(text):
+        text = '<img border="0" src="' + text + '" />'
+
+    if not link_class:
+        if is_external_url(params):
+            link_class = 'external'
+        elif file_re.match(params) and Page(params).exists():
+            link_class = 'wikilink'
+        else:
+            params = nonexist_pfx + params
+            link_class = 'nonexistent'
+
+    classattr = 'class="%s" ' % link_class
+    # Prevent crawlers from following links potentially added by spammers or to generated pages
+    if link_class == 'external' or link_class == 'navlink':
+        classattr += 'rel="nofollow"'
+
     return '<a %shref="%s">%s</a>' % (classattr, relative_url(params, privileged=privileged), text)
 
 # Search ---------------------------------------------------
@@ -221,7 +222,7 @@ def handle_fullsearch(needle):
 
     print "<ul>"
     for (count, page_name) in hits:
-        print '<li><p>' + Page(page_name).link_to()
+        print '<li><p>' + link_tag(page_name)
         print ' . . . . ' + `count`
         print ['match', 'matches'][count != 1]
         print '</p></li>'
@@ -239,7 +240,7 @@ def handle_titlesearch(needle):
 
     print "<ul>"
     for filename in hits:
-        print '<li><p>' + Page(filename).link_to() + "</p></li>"
+        print '<li><p>' + link_tag(filename) + "</p></li>"
     print "</ul>"
 
     print_search_stats(len(hits), len(all_pages))
@@ -346,19 +347,6 @@ class WikiFormatter:
     def _rule_repl(self, word):
         return self._undent() + '\n<hr size="%d" noshade="noshade" />\n' % (len(word) - 2)
 
-    def _word_repl(self, word):
-        return Page(word).link_to()
-
-    def _img_repl(self, word):
-        pathname = relative_url(word)
-        return '<a href="%s"><img border="0" src="%s" /></a>' % (pathname, pathname)
-
-    def _url_repl(self, word):
-        if img_re.match(word):
-            return '<a href="%s"><img border="0" src="%s" /></a>' % (word, word)
-        else:
-            return '<a href="%s" rel="nofollow" class="external">%s</a>' % (word, word)
-
     def _macro_repl(self, word):
         m = re.compile("\<\<([^\s\|\>]+)(?:\s*\|\s*([^\>]+)|)\>\>").match(word)
         name = m.group(1)
@@ -381,14 +369,13 @@ class WikiFormatter:
 
     def _hurl_repl(self, word):
         m = link_re.match(word)
-        name = m.group(1)
-        descr = m.group(2)
-        if descr is None:
-            descr = name
-        elif img_re.match(m.group(2)):
-            descr = '<img border="0" src="' + descr + '" />'
+        return link_tag(m.group(1), m.group(2))
+
+    def _url_repl(self, word):
+        return link_tag(word)
 
-        return link_tag(name, descr, 'wikilink')
+    def _word_repl(self, word):
+        return link_tag(word)
 
     def _inl_repl(self, word):
         m = link_re.match(word)
@@ -410,6 +397,9 @@ class WikiFormatter:
         else:
             return '<a href="%s"><img border="0" src="%s" /></a>' % (name, name)
 
+    def _img_repl(self, word):
+        return self._inl_repl('{{' + word + '}}')
+
     def _email_repl(self, word):
         return '<a href="mailto:%s">%s</a>' % (word, word)
 
@@ -521,7 +511,7 @@ class WikiFormatter:
             + r"|(?P<ent>[<>&])"
 
             # Auto links (LEGACY)
-            + r"|(?P<img>\b[a-zA-Z0-9_/-]+\.(png|gif|jpg|jpeg|bmp|ico))"
+            + r"|(?P<img>\b[a-zA-Z0-9_/-]+\.(png|gif|jpg|jpeg|bmp|ico|ogm|ogg|mkv|mpg|mpeg|mp4|avi|asf|flv|wmv|qt))"
             + r"|(?P<word>\b(?:[A-Z][a-z]+){2,}\b)"
             + r"|(?P<url>(http|https|ftp|mailto)\:[^\s'\"]+\S)"
             + r"|(?P<email>[-\w._+]+\@[\w.-]+)"
@@ -596,13 +586,6 @@ class Page:
                 return False
             raise err
 
-    def link_to(self):
-        word = self.page_name
-        if self.exists():
-            return link_tag(word, word, 'wikilink')
-        else:
-            return link_tag(word, nonexist_pfx + word, 'nonexistent')
-
     def get_raw_body(self):
         try:
             return open(self._filename(), 'rb').read()
@@ -732,7 +715,7 @@ class Page:
             //-->
             </script>
             """
-        print "<p>" + Page('EditingTips').link_to() + "</p>"
+        print "<p>" + link_tag('EditingTips') + "</p>"
         if preview:
             print "<div class='preview'>"
             WikiFormatter(preview).print_html()