3 # Copyright 1999, 2000 Martin Pool <mbp@humbug.org.au>
4 # Copyright 2002 Gerardo Poggiali
5 # Copyright 2007 Bernardo Innocenti <bernie@codewiz.org>
7 # This program is free software: you can redistribute it and/or modify
8 # it under the terms of the GNU General Public License as published by
9 # the Free Software Foundation, either version 3 of the License, or
10 # (at your option) any later version.
12 # This program is distributed in the hope that it will be useful, but
13 # WITHOUT ANY WARRANTY; without even the implied warranty of
14 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15 # General Public License for more details.
17 # You should have received a copy of the GNU General Public License
18 # along with this program. If not, see <http://www.gnu.org/licenses/>.
20 __version__ = '$Id$'[4:12]
22 from time import clock
25 import cgi, sys, string, os, re, errno, stat
26 from os import path, environ
28 # Regular expression defining a WikiWord
29 # (but this definition is also assumed in other places)
30 file_re = re.compile(r"^\b([A-Za-z0-9_\.\-]+)\b$")
31 word_re = re.compile(r"^\b([A-Z][a-z]+){2,}\b$")
32 img_re = re.compile(r"^.*\.(png|gif|jpg|jpeg)$", re.IGNORECASE)
33 url_re = re.compile(r"^[a-z]{3,8}://[^\s'\"]+\S$")
38 # CGI stuff ---------------------------------------------------------
41 return environ.get('SCRIPT_NAME', '')
43 def privileged_path():
44 return privileged_url or script_name()
47 user = environ.get('REMOTE_USER', '')
48 if user is None or user == '' or user == 'anonymous':
49 user = 'AnonymousCoward'
53 return environ.get('REMOTE_ADDR', '')
55 def get_hostname(addr):
57 from socket import gethostbyaddr
58 return gethostbyaddr(addr)[0] + ' (' + addr + ')'
62 # Formatting stuff --------------------------------------------------
64 def emit_header(type="text/html"):
65 print "Content-type: " + type + "; charset=utf-8"
68 def send_guru(msg, msg_type):
69 if msg is None or msg == '': return
70 print '<pre id="guru" onclick="this.style.display = \'none\'" class="' + msg_type + '">'
71 if msg_type == 'error':
72 print ' Software Failure. Press left mouse button to continue.\n'
74 if msg_type == 'error':
75 print ' Guru Meditation #DEADBEEF.ABADC0DE'
77 # FIXME: This simple JS snippet is harder to pass than ACID 3.0
79 <script language="JavaScript" type="text/javascript">
80 var guru = document.getElementById('guru');
81 // Firefox 2.0 doesn't take border-color, but returns border-top-color fine
82 var color = document.defaultView.getComputedStyle(guru,null).getPropertyValue('border-top-color');
85 guru.style.setProperty('border-color', color, '');
86 setTimeout('guruOff()', 1000);
89 guru.style.setProperty('border-color', '#000000', '');
90 setTimeout('guruOn()', 1000);
92 // Safari 2.0 returns this rgba crap
93 // Konqueror 3.5.6 doesn't seem to support computed properties
94 if (color && color != 'rgba(0, 0, 0, 0)') {
95 //window.alert("enabled! color='" + color + "'");
100 def send_title(name, text="Limbo", msg=None, msg_type='error'):
102 if title_done: return
106 print '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"'
107 print ' "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">'
108 print '<html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en">'
110 site_name = globals().get('site_name', 'Unconfigured Site')
111 print "<head><title>%s: %s</title>" % (site_name, text)
112 print ' <meta http-equiv="Content-Type" content="application/xhtml+xml; charset=utf-8" />'
114 print ' <meta name="robots" content="noindex,nofollow" />'
115 if globals().has_key('css_url'):
116 print ' <link rel="stylesheet" type="text/css" href="%s" />' % css_url
120 if name and privileged_url is not None:
121 print '<body ondblclick="location.href=\'' + privileged_path() + '?edit=' + name + '\'">'
126 send_guru(msg, msg_type)
129 print '<div class="nav">'
130 print ' <b>' + site_name + ': ',
132 print link_tag('?fullsearch=' + name, text, 'navlink') + '</b> '
135 print ' | ' + link_tag('FrontPage', 'Front Page', 'navlink')
136 print ' | ' + link_tag('FindPage', 'Find Page', 'navlink')
137 if globals().has_key('history_url'):
138 print ' | <a href="' + history_url + '" class="navlink">Recent Changes</a>'
140 print ' | <a href="' + history_url + '?a=history;f=' + name + '" class="navlink">Page History</a>'
143 print ' | ' + link_tag('?raw=' + name, 'Raw Text', 'navlink')
144 if privileged_url is not None:
145 print ' | ' + link_tag('?edit=' + name, 'Edit Page', 'navlink', authentication=True)
147 print ' | <i>Immutable Page</i>'
150 if user != 'AnonymousCoward':
151 print ' | <span class="login"><i>logged in as <b>' + cgi.escape(user) + '</b></i></span>'
155 def link_tag(params, text=None, ss_class=None, authentication=False):
157 text = params # default
160 classattr += 'class="%s" ' % ss_class
161 # Prevent crawlers from following links potentially added by spammers or to generated pages
162 if ss_class == 'external' or ss_class == 'navlink':
163 classattr += 'rel="nofollow" '
165 path = privileged_path()
168 return '<a %shref="%s/%s">%s</a>' % (classattr, path, params, text)
170 # Search ---------------------------------------------------
172 def do_fullsearch(needle):
173 send_title(None, 'Full text search for "%s"' % (needle))
175 needle_re = re.compile(needle, re.IGNORECASE)
177 all_pages = page_list()
178 for page_name in all_pages:
179 body = Page(page_name).get_raw_body()
180 count = len(needle_re.findall(body))
182 hits.append((count, page_name))
184 # The default comparison for tuples compares elements in order,
185 # so this sorts by number of hits
190 for (count, page_name) in hits:
191 print '<li><p>' + Page(page_name).link_to()
192 print ' . . . . ' + `count`
193 print ['match', 'matches'][count != 1]
197 print_search_stats(len(hits), len(all_pages))
199 def do_titlesearch(needle):
200 # TODO: check needle is legal -- but probably we can just accept any RE
201 send_title(None, "Title search for \"" + needle + '"')
203 needle_re = re.compile(needle, re.IGNORECASE)
204 all_pages = page_list()
205 hits = filter(needle_re.search, all_pages)
208 for filename in hits:
209 print '<li><p>' + Page(filename).link_to() + "</p></li>"
212 print_search_stats(len(hits), len(all_pages))
214 def print_search_stats(hits, searched):
215 print "<p>%d hits out of %d pages searched.</p>" % (hits, searched)
217 #TODO: merge into do_savepage()
218 def do_edit(pagename):
219 Page(pagename).send_editor()
221 def do_raw(pagename):
222 Page(pagename).send_raw()
224 def do_savepage(pagename):
227 if 'preview' in form:
228 pg.send_editor(form['savetext'].value)
230 pg.save_text(form['savetext'].value)
232 elif 'cancel' in form:
233 pg.msg = 'Editing canceled'
234 pg.msg_type = 'notice'
237 raise 'What did you press?'
239 def make_index_key():
241 links = map(lambda ch: '<a href="#%s">%s</a>' % (ch, ch),
243 s = s + string.join(links, ' | ')
244 s = s + '</center></p>'
248 return filter(word_re.match, os.listdir(data_dir))
250 def send_footer(name, mod_string=None):
251 if globals().get('debug_cgi', False):
252 cgi.print_arguments()
253 cgi.print_form(cgi.FieldStorage())
256 print '<div id="footer"><hr />'
257 print ('<p class="copyright"><span class="benchmark">generated in %0.3fs</span>' +
258 ' by <a href="http://www.codewiz.org/wiki/GeekiGeeki">GeekiGeeki</a>' +
259 ' version %s</p>') % (clock() - start_time, __version__)
261 print '<p class="modified">last modified %s</p>' % mod_string
262 print '</div></body></html>'
264 # ----------------------------------------------------------
266 def _macro_TitleSearch(*vargs):
267 return _macro_search("titlesearch")
269 def _macro_FullSearch(*vargs):
270 return _macro_search("fullsearch")
272 def _macro_search(type):
273 if form.has_key('value'):
274 default = form["value"].value
277 return """<form method="get"><input name="%s" size="30" value="%s" /><input type="submit" value="Search" /></form>""" % (type, default)
279 def _macro_WordIndex(*vargs):
281 pages = list(page_list())
283 word_re = re.compile('[A-Z][a-z]+')
285 for word in word_re.findall(name):
287 map[word].append(name)
291 all_words = map.keys()
295 for word in all_words:
296 letter = string.lower(word[0])
297 if letter != last_letter:
298 s = s + '; <a name="%s"><h3>%s</h3></a>' % (letter, letter)
301 s = s + '<b>%s</b><ul>' % word
306 if name == last_page: continue
307 s = s + '<li>' + Page(name).link_to()
312 def _macro_TitleIndex(*vargs):
314 pages = list(page_list())
316 current_letter = None
318 letter = string.lower(name[0])
319 if letter != current_letter:
320 s = s + '<a name="%s"><h3>%s</h3></a>' % (letter, letter)
321 current_letter = letter
324 s = s + Page(name).link_to()
328 # ----------------------------------------------------------
330 """Object that turns Wiki markup into HTML.
332 All formatting commands can be parsed one line at a time, though
333 some state is carried over between lines.
335 def __init__(self, raw):
338 self.in_pre = self.in_table = self.in_var = self.in_em = self.in_b = False
339 self.in_header = True
340 self.list_indents = []
341 self.tr_cnt = self.h_cnt = 0
343 def _b_repl(self, word):
344 self.in_b = not self.in_b
345 return ['</strong>', '<strong>'][self.in_b]
347 def _em_repl(self, word):
348 self.in_em = not self.in_em
349 return ['</em>', '<em>'][self.in_em]
351 def _tit_repl(self, word):
353 result = '</h%d>' % self.h_level
356 self.h_level = len(word) - 1
358 result = '<h%d id="%d"><a class="heading" href="#%d">*</a> ' % (self.h_level, self.h_cnt, self.h_cnt)
361 def _br_repl(self, word):
364 def _rule_repl(self, word):
365 return self._undent() + '\n<hr size="%d" noshade="noshade" />\n' % (len(word) - 2)
367 def _word_repl(self, word):
368 return Page(word).link_to()
370 def _img_repl(self, word):
371 path = script_name() + '/' + word;
372 return '<a href="%s"><img border="0" src="%s" /></a>' % (path, path)
374 def _url_repl(self, word):
375 if img_re.match(word):
376 return '<a href="%s"><img border="0" src="%s" /></a>' % (word, word)
378 return '<a href="%s" rel="nofollow" class="external">%s</a>' % (word, word)
380 def _hurl_repl(self, word):
381 m = re.compile("\[\[(\S+)(?:\s*\|\s*([^\]]*)|)\]\]").match(word)
383 descr = m.group(2) or name
385 macro = globals().get('_macro_' + name)
387 return apply(macro, (name, descr))
388 elif img_re.match(name):
389 return '<a href="%s"><img border="0" src="%s" alt="%s" /></a>' % (name, name, descr)
390 elif url_re.match(name):
391 return '<a href="%s" rel="nofollow" class="external">%s</a>' % (name, descr)
392 elif name.startswith('/'):
393 return '<a href="%s">%s</a>' % (name, descr)
395 return link_tag(name, descr, 'wikilink')
397 def _email_repl(self, word):
398 return '<a href="mailto:%s">%s</a>' % (word, word)
400 def _html_repl(self, word):
401 return word; # Pass through
403 def _ent_repl(self, s):
404 return {'&': '&',
408 def _li_repl(self, match):
411 def _pre_repl(self, word):
412 if word == '{{{' and not self.in_pre:
420 def _hi_repl(self, word):
427 return '<strong class="highlight ' + cl + '">' + word + '</strong>'
429 def _var_repl(self, word):
430 if word == '{{' and not self.in_var:
438 def _tr_repl(self, word):
440 if not self.in_table:
443 out = '</p><table><tbody>\n'
445 out = out + '<tr class="' + ['even', 'odd'][self.tr_cnt % 2] + '">'
446 return out + ['<td>', '<th>'][word.strip() == '||=']
448 def _td_repl(self, word):
450 return ['</td><td>', '</th><th>'][word.strip() == '||=']
453 def _tre_repl(self, word):
455 return ['</td></tr>', '</th></tr>'][word.strip() == '||=']
458 def _indent_level(self):
459 return len(self.list_indents) and self.list_indents[-1]
461 def _indent_to(self, new_level):
462 if self._indent_level() == new_level:
465 while self._indent_level() > new_level:
466 del(self.list_indents[-1])
468 while self._indent_level() < new_level:
469 self.list_indents.append(new_level)
476 res += '</ul>' * len(self.list_indents)
478 self.list_indents = []
481 def replace(self, match):
482 for type, hit in match.groupdict().items():
484 return apply(getattr(self, '_' + type + '_repl'), (hit,))
486 raise "Can't handle match " + `match`
488 def print_html(self):
489 print '<div class="wiki"><p>'
491 # For each line, we scan through looking for magic
492 # strings, outputting verbatim any intervening text
493 # TODO: highlight search words (look at referer)
494 scan_re = re.compile(
499 + r"|(?P<tit>\={2,6})"
501 + r"|(?P<rule>^-{3,})"
502 + r"|(?P<html><(/|)(div|span|iframe)[^<>]*>)"
504 + r"|(?P<hi>\b(FIXME|TODO|DONE)\b)"
507 + r"|(?P<img>\b[a-zA-Z0-9_-]+\.(png|gif|jpg|jpeg|bmp))"
508 + r"|(?P<word>\b(?:[A-Z][a-z]+){2,}\b)"
509 + r"|(?P<hurl>\[\[(\S+)(?:\s*\|\s*([^\]]*)|)\]\])"
510 + r"|(?P<url>(http|https|ftp|mailto)\:[^\s'\"]+\S)"
511 + r"|(?P<email>[-\w._+]+\@[\w.-]+)"
514 + r"|(?P<li>^\s+[\*#] +)"
515 + r"|(?P<pre>\{\{\{|\s*\}\}\})"
516 + r"|(?P<var>\{\{|\}\})"
519 + r"|(?P<tr>^\s*\|\|(=|)\s*)"
520 + r"|(?P<tre>\s*\|\|(=|)\s*$)"
521 + r"|(?P<td>\s*\|\|(=|)\s*)"
525 + r"(?P<pre>\s*\}\}\})"
527 blank_re = re.compile(r"^\s*$")
528 indent_re = re.compile(r"^\s*")
529 tr_re = re.compile(r"^\s*\|\|")
530 eol_re = re.compile(r"\r?\n")
531 raw = string.expandtabs(self.raw)
532 for line in eol_re.split(raw):
535 if line.startswith('#'):
537 self.in_header = False
540 print re.sub(pre_re, self.replace, line)
542 if self.in_table and not tr_re.match(line):
543 self.in_table = False
544 print '</tbody></table><p>'
546 if blank_re.match(line):
549 indent = indent_re.match(line)
550 print self._indent_to(len(indent.group(0)))
551 print re.sub(scan_re, self.replace, line)
553 if self.in_pre: print '</pre>'
554 if self.in_table: print '</tbody></table><p>'
558 # ----------------------------------------------------------
560 def __init__(self, page_name):
561 self.page_name = page_name
563 self.msg_type = 'error'
566 def split_title(self):
567 # look for the end of words and the start of a new word,
568 # and insert a space there
569 return re.sub('([a-z])([A-Z])', r'\1 \2', self.page_name)
571 def _text_filename(self):
572 return path.join(data_dir, self.page_name)
574 def _tmp_filename(self):
575 return path.join(data_dir, ('#' + self.page_name + '.' + `os.getpid()` + '#'))
579 os.stat(self._text_filename())
582 if er.errno == errno.ENOENT:
588 word = self.page_name
590 return link_tag(word, word, 'wikilink')
592 return link_tag(word, nonexist_pfx + word, 'nonexistent')
594 def get_raw_body(self):
596 return open(self._text_filename(), 'rt').read()
598 if er.errno == errno.ENOENT:
599 return '' # just doesn't exist, use default
606 file = open(self._text_filename(), 'rt')
607 attr_re = re.compile(r"^#(\S*)(.*)$")
609 m = attr_re.match(line)
612 self.attrs[m.group(1)] = m.group(2).strip()
613 #print "bernie: attrs[" + m.group(1) + "] = " + m.group(2) + "<br>\n"
615 if er.errno != errno.ENOENT:
619 def can(self, action, default=True):
620 attrs = self.get_attrs()
622 # SomeUser:read,write All:read
624 for rule in acl.split():
625 (user,perms) = rule.split(':')
626 if user == remote_user() or user == "All":
627 if action in perms.split(','):
632 except Exception, er:
637 return self.can("write", True)
640 return self.can("read", True)
645 page_name = self.page_name
646 send_title(page_name, self.split_title(), msg=self.msg, msg_type=self.msg_type)
648 PageFormatter(self.get_raw_body()).print_html()
650 send_guru("Read access denied by ACLs", "notice")
651 send_footer(page_name, self._last_modified())
653 def _last_modified(self):
655 from time import localtime, strftime
656 modtime = localtime(os.stat(self._text_filename())[stat.ST_MTIME])
658 if er.errno != errno.ENOENT:
661 return strftime(datetime_fmt, modtime)
663 def send_editor(self, preview=None):
664 send_title(None, 'Edit ' + self.split_title(), msg=self.msg, msg_type=self.msg_type)
665 if not self.can_write():
666 send_guru("Write access denied by ACLs", "error")
669 print ('<p><b>Editing ' + self.page_name
670 + ' for ' + cgi.escape(remote_user())
671 + ' from ' + cgi.escape(get_hostname(remote_host()))
673 print '<div class="editor"><form method="post" action="%s/%s">' % (script_name(), self.page_name)
674 print '<input type="hidden" name="savepage" value="%s">' % (self.page_name)
675 print """<textarea wrap="virtual" id="editor" name="savetext" rows="17" cols="80">%s</textarea>""" % (preview or self.get_raw_body())
678 <input type="submit" name="save" value="Save" />
679 <input type="submit" name="preview" value="Preview" />
680 <input type="reset" value="Reset" />
681 <input type="submit" name="cancel" value="Cancel" />
684 print "<p>" + Page('EditingTips').link_to() + "</p>"
686 print "<div class='preview'>"
687 PageFormatter(preview).print_html()
689 send_footer(self.page_name)
692 if not self.can_read():
693 send_title(None, msg='Read access denied by ACLs', msg_type='notice')
695 emit_header("text/plain")
696 print self.get_raw_body()
698 def _write_file(self, text):
699 tmp_filename = self._tmp_filename()
700 open(tmp_filename, 'wt').write(text.replace('\r\n', '\n'))
701 text = self._text_filename()
703 # Bad Bill! POSIX rename ought to replace. :-(
707 if er.errno != errno.ENOENT: raise er
708 os.rename(tmp_filename, text)
710 def save_text(self, newtext):
711 if not self.can_write():
712 self.msg = 'Write access denied by ACLs'
713 self.msg_type = 'error'
716 self._write_file(newtext)
719 # FIXME: what's the std way to perform shell quoting in python?
720 cmd = ( post_edit_hook
721 + " '" + data_dir + '/' + self.page_name
722 + "' '" + remote_user()
723 + "' '" + remote_host() + "'"
729 self.msg += "Post-editing hook returned %d.\n" % rc
730 self.msg += 'Command was: ' + cmd + '\n'
732 self.msg += 'Output follows:\n' + msg
734 self.msg = 'Thank you for your contribution. Your attention to detail is appreciated.'
735 self.msg_type = 'success'
737 #TODO: merge into send_raw()
738 def send_verbatim(filename, mime_type='application/octet-stream'):
739 pathname = path.join(data_dir, filename)
740 data = open(pathname, 'rb').read()
741 emit_header(mime_type)
742 sys.stdout.write(data)
744 # Main ---------------------------------------------------------------
746 execfile("geekigeeki.conf.py")
748 form = cgi.FieldStorage()
750 handlers = { 'fullsearch': do_fullsearch,
751 'titlesearch': do_titlesearch,
754 'savepage': do_savepage }
756 for cmd in handlers.keys():
757 if form.has_key(cmd):
758 apply(handlers[cmd], (form[cmd].value,))
761 path_info = environ.get('PATH_INFO', '')
762 if len(path_info) and path_info[0] == '/':
763 query = path_info[1:] or 'FrontPage'
765 query = environ.get('QUERY_STRING', '') or 'FrontPage'
767 if file_re.match(query):
768 if word_re.match(query):
769 Page(query).send_page()
770 elif img_re.match(query):
771 #FIXME: use correct mime type
772 send_verbatim(query, 'image/jpeg')
776 print "Status: 404 Not Found"
777 send_title(None, msg='Can\'t work out query: ' + query)
780 msg=traceback.format_exc()
782 send_guru(msg, "error")
784 send_title(None, msg=msg)