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|bmp|ico)$", 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 '\n 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', writable=False):
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 for link in link_urls:
131 print ' <link rel="%s" href="%s" />' % (rel, relative_url(href))
133 if name and writable and privileged_url is not None:
134 print ' <link rel="alternate" type="application/x-wiki" title="Edit this page" href="%s" />' \
135 % (privileged_path() + '?edit=' + name)
137 if history_url is not None:
138 print ' <link rel="alternate" type="application/rss+xml" title="RSS" href="%s" />' \
139 % relative_url(history_url + '?a=rss')
144 if name and writable and privileged_url is not None:
145 print '<body ondblclick="location.href=\'' + privileged_path() + '?edit=' + name + '\'">'
150 send_guru(msg_text, msg_type)
153 print '<div class="nav">'
155 print ' <b>' + link_tag('?fullsearch=' + name, text, 'navlink') + '</b> '
157 print ' <b>' + text + '</b> '
158 print ' | ' + link_tag('FrontPage', 'Home', 'navlink')
159 print ' | ' + link_tag('FindPage', 'Find Page', 'navlink')
160 if 'history_url' in globals():
161 print ' | <a href="' + relative_url(history_url) + '" class="navlink">Recent Changes</a>'
163 print ' | <a href="' + relative_url(history_url + '?a=history;f=' + name) + '" class="navlink">Page History</a>'
166 print ' | ' + link_tag('?raw=' + name, 'Raw Text', 'navlink')
167 if privileged_url is not None:
169 print ' | ' + link_tag('?edit=' + name, 'Edit', 'navlink', privileged=True)
171 print ' | ' + link_tag(name, 'Login', 'navlink', privileged=True)
174 print ' | <i>Immutable Page</i>'
177 if user != 'AnonymousCoward':
178 print ' | <span class="login"><i>logged in as <b>' + cgi.escape(user) + '</b></i></span>'
182 def send_httperror(status="403 Not Found", query=""):
183 print "Status: %s" % status
184 send_title(None, msg_text=("%s: on query '%s'" % (status, query)))
187 def link_tag(params, text=None, ss_class=None, privileged=False):
189 text = params # default
192 classattr += 'class="%s" ' % ss_class
193 # Prevent crawlers from following links potentially added by spammers or to generated pages
194 if ss_class == 'external' or ss_class == 'navlink':
195 classattr += 'rel="nofollow" '
196 elif url_re.match(params):
197 classattr += 'rel="nofollow" '
198 return '<a %shref="%s">%s</a>' % (classattr, relative_url(params, privileged=privileged), text)
200 # Search ---------------------------------------------------
202 def handle_fullsearch(needle):
203 send_title(None, 'Full text search for "%s"' % (needle))
205 needle_re = re.compile(needle, re.IGNORECASE)
207 all_pages = page_list()
208 for page_name in all_pages:
209 body = Page(page_name).get_raw_body()
210 count = len(needle_re.findall(body))
212 hits.append((count, page_name))
214 # The default comparison for tuples compares elements in order,
215 # so this sorts by number of hits
220 for (count, page_name) in hits:
221 print '<li><p>' + Page(page_name).link_to()
222 print ' . . . . ' + `count`
223 print ['match', 'matches'][count != 1]
227 print_search_stats(len(hits), len(all_pages))
229 def handle_titlesearch(needle):
230 # TODO: check needle is legal -- but probably we can just accept any RE
231 send_title(None, "Title search for \"" + needle + '"')
233 needle_re = re.compile(needle, re.IGNORECASE)
234 all_pages = page_list()
235 hits = filter(needle_re.search, all_pages)
238 for filename in hits:
239 print '<li><p>' + Page(filename).link_to() + "</p></li>"
242 print_search_stats(len(hits), len(all_pages))
244 def print_search_stats(hits, searched):
245 print "<p>%d hits out of %d pages searched.</p>" % (hits, searched)
247 def handle_raw(pagename):
248 if not file_re.match(pagename):
249 send_httperror("403 Forbidden", pagename)
252 Page(pagename).send_raw()
254 def handle_edit(pagename):
255 if not file_re.match(pagename):
256 send_httperror("403 Forbidden", pagename)
261 if form['file'].value:
262 pg.save(form['file'].file.read(), form['changelog'].value)
264 pg.save(form['savetext'].value.replace('\r\n', '\n'), form['changelog'].value)
266 elif 'cancel' in form:
267 pg.msg_text = 'Editing canceled'
268 pg.msg_type = 'notice'
270 else: # preview or edit
272 if 'preview' in form:
273 text = form['savetext'].value
276 def make_index_key():
277 links = map(lambda ch: '<a href="#%s">%s</a>' % (ch, ch), 'abcdefghijklmnopqrstuvwxyz')
278 return '<p><center>'+ ' | '.join(links) + '</center></p>'
280 def page_list(dir = None, re = word_re):
281 return sorted(filter(re.match, os.listdir(dir or data_dir)))
283 def send_footer(name, mod_string=None):
284 if globals().get('debug_cgi', False):
285 cgi.print_arguments()
289 <div id="footer"><hr />
290 <p class="copyright">
291 <a rel="license" href="http://creativecommons.org/licenses/by-sa/3.0/"><img class="license" alt="Creative Commons License" src="http://i.creativecommons.org/l/by-sa/3.0/80x15.png" /></a>
292 <span class="benchmark">generated in %0.3fs</span> by <a href="http://www.codewiz.org/wiki/GeekiGeeki">GeekiGeeki</a> version %s
294 ''' % (clock() - start_time, __version__)
296 print '<p class="modified">last modified %s</p>' % mod_string
297 print '</div></body></html>'
300 """Object that turns Wiki markup into HTML.
302 All formatting commands can be parsed one line at a time, though
303 some state is carried over between lines.
305 def __init__(self, raw):
308 self.in_pre = self.in_html = self.in_table = self.in_li = False
309 self.in_header = True
310 self.list_indents = []
321 "^^": ["sup", False],
325 def _b_repl(self, word):
326 style = self.styles[word]
327 style[1] = not style[1]
328 return ['</', '<'][style[1]] + style[0] + '>'
330 def _tit_repl(self, word):
332 result = '</h%d><p>\n' % self.h_level
335 self.h_level = len(word) - 1
336 link = permalink(self.line)
337 result = '\n</p><h%d id="%s"><a class="heading" href="#%s">¶</a> ' % (self.h_level, link, link)
340 def _br_repl(self, word):
343 def _rule_repl(self, word):
344 return self._undent() + '\n<hr size="%d" noshade="noshade" />\n' % (len(word) - 2)
346 def _word_repl(self, word):
347 return Page(word).link_to()
349 def _img_repl(self, word):
350 path = relative_url(word)
351 return '<a href="%s"><img border="0" src="%s" /></a>' % (path, path)
353 def _url_repl(self, word):
354 if img_re.match(word):
355 return '<a href="%s"><img border="0" src="%s" /></a>' % (word, word)
357 return '<a href="%s" rel="nofollow" class="external">%s</a>' % (word, word)
359 def _macro_repl(self, word):
360 m = re.compile("\<\<([^\s\|\>]+)(?:\s*\|\s*([^\>]+)|)\>\>").match(word)
364 argv.extend(m.group(2).split('|'))
365 argv = map(str.strip, argv)
367 macro = globals().get('_macro_' + name)
369 execfile("macros/" + name + ".py", globals())
370 macro = globals().get('_macro_' + name)
374 return '<strong class="error"><<' + '|'.join(argv) + '>></strong>'
376 def _hurl_repl(self, word):
377 m = link_re.match(word)
382 elif img_re.match(m.group(2)):
383 descr = '<img border="0" src="' + descr + '" />'
385 return link_tag(name, descr, 'wikilink')
387 def _inl_repl(self, word):
388 m = link_re.match(word)
390 descr = m.group(2) or name
391 name = relative_url(name)
392 argv = descr.split('|')
396 args = '?' + '&'.join(argv)
401 # The "extthumb" nonsense works around a limitation of the HTML block model
402 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>' \
403 % (name, name + args, descr, descr)
405 return '<a href="%s"><img border="0" src="%s" /></a>' % (name, name + args)
407 def _email_repl(self, word):
408 return '<a href="mailto:%s">%s</a>' % (word, word)
410 def _html_repl(self, word):
412 return word; # Pass through
414 def _ent_repl(self, s):
415 if self.in_html and s == '>':
418 return {'&': '&',
422 def _li_repl(self, match):
429 def _pre_repl(self, word):
430 if word == '{{{' and not self.in_pre:
438 def _hi_repl(self, word):
439 return '<strong class="highlight ' + word + '">' + word + '</strong>'
441 def _tr_repl(self, word):
443 if not self.in_table:
446 out = '</p><table><tbody>\n'
448 out = out + '<tr class="' + ['even', 'odd'][self.tr_cnt % 2] + '">'
449 return out + ['<td>', '<th>'][word.strip() == '||=']
451 def _td_repl(self, word):
453 return ['</td><td>', '</th><th>'][word.strip() == '||=']
456 def _tre_repl(self, word):
458 return ['</td></tr>', '</th></tr>'][word.strip() == '||=']
461 def _indent_level(self):
462 return len(self.list_indents) and self.list_indents[-1]
464 def _indent_to(self, new_level):
465 if self._indent_level() == new_level:
468 while self._indent_level() > new_level:
469 del(self.list_indents[-1])
472 self.in_li = False # FIXME
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 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 referrer)
500 scan_re = re.compile(
503 + r"(?P<b>\*\*|'''|//|''|##|``|__|\^\^|,,)"
504 + r"|(?P<tit>\={2,6})"
506 + r"|(?P<rule>^-{3,})"
507 + r"|(?P<hi>\b(FIXME|TODO|DONE)\b)"
510 + r"|(?P<macro>\<\<([^\s\|\>]+)(?:\s*\|\s*([^\>]+)|)\>\>)"
511 + r"|(?P<hurl>\[\[([^\s\|]+)(?:\s*\|\s*([^\]]+)|)\]\])"
514 + r"|(?P<html><(/|)(br|hr|div|form|iframe|input|span))"
517 # Auto links (LEGACY)
518 + r"|(?P<img>\b[a-zA-Z0-9_/-]+\.(png|gif|jpg|jpeg|bmp|ico))"
519 + r"|(?P<word>\b(?:[A-Z][a-z]+){2,}\b)"
520 + r"|(?P<url>(http|https|ftp|mailto)\:[^\s'\"]+\S)"
521 + r"|(?P<email>[-\w._+]+\@[\w.-]+)"
524 + r"|(?P<li>^\s+[\*#] +)"
525 + r"|(?P<pre>\{\{\{|\s*\}\}\})"
526 + r"|(?P<inl>\{\{([^\s\|]+)(?:\s*\|\s*([^\]]+)|)\}\})"
529 + r"|(?P<tr>^\s*\|\|(=|)\s*)"
530 + r"|(?P<tre>\s*\|\|(=|)\s*$)"
531 + r"|(?P<td>\s*\|\|(=|)\s*)"
535 + r"(?P<pre>\s*\}\}\})"
538 blank_re = re.compile(r"^\s*$")
539 indent_re = re.compile(r"^\s*")
540 tr_re = re.compile(r"^\s*\|\|")
541 eol_re = re.compile(r"\r?\n")
542 for self.line in eol_re.split(self.raw.expandtabs()):
545 if self.line.startswith('#'):
547 self.in_header = False
550 print re.sub(pre_re, self.replace, self.line)
552 if self.in_table and not tr_re.match(self.line):
553 self.in_table = False
554 print '</tbody></table><p>'
556 if blank_re.match(self.line):
559 indent = indent_re.match(self.line)
560 print self._indent_to(len(indent.group(0)))
561 print re.sub(scan_re, self.replace, self.line)
563 if self.in_pre: print '</pre>'
564 if self.in_table: print '</tbody></table><p>'
569 def __init__(self, page_name):
570 self.page_name = page_name
572 self.msg_type = 'error'
574 def split_title(self):
575 # look for the end of words and the start of a new word and insert a space there
576 return re.sub('([a-z])([A-Z])', r'\1 \2', self.page_name)
579 return path.join(data_dir, self.page_name)
581 def _tmp_filename(self):
582 return path.join(data_dir, ('#' + self.page_name.replace('/','_') + '.' + `os.getpid()` + '#'))
586 os.stat(self._filename())
589 if er.errno == errno.ENOENT:
594 word = self.page_name
596 return link_tag(word, word, 'wikilink')
598 return link_tag(word, nonexist_pfx + word, 'nonexistent')
600 def get_raw_body(self):
602 return open(self._filename(), 'rb').read()
604 if er.errno == errno.ENOENT:
605 return '' # just doesn't exist, use default
606 if er.errno == errno.EISDIR:
607 return self.format_dir()
610 def format_dir(self):
613 for dir in self.page_name.split('/'):
614 path = (path + '/' + dir) if path else dir
615 out += '[[' + path + '|' + dir + ']]/'
618 for file in page_list(self._filename(), file_re):
619 if img_re.match(file):
621 maxwidth_arg = '|maxwidth=' + str(image_maxwidth)
622 out += '{{' + self.page_name + '/' + file + '|' + file + maxwidth_arg + '}}\n'
624 out += ' * [[' + self.page_name + '/' + file + ']]\n'
627 if 'attrs' in self.__dict__:
631 file = open(self._filename(), 'rt')
632 attr_re = re.compile(r"^#(\S*)(.*)$")
634 m = attr_re.match(line)
637 self.attrs[m.group(1)] = m.group(2).strip()
638 #print "bernie: attrs[" + m.group(1) + "] = " + m.group(2) + "<br>\n"
640 if er.errno != errno.ENOENT and er.errno != errno.EISDIR:
644 def get_attr(self, name, default):
645 return self.get_attrs().get(name, default)
647 def can(self, action, default=True):
650 #acl SomeUser:read,write All:read
651 acl = self.get_attr("acl", None)
652 for rule in acl.split():
653 (user, perms) = rule.split(':')
654 if user == remote_user() or user == "All":
655 return action in perms.split(',')
657 except Exception, er:
659 self.msg_text = 'Illegal acl line: ' + acl
663 return self.can("write", True)
666 return self.can("read", True)
668 def send_naked(self):
670 WikiFormatter(self.get_raw_body()).print_html()
672 send_guru("Read access denied by ACLs", "notice")
676 value = self.get_attr("css", None)
679 link_urls += [ [ "stylesheet", value ] ]
681 send_title(self.page_name, self.split_title(),
682 msg_text=self.msg_text, msg_type=self.msg_type, writable=self.can_write())
684 send_footer(self.page_name, self._last_modified())
686 def _last_modified(self):
688 from time import localtime, strftime
689 modtime = localtime(os.stat(self._filename())[stat.ST_MTIME])
691 if er.errno != errno.ENOENT:
694 return strftime(datetime_fmt, modtime)
696 def send_editor(self, preview=None):
697 send_title(None, 'Edit ' + self.split_title(), msg_text=self.msg_text, msg_type=self.msg_type)
698 if not self.can_write():
699 send_guru("Write access denied by ACLs", "error")
704 file = form['file'].value
706 print ('<p><b>Editing ' + self.page_name
707 + ' for ' + cgi.escape(remote_user())
708 + ' from ' + cgi.escape(get_hostname(remote_host()))
710 print '<div class="editor"><form name="editform" method="post" enctype="multipart/form-data" action="%s">' % relative_url(self.page_name)
711 print '<input type="hidden" name="edit" value="%s">' % (self.page_name)
712 print '<input type="input" id="editor" name="changelog" value="Edit page %s" accesskey="c" /><br />' % (self.page_name)
713 print '<textarea wrap="off" spellcheck="true" id="editor" name="savetext" rows="17" cols="100" accesskey="e">%s</textarea>' % (preview or self.get_raw_body())
714 print '<label for="file" accesskey="u">Or Upload a file:</label> <input type="file" name="file" value="%s" />' % file
717 <input type="submit" name="save" value="Save" accesskey="s">
718 <input type="submit" name="preview" value="Preview" accesskey="p" />
719 <input type="reset" value="Reset" />
720 <input type="submit" name="cancel" value="Cancel" />
723 <script language="javascript">
725 document.editform.savetext.focus()
729 print "<p>" + Page('EditingTips').link_to() + "</p>"
731 print "<div class='preview'>"
732 WikiFormatter(preview).print_html()
734 send_footer(self.page_name)
736 def send_raw(self, mimetype='text/plain'):
738 body = self.get_raw_body()
739 emit_header(mimetype)
742 send_title(None, msg_text='Read access denied by ACLs', msg_type='notice')
744 def send_image(self, mimetype, args=[]):
745 if 'maxwidth' in args:
747 emit_header(mimetype)
749 subprocess.check_call(['gm', 'convert', self._filename(),
750 '-scale', args['maxwidth'].value + ' >', '-'])
752 self.send_raw(mimetype)
754 def _write_file(self, data):
755 tmp_filename = self._tmp_filename()
756 open(tmp_filename, 'wb').write(data)
757 name = self._filename()
759 # Bad Bill! POSIX rename ought to replace. :-(
763 if er.errno != errno.ENOENT: raise er
764 os.rename(tmp_filename, name)
766 def save(self, newdata, changelog):
767 if not self.can_write():
768 self.msg_text = 'Write access denied by ACLs'
769 self.msg_type = 'error'
772 self._write_file(newdata)
775 # FIXME: what's the std way to perform shell quoting in python?
776 cmd = ( post_edit_hook
777 + " '" + data_dir + '/' + self.page_name
778 + "' '" + remote_user()
779 + "' '" + remote_host()
780 + "' '" + changelog + "'"
786 self.msg_text += "Post-editing hook returned %d.\n" % rc
787 self.msg_text += 'Command was: ' + cmd + '\n'
789 self.msg_text += 'Output follows:\n' + output
791 self.msg_text = 'Thank you for your contribution. Your attention to detail is appreciated.'
792 self.msg_type = 'success'
794 # Main ---------------------------------------------------------------
796 execfile("geekigeeki.conf.py")
797 form = cgi.FieldStorage()
800 handler = globals().get('handle_' + cmd)
802 handler(form[cmd].value)
805 path_info = environ.get('PATH_INFO', '')
806 if len(path_info) and path_info[0] == '/':
807 query = path_info[1:] or 'FrontPage'
809 query = environ.get('QUERY_STRING', '') or 'FrontPage'
811 if file_re.match(query):
812 if word_re.match(query):
815 from mimetypes import MimeTypes
816 type, encoding = MimeTypes().guess_type(query)
817 #type = type or 'text/plain'
818 #Page(query).send_raw(mimetype=type)
820 if type.startswith('image/'):
821 Page(query).send_image(mimetype=type,args=form)
823 Page(query).send_raw(mimetype=type)
827 send_httperror("403 Forbidden", query)
830 msg_text = traceback.format_exc()
832 send_guru(msg_text, "error")
834 send_title(None, msg_text=msg_text)