2 # -*- coding: utf-8 -*-
4 # Copyright 1999, 2000 Martin Pool <mbp@humbug.org.au>
5 # Copyright 2002 Gerardo Poggiali
6 # Copyright 2007 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, string, 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,}\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 # Formatting stuff --------------------------------------------------
65 def emit_header(type="text/html"):
66 print "Content-type: " + type + "; charset=utf-8"
69 def send_guru(msg, msg_type):
70 if msg is None or msg == '': return
71 print '<pre id="guru" onclick="this.style.display = \'none\'" class="' + msg_type + '">'
72 if msg_type == 'error':
73 print ' Software Failure. Press left mouse button to continue.\n'
75 if msg_type == 'error':
76 print ' Guru Meditation #DEADBEEF.ABADC0DE'
78 # FIXME: This simple JS snippet is harder to pass than ACID 3.0
80 <script language="JavaScript" type="text/javascript">
81 var guru = document.getElementById('guru');
82 // Firefox 2.0 doesn't take border-color, but returns border-top-color fine
83 var color = document.defaultView.getComputedStyle(guru,null).getPropertyValue('border-top-color');
86 guru.style.setProperty('border-color', color, '');
87 setTimeout('guruOff()', 1000);
90 guru.style.setProperty('border-color', '#000000', '');
91 setTimeout('guruOn()', 1000);
93 // Safari 2.0 returns this rgba crap
94 // Konqueror 3.5.6 doesn't seem to support computed properties
95 if (color && color != 'rgba(0, 0, 0, 0)') {
96 //window.alert("enabled! color='" + color + "'");
101 def send_title(name, text="Limbo", msg=None, msg_type='error'):
103 if title_done: return
107 print '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"'
108 print ' "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">'
109 print '<html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en">'
111 site_name = globals().get('site_name', 'Unconfigured Site')
112 print "<head><title>%s: %s</title>" % (site_name, text)
113 print ' <meta http-equiv="Content-Type" content="application/xhtml+xml; charset=utf-8" />'
115 print ' <meta name="robots" content="noindex,nofollow" />'
117 print ' <link rel="stylesheet" type="text/css" href="%s" />' % css
121 if name and privileged_url is not None:
122 print '<body ondblclick="location.href=\'' + privileged_path() + '?edit=' + name + '\'">'
127 send_guru(msg, msg_type)
130 print '<div class="nav">'
131 print ' <b>' + site_name + ': ',
133 print link_tag('?fullsearch=' + name, text, 'navlink') + '</b> '
136 print ' | ' + link_tag('FrontPage', 'Front Page', 'navlink')
137 print ' | ' + link_tag('FindPage', 'Find Page', 'navlink')
138 if globals().has_key('history_url'):
139 print ' | <a href="' + history_url + '" class="navlink">Recent Changes</a>'
141 print ' | <a href="' + history_url + '?a=history;f=' + name + '" class="navlink">Page History</a>'
144 print ' | ' + link_tag('?raw=' + name, 'Raw Text', 'navlink')
145 if privileged_url is not None:
146 print ' | ' + link_tag('?edit=' + name, 'Edit Page', 'navlink', authentication=True)
148 print ' | <i>Immutable Page</i>'
151 if user != 'AnonymousCoward':
152 print ' | <span class="login"><i>logged in as <b>' + cgi.escape(user) + '</b></i></span>'
156 def link_tag(params, text=None, ss_class=None, authentication=False):
158 text = params # default
161 classattr += 'class="%s" ' % ss_class
162 # Prevent crawlers from following links potentially added by spammers or to generated pages
163 if ss_class == 'external' or ss_class == 'navlink':
164 classattr += 'rel="nofollow" '
166 path = privileged_path()
169 return '<a %shref="%s/%s">%s</a>' % (classattr, path, params, text)
171 # Search ---------------------------------------------------
173 def do_fullsearch(needle):
174 send_title(None, 'Full text search for "%s"' % (needle))
176 needle_re = re.compile(needle, re.IGNORECASE)
178 all_pages = page_list()
179 for page_name in all_pages:
180 body = Page(page_name).get_raw_body()
181 count = len(needle_re.findall(body))
183 hits.append((count, page_name))
185 # The default comparison for tuples compares elements in order,
186 # so this sorts by number of hits
191 for (count, page_name) in hits:
192 print '<li><p>' + Page(page_name).link_to()
193 print ' . . . . ' + `count`
194 print ['match', 'matches'][count != 1]
198 print_search_stats(len(hits), len(all_pages))
200 def do_titlesearch(needle):
201 # TODO: check needle is legal -- but probably we can just accept any RE
202 send_title(None, "Title search for \"" + needle + '"')
204 needle_re = re.compile(needle, re.IGNORECASE)
205 all_pages = page_list()
206 hits = filter(needle_re.search, all_pages)
209 for filename in hits:
210 print '<li><p>' + Page(filename).link_to() + "</p></li>"
213 print_search_stats(len(hits), len(all_pages))
215 def print_search_stats(hits, searched):
216 print "<p>%d hits out of %d pages searched.</p>" % (hits, searched)
218 #TODO: merge into do_savepage()
219 def do_edit(pagename):
220 Page(pagename).send_editor()
222 def do_raw(pagename):
223 Page(pagename).send_raw()
225 def do_savepage(pagename):
228 if 'preview' in form:
229 pg.send_editor(form['savetext'].value)
231 pg.save_text(form['savetext'].value)
233 elif 'cancel' in form:
234 pg.msg = 'Editing canceled'
235 pg.msg_type = 'notice'
238 raise 'What did you press?'
240 def make_index_key():
242 links = map(lambda ch: '<a href="#%s">%s</a>' % (ch, ch),
244 s = s + string.join(links, ' | ')
245 s = s + '</center></p>'
249 return filter(word_re.match, os.listdir(data_dir))
251 def send_footer(name, mod_string=None):
252 if globals().get('debug_cgi', False):
253 cgi.print_arguments()
254 cgi.print_form(cgi.FieldStorage())
257 print '<div id="footer"><hr />'
258 print ('<p class="copyright"><span class="benchmark">generated in %0.3fs</span>' +
259 ' by <a href="http://www.codewiz.org/wiki/GeekiGeeki">GeekiGeeki</a>' +
260 ' version %s</p>') % (clock() - start_time, __version__)
262 print '<p class="modified">last modified %s</p>' % mod_string
263 print '</div></body></html>'
265 # ----------------------------------------------------------
267 def _macro_TitleSearch(*vargs):
268 return _macro_search("titlesearch")
270 def _macro_FullSearch(*vargs):
271 return _macro_search("fullsearch")
273 def _macro_search(type):
274 if form.has_key('value'):
275 default = form["value"].value
278 return """<form method="get"><input name="%s" size="30" value="%s" /><input type="submit" value="Search" /></form>""" % (type, default)
280 def _macro_WordIndex(*vargs):
282 pages = list(page_list())
284 word_re = re.compile('[A-Z][a-z]+')
286 for word in word_re.findall(name):
288 map[word].append(name)
292 all_words = map.keys()
296 for word in all_words:
297 letter = string.lower(word[0])
298 if letter != last_letter:
299 s = s + '; <a name="%s"><h3>%s</h3></a>' % (letter, letter)
302 s = s + '<b>%s</b><ul>' % word
307 if name == last_page: continue
308 s = s + '<li>' + Page(name).link_to()
313 def _macro_TitleIndex(*vargs):
315 pages = list(page_list())
317 current_letter = None
319 letter = string.lower(name[0])
320 if letter != current_letter:
321 s = s + '<a name="%s"><h3>%s</h3></a>' % (letter, letter)
322 current_letter = letter
325 s = s + Page(name).link_to()
329 # ----------------------------------------------------------
331 """Object that turns Wiki markup into HTML.
333 All formatting commands can be parsed one line at a time, though
334 some state is carried over between lines.
336 def __init__(self, raw):
339 self.in_pre = self.in_table = False
340 self.in_header = True
341 self.list_indents = []
342 self.tr_cnt = self.h_cnt = 0
352 "^^": ["sup", False],
356 def _b_repl(self, word):
357 style = self.styles[word]
358 style[1] = not style[1]
359 return ['</','<'][style[1]] + style[0] + '>'
361 def _tit_repl(self, word):
363 result = '</h%d>' % self.h_level
366 self.h_level = len(word) - 1
368 #abridged = re.sub('[^a-z_]', '', word.lower().replace(' ', '_'))
369 result = '<h%d id="%d"><a class="heading" href="#%d">¶</a> ' % (self.h_level, self.h_cnt, self.h_cnt)
372 def _br_repl(self, word):
375 def _rule_repl(self, word):
376 return self._undent() + '\n<hr size="%d" noshade="noshade" />\n' % (len(word) - 2)
378 def _word_repl(self, word):
379 return Page(word).link_to()
381 def _img_repl(self, word):
382 path = script_name() + '/' + word;
383 return '<a href="%s"><img border="0" src="%s" /></a>' % (path, path)
385 def _url_repl(self, word):
386 if img_re.match(word):
387 return '<a href="%s"><img border="0" src="%s" /></a>' % (word, word)
389 return '<a href="%s" rel="nofollow" class="external">%s</a>' % (word, word)
391 def _hurl_repl(self, word):
392 m = re.compile("\[\[(\S+)(?:\s*\|\s*([^\]]*)|)\]\]").match(word)
394 descr = m.group(2) or name
396 macro = globals().get('_macro_' + name)
398 return apply(macro, (name, descr))
399 elif img_re.match(name):
400 return '<a href="%s"><img border="0" src="%s" alt="%s" /></a>' % (name, name, descr)
402 if img_re.match(descr):
403 descr = '<img border="0" src="' + descr + '" />'
405 if url_re.match(name):
406 return '<a href="%s" rel="nofollow" class="external">%s</a>' % (name, descr)
407 elif name.startswith('/'):
408 return '<a href="%s">%s</a>' % (name, descr)
410 return link_tag(name, descr, 'wikilink')
412 def _email_repl(self, word):
413 return '<a href="mailto:%s">%s</a>' % (word, word)
415 def _html_repl(self, word):
416 return word; # Pass through
418 def _ent_repl(self, s):
419 return {'&': '&',
423 def _li_repl(self, match):
426 def _pre_repl(self, word):
427 if word == '{{{' and not self.in_pre:
435 def _hi_repl(self, word):
442 return '<strong class="highlight ' + cl + '">' + word + '</strong>'
444 def _tr_repl(self, word):
446 if not self.in_table:
449 out = '</p><table><tbody>\n'
451 out = out + '<tr class="' + ['even', 'odd'][self.tr_cnt % 2] + '">'
452 return out + ['<td>', '<th>'][word.strip() == '||=']
454 def _td_repl(self, word):
456 return ['</td><td>', '</th><th>'][word.strip() == '||=']
459 def _tre_repl(self, word):
461 return ['</td></tr>', '</th></tr>'][word.strip() == '||=']
464 def _indent_level(self):
465 return len(self.list_indents) and self.list_indents[-1]
467 def _indent_to(self, new_level):
468 if self._indent_level() == new_level:
471 while self._indent_level() > new_level:
472 del(self.list_indents[-1])
474 while self._indent_level() < new_level:
475 self.list_indents.append(new_level)
482 res += '</ul>' * len(self.list_indents)
484 self.list_indents = []
487 def replace(self, match):
488 for type, hit in match.groupdict().items():
490 return apply(getattr(self, '_' + type + '_repl'), (hit,))
492 raise "Can't handle match " + `match`
494 def print_html(self):
495 print '<div class="wiki"><p>'
497 # For each line, we scan through looking for magic
498 # strings, outputting verbatim any intervening text
499 # TODO: highlight search words (look at referer)
500 scan_re = re.compile(
503 + r"(?P<b>\*\*|'''|//|''|##|``|__|\^\^|,,)"
504 + r"|(?P<tit>\={2,6})"
506 + r"|(?P<rule>^-{3,})"
507 + r"|(?P<html><(/|)(div|span|iframe)[^<>]*>)"
509 + r"|(?P<hi>\b(FIXME|TODO|DONE)\b)"
512 + r"|(?P<img>\b[a-zA-Z0-9_-]+\.(png|gif|jpg|jpeg|bmp))"
513 + r"|(?P<word>\b(?:[A-Z][a-z]+){2,}\b)"
514 + r"|(?P<hurl>\[\[(\S+)(?:\s*\|\s*([^\]]*)|)\]\])"
515 + r"|(?P<url>(http|https|ftp|mailto)\:[^\s'\"]+\S)"
516 + r"|(?P<email>[-\w._+]+\@[\w.-]+)"
519 + r"|(?P<li>^\s+[\*#] +)"
520 + r"|(?P<pre>\{\{\{|\s*\}\}\})"
523 + r"|(?P<tr>^\s*\|\|(=|)\s*)"
524 + r"|(?P<tre>\s*\|\|(=|)\s*$)"
525 + r"|(?P<td>\s*\|\|(=|)\s*)"
529 + r"(?P<pre>\s*\}\}\})"
531 blank_re = re.compile(r"^\s*$")
532 indent_re = re.compile(r"^\s*")
533 tr_re = re.compile(r"^\s*\|\|")
534 eol_re = re.compile(r"\r?\n")
535 raw = string.expandtabs(self.raw)
536 for line in eol_re.split(raw):
539 if line.startswith('#'):
541 self.in_header = False
544 print re.sub(pre_re, self.replace, line)
546 if self.in_table and not tr_re.match(line):
547 self.in_table = False
548 print '</tbody></table><p>'
550 if blank_re.match(line):
553 indent = indent_re.match(line)
554 print self._indent_to(len(indent.group(0)))
555 print re.sub(scan_re, self.replace, line)
557 if self.in_pre: print '</pre>'
558 if self.in_table: print '</tbody></table><p>'
562 # ----------------------------------------------------------
564 def __init__(self, page_name):
565 self.page_name = page_name
567 self.msg_type = 'error'
569 def split_title(self):
570 # look for the end of words and the start of a new word,
571 # and insert a space there
572 return re.sub('([a-z])([A-Z])', r'\1 \2', self.page_name)
574 def _text_filename(self):
575 return path.join(data_dir, self.page_name)
577 def _tmp_filename(self):
578 return path.join(data_dir, ('#' + self.page_name + '.' + `os.getpid()` + '#'))
582 os.stat(self._text_filename())
585 if er.errno == errno.ENOENT:
591 word = self.page_name
593 return link_tag(word, word, 'wikilink')
595 return link_tag(word, nonexist_pfx + word, 'nonexistent')
597 def get_raw_body(self):
599 return open(self._text_filename(), 'rt').read()
601 if er.errno == errno.ENOENT:
602 return '' # just doesn't exist, use default
606 if self.__dict__.has_key('attrs'):
610 file = open(self._text_filename(), 'rt')
611 attr_re = re.compile(r"^#(\S*)(.*)$")
613 m = attr_re.match(line)
616 self.attrs[m.group(1)] = m.group(2).strip()
617 #print "bernie: attrs[" + m.group(1) + "] = " + m.group(2) + "<br>\n"
619 if er.errno != errno.ENOENT:
623 def get_attr(self, name, default):
624 if self.get_attrs().has_key(name):
625 return self.get_attrs()[name]
629 def can(self, action, default=True):
631 #acl SomeUser:read,write All:read
632 acl = self.get_attr("acl", None)
633 for rule in acl.split():
634 (user,perms) = rule.split(':')
635 if user == remote_user() or user == "All":
636 if action in perms.split(','):
641 except Exception, er:
646 return self.can("write", True)
649 return self.can("read", True)
654 page_name = self.page_name
656 #FIXME: are there security implications?
659 css_url = css_url + self.get_attr("css", "").split()
661 send_title(page_name, self.split_title(), msg=self.msg, msg_type=self.msg_type)
663 PageFormatter(self.get_raw_body()).print_html()
665 send_guru("Read access denied by ACLs", "notice")
666 send_footer(page_name, self._last_modified())
668 def _last_modified(self):
670 from time import localtime, strftime
671 modtime = localtime(os.stat(self._text_filename())[stat.ST_MTIME])
673 if er.errno != errno.ENOENT:
676 return strftime(datetime_fmt, modtime)
678 def send_editor(self, preview=None):
679 send_title(None, 'Edit ' + self.split_title(), msg=self.msg, msg_type=self.msg_type)
680 if not self.can_write():
681 send_guru("Write access denied by ACLs", "error")
684 print ('<p><b>Editing ' + self.page_name
685 + ' for ' + cgi.escape(remote_user())
686 + ' from ' + cgi.escape(get_hostname(remote_host()))
688 print '<div class="editor"><form method="post" action="%s/%s">' % (script_name(), self.page_name)
689 print '<input type="hidden" name="savepage" value="%s">' % (self.page_name)
690 print """<textarea wrap="off" spellcheck="true" id="editor" name="savetext" rows="17" cols="100">%s</textarea>""" % (preview or self.get_raw_body())
693 <input type="submit" name="save" value="Save" />
694 <input type="submit" name="preview" value="Preview" />
695 <input type="reset" value="Reset" />
696 <input type="submit" name="cancel" value="Cancel" />
699 print "<p>" + Page('EditingTips').link_to() + "</p>"
701 print "<div class='preview'>"
702 PageFormatter(preview).print_html()
704 send_footer(self.page_name)
707 if not self.can_read():
708 send_title(None, msg='Read access denied by ACLs', msg_type='notice')
710 emit_header("text/plain")
711 print self.get_raw_body()
713 def _write_file(self, text):
714 tmp_filename = self._tmp_filename()
715 open(tmp_filename, 'wt').write(text.replace('\r\n', '\n'))
716 text = self._text_filename()
718 # Bad Bill! POSIX rename ought to replace. :-(
722 if er.errno != errno.ENOENT: raise er
723 os.rename(tmp_filename, text)
725 def save_text(self, newtext):
726 if not self.can_write():
727 self.msg = 'Write access denied by ACLs'
728 self.msg_type = 'error'
731 self._write_file(newtext)
734 # FIXME: what's the std way to perform shell quoting in python?
735 cmd = ( post_edit_hook
736 + " '" + data_dir + '/' + self.page_name
737 + "' '" + remote_user()
738 + "' '" + remote_host() + "'"
744 self.msg += "Post-editing hook returned %d.\n" % rc
745 self.msg += 'Command was: ' + cmd + '\n'
747 self.msg += 'Output follows:\n' + msg
749 self.msg = 'Thank you for your contribution. Your attention to detail is appreciated.'
750 self.msg_type = 'success'
752 #TODO: merge into send_raw()
753 def send_verbatim(filename, mime_type='application/octet-stream'):
754 pathname = path.join(data_dir, filename)
755 data = open(pathname, 'rb').read()
756 emit_header(mime_type)
757 sys.stdout.write(data)
759 # Main ---------------------------------------------------------------
761 execfile("geekigeeki.conf.py")
763 form = cgi.FieldStorage()
765 handlers = { 'fullsearch': do_fullsearch,
766 'titlesearch': do_titlesearch,
769 'savepage': do_savepage }
771 for cmd in handlers.keys():
772 if form.has_key(cmd):
773 apply(handlers[cmd], (form[cmd].value,))
776 path_info = environ.get('PATH_INFO', '')
777 if len(path_info) and path_info[0] == '/':
778 query = path_info[1:] or 'FrontPage'
780 query = environ.get('QUERY_STRING', '') or 'FrontPage'
782 if file_re.match(query):
783 if word_re.match(query):
784 Page(query).send_page()
785 elif img_re.match(query):
786 #FIXME: use correct mime type
787 send_verbatim(query, 'image/jpeg')
791 print "Status: 404 Not Found"
792 send_title(None, msg='Can\'t work out query: ' + query)
795 msg=traceback.format_exc()
797 send_guru(msg, "error")
799 send_title(None, msg=msg)