Print version
[geekigeeki.git] / geekigeeki.py
index aa6d332a449e2b9b3ce481e38c0862f820ce67af..e6cfeca70ef5501177e27af3711418b1636cb81c 100755 (executable)
@@ -19,7 +19,7 @@
 # You should have received a copy of the GNU General Public License
 # along with this program.  If not, see <http://www.gnu.org/licenses/>.
 
-__version__ = '$Revision: 1.63+gerry+bernie $'[11:-2]
+__version__ = '$Id$'[3:-2]
 
 import cgi, sys, string, os, re, errno, time, stat
 from os import path, environ
@@ -154,8 +154,7 @@ def link_tag(params, text=None, ss_class=None, authentication=False):
     classattr = ''
     if ss_class:
         classattr += 'class="%s" ' % ss_class
-        # Prevent crawlers from following links to generated pages
-        # and links added by potential spammers
+        # Prevent crawlers from following links potentially added by spammers or to generated pages
         if ss_class == 'external' or ss_class == 'navlink':
             classattr += 'rel="nofollow" '
     if authentication:
@@ -220,9 +219,6 @@ def do_raw(pagename):
     Page(pagename).send_raw()
 
 def do_savepage(pagename):
-    if privileged_url is None:
-        raise 'editing disallowed for ' + pagename
-
     global form
     pg = Page(pagename)
     if 'preview' in form:
@@ -231,7 +227,7 @@ def do_savepage(pagename):
         pg.save_text(form['savetext'].value)
         pg.send_page()
     elif 'cancel' in form:
-        pg.msg = 'Editing cancelled'
+        pg.msg = 'Editing canceled'
         pg.msg_type = 'notice'
         pg.send_page()
     else:
@@ -255,8 +251,11 @@ def send_footer(name, mod_string=None):
         cgi.print_arguments()
         cgi.print_form(cgi.FieldStorage())
         cgi.print_environ()
+    global __version__
     print '<div id="footer"><hr />'
-    print '<p class="copyright">Powered by <a href="http://www.codewiz.org/wiki/GeekiGeeki">GeekiGeeki</a></p>'
+    print ('<p class="copyright">Powered by' +
+        ' <a href="http://www.codewiz.org/wiki/GeekiGeeki">GeekiGeeki</a>' +
+        ' version %s</p>' % __version__)
     if mod_string:
         print '<p class="modified">last modified %s</p>' % mod_string
     print '</div></body></html>'
@@ -264,10 +263,10 @@ def send_footer(name, mod_string=None):
 
 # ----------------------------------------------------------
 # Macros
-def _macro_TitleSearch():
+def _macro_TitleSearch(*vargs):
     return _macro_search("titlesearch")
 
-def _macro_FullSearch():
+def _macro_FullSearch(*vargs):
     return _macro_search("fullsearch")
 
 def _macro_search(type):
@@ -275,9 +274,9 @@ def _macro_search(type):
         default = form["value"].value
     else:
         default = ''
-    return """<form method="get"><input name="%s" size="30" value="%s"><input type="submit" value="Go" /></form>""" % (type, default)
+    return """<form method="get"><input name="%s" size="30" value="%s" /><input type="submit" value="Search" /></form>""" % (type, default)
 
-def _macro_WordIndex():
+def _macro_WordIndex(*vargs):
     s = make_index_key()
     pages = list(page_list())
     map = {}
@@ -310,7 +309,7 @@ def _macro_WordIndex():
     return s
 
 
-def _macro_TitleIndex():
+def _macro_TitleIndex(*vargs):
     s = make_index_key()
     pages = list(page_list())
     pages.sort()
@@ -337,6 +336,7 @@ class PageFormatter:
         self.raw = raw
         self.is_em = self.is_b = 0
         self.h_level = 0
+        self.h_count = 0
         self.list_indents = []
         self.in_pre = False
         self.in_table = False
@@ -354,60 +354,61 @@ class PageFormatter:
 
     def _tit_repl(self, word):
         if self.h_level:
-            result = "</h%d>" % self.h_level
+            result = '</h%d>' % self.h_level
             self.h_level = 0
         else:
             self.h_level = len(word) - 1
-            result = "<h%d>" % self.h_level
+            self.h_count += 1
+            result = '<h%d id="%d"><a class="heading" href="#%d">*</a> ' % (self.h_level, self.h_count, self.h_count)
         return result
 
     def _rule_repl(self, word):
