2 # -*- coding: utf-8 -*-
4 # Copyright 1999, 2000 Martin Pool <mbp@humbug.org.au>
5 # Copyright 2002 Gerardo Poggiali
6 # Copyright 2007, 2008 Bernie 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 word_re = re.compile(r"^\b((([A-Z][a-z0-9]+){2,}/)*([A-Z][a-z0-9]+){2,})\b$")
32 # FIXME: we accept stuff like foo/../bar and we shouldn't
33 file_re = re.compile(r"^\b([A-Za-z0-9_\-][A-Za-z0-9_\.\-/]*)\b$")
34 img_re = re.compile(r"^.*\.(png|gif|jpg|jpeg)$", re.IGNORECASE)
35 url_re = re.compile(r"^[a-z]{3,8}://[^\s'\"]+\S$")
36 link_re = re.compile("(?:\[\[|{{)([^\s\|]+)(?:\s*\|\s*([^\]]+)|)(?:\]\]|}})")
41 # CGI stuff ---------------------------------------------------------
44 return environ.get('SCRIPT_NAME', '')
46 def privileged_path():
47 return privileged_url or script_name()
50 user = environ.get('REMOTE_USER', '')
51 if user is None or user == '' or user == 'anonymous':
52 user = 'AnonymousCoward'
56 return environ.get('REMOTE_ADDR', '')
58 def get_hostname(addr):
60 from socket import gethostbyaddr
61 return gethostbyaddr(addr)[0] + ' (' + addr + ')'
65 def relative_url(pathname, privileged=False):
66 if not (url_re.match(pathname) or pathname.startswith('/')):
68 url = privileged_path()
71 pathname = url + '/' + pathname
75 return re.sub(' ', '-', re.sub('[^a-z0-9_ ]', '', s.lower()).strip())
77 # Formatting stuff --------------------------------------------------
78 def emit_header(mime_type="text/html"):
79 print "Content-type: " + mime_type + "; charset=utf-8\n"
81 def send_guru(msg_text, msg_type):
82 if not msg_text: return
83 print '<pre id="guru" onclick="this.style.display = \'none\'" class="' + msg_type + '">'
84 if msg_type == 'error':
85 print ' Software Failure. Press left mouse button to continue.\n'
87 if msg_type == 'error':
88 print ' Guru Meditation #DEADBEEF.ABADC0DE'
90 # FIXME: This little JS snippet is harder to pass than ACID 3.0
92 <script language="JavaScript" type="text/javascript">
93 var guru = document.getElementById('guru');
94 // Firefox 2.0 doesn't take border-color, but returns border-top-color fine
95 var color = document.defaultView.getComputedStyle(guru,null).getPropertyValue('border-top-color');
98 guru.style.setProperty('border-color', color, '');
99 setTimeout('guruOff()', 1000);
102 guru.style.setProperty('border-color', '#000000', '');
103 setTimeout('guruOn()', 1000);
105 // Safari 2.0 returns this rgba crap
106 // Konqueror 3.5.6 doesn't seem to support computed properties
107 if (color && color != 'rgba(0, 0, 0, 0)') {
108 //window.alert("enabled! color='" + color + "'");
113 def send_title(name, text="Limbo", msg_text=None, msg_type='error'):
115 if title_done: return
119 print '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"'
120 print ' "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">'
121 print '<html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en">'
123 site_name = globals().get('site_name', 'Unconfigured Site')
124 print "<head><title>%s: %s</title>" % (site_name, text)
125 print ' <meta http-equiv="Content-Type" content="application/xhtml+xml; charset=utf-8" />'
127 print ' <meta name="robots" content="noindex,nofollow" />'
129 print ' <link rel="stylesheet" type="text/css" href="%s" />' % relative_url(css)
133 if name and privileged_url is not None:
134 print '<body ondblclick="location.href=\'' + privileged_path() + '?edit=' + name + '\'">'
139 send_guru(msg_text, msg_type)
142 print '<div class="nav">'
144 print ' <b>' + link_tag('?fullsearch=' + name, text, 'navlink') + '</b> '
146 print ' <b>' + text + '</b> '
147 print ' | ' + link_tag('FrontPage', 'Front Page', 'navlink')
148 print ' | ' + link_tag('FindPage', 'Find Page', 'navlink')
149 if 'history_url' in globals():
150 print ' | <a href="' + history_url + '" class="navlink">Recent Changes</a>'
152 print ' | <a href="' + history_url + '?a=history;f=' + name + '" class="navlink">Page History</a>'
155 print ' | ' + link_tag('?raw=' + name, 'Raw Text', 'navlink')
156 if privileged_url is not None:
157 print ' | ' + link_tag('?edit=' + name, 'Edit Page', 'navlink', privileged=True)
159 print ' | <i>Immutable Page</i>'
162 if user != 'AnonymousCoward':
163 print ' | <span class="login"><i>logged in as <b>' + cgi.escape(user) + '</b></i></span>'
167 def link_tag(params, text=None, ss_class=None, privileged=False):
169 text = params # default
172 classattr += 'class="%s" ' % ss_class
173 # Prevent crawlers from following links potentially added by spammers or to generated pages
174 if ss_class == 'external' or ss_class == 'navlink':
175 classattr += 'rel="nofollow" '
176 elif url_re.match(params):
177 classattr += 'rel="nofollow" '
178 return '<a %shref="%s">%s</a>' % (classattr, relative_url(params, privileged=privileged), text)
180 # Search ---------------------------------------------------
182 def handle_fullsearch(needle):
183 send_title(None, 'Full text search for "%s"' % (needle))
185 needle_re = re.compile(needle, re.IGNORECASE)
187 all_pages = page_list()
188 for page_name in all_pages:
189 body = Page(page_name).get_raw_body()
190 count = len(needle_re.findall(body))
192 hits.append((count, page_name))
194 # The default comparison for tuples compares elements in order,
195 # so this sorts by number of hits
200 for (count, page_name) in hits:
201 print '<li><p>' + Page(page_name).link_to()
202 print ' . . . . ' + `count`
203 print ['match', 'matches'][count != 1]
207 print_search_stats(len(hits), len(all_pages))
209 def handle_titlesearch(needle):
210 # TODO: check needle is legal -- but probably we can just accept any RE
211 send_title(None, "Title search for \"" + needle + '"')
213 needle_re = re.compile(needle, re.IGNORECASE)
214 all_pages = page_list()
215 hits = filter(needle_re.search, all_pages)
218 for filename in hits:
219 print '<li><p>' + Page(filename).link_to() + "</p></li>"
222 print_search_stats(len(hits), len(all_pages))
224 def print_search_stats(hits, searched):
225 print "<p>%d hits out of %d pages searched.</p>" % (hits, searched)
227 def handle_raw(pagename):
228 Page(pagename).send_raw()
230 def handle_edit(pagename):
233 if form['file'].value:
234 pg.save(form['file'].file.read())
236 pg.save(form['savetext'].value.replace('\r\n', '\n'))
238 elif 'cancel' in form:
239 pg.msg_text = 'Editing canceled'
240 pg.msg_type = 'notice'
242 else: # preview or edit
244 if 'preview' in form:
245 text = form['savetext'].value
248 def make_index_key():
249 links = map(lambda ch: '<a href="#%s">%s</a>' % (ch, ch), 'abcdefghijklmnopqrstuvwxyz')
250 return '<p><center>'+ ' | '.join(links) + '</center></p>'
252 def page_list(dir = None, re = word_re):
253 return filter(re.match, os.listdir(dir or data_dir))
255 def send_footer(name, mod_string=None):
256 if globals().get('debug_cgi', False):
257 cgi.print_arguments()
260 print '<div id="footer"><hr />'
261 print ('<p class="copyright"><span class="benchmark">generated in %0.3fs</span>' +
262 ' by <a href="http://www.codewiz.org/wiki/GeekiGeeki">GeekiGeeki</a>' +
263 ' version %s</p>') % (clock() - start_time, __version__)
265 print '<p class="modified">last modified %s</p>' % mod_string
266 print '</div></body></html>'
269 """Object that turns Wiki markup into HTML.
271 All formatting commands can be parsed one line at a time, though
272 some state is carried over between lines.
274 def __init__(self, raw):
277 self.in_pre = self.in_html = self.in_table = self.in_li = False
278 self.in_header = True
279 self.list_indents = []
290 "^^": ["sup", False],
294 def _b_repl(self, word):
295 style = self.styles[word]
296 style[1] = not style[1]
297 return ['</', '<'][style[1]] + style[0] + '>'
299 def _tit_repl(self, word):
301 result = '</h%d><p>\n' % self.h_level
304 self.h_level = len(word) - 1
305 link = permalink(self.line)
306 result = '\n</p><h%d id="%s"><a class="heading" href="#%s">¶</a> ' % (self.h_level, link, link)
309 def _br_repl(self, word):
312 def _rule_repl(self, word):
313 return self._undent() + '\n<hr size="%d" noshade="noshade" />\n' % (len(word) - 2)
315 def _word_repl(self, word):
316 return Page(word).link_to()
318 def _img_repl(self, word):
319 path = relative_url(word)
320 return '<a href="%s"><img border="0" src="%s" /></a>' % (path, path)
322 def _url_repl(self, word):
323 if img_re.match(word):
324 return '<a href="%s"><img border="0" src="%s" /></a>' % (word, word)
326 return '<a href="%s" rel="nofollow" class="external">%s</a>' % (word, word)
328 def _macro_repl(self, word):
329 m = re.compile("\<\<([^\s\|\>]+)(?:\s*\|\s*([^\>]+)|)\>\>").match(word)
333 argv.extend(m.group(2).split('|'))
334 argv = map(str.strip, argv)
336 macro = globals().get('_macro_' + name)
338 execfile("macros/" + name + ".py", globals())
339 macro = globals().get('_macro_' + name)
343 return '<strong class="error"><<' + '|'.join(argv) + '>></strong>'
345 def _hurl_repl(self, word):
346 m = link_re.match(word)
348 descr = m.group(2) or name
350 if img_re.match(name):
351 # DEPRECATED SYNTAX: use {{foo.jpg|descr}} instead
352 _inl_repl(self, word)
354 if img_re.match(descr):
355 descr = '<img border="0" src="' + descr + '" />'
357 return link_tag(name, descr, 'wikilink')
359 def _inl_repl(self, word):
360 m = link_re.match(word)
362 descr = m.group(2) or name
363 name = relative_url(name)
365 # The "extthumb" nonsense works around a limitation of the HTML block model
366 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)
368 return '<a href="%s"><img border="0" src="%s" /></a>' % (name, name)
370 def _email_repl(self, word):
371 return '<a href="mailto:%s">%s</a>' % (word, word)
373 def _html_repl(self, word):
375 return word; # Pass through
377 def _ent_repl(self, s):
378 if self.in_html and s == '>':
381 return {'&': '&',
385 def _li_repl(self, match):
392 def _pre_repl(self, word):
393 if word == '{{{' and not self.in_pre:
401 def _hi_repl(self, word):
402 return '<strong class="highlight ' + word + '">' + word + '</strong>'
404 def _tr_repl(self, word):
406 if not self.in_table:
409 out = '</p><table><tbody>\n'
411 out = out + '<tr class="' + ['even', 'odd'][self.tr_cnt % 2] + '">'
412 return out + ['<td>', '<th>'][word.strip() == '||=']
414 def _td_repl(self, word):
416 return ['</td><td>', '</th><th>'][word.strip() == '||=']
419 def _tre_repl(self, word):
421 return ['</td></tr>', '</th></tr>'][word.strip() == '||=']
424 def _indent_level(self):
425 return len(self.list_indents) and self.list_indents[-1]
427 def _indent_to(self, new_level):
428 if self._indent_level() == new_level:
431 while self._indent_level() > new_level:
432 del(self.list_indents[-1])
435 self.in_li = False # FIXME
437 while self._indent_level() < new_level:
438 self.list_indents.append(new_level)
445 res += '</ul>' * len(self.list_indents)
447 self.list_indents = []
450 def replace(self, match):
451 for type, hit in match.groupdict().items():
453 return getattr(self, '_' + type + '_repl')(hit)
455 raise "Can't handle match " + `match`
457 def print_html(self):
458 print '<div class="wiki"><p>'
460 # For each line, we scan through looking for magic
461 # strings, outputting verbatim any intervening text
462 # TODO: highlight search words (look at referrer)
463 scan_re = re.compile(
466 + r"(?P<b>\*\*|'''|//|''|##|``|__|\^\^|,,)"
467 + r"|(?P<tit>\={2,6})"
469 + r"|(?P<rule>^-{3,})"
470 + r"|(?P<hi>\b(FIXME|TODO|DONE)\b)"
473 + r"|(?P<macro>\<\<([^\s\|\>]+)(?:\s*\|\s*([^\>]+)|)\>\>)"
474 + r"|(?P<hurl>\[\[([^\s\|]+)(?:\s*\|\s*([^\]]+)|)\]\])"
477 + r"|(?P<html><(/|)(br|hr|div|form|iframe|input|span))"
481 + r"|(?P<img>\b[a-zA-Z0-9_/-]+\.(png|gif|jpg|jpeg|bmp))" # LEGACY
482 + r"|(?P<word>\b(?:[A-Z][a-z]+){2,}\b)" # LEGACY
483 + r"|(?P<url>(http|https|ftp|mailto)\:[^\s'\"]+\S)" # LEGACY
484 + r"|(?P<email>[-\w._+]+\@[\w.-]+)" # LEGACY
487 + r"|(?P<li>^\s+[\*#] +)"
488 + r"|(?P<pre>\{\{\{|\s*\}\}\})"
489 + r"|(?P<inl>\{\{([^\s\|]+)(?:\s*\|\s*([^\]]+)|)\}\})" #TODO
492 + r"|(?P<tr>^\s*\|\|(=|)\s*)"
493 + r"|(?P<tre>\s*\|\|(=|)\s*$)"
494 + r"|(?P<td>\s*\|\|(=|)\s*)"
498 + r"(?P<pre>\s*\}\}\})"
501 blank_re = re.compile(r"^\s*$")
502 indent_re = re.compile(r"^\s*")
503 tr_re = re.compile(r"^\s*\|\|")
504 eol_re = re.compile(r"\r?\n")
505 for self.line in eol_re.split(self.raw.expandtabs()):
508 if self.line.startswith('#'):
510 self.in_header = False
513 print re.sub(pre_re, self.replace, self.line)
515 if self.in_table and not tr_re.match(self.line):
516 self.in_table = False
517 print '</tbody></table><p>'
519 if blank_re.match(self.line):
522 indent = indent_re.match(self.line)
523 print self._indent_to(len(indent.group(0)))
524 print re.sub(scan_re, self.replace, self.line)
526 if self.in_pre: print '</pre>'
527 if self.in_table: print '</tbody></table><p>'
532 def __init__(self, page_name):
533 self.page_name = page_name
535 self.msg_type = 'error'
537 def split_title(self):
538 # look for the end of words and the start of a new word and insert a space there
539 return re.sub('([a-z])([A-Z])', r'\1 \2', self.page_name)
542 return path.join(data_dir, self.page_name)
544 def _tmp_filename(self):
545 return path.join(data_dir, ('#' + self.page_name.replace('/','_') + '.' + `os.getpid()` + '#'))
549 os.stat(self._filename())
552 if er.errno == errno.ENOENT:
557 word = self.page_name
559 return link_tag(word, word, 'wikilink')
561 return link_tag(word, nonexist_pfx + word, 'nonexistent')
563 def get_raw_body(self):
565 return open(self._filename(), 'rb').read()
567 if er.errno == errno.ENOENT:
568 return '' # just doesn't exist, use default
569 if er.errno == errno.EISDIR:
570 return self.format_dir()
573 def format_dir(self):
575 for file in page_list(self._filename(), file_re):
576 if img_re.match(file):
577 out += ' * {{' + self.page_name + '/' + file + '}}\n'
579 out += ' * [[' + self.page_name + '/' + file + ']]\n'
582 if 'attrs' in self.__dict__:
586 file = open(self._filename(), 'rt')
587 attr_re = re.compile(r"^#(\S*)(.*)$")
589 m = attr_re.match(line)
592 self.attrs[m.group(1)] = m.group(2).strip()
593 #print "bernie: attrs[" + m.group(1) + "] = " + m.group(2) + "<br>\n"
595 if er.errno != errno.ENOENT:
599 def get_attr(self, name, default):
600 return self.get_attrs().get(name, default)
602 def can(self, action, default=True):
605 #acl SomeUser:read,write All:read
606 acl = self.get_attr("acl", None)
607 for rule in acl.split():
608 (user, perms) = rule.split(':')
609 if user == remote_user() or user == "All":
610 return action in perms.split(',')
612 except Exception, er:
614 self.msg_text = 'Illegal acl line: ' + acl
618 return self.can("write", True)
621 return self.can("read", True)
623 def send_naked(self):
625 WikiFormatter(self.get_raw_body()).print_html()
627 send_guru("Read access denied by ACLs", "notice")
632 page_name = self.page_name
636 css_url = self.get_attr("css", "").split() + css_url
638 send_title(page_name, self.split_title(), msg_text=self.msg_text, msg_type=self.msg_type)
640 send_footer(page_name, self._last_modified())
642 def _last_modified(self):
644 from time import localtime, strftime
645 modtime = localtime(os.stat(self._filename())[stat.ST_MTIME])
647 if er.errno != errno.ENOENT:
650 return strftime(datetime_fmt, modtime)
652 def send_editor(self, preview=None):
653 send_title(None, 'Edit ' + self.split_title(), msg_text=self.msg_text, msg_type=self.msg_type)
654 if not self.can_write():
655 send_guru("Write access denied by ACLs", "error")
660 file = form['file'].value
662 print ('<p><b>Editing ' + self.page_name
663 + ' for ' + cgi.escape(remote_user())
664 + ' from ' + cgi.escape(get_hostname(remote_host()))
666 print '<div class="editor"><form method="post" enctype="multipart/form-data" action="%s">' % relative_url(self.page_name)
667 print '<input type="hidden" name="edit" value="%s">' % (self.page_name)
668 print '<textarea wrap="off" spellcheck="true" id="editor" name="savetext" rows="17" cols="100">%s</textarea>' % (preview or self.get_raw_body())
669 print 'Or upload a file: <input type="file" name="file" value="%s" />' % file
672 <input type="submit" name="save" value="Save" />
673 <input type="submit" name="preview" value="Preview" />
674 <input type="reset" value="Reset" />
675 <input type="submit" name="cancel" value="Cancel" />
678 print "<p>" + Page('EditingTips').link_to() + "</p>"
680 print "<div class='preview'>"
681 WikiFormatter(preview).print_html()
683 send_footer(self.page_name)
685 def send_raw(self, mimetype='text/plain'):
687 body = self.get_raw_body()
688 emit_header(mimetype)
691 send_title(None, msg_text='Read access denied by ACLs', msg_type='notice')
693 def _write_file(self, data):
694 tmp_filename = self._tmp_filename()
695 open(tmp_filename, 'wb').write(data)
696 name = self._filename()
698 # Bad Bill! POSIX rename ought to replace. :-(
702 if er.errno != errno.ENOENT: raise er
703 os.rename(tmp_filename, name)
705 def save(self, newdata):
706 if not self.can_write():
707 self.msg_text = 'Write access denied by ACLs'
708 self.msg_type = 'error'
711 self._write_file(newdata)
714 # FIXME: what's the std way to perform shell quoting in python?
715 cmd = ( post_edit_hook
716 + " '" + data_dir + '/' + self.page_name
717 + "' '" + remote_user()
718 + "' '" + remote_host() + "'"
724 self.msg_text += "Post-editing hook returned %d.\n" % rc
725 self.msg_text += 'Command was: ' + cmd + '\n'
727 self.msg_text += 'Output follows:\n' + output
729 self.msg_text = 'Thank you for your contribution. Your attention to detail is appreciated.'
730 self.msg_type = 'success'
732 # Main ---------------------------------------------------------------
734 execfile("geekigeeki.conf.py")
735 form = cgi.FieldStorage()
738 handler = globals().get('handle_' + cmd)
740 handler(form[cmd].value)
743 path_info = environ.get('PATH_INFO', '')
744 if len(path_info) and path_info[0] == '/':
745 query = path_info[1:] or 'FrontPage'
747 query = environ.get('QUERY_STRING', '') or 'FrontPage'
749 if file_re.match(query):
750 if word_re.match(query):
753 from mimetypes import MimeTypes
754 type, encoding = MimeTypes().guess_type(query)
755 type = type or 'text/plain'
756 Page(query).send_raw(mimetype=type)
758 print "Status: 404 Not Found"
759 send_title(None, msg_text='Can\'t work out query: ' + query)
763 msg_text = traceback.format_exc()
765 send_guru(msg_text, "error")
767 send_title(None, msg_text=msg_text)