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 word_re = re.compile(r"^\b((([A-Z][a-z]+){2,}/)*([A-Z][a-z]+){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$")
40 # CGI stuff ---------------------------------------------------------
43 return environ.get('SCRIPT_NAME', '')
45 def privileged_path():
46 return privileged_url or script_name()
49 user = environ.get('REMOTE_USER', '')
50 if user is None or user == '' or user == 'anonymous':
51 user = 'AnonymousCoward'
55 return environ.get('REMOTE_ADDR', '')
57 def get_hostname(addr):
59 from socket import gethostbyaddr
60 return gethostbyaddr(addr)[0] + ' (' + addr + ')'
64 def relative_url(pathname, privileged=False):
65 if not (url_re.match(pathname) or pathname.startswith('/')):
67 url = privileged_path()
70 pathname = url + '/' + pathname
74 return re.sub(' ', '-', re.sub('[^a-z0-9_ ]', '', s.lower()).strip())
76 # Formatting stuff --------------------------------------------------
77 def emit_header(mime_type="text/html"):
78 print "Content-type: " + mime_type + "; charset=utf-8\n"
80 def send_guru(msg_text, msg_type):
81 if not msg_text: return
82 print '<pre id="guru" onclick="this.style.display = \'none\'" class="' + msg_type + '">'
83 if msg_type == 'error':
84 print ' Software Failure. Press left mouse button to continue.\n'
86 if msg_type == 'error':
87 print ' Guru Meditation #DEADBEEF.ABADC0DE'
89 # FIXME: This little JS snippet is harder to pass than ACID 3.0
91 <script language="JavaScript" type="text/javascript">
92 var guru = document.getElementById('guru');
93 // Firefox 2.0 doesn't take border-color, but returns border-top-color fine
94 var color = document.defaultView.getComputedStyle(guru,null).getPropertyValue('border-top-color');
97 guru.style.setProperty('border-color', color, '');
98 setTimeout('guruOff()', 1000);
101 guru.style.setProperty('border-color', '#000000', '');
102 setTimeout('guruOn()', 1000);
104 // Safari 2.0 returns this rgba crap
105 // Konqueror 3.5.6 doesn't seem to support computed properties
106 if (color && color != 'rgba(0, 0, 0, 0)') {
107 //window.alert("enabled! color='" + color + "'");
112 def send_title(name, text="Limbo", msg_text=None, msg_type='error'):
114 if title_done: return
118 print '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"'
119 print ' "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">'
120 print '<html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en">'
122 site_name = globals().get('site_name', 'Unconfigured Site')
123 print "<head><title>%s: %s</title>" % (site_name, text)
124 print ' <meta http-equiv="Content-Type" content="application/xhtml+xml; charset=utf-8" />'
126 print ' <meta name="robots" content="noindex,nofollow" />'
128 print ' <link rel="stylesheet" type="text/css" href="%s" />' % relative_url(css)
132 if name and privileged_url is not None:
133 print '<body ondblclick="location.href=\'' + privileged_path() + '?edit=' + name + '\'">'
138 send_guru(msg_text, msg_type)
141 print '<div class="nav">'
143 print ' <b>' + link_tag('?fullsearch=' + name, text, 'navlink') + '</b> '
145 print ' <b>' + text + '</b> '
146 print ' | ' + link_tag('FrontPage', 'Front Page', 'navlink')
147 print ' | ' + link_tag('FindPage', 'Find Page', 'navlink')
148 if 'history_url' in globals():
149 print ' | <a href="' + history_url + '" class="navlink">Recent Changes</a>'
151 print ' | <a href="' + history_url + '?a=history;f=' + name + '" class="navlink">Page History</a>'
154 print ' | ' + link_tag('?raw=' + name, 'Raw Text', 'navlink')
155 if privileged_url is not None:
156 print ' | ' + link_tag('?edit=' + name, 'Edit Page', 'navlink', privileged=True)
158 print ' | <i>Immutable Page</i>'
161 if user != 'AnonymousCoward':
162 print ' | <span class="login"><i>logged in as <b>' + cgi.escape(user) + '</b></i></span>'
166 def link_tag(params, text=None, ss_class=None, privileged=False):
168 text = params # default
171 classattr += 'class="%s" ' % ss_class
172 # Prevent crawlers from following links potentially added by spammers or to generated pages
173 if ss_class == 'external' or ss_class == 'navlink':
174 classattr += 'rel="nofollow" '
175 elif url_re.match(params):
176 classattr += 'rel="nofollow" '
177 return '<a %shref="%s">%s</a>' % (classattr, relative_url(params, privileged=privileged), text)
179 # Search ---------------------------------------------------
181 def handle_fullsearch(needle):
182 send_title(None, 'Full text search for "%s"' % (needle))
184 needle_re = re.compile(needle, re.IGNORECASE)
186 all_pages = page_list()
187 for page_name in all_pages:
188 body = Page(page_name).get_raw_body()
189 count = len(needle_re.findall(body))
191 hits.append((count, page_name))
193 # The default comparison for tuples compares elements in order,
194 # so this sorts by number of hits
199 for (count, page_name) in hits:
200 print '<li><p>' + Page(page_name).link_to()
201 print ' . . . . ' + `count`
202 print ['match', 'matches'][count != 1]
206 print_search_stats(len(hits), len(all_pages))
208 def handle_titlesearch(needle):
209 # TODO: check needle is legal -- but probably we can just accept any RE
210 send_title(None, "Title search for \"" + needle + '"')
212 needle_re = re.compile(needle, re.IGNORECASE)
213 all_pages = page_list()
214 hits = filter(needle_re.search, all_pages)
217 for filename in hits:
218 print '<li><p>' + Page(filename).link_to() + "</p></li>"
221 print_search_stats(len(hits), len(all_pages))
223 def print_search_stats(hits, searched):
224 print "<p>%d hits out of %d pages searched.</p>" % (hits, searched)
226 def handle_raw(pagename):
227 Page(pagename).send_raw()
229 def handle_edit(pagename):
232 if form['file'].value:
233 pg.save(form['file'].file.read())
235 pg.save(form['savetext'].value.replace('\r\n', '\n'))
237 elif 'cancel' in form:
238 pg.msg_text = 'Editing canceled'
239 pg.msg_type = 'notice'
241 else: # preview or edit
243 if 'preview' in form:
244 text = form['savetext'].value
247 def make_index_key():
248 links = map(lambda ch: '<a href="#%s">%s</a>' % (ch, ch), 'abcdefghijklmnopqrstuvwxyz')
249 return '<p><center>'+ ' | '.join(links) + '</center></p>'
252 return filter(word_re.match, os.listdir(data_dir))
254 def send_footer(name, mod_string=None):
255 if globals().get('debug_cgi', False):
256 cgi.print_arguments()
259 print '<div id="footer"><hr />'
260 print ('<p class="copyright"><span class="benchmark">generated in %0.3fs</span>' +
261 ' by <a href="http://www.codewiz.org/wiki/GeekiGeeki">GeekiGeeki</a>' +
262 ' version %s</p>') % (clock() - start_time, __version__)
264 print '<p class="modified">last modified %s</p>' % mod_string
265 print '</div></body></html>'
267 # Macros ------------------------------------------------------------
268 def _macro_TitleSearch(*vargs):
269 return _macro_search("titlesearch")
271 def _macro_FullSearch(*vargs):
272 return _macro_search("fullsearch")
274 def _macro_search(type):
277 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 = word[0].lower()
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 = name[0].lower()
320 if letter != current_letter:
321 s += '<a name="%s"><h3>%s</h3></a>' % (letter, letter)
322 current_letter = letter
325 s += Page(name).link_to()
329 """Object that turns Wiki markup into HTML.
331 All formatting commands can be parsed one line at a time, though
332 some state is carried over between lines.
334 def __init__(self, raw):
337 self.in_pre = self.in_table = self.in_li = False
338 self.in_header = True
339 self.list_indents = []
350 "^^": ["sup", False],
354 def _b_repl(self, word):
355 style = self.styles[word]
356 style[1] = not style[1]
357 return ['</', '<'][style[1]] + style[0] + '>'
359 def _tit_repl(self, word):
361 result = '</h%d><p>\n' % self.h_level
364 self.h_level = len(word) - 1
365 link = permalink(self.line)
366 result = '\n</p><h%d id="%s"><a class="heading" href="#%s">¶</a> ' % (self.h_level, link, link)
369 def _br_repl(self, word):
372 def _rule_repl(self, word):
373 return self._undent() + '\n<hr size="%d" noshade="noshade" />\n' % (len(word) - 2)
375 def _word_repl(self, word):
376 return Page(word).link_to()
378 def _img_repl(self, word):
379 path = relative_url(word)
380 return '<a href="%s"><img border="0" src="%s" /></a>' % (path, path)
382 def _url_repl(self, word):
383 if img_re.match(word):
384 return '<a href="%s"><img border="0" src="%s" /></a>' % (word, word)
386 return '<a href="%s" rel="nofollow" class="external">%s</a>' % (word, word)
388 def _hurl_repl(self, word):
389 m = re.compile("\[\[([^ \t\n\r\f\v\|]+)(?:\s*\|\s*([^\]]+)|)\]\]").match(word)
391 descr = m.group(2) or name
393 macro = globals().get('_macro_' + name)
395 return macro(name, descr)
396 elif img_re.match(name):
397 name = relative_url(name)
398 # The "extthumb" nonsense works around a limitation of the HTML block model
399 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)
401 if img_re.match(descr):
402 descr = '<img border="0" src="' + descr + '" />'
404 return link_tag(name, descr, 'wikilink')
406 def _email_repl(self, word):
407 return '<a href="mailto:%s">%s</a>' % (word, word)
409 def _html_repl(self, word):
410 return word; # Pass through
412 def _ent_repl(self, s):
413 return {'&': '&',
417 def _li_repl(self, match):
424 def _pre_repl(self, word):
425 if word == '{{{' and not self.in_pre:
433 def _hi_repl(self, word):
434 return '<strong class="highlight ' + word + '">' + word + '</strong>'
436 def _tr_repl(self, word):
438 if not self.in_table:
441 out = '</p><table><tbody>\n'
443 out = out + '<tr class="' + ['even', 'odd'][self.tr_cnt % 2] + '">'
444 return out + ['<td>', '<th>'][word.strip() == '||=']
446 def _td_repl(self, word):
448 return ['</td><td>', '</th><th>'][word.strip() == '||=']
451 def _tre_repl(self, word):
453 return ['</td></tr>', '</th></tr>'][word.strip() == '||=']
456 def _indent_level(self):
457 return len(self.list_indents) and self.list_indents[-1]
459 def _indent_to(self, new_level):
460 if self._indent_level() == new_level:
463 while self._indent_level() > new_level:
464 del(self.list_indents[-1])
467 self.in_li = False # FIXME
469 while self._indent_level() < new_level:
470 self.list_indents.append(new_level)
477 res += '</ul>' * len(self.list_indents)
479 self.list_indents = []
482 def replace(self, match):
483 for type, hit in match.groupdict().items():
485 return getattr(self, '_' + type + '_repl')(hit)
487 raise "Can't handle match " + `match`
489 def print_html(self):
490 print '<div class="wiki"><p>'
492 # For each line, we scan through looking for magic
493 # strings, outputting verbatim any intervening text
494 # TODO: highlight search words (look at referrer)
495 scan_re = re.compile(
498 + r"(?P<b>\*\*|'''|//|''|##|``|__|\^\^|,,)"
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<hurl>\{\{([^\s\|]+)(?:\s*\|\s*([^\]]+)|)\}\})"
519 + r"|(?P<tr>^\s*\|\|(=|)\s*)"
520 + r"|(?P<tre>\s*\|\|(=|)\s*$)"
521 + r"|(?P<td>\s*\|\|(=|)\s*)"
525 + r"(?P<pre>\s*\}\}\})"
528 blank_re = re.compile(r"^\s*$")
529 indent_re = re.compile(r"^\s*")
530 tr_re = re.compile(r"^\s*\|\|")
531 eol_re = re.compile(r"\r?\n")
532 for self.line in eol_re.split(self.raw.expandtabs()):
535 if self.line.startswith('#'):
537 self.in_header = False
540 print re.sub(pre_re, self.replace, self.line)
542 if self.in_table and not tr_re.match(self.line):
543 self.in_table = False
544 print '</tbody></table><p>'
546 if blank_re.match(self.line):
549 indent = indent_re.match(self.line)
550 print self._indent_to(len(indent.group(0)))
551 print re.sub(scan_re, self.replace, self.line)
553 if self.in_pre: print '</pre>'
554 if self.in_table: print '</tbody></table><p>'
559 def __init__(self, page_name):
560 self.page_name = page_name
562 self.msg_type = 'error'
564 def split_title(self):
565 # look for the end of words and the start of a new word and insert a space there
566 return re.sub('([a-z])([A-Z])', r'\1 \2', self.page_name)
568 def _text_filename(self):
569 return path.join(data_dir, self.page_name)
571 def _tmp_filename(self):
572 return path.join(data_dir, ('#' + self.page_name.replace('/','_') + '.' + `os.getpid()` + '#'))
576 os.stat(self._text_filename())
579 if er.errno == errno.ENOENT:
584 word = self.page_name
586 return link_tag(word, word, 'wikilink')
588 return link_tag(word, nonexist_pfx + word, 'nonexistent')
590 def get_raw_body(self):
592 return open(self._text_filename(), 'rb').read()
594 if er.errno == errno.ENOENT:
595 return '' # just doesn't exist, use default
596 if er.errno == errno.EISDIR:
601 if 'attrs' in self.__dict__:
605 file = open(self._text_filename(), 'rt')
606 attr_re = re.compile(r"^#(\S*)(.*)$")
608 m = attr_re.match(line)
611 self.attrs[m.group(1)] = m.group(2).strip()
612 #print "bernie: attrs[" + m.group(1) + "] = " + m.group(2) + "<br>\n"
614 if er.errno != errno.ENOENT:
618 def get_attr(self, name, default):
619 return self.get_attrs().get(name, default)
621 def can(self, action, default=True):
624 #acl SomeUser:read,write All:read
625 acl = self.get_attr("acl", None)
626 for rule in acl.split():
627 (user, perms) = rule.split(':')
628 if user == remote_user() or user == "All":
629 return action in perms.split(',')
631 except Exception, er:
633 self.msg_text = 'Illegal acl line: ' + acl
637 return self.can("write", True)
640 return self.can("read", True)
645 page_name = self.page_name
649 css_url = self.get_attr("css", "").split() + css_url
651 send_title(page_name, self.split_title(), msg_text=self.msg_text, msg_type=self.msg_type)
653 PageFormatter(self.get_raw_body()).print_html()
655 send_guru("Read access denied by ACLs", "notice")
656 send_footer(page_name, self._last_modified())
658 def _last_modified(self):
660 from time import localtime, strftime
661 modtime = localtime(os.stat(self._text_filename())[stat.ST_MTIME])
663 if er.errno != errno.ENOENT:
666 return strftime(datetime_fmt, modtime)
668 def send_editor(self, preview=None):
669 send_title(None, 'Edit ' + self.split_title(), msg_text=self.msg_text, msg_type=self.msg_type)
670 if not self.can_write():
671 send_guru("Write access denied by ACLs", "error")
676 file = form['file'].value
678 print ('<p><b>Editing ' + self.page_name
679 + ' for ' + cgi.escape(remote_user())
680 + ' from ' + cgi.escape(get_hostname(remote_host()))
682 print '<div class="editor"><form method="post" enctype="multipart/form-data" action="%s">' % relative_url(self.page_name)
683 print '<input type="hidden" name="edit" value="%s">' % (self.page_name)
684 print '<textarea wrap="off" spellcheck="true" id="editor" name="savetext" rows="17" cols="100">%s</textarea>' % (preview or self.get_raw_body())
685 print 'Or upload a file: <input type="file" name="file" value="%s" />' % file
688 <input type="submit" name="save" value="Save" />
689 <input type="submit" name="preview" value="Preview" />
690 <input type="reset" value="Reset" />
691 <input type="submit" name="cancel" value="Cancel" />
694 print "<p>" + Page('EditingTips').link_to() + "</p>"
696 print "<div class='preview'>"
697 PageFormatter(preview).print_html()
699 send_footer(self.page_name)
701 def send_raw(self, mimetype='text/plain'):
703 body = self.get_raw_body()
704 emit_header(mimetype)
707 send_title(None, msg_text='Read access denied by ACLs', msg_type='notice')
709 def _write_file(self, data):
710 tmp_filename = self._tmp_filename()
711 open(tmp_filename, 'wb').write(data)
712 name = self._text_filename()
714 # Bad Bill! POSIX rename ought to replace. :-(
718 if er.errno != errno.ENOENT: raise er
719 os.rename(tmp_filename, name)
721 def save(self, newdata):
722 if not self.can_write():
723 self.msg_text = 'Write access denied by ACLs'
724 self.msg_type = 'error'
727 self._write_file(newdata)
730 # FIXME: what's the std way to perform shell quoting in python?
731 cmd = ( post_edit_hook
732 + " '" + data_dir + '/' + self.page_name
733 + "' '" + remote_user()
734 + "' '" + remote_host() + "'"
740 self.msg_text += "Post-editing hook returned %d.\n" % rc
741 self.msg_text += 'Command was: ' + cmd + '\n'
743 self.msg_text += 'Output follows:\n' + output
745 self.msg_text = 'Thank you for your contribution. Your attention to detail is appreciated.'
746 self.msg_type = 'success'
748 # Main ---------------------------------------------------------------
750 execfile("geekigeeki.conf.py")
751 form = cgi.FieldStorage()
754 handler = globals().get('handle_' + cmd)
756 handler(form[cmd].value)
759 path_info = environ.get('PATH_INFO', '')
760 if len(path_info) and path_info[0] == '/':
761 query = path_info[1:] or 'FrontPage'
763 query = environ.get('QUERY_STRING', '') or 'FrontPage'
765 if file_re.match(query):
766 if word_re.match(query):
767 Page(query).send_page()
769 from mimetypes import MimeTypes
770 type, encoding = MimeTypes().guess_type(query)
771 type = type or 'text/plain'
772 Page(query).send_raw(mimetype=type)
774 print "Status: 404 Not Found"
775 send_title(None, msg_text='Can\'t work out query: ' + query)
779 msg_text = traceback.format_exc()
781 send_guru(msg_text, "error")
783 send_title(None, msg_text=msg_text)