2 # -*- coding: utf-8 -*-
4 # Copyright 1999, 2000 Martin Pool <mbp@humbug.org.au>
5 # Copyright 2002 Gerardo Poggiali
6 # Copyright 2007, 2008 Bernardo Innocenti <bernie@codewiz.org>
8 # This program is free software: you can redistribute it and/or modify
9 # it under the terms of the GNU General Public License as published by
10 # the Free Software Foundation, either version 3 of the License, or
11 # (at your option) any later version.
13 # This program is distributed in the hope that it will be useful, but
14 # WITHOUT ANY WARRANTY; without even the implied warranty of
15 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
16 # General Public License for more details.
18 # You should have received a copy of the GNU General Public License
19 # along with this program. If not, see <http://www.gnu.org/licenses/>.
21 __version__ = '$Id$'[4:12]
23 from time import clock
26 import cgi, sys, os, re, errno, stat
27 from os import path, environ
29 # Regular expression defining a WikiWord
30 # (but this definition is also assumed in other places)
31 file_re = re.compile(r"^\b([A-Za-z0-9_\.\-/]+)\b$")
32 word_re = re.compile(r"^\b((([A-Z][a-z]+){2,}/)*([A-Z][a-z]+){2,})\b$")
33 img_re = re.compile(r"^.*\.(png|gif|jpg|jpeg)$", re.IGNORECASE)
34 url_re = re.compile(r"^[a-z]{3,8}://[^\s'\"]+\S$")
39 # CGI stuff ---------------------------------------------------------
42 return environ.get('SCRIPT_NAME', '')
44 def privileged_path():
45 return privileged_url or script_name()
48 user = environ.get('REMOTE_USER', '')
49 if user is None or user == '' or user == 'anonymous':
50 user = 'AnonymousCoward'
54 return environ.get('REMOTE_ADDR', '')
56 def get_hostname(addr):
58 from socket import gethostbyaddr
59 return gethostbyaddr(addr)[0] + ' (' + addr + ')'
63 def relative_url(pathname, privileged=False):
64 if not (url_re.match(pathname) or pathname.startswith('/')):
66 url = privileged_path()
69 pathname = url + '/' + pathname
72 # Formatting stuff --------------------------------------------------
74 def emit_header(mime_type="text/html"):
75 print "Content-type: " + mime_type + "; charset=utf-8\n"
77 def send_guru(msg_text, msg_type):
78 if not msg_text: return
79 print '<pre id="guru" onclick="this.style.display = \'none\'" class="' + msg_type + '">'
80 if msg_type == 'error':
81 print ' Software Failure. Press left mouse button to continue.\n'
83 if msg_type == 'error':
84 print ' Guru Meditation #DEADBEEF.ABADC0DE'
86 # FIXME: This little JS snippet is harder to pass than ACID 3.0
88 <script language="JavaScript" type="text/javascript">
89 var guru = document.getElementById('guru');
90 // Firefox 2.0 doesn't take border-color, but returns border-top-color fine
91 var color = document.defaultView.getComputedStyle(guru,null).getPropertyValue('border-top-color');
94 guru.style.setProperty('border-color', color, '');
95 setTimeout('guruOff()', 1000);
98 guru.style.setProperty('border-color', '#000000', '');
99 setTimeout('guruOn()', 1000);
101 // Safari 2.0 returns this rgba crap
102 // Konqueror 3.5.6 doesn't seem to support computed properties
103 if (color && color != 'rgba(0, 0, 0, 0)') {
104 //window.alert("enabled! color='" + color + "'");
109 def send_title(name, text="Limbo", msg_text=None, msg_type='error'):
111 if title_done: return
115 print '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"'
116 print ' "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">'
117 print '<html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en">'
119 site_name = globals().get('site_name', 'Unconfigured Site')
120 print "<head><title>%s: %s</title>" % (site_name, text)
121 print ' <meta http-equiv="Content-Type" content="application/xhtml+xml; charset=utf-8" />'
123 print ' <meta name="robots" content="noindex,nofollow" />'
125 print ' <link rel="stylesheet" type="text/css" href="%s" />' % relative_url(css)
129 if name and privileged_url is not None:
130 print '<body ondblclick="location.href=\'' + privileged_path() + '?edit=' + name + '\'">'
135 send_guru(msg_text, msg_type)
138 print '<div class="nav">'
139 print ' <b>' + site_name + ': ',
141 print link_tag('?fullsearch=' + name, text, 'navlink') + '</b> '
144 print ' | ' + link_tag('FrontPage', 'Front Page', 'navlink')
145 print ' | ' + link_tag('FindPage', 'Find Page', 'navlink')
146 if globals().has_key('history_url'):
147 print ' | <a href="' + history_url + '" class="navlink">Recent Changes</a>'
149 print ' | <a href="' + history_url + '?a=history;f=' + name + '" class="navlink">Page History</a>'
152 print ' | ' + link_tag('?raw=' + name, 'Raw Text', 'navlink')
153 if privileged_url is not None:
154 print ' | ' + link_tag('?edit=' + name, 'Edit Page', 'navlink', privileged=True)
156 print ' | <i>Immutable Page</i>'
159 if user != 'AnonymousCoward':
160 print ' | <span class="login"><i>logged in as <b>' + cgi.escape(user) + '</b></i></span>'
164 def link_tag(params, text=None, ss_class=None, privileged=False):
166 text = params # default
169 classattr += 'class="%s" ' % ss_class
170 # Prevent crawlers from following links potentially added by spammers or to generated pages
171 if ss_class == 'external' or ss_class == 'navlink':
172 classattr += 'rel="nofollow" '
173 elif url_re.match(params):
174 classattr += 'rel="nofollow" '
175 return '<a %shref="%s">%s</a>' % (classattr, relative_url(params, privileged=privileged), text)
177 # Search ---------------------------------------------------
179 def do_fullsearch(needle):
180 send_title(None, 'Full text search for "%s"' % (needle))
182 needle_re = re.compile(needle, re.IGNORECASE)
184 all_pages = page_list()
185 for page_name in all_pages:
186 body = Page(page_name).get_raw_body()
187 count = len(needle_re.findall(body))
189 hits.append((count, page_name))
191 # The default comparison for tuples compares elements in order,
192 # so this sorts by number of hits
197 for (count, page_name) in hits:
198 print '<li><p>' + Page(page_name).link_to()
199 print ' . . . . ' + `count`
200 print ['match', 'matches'][count != 1]
204 print_search_stats(len(hits), len(all_pages))
206 def do_titlesearch(needle):
207 # TODO: check needle is legal -- but probably we can just accept any RE
208 send_title(None, "Title search for \"" + needle + '"')
210 needle_re = re.compile(needle, re.IGNORECASE)
211 all_pages = page_list()
212 hits = filter(needle_re.search, all_pages)
215 for filename in hits:
216 print '<li><p>' + Page(filename).link_to() + "</p></li>"
219 print_search_stats(len(hits), len(all_pages))
221 def print_search_stats(hits, searched):
222 print "<p>%d hits out of %d pages searched.</p>" % (hits, searched)
224 def do_raw(pagename):
225 Page(pagename).send_raw()
227 def do_edit(pagename):
229 if 'preview' in form:
230 pg.send_editor(form['savetext'].value)
232 pg.save_text(form['savetext'].value)
234 elif 'cancel' in form:
235 pg.msg_text = 'Editing canceled'
236 pg.msg_type = 'notice'
241 def make_index_key():
242 links = map(lambda ch: '<a href="#%s">%s</a>' % (ch, ch), 'abcdefghijklmnopqrstuvwxyz')
243 return '<p><center>'+ ' | '.join(links) + '</center></p>'
246 return filter(word_re.match, os.listdir(data_dir))
248 def send_footer(name, mod_string=None):
249 if globals().get('debug_cgi', False):
250 cgi.print_arguments()
251 cgi.print_form(cgi.FieldStorage())
253 print '<div id="footer"><hr />'
254 print ('<p class="copyright"><span class="benchmark">generated in %0.3fs</span>' +
255 ' by <a href="http://www.codewiz.org/wiki/GeekiGeeki">GeekiGeeki</a>' +
256 ' version %s</p>') % (clock() - start_time, __version__)
258 print '<p class="modified">last modified %s</p>' % mod_string
259 print '</div></body></html>'
261 # ----------------------------------------------------------
263 def _macro_TitleSearch(*vargs):
264 return _macro_search("titlesearch")
266 def _macro_FullSearch(*vargs):
267 return _macro_search("fullsearch")
269 def _macro_search(type):
270 if form.has_key('value'):
271 default = form["value"].value
274 return """<form method="get"><input name="%s" size="30" value="%s" /><input type="submit" value="Search" /></form>""" % (type, default)
276 def _macro_WordIndex(*vargs):
278 pages = list(page_list())
280 word_re = re.compile('[A-Z][a-z]+')
282 for word in word_re.findall(name):
284 map[word].append(name)
288 all_words = map.keys()
292 for word in all_words:
293 letter = word[0].lower()
294 if letter != last_letter:
295 s = s + '; <a name="%s"><h3>%s</h3></a>' % (letter, letter)
298 s = s + '<b>%s</b><ul>' % word
303 if name == last_page: continue
304 s = s + '<li>' + Page(name).link_to()
309 def _macro_TitleIndex(*vargs):
311 pages = list(page_list())
313 current_letter = None
315 letter = name[0].lower()
316 if letter != current_letter:
317 s += '<a name="%s"><h3>%s</h3></a>' % (letter, letter)
318 current_letter = letter
321 s += Page(name).link_to()
325 # ----------------------------------------------------------
327 """Object that turns Wiki markup into HTML.
329 All formatting commands can be parsed one line at a time, though
330 some state is carried over between lines.
332 def __init__(self, raw):
335 self.in_pre = self.in_table = False
336 self.in_header = True
337 self.list_indents = []
338 self.tr_cnt = self.h_cnt = 0
348 "^^": ["sup", False],
352 def _b_repl(self, word):
353 style = self.styles[word]
354 style[1] = not style[1]
355 return ['</', '<'][style[1]] + style[0] + '>'
357 def _tit_repl(self, word):
359 result = '</h%d>' % self.h_level
362 self.h_level = len(word) - 1
364 #abridged = re.sub('[^a-z_]', '', word.lower().replace(' ', '_'))
365 result = '<h%d id="%d"><a class="heading" href="#%d">¶</a> ' % (self.h_level, self.h_cnt, self.h_cnt)
368 def _br_repl(self, word):
371 def _rule_repl(self, word):
372 return self._undent() + '\n<hr size="%d" noshade="noshade" />\n' % (len(word) - 2)
374 def _word_repl(self, word):
375 return Page(word).link_to()
377 def _img_repl(self, word):
378 path = relative_url(word)
379 return '<a href="%s"><img border="0" src="%s" /></a>' % (path, path)
381 def _url_repl(self, word):
382 if img_re.match(word):
383 return '<a href="%s"><img border="0" src="%s" /></a>' % (word, word)
385 return '<a href="%s" rel="nofollow" class="external">%s</a>' % (word, word)
387 def _hurl_repl(self, word):
388 m = re.compile("\[\[([^ \t\n\r\f\v\|]+)(?:\s*\|\s*([^\]]+)|)\]\]").match(word)
390 descr = m.group(2) or name
392 macro = globals().get('_macro_' + name)
394 return apply(macro, (name, descr))
395 elif img_re.match(name):
396 name = relative_url(name)
397 # The "extthumb" nonsense works around a limitation of the HTML block model
398 return '<div class="extthumb"><div class="thumb"><a href="%s"><img border="0" src="%s" alt="%s" /></a><div class="caption">%s</div></div></div>' % (name, name, descr, descr)
400 if img_re.match(descr):
401 descr = '<img border="0" src="' + descr + '" />'
403 return link_tag(name, descr, 'wikilink')
405 def _email_repl(self, word):
406 return '<a href="mailto:%s">%s</a>' % (word, word)
408 def _html_repl(self, word):
409 return word; # Pass through
411 def _ent_repl(self, s):
412 return {'&': '&',
416 def _li_repl(self, match):
419 def _pre_repl(self, word):
420 if word == '{{{' and not self.in_pre:
428 def _hi_repl(self, word):
429 return '<strong class="highlight ' + word + '">' + word + '</strong>'
431 def _tr_repl(self, word):
433 if not self.in_table:
436 out = '</p><table><tbody>\n'
438 out = out + '<tr class="' + ['even', 'odd'][self.tr_cnt % 2] + '">'
439 return out + ['<td>', '<th>'][word.strip() == '||=']
441 def _td_repl(self, word):
443 return ['</td><td>', '</th><th>'][word.strip() == '||=']
446 def _tre_repl(self, word):
448 return ['</td></tr>', '</th></tr>'][word.strip() == '||=']
451 def _indent_level(self):
452 return len(self.list_indents) and self.list_indents[-1]
454 def _indent_to(self, new_level):
455 if self._indent_level() == new_level:
458 while self._indent_level() > new_level:
459 del(self.list_indents[-1])
461 while self._indent_level() < new_level:
462 self.list_indents.append(new_level)
469 res += '</ul>' * len(self.list_indents)
471 self.list_indents = []
474 def replace(self, match):
475 for type, hit in match.groupdict().items():
477 return apply(getattr(self, '_' + type + '_repl'), (hit,))
479 raise "Can't handle match " + `match`
481 def print_html(self):
482 print '<div class="wiki"><p>'
484 # For each line, we scan through looking for magic
485 # strings, outputting verbatim any intervening text
486 # TODO: highlight search words (look at referrer)
487 scan_re = re.compile(
490 + r"(?P<b>\*\*|'''|//|''|##|``|__|\^\^|,,)"
491 + r"|(?P<tit>\={2,6})"
493 + r"|(?P<rule>^-{3,})"
494 + r"|(?P<html><(/|)(div|span|iframe)[^<>]*>)"
496 + r"|(?P<hi>\b(FIXME|TODO|DONE)\b)"
499 + r"|(?P<img>\b[a-zA-Z0-9_-]+\.(png|gif|jpg|jpeg|bmp))"
500 + r"|(?P<word>\b(?:[A-Z][a-z]+){2,}\b)"
501 + r"|(?P<hurl>\[\[([^ \t\n\r\f\v\|]+)(?:\s*\|\s*([^\]]+)|)\]\])"
502 + r"|(?P<url>(http|https|ftp|mailto)\:[^\s'\"]+\S)"
503 + r"|(?P<email>[-\w._+]+\@[\w.-]+)"
506 + r"|(?P<li>^\s+[\*#] +)"
507 + r"|(?P<pre>\{\{\{|\s*\}\}\})"
510 + r"|(?P<tr>^\s*\|\|(=|)\s*)"
511 + r"|(?P<tre>\s*\|\|(=|)\s*$)"
512 + r"|(?P<td>\s*\|\|(=|)\s*)"
516 + r"(?P<pre>\s*\}\}\})"
519 blank_re = re.compile(r"^\s*$")
520 indent_re = re.compile(r"^\s*")
521 tr_re = re.compile(r"^\s*\|\|")
522 eol_re = re.compile(r"\r?\n")
523 for line in eol_re.split(self.raw.expandtabs()):
526 if line.startswith('#'):
528 self.in_header = False
531 print re.sub(pre_re, self.replace, line)
533 if self.in_table and not tr_re.match(line):
534 self.in_table = False
535 print '</tbody></table><p>'
537 if blank_re.match(line):
540 indent = indent_re.match(line)
541 print self._indent_to(len(indent.group(0)))
542 print re.sub(scan_re, self.replace, line)
544 if self.in_pre: print '</pre>'
545 if self.in_table: print '</tbody></table><p>'
549 # ----------------------------------------------------------
551 def __init__(self, page_name):
552 self.page_name = page_name
554 self.msg_type = 'error'
556 def split_title(self):
557 # look for the end of words and the start of a new word and insert a space there
558 return re.sub('([a-z])([A-Z])', r'\1 \2', self.page_name)
560 def _text_filename(self):
561 return path.join(data_dir, self.page_name)
563 def _tmp_filename(self):
564 return path.join(data_dir, ('#' + self.page_name.replace('/','_') + '.' + `os.getpid()` + '#'))
568 os.stat(self._text_filename())
571 if er.errno == errno.ENOENT:
576 word = self.page_name
578 return link_tag(word, word, 'wikilink')
580 return link_tag(word, nonexist_pfx + word, 'nonexistent')
582 def get_raw_body(self):
584 return open(self._text_filename(), 'rb').read()
586 if er.errno == errno.ENOENT:
587 return '' # just doesn't exist, use default
588 if er.errno == errno.EISDIR:
593 if self.__dict__.has_key('attrs'):
597 file = open(self._text_filename(), 'rt')
598 attr_re = re.compile(r"^#(\S*)(.*)$")
600 m = attr_re.match(line)
603 self.attrs[m.group(1)] = m.group(2).strip()
604 #print "bernie: attrs[" + m.group(1) + "] = " + m.group(2) + "<br>\n"
606 if er.errno != errno.ENOENT:
610 def get_attr(self, name, default):
611 return self.get_attrs().get(name, default)
613 def can(self, action, default=True):
615 #acl SomeUser:read,write All:read
616 acl = self.get_attr("acl", None)
617 for rule in acl.split():
618 (user, perms) = rule.split(':')
619 if user == remote_user() or user == "All":
620 return action in perms.split(',')
622 except Exception, er:
627 return self.can("write", True)
630 return self.can("read", True)
635 page_name = self.page_name
639 css_url = self.get_attr("css", "").split() + css_url
641 send_title(page_name, self.split_title(), msg_text=self.msg_text, msg_type=self.msg_type)
643 PageFormatter(self.get_raw_body()).print_html()
645 send_guru("Read access denied by ACLs", "notice")
646 send_footer(page_name, self._last_modified())
648 def _last_modified(self):
650 from time import localtime, strftime
651 modtime = localtime(os.stat(self._text_filename())[stat.ST_MTIME])
653 if er.errno != errno.ENOENT:
656 return strftime(datetime_fmt, modtime)
658 def send_editor(self, preview=None):
659 send_title(None, 'Edit ' + self.split_title(), msg_text=self.msg_text, msg_type=self.msg_type)
660 if not self.can_write():
661 send_guru("Write access denied by ACLs", "error")
664 print ('<p><b>Editing ' + self.page_name
665 + ' for ' + cgi.escape(remote_user())
666 + ' from ' + cgi.escape(get_hostname(remote_host()))
668 print '<div class="editor"><form method="post" action="%s">' % relative_url(self.page_name)
669 print '<input type="hidden" name="edit" value="%s">' % (self.page_name)
670 print """<textarea wrap="off" spellcheck="true" id="editor" name="savetext" rows="17" cols="100">%s</textarea>""" % (preview or self.get_raw_body())
673 <input type="submit" name="save" value="Save" />
674 <input type="submit" name="preview" value="Preview" />
675 <input type="reset" value="Reset" />
676 <input type="submit" name="cancel" value="Cancel" />
679 print "<p>" + Page('EditingTips').link_to() + "</p>"
681 print "<div class='preview'>"
682 PageFormatter(preview).print_html()
684 send_footer(self.page_name)
686 def send_raw(self, mimetype='text/plain'):
688 body = self.get_raw_body()
689 emit_header(mimetype)
692 send_title(None, msg_text='Read access denied by ACLs', msg_type='notice')
694 def _write_file(self, text):
695 tmp_filename = self._tmp_filename()
696 open(tmp_filename, 'wt').write(text.replace('\r\n', '\n'))
697 text = self._text_filename()
699 # Bad Bill! POSIX rename ought to replace. :-(
703 if er.errno != errno.ENOENT: raise er
704 os.rename(tmp_filename, text)
706 def save_text(self, newtext):
707 if not self.can_write():
708 self.msg_text = 'Write access denied by ACLs'
709 self.msg_type = 'error'
712 self._write_file(newtext)
715 # FIXME: what's the std way to perform shell quoting in python?
716 cmd = ( post_edit_hook
717 + " '" + data_dir + '/' + self.page_name
718 + "' '" + remote_user()
719 + "' '" + remote_host() + "'"
725 self.msg_text += "Post-editing hook returned %d.\n" % rc
726 self.msg_text += 'Command was: ' + cmd + '\n'
728 self.msg_text += 'Output follows:\n' + output
730 self.msg_text = 'Thank you for your contribution. Your attention to detail is appreciated.'
731 self.msg_type = 'success'
733 # Main ---------------------------------------------------------------
735 execfile("geekigeeki.conf.py")
736 form = cgi.FieldStorage()
738 'fullsearch': do_fullsearch,
739 'titlesearch': do_titlesearch,
744 for cmd in handlers.keys():
745 if form.has_key(cmd):
746 apply(handlers[cmd], (form[cmd].value,))
749 path_info = environ.get('PATH_INFO', '')
750 if len(path_info) and path_info[0] == '/':
751 query = path_info[1:] or 'FrontPage'
753 query = environ.get('QUERY_STRING', '') or 'FrontPage'
755 if file_re.match(query):
756 if word_re.match(query):
757 Page(query).send_page()
758 elif img_re.match(query):
759 #FIXME: use correct mime type
760 Page(query).send_raw(mimetype='image/jpeg')
762 Page(query).send_raw(mimetype='application/octet-stream')
764 print "Status: 404 Not Found"
765 send_title(None, msg_text='Can\'t work out query: ' + query)
768 msg_text = traceback.format_exc()
770 send_guru(msg_text, "error")
772 send_title(None, msg_text=msg_text)