-        s = self._undent()
-        if len(word) <= 3:
-            s = s + "\n<hr size='1' noshade=\"noshade\" />\n"
-        else:
-            s = s + "\n<hr size='%d' noshade=\"noshade\" />\n" % (len(word) - 2 )
-        return s
+        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):
-        return '<img border="0" src="%s/%s" />' % (script_name(), word)
+        path = script_name() + '/' + word;
+        return '<a href="%s"><img border="0" src="%s" /></a>' % (path, path)
 
     def _url_repl(self, word):
         if img_re.match(word):
-            return '<img border="0" src="%s" />' % 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 _hurl_repl(self, word):
-        m = re.compile("\[\[(\S+)\ (.+)\]\]").match(word)
-        anchor = m.group(1)
-        descr = m.group(2)
-        if img_re.match(anchor):
-            return '<img border="0" src="%s" alt="%s" />' % (anchor, descr)
-        elif url_re.match(anchor):
-            return '<a href="%s" rel="nofollow" class="external">%s</a>' % (anchor, descr)
-        elif anchor.startswith('/'):
-            return '<a href="%s">%s</a>' % (anchor, descr)
+        m = re.compile("\[\[(\S+)([^\]]*)\]\]").match(word)
+        name = m.group(1)
+        descr = m.group(2).strip() or name
+
+        macro = globals().get('_macro_' + name)
+        if macro:
+            return apply(macro, (name, descr))
+        elif img_re.match(name):
+            return '<a href="%s"><img border="0" src="%s" alt="%s" /></a>' % (name, name, descr)
+        elif url_re.match(name):
+            return '<a href="%s" rel="nofollow" class="external">%s</a>' % (name, descr)
+        elif name.startswith('/'):
+            return '<a href="%s">%s</a>' % (name, descr)
         else:
-            return link_tag(anchor, descr)
+            return link_tag(name, descr)
 
     def _email_repl(self, word):
         return '<a href="mailto:%s">%s</a>' % (word, word)
 
+    def _html_repl(self, word):
+        return word; # Pass through
 
     def _ent_repl(self, s):
         return {'&': '&amp;',
                 '<': '&lt;',
                 '>': '&gt;'}[s]
 
-
     def _li_repl(self, match):
         return '<li>'
 
-
     def _pre_repl(self, word):
         if word == '{{{' and not self.in_pre:
             self.in_pre = True
@@ -417,8 +418,14 @@ class PageFormatter:
             return '</pre>'
         return ''
 
-    def _hilight_repl(self, word):
-        return '<strong class="hilight">' + word + '</strong>'
+    def _hi_repl(self, word):
+        if word == 'FIXME':
+            cl = 'error'
+        elif word == 'DONE':
+            cl = 'success'
+        elif word == 'TODO':
+            cl = 'notice'
+        return '<strong class="highlight ' + cl + '">' + word + '</strong>'
 
     def _var_repl(self, word):
         if word == '{{' and not self.in_var:
@@ -448,11 +455,6 @@ class PageFormatter:
             return '</td><td>'
         return ''
 
-    def _macro_repl(self, word):
-        macro_name = word[2:-2]
-        # TODO: Somehow get the default value into the search field
-        return apply(globals()['_macro_' + macro_name], ())
-
     def _indent_level(self):
         return len(self.list_indents) and self.list_indents[-1]
 
@@ -484,7 +486,7 @@ class PageFormatter:
             raise "Can't handle match " + `match`
 
     def print_html(self):
-        print "<div class='wiki'><p>"
+        print '<div class="wiki"><p>'
 
         # For each line, we scan through looking for magic
         # strings, outputting verbatim any intervening text
@@ -495,14 +497,15 @@ class PageFormatter:
             + r"(?P<emph>'{2,3})"
             + r"|(?P<tit>\={2,6})"
             + r"|(?P<rule>^-{3,})"
+            + r"|(?P<html><(/|)(div|span|iframe)[^<>]*>)"
             + r"|(?P<ent>[<>&])"
-            + r"|(?P<hilight>\b(FIXME|TODO)\b)"
+            + r"|(?P<hi>\b(FIXME|TODO|DONE)\b)"
 
             # Links
             + r"|(?P<img>\b[a-zA-Z0-9_-]+\.(png|gif|jpg|jpeg|bmp))"
             + r"|(?P<word>\b(?:[A-Z][a-z]+){2,}\b)"
-            + r"|(?P<hurl>\[\[\S+\s+.+\]\])"
-            + r"|(?P<url>(http|ftp|nntp|news|mailto)\:[^\s'\"]+\S)"
+            + r"|(?P<hurl>\[\[\S+[^\]]*\]\])"
+            + r"|(?P<url>(http|https|ftp|mailto)\:[^\s'\"]+\S)"
             + r"|(?P<email>[-\w._+]+\@[\w.-]+)"
 
             # Lists, divs, spans
@@ -514,9 +517,6 @@ class PageFormatter:
             + r"|(?P<tr>^\s*\|\|\s*)"
             + r"|(?P<tre>\s*\|\|\s*$)"
             + r"|(?P<td>\s*\|\|\s*)"
-
-            # Macros
-            + r"|(?P<macro>\[\[(TitleSearch|FullSearch|WordIndex|TitleIndex)\]\])"
             + r")")
         pre_re = re.compile(
             r"(?:"
@@ -551,7 +551,7 @@ class PageFormatter:
         if self.in_pre: print '</pre>'
         if self.in_table: print '</tbody></table><p>'
         print self._undent()
-        print "</p></div>"
+        print '</p></div>'
 
 # ----------------------------------------------------------
 class Page:
@@ -587,11 +587,7 @@ class Page:
         if self.exists():
             return link_tag(word, word, 'wikilink')
         else:
-            if nonexist_qm:
-                return link_tag(word, '?', 'nonexistent') + word
-            else:
-                return link_tag(word, word, 'nonexistent')
-
+            return link_tag(word, nonexist_pfx + word, 'nonexistent')
 
     def get_raw_body(self):
         try:
@@ -620,27 +616,38 @@ class Page:
                 raise er
         return self.attrs
 
-    def can_edit(self):
+    def can(self, action, default=True):
         attrs = self.get_attrs()
         try:
             # SomeUser:read,write All:read
             acl = attrs["acl"]
             for rule in acl.split():
-                (user,perms) = acl.split(':')
+                (user,perms) = rule.split(':')
                 if user == remote_user() or user == "All":
-                    if 'write' in perms.split(','):
+                    if action in perms.split(','):
                         return True
+                    else:
+                        return False
             return False
-        except:
+        except Exception, er:
             pass
-        return True
+        return default
+
+    def can_write(self):
+        return self.can("write", True)
+
+    def can_read(self):
+        return self.can("read", True)
 
     def send_page(self):
         page_name = None
-        if self.can_edit():
+        if self.can_write():
             page_name = self.page_name
         send_title(page_name, self.split_title(), msg=self.msg, msg_type=self.msg_type)
-        PageFormatter(self.get_raw_body()).print_html()
+        if self.can_read():
+            PageFormatter(self.get_raw_body()).print_html()
+        else:
+            send_guru("Read access denied by ACLs", "notice")
         send_footer(page_name, self._last_modified())
 
     def _last_modified(self):
@@ -652,6 +659,9 @@ class Page:
 
     def send_editor(self, preview=None):
         send_title(None, 'Edit ' + self.split_title(), msg=self.msg, msg_type=self.msg_type)
+        if not self.can_write():
+            send_guru("Write access denied by ACLs", "error")
+            return
 
         print ('<p><b>Editing ' + self.page_name
             + ' for ' + cgi.escape(remote_user())
@@ -676,6 +686,9 @@ class Page:
         send_footer(self.page_name)
 
     def send_raw(self):
+        if not self.can_read():
+            send_title(None, msg='Read access denied by ACLs', msg_type='notice')
+            return
         emit_header("text/plain")
         print self.get_raw_body()
 
@@ -692,6 +705,11 @@ class Page:
         os.rename(tmp_filename, text)
 
     def save_text(self, newtext):
+        if not self.can_write():
+            self.msg = 'Write access denied by ACLs'
+            self.msg_type = 'error'
+            return
+
         self._write_file(newtext)
         rc = 0
         if post_edit_hook:
@@ -710,7 +728,7 @@ class Page:
             if msg:
                 self.msg += 'Output follows:\n' + msg
         else:
-            self.msg = 'Thankyou for your contribution.  Your attention to detail is appreciated.'
+            self.msg = 'Thank you for your contribution.  Your attention to detail is appreciated.'
             self.msg_type = 'success'
 
 def send_verbatim(filename, mime_type='application/octet-stream'):
@@ -724,8 +742,7 @@ try:
     # Configuration values
     site_name = 'Codewiz'
 
-    # set to None for read-only sites
-    # leave empty ('') to allow anonymous edits
+    # set to None for read-only sites, leave empty ('') to allow anonymous edits
     # otherwise, set to a URL that requires authentication
     privileged_url = 'https://www.codewiz.org/~bernie/wiki'
 
@@ -737,7 +754,7 @@ try:
     datetime_fmt = '%a %d %b %Y %I:%M %p'
     allow_edit = True                       # Is it possible to edit pages?
     show_hosts = True                       # show hostnames?
-    nonexist_qm = False                     # show '?' for nonexistent?
+    nonexist_pfx = ''                       # prefix before nonexistent link (usually '?')
     debug_cgi = False                       # Set to True for CGI var dump
 
     form = cgi.FieldStorage()