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
28 # Regular expression defining a WikiWord
29 # (but this definition is also assumed in other places)
30 word_re = re.compile(r"^\b((([A-Z][a-z0-9]+){2,}/)*([A-Z][a-z0-9]+){2,})\b$")
31 # FIXME: we accept stuff like foo/../bar and we shouldn't
32 file_re = re.compile(r"^\b([A-Za-z0-9_\-][A-Za-z0-9_\.\-/]*)\b$")
33 img_re = re.compile(r"^.*\.(png|gif|jpg|jpeg|bmp|ico|ogm|ogg|mkv|mpg|mpeg|mp4|avi|asf|flv|wmv|qt)$", re.IGNORECASE)
34 video_re = re.compile(r"^.*\.(ogm|ogg|mkv|mpg|mpeg|mp4|avi|asf|flv|wmv|qt)$", 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 os.environ.get('SCRIPT_NAME', '')
46 def privileged_path():
47 return privileged_url or script_name()
50 user = os.environ.get('REMOTE_USER', '')
51 if user is None or user == '' or user == 'anonymous':
52 user = 'AnonymousCoward'
56 return os.environ.get('REMOTE_ADDR', '')
58 def get_hostname(addr):
60 from socket import gethostbyaddr
61 return gethostbyaddr(addr)[0] + ' (' + addr + ')'
65 def is_external_url(pathname):
66 return (url_re.match(pathname) or pathname.startswith('/'))
68 def relative_url(pathname, privileged=False):
69 if not is_external_url(pathname):
71 url = privileged_path()
74 pathname = url + '/' + pathname
78 return re.sub(' ', '-', re.sub('[^a-z0-9_ ]', '', s.lower()).strip())
80 # Formatting stuff --------------------------------------------------
81 def emit_header(mime_type="text/html"):
82 print "Content-type: " + mime_type + "; charset=utf-8\n"
84 def sendfile(dest_file, src_file):
85 """Efficiently copy file data between file descriptors"""
87 data = src_file.read(65536)
91 def send_guru(msg_text, msg_type):
92 if not msg_text: return
93 print '<pre id="guru" onclick="this.style.display = \'none\'" class="' + msg_type + '">'
94 if msg_type == 'error':
95 print ' Software Failure. Press left mouse button to continue.\n'
97 if msg_type == 'error':
98 print '\n Guru Meditation #DEADBEEF.ABADC0DE'
101 sendfile(sys.stdout, open('gurumeditation.js', 'rb'))
105 def send_title(name, text="Limbo", msg_text=None, msg_type='error', writable=False):
107 if title_done: return
111 print '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"'
112 print ' "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">'
113 print '<html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en">'
115 print "<head><title>%s: %s</title>" % (site_name, text)
116 print ' <meta http-equiv="Content-Type" content="application/xhtml+xml; charset=utf-8" />'
118 print ' <meta name="robots" content="noindex,nofollow" />'
120 for meta in meta_urls:
121 http_equiv, content = meta
122 print ' <meta http-equiv="%s" content="%s" />' % (http_equiv, relative_url(content))
124 for link in link_urls:
126 print ' <link rel="%s" href="%s" />' % (rel, relative_url(href))
128 if name and writable and privileged_url is not None:
129 print ' <link rel="alternate" type="application/x-wiki" title="Edit this page" href="%s" />' \
130 % (privileged_path() + '?edit=' + name)
132 if history_url is not None:
133 print ' <link rel="alternate" type="application/rss+xml" title="RSS" href="%s" />' \
134 % relative_url(history_url + '?a=rss')
139 if name and writable and privileged_url is not None:
140 print '<body ondblclick="location.href=\'' + privileged_path() + '?edit=' + name + '\'">'
145 send_guru(msg_text, msg_type)
148 print '<div class="nav">'
150 print ' <b>' + link_tag('?fullsearch=' + name, text, 'navlink') + '</b> '
152 print ' <b>' + text + '</b> '
153 print ' | ' + link_tag('FrontPage', 'Home', 'navlink')
154 print ' | ' + link_tag('FindPage', 'Find Page', 'navlink')
155 if 'history_url' in globals():
156 print ' | <a href="' + relative_url(history_url) + '" class="navlink">Recent Changes</a>'
158 print ' | <a href="' + relative_url(history_url + '?a=history;f=' + name) + '" class="navlink">Page History</a>'
161 print ' | ' + link_tag('?raw=' + name, 'Raw Text', 'navlink')
162 if privileged_url is not None:
164 print ' | ' + link_tag('?edit=' + name, 'Edit', 'navlink', privileged=True)
166 print ' | ' + link_tag(name, 'Login', 'navlink', privileged=True)
169 print ' | <i>Immutable Page</i>'
172 if user != 'AnonymousCoward':
173 print ' | <span class="login"><i>logged in as <b>' + cgi.escape(user) + '</b></i></span>'
177 def send_httperror(status="403 Not Found", query=""):
178 print "Status: %s" % status
179 send_title(None, msg_text=("%s: on query '%s'" % (status, query)))
182 def link_tag(params, text=None, link_class=None, privileged=False):
184 text = params # default
185 elif img_re.match(text):
186 text = '<img border="0" src="' + text + '" />'
189 if is_external_url(params):
190 link_class = 'external'
191 elif file_re.match(params) and Page(params).exists():
192 link_class = 'wikilink'
194 params = nonexist_pfx + params
195 link_class = 'nonexistent'
197 classattr = 'class="%s" ' % link_class
198 # Prevent crawlers from following links potentially added by spammers or to generated pages
199 if link_class == 'external' or link_class == 'navlink':
200 classattr += 'rel="nofollow"'
202 return '<a %shref="%s">%s</a>' % (classattr, relative_url(params, privileged=privileged), text)
204 # Search ---------------------------------------------------
206 def handle_fullsearch(needle):
207 send_title(None, 'Full text search for "%s"' % (needle))
209 needle_re = re.compile(needle, re.IGNORECASE)
211 all_pages = page_list()
212 for page_name in all_pages:
213 body = Page(page_name).get_raw_body()
214 count = len(needle_re.findall(body))
216 hits.append((count, page_name))
218 # The default comparison for tuples compares elements in order,
219 # so this sorts by number of hits
224 for (count, page_name) in hits:
225 print '<li><p>' + link_tag(page_name)
226 print ' . . . . ' + `count`
227 print ['match', 'matches'][count != 1]
231 print_search_stats(len(hits), len(all_pages))
233 def handle_titlesearch(needle):
234 # TODO: check needle is legal -- but probably we can just accept any RE
235 send_title(None, "Title search for \"" + needle + '"')
237 needle_re = re.compile(needle, re.IGNORECASE)
238 all_pages = page_list()
239 hits = filter(needle_re.search, all_pages)
242 for filename in hits:
243 print '<li><p>' + link_tag(filename) + "</p></li>"
246 print_search_stats(len(hits), len(all_pages))
248 def print_search_stats(hits, searched):
249 print "<p>%d hits out of %d pages searched.</p>" % (hits, searched)
251 def handle_raw(pagename):
252 if not file_re.match(pagename):
253 send_httperror("403 Forbidden", pagename)
256 Page(pagename).send_raw()
258 def handle_edit(pagename):
259 if not file_re.match(pagename):
260 send_httperror("403 Forbidden", pagename)
265 if form['file'].value:
266 pg.save(form['file'].file.read(), form['changelog'].value)
268 pg.save(form['savetext'].value.replace('\r\n', '\n'), form['changelog'].value)
270 elif 'cancel' in form:
271 pg.msg_text = 'Editing canceled'
272 pg.msg_type = 'notice'
274 else: # preview or edit
276 if 'preview' in form:
277 text = form['savetext'].value
280 def make_index_key():
281 links = map(lambda ch: '<a href="#%s">%s</a>' % (ch, ch), 'abcdefghijklmnopqrstuvwxyz')
282 return '<p><center>'+ ' | '.join(links) + '</center></p>'
284 def page_list(dirname = None, re = word_re):
285 return sorted(filter(re.match, os.listdir(dirname or data_dir)))
287 def send_footer(mod_string=None):
288 if globals().get('debug_cgi', False):
289 cgi.print_arguments()
293 <div id="footer"><hr />
294 <p class="copyright">
295 <a rel="license" href="http://creativecommons.org/licenses/by-sa/3.0/"><img class="license" alt="Creative Commons License" src="%s" /></a>
296 <span class="benchmark">generated in %0.3fs</span> by <a href="http://www.codewiz.org/wiki/GeekiGeeki">GeekiGeeki</a> version %s
298 ''' % (relative_url('cc-by-sa.png'), clock() - start_time, __version__)
300 print '<p class="modified">last modified %s</p>' % mod_string
301 print '</div></body></html>'
304 """Object that turns Wiki markup into HTML.
306 All formatting commands can be parsed one line at a time, though
307 some state is carried over between lines.
309 def __init__(self, raw):
312 self.in_pre = self.in_html = self.in_table = self.in_li = False
313 self.in_header = True
314 self.list_indents = []
325 "^^": ["sup", False],
329 def _b_repl(self, word):
330 style = self.styles[word]
331 style[1] = not style[1]
332 return ['</', '<'][style[1]] + style[0] + '>'
334 def _tit_repl(self, word):
336 result = '</h%d><p>\n' % self.h_level
339 self.h_level = len(word) - 1
340 link = permalink(self.line)
341 result = '\n</p><h%d id="%s"><a class="heading" href="#%s">¶</a> ' % (self.h_level, link, link)
344 def _br_repl(self, word):
347 def _rule_repl(self, word):
348 return self._undent() + '\n<hr size="%d" noshade="noshade" />\n' % (len(word) - 2)
350 def _macro_repl(self, word):
351 m = re.compile("\<\<([^\s\|\>]+)(?:\s*\|\s*([^\>]+)|)\>\>").match(word)
355 argv.extend(m.group(2).split('|'))
356 argv = map(str.strip, argv)
358 macro = globals().get('_macro_' + name)
361 execfile("macros/" + name + ".py", globals())
363 if err.errno == errno.ENOENT: pass
364 macro = globals().get('_macro_' + name)
368 return '<strong class="error"><<' + '|'.join(argv) + '>></strong>'
370 def _hurl_repl(self, word):
371 m = link_re.match(word)
372 return link_tag(m.group(1), m.group(2))
374 def _url_repl(self, word):
375 return link_tag(word)
377 def _word_repl(self, word):
378 return link_tag(word)
380 def _inl_repl(self, word):
381 m = link_re.match(word)
382 name = relative_url(m.group(1))
386 argv = descr.split('|')
390 args = '?' + '&'.join(argv)
392 # The "extthumb" nonsense works around a limitation of the HTML block model
393 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>' \
394 % (name, name + args, descr, descr)
395 elif video_re.match(name):
396 return '<video src="%s">Your browser does not support the HTML5 video tag</video>' % name
398 return '<a href="%s"><img border="0" src="%s" /></a>' % (name, name)
400 def _img_repl(self, word):
401 return self._inl_repl('{{' + word + '}}')
403 def _email_repl(self, word):
404 return '<a href="mailto:%s">%s</a>' % (word, word)
406 def _html_repl(self, word):
408 return word; # Pass through
410 def _ent_repl(self, s):
411 if self.in_html and s == '>':
414 return {'&': '&',
418 def _li_repl(self, match):
425 def _pre_repl(self, word):
426 if word == '{{{' and not self.in_pre:
434 def _hi_repl(self, word):
435 return '<strong class="highlight ' + word + '">' + word + '</strong>'
437 def _tr_repl(self, word):
439 if not self.in_table:
442 out = '</p><table><tbody>\n'
444 out = out + '<tr class="' + ['even', 'odd'][self.tr_cnt % 2] + '">'
445 return out + ['<td>', '<th>'][word.strip() == '||=']
447 def _td_repl(self, word):
449 return ['</td><td>', '</th><th>'][word.strip() == '||=']
452 def _tre_repl(self, word):
454 return ['</td></tr>', '</th></tr>'][word.strip() == '||=']
457 def _indent_level(self):
458 return len(self.list_indents) and self.list_indents[-1]
460 def _indent_to(self, new_level):
461 if self._indent_level() == new_level:
464 while self._indent_level() > new_level:
465 del(self.list_indents[-1])
468 self.in_li = False # FIXME
470 while self._indent_level() < new_level:
471 self.list_indents.append(new_level)
478 res += '</ul>' * len(self.list_indents)
480 self.list_indents = []
483 def replace(self, match):
484 for rule, hit in match.groupdict().items():
486 return getattr(self, '_' + rule + '_repl')(hit)
488 raise "Can't handle match " + repr(match)
490 def print_html(self):
491 print '<div class="wiki"><p>'
493 # For each line, we scan through looking for magic
494 # strings, outputting verbatim any intervening text
495 # TODO: highlight search words (look at referrer)
496 scan_re = re.compile(
499 + r"(?P<b>\*\*|'''|//|''|##|``|__|\^\^|,,)"
500 + r"|(?P<tit>\={2,6})"
502 + r"|(?P<rule>^-{3,})"
503 + r"|(?P<hi>\b(FIXME|TODO|DONE)\b)"
506 + r"|(?P<macro>\<\<([^\s\|\>]+)(?:\s*\|\s*([^\>]+)|)\>\>)"
507 + r"|(?P<hurl>\[\[([^\s\|]+)(?:\s*\|\s*([^\]]+)|)\]\])"
510 + r"|(?P<html><(/|)(br|hr|div|span|form|iframe|input|textarea|a|img|h[1-5])[^>]*>)"
513 # Auto links (LEGACY)
514 + r"|(?P<img>\b[a-zA-Z0-9_/-]+\.(png|gif|jpg|jpeg|bmp|ico|ogm|ogg|mkv|mpg|mpeg|mp4|avi|asf|flv|wmv|qt))"
515 + r"|(?P<word>\b(?:[A-Z][a-z]+){2,}\b)"
516 + r"|(?P<url>(http|https|ftp|mailto)\:[^\s'\"]+\S)"
517 + r"|(?P<email>[-\w._+]+\@[\w.-]+)"
520 + r"|(?P<li>^\s+[\*#] +)"
521 + r"|(?P<pre>\{\{\{|\s*\}\}\})"
522 + r"|(?P<inl>\{\{([^\s\|]+)(?:\s*\|\s*([^\]]+)|)\}\})"
525 + r"|(?P<tr>^\s*\|\|(=|)\s*)"
526 + r"|(?P<tre>\s*\|\|(=|)\s*$)"
527 + r"|(?P<td>\s*\|\|(=|)\s*)"
531 + r"(?P<pre>\s*\}\}\})"
534 blank_re = re.compile(r"^\s*$")
535 indent_re = re.compile(r"^\s*")
536 tr_re = re.compile(r"^\s*\|\|")
537 eol_re = re.compile(r"\r?\n")
538 for self.line in eol_re.split(self.raw.expandtabs()):
541 if self.line.startswith('#'):
543 self.in_header = False
546 print re.sub(pre_re, self.replace, self.line)
548 if self.in_table and not tr_re.match(self.line):
549 self.in_table = False
550 print '</tbody></table><p>'
552 if blank_re.match(self.line):
555 indent = indent_re.match(self.line)
556 print self._indent_to(len(indent.group(0))) ,
557 print re.sub(scan_re, self.replace, self.line)
559 if self.in_pre: print '</pre>'
560 if self.in_table: print '</tbody></table><p>'
565 def __init__(self, page_name):
566 self.page_name = page_name
568 self.msg_type = 'error'
570 def split_title(self):
571 # look for the end of words and the start of a new word and insert a space there
572 return re.sub('([a-z])([A-Z])', r'\1 \2', self.page_name)
575 return os.path.join(data_dir, self.page_name)
577 def _tmp_filename(self):
578 return os.path.join(data_dir, ('#' + self.page_name.replace('/','_') + '.' + `os.getpid()` + '#'))
582 os.stat(self._filename())
585 if err.errno == errno.ENOENT:
589 def get_raw_body(self):
591 return open(self._filename(), 'rb').read()
593 if err.errno == errno.ENOENT:
594 return '' # just doesn't exist, use default
595 if err.errno == errno.EISDIR:
596 return self.format_dir()
599 def format_dir(self):
602 for dirname in self.page_name.split('/'):
603 pathname = (pathname + '/' + dirname) if pathname else dirname
604 out += '[[' + pathname + '|' + dirname + ']]/'
607 for filename in page_list(self._filename(), file_re):
608 if img_re.match(filename):
610 maxwidth_arg = '|maxwidth=' + str(image_maxwidth)
611 out += '{{' + self.page_name + '/' + filename + '|' + filename + maxwidth_arg + '}}\n'
613 out += ' * [[' + self.page_name + '/' + filename + ']]\n'
617 if not '_pragmas' in self.__dict__:
620 f = open(self._filename(), 'rt')
621 attr_re = re.compile(r"^#(\S*)(.*)$")
623 m = attr_re.match(line)
626 self._pragmas[m.group(1)] = m.group(2).strip()
627 #print "bernie: _pragmas[" + m.group(1) + "] = " + m.group(2) + "<br>\n"
629 if err.errno != errno.ENOENT and err.errno != errno.EISDIR:
633 def pragma(self, name, default):
634 return self.pragmas().get(name, default)
636 def can(self, action, default=True):
639 #acl SomeUser:read,write All:read
640 acl = self.pragma("acl", None)
641 for rule in acl.split():
642 (user, perms) = rule.split(':')
643 if user == remote_user() or user == "All":
644 return action in perms.split(',')
648 self.msg_text = 'Illegal acl line: ' + acl
652 return self.can("write", True)
655 return self.can("read", True)
657 def send_naked(self):
659 WikiFormatter(self.get_raw_body()).print_html()
661 send_guru("Read access denied by ACLs", "notice")
665 value = self.pragma("css", None)
668 link_urls += [ [ "stylesheet", value ] ]
670 send_title(self.page_name, self.split_title(),
671 msg_text=self.msg_text, msg_type=self.msg_type, writable=self.can_write())
673 send_footer(self._last_modified())
675 def _last_modified(self):
677 from time import localtime, strftime
678 modtime = localtime(os.stat(self._filename())[stat.ST_MTIME])
680 if err.errno != errno.ENOENT:
683 return strftime(datetime_fmt, modtime)
685 def send_editor(self, preview=None):
686 send_title(None, 'Edit ' + self.split_title(), msg_text=self.msg_text, msg_type=self.msg_type)
687 if not self.can_write():
688 send_guru("Write access denied by ACLs", "error")
693 filename = form['file'].value
695 print ('<p><b>Editing ' + self.page_name
696 + ' for ' + cgi.escape(remote_user())
697 + ' from ' + cgi.escape(get_hostname(remote_host()))
699 print '<div class="editor"><form name="editform" method="post" enctype="multipart/form-data" action="%s">' % relative_url(self.page_name)
700 print '<input type="hidden" name="edit" value="%s">' % (self.page_name)
701 print '<input type="input" id="editor" name="changelog" value="Edit page %s" accesskey="c" /><br />' % (self.page_name)
702 print '<textarea wrap="off" spellcheck="true" id="editor" name="savetext" rows="17" cols="100" accesskey="e">%s</textarea>' % cgi.escape(preview or self.get_raw_body())
703 print '<label for="file" accesskey="u">Or Upload a file:</label> <input type="file" name="file" value="%s" />' % filename
706 <input type="submit" name="save" value="Save" accesskey="s">
707 <input type="submit" name="preview" value="Preview" accesskey="p" />
708 <input type="reset" value="Reset" />
709 <input type="submit" name="cancel" value="Cancel" />
712 <script language="javascript">
714 document.editform.savetext.focus()
718 print "<p>" + link_tag('EditingTips') + "</p>"
720 print "<div class='preview'>"
721 WikiFormatter(preview).print_html()
725 def send_raw(self, mimetype='text/plain'):
727 body = self.get_raw_body()
728 emit_header(mimetype)
731 send_title(None, msg_text='Read access denied by ACLs', msg_type='notice')
733 def send_image(self, mimetype, args=[]):
734 if 'maxwidth' in args:
736 emit_header(mimetype)
738 subprocess.check_call(['gm', 'convert', self._filename(),
739 '-scale', args['maxwidth'].value + ' >', '-'])
741 self.send_raw(mimetype)
743 def _write_file(self, data):
744 tmp_filename = self._tmp_filename()
745 open(tmp_filename, 'wb').write(data)
746 name = self._filename()
748 # Bad Bill! POSIX rename ought to replace. :-(
752 if err.errno != errno.ENOENT: raise err
753 os.rename(tmp_filename, name)
755 def save(self, newdata, changelog):
756 if not self.can_write():
757 self.msg_text = 'Write access denied by ACLs'
758 self.msg_type = 'error'
761 self._write_file(newdata)
764 # FIXME: what's the std way to perform shell quoting in python?
765 cmd = ( post_edit_hook
766 + " '" + data_dir + '/' + self.page_name
767 + "' '" + remote_user()
768 + "' '" + remote_host()
769 + "' '" + changelog + "'"
775 self.msg_text += "Post-editing hook returned %d.\n" % rc
776 self.msg_text += 'Command was: ' + cmd + '\n'
778 self.msg_text += 'Output follows:\n' + output
780 self.msg_text = 'Thank you for your contribution. Your attention to detail is appreciated.'
781 self.msg_type = 'success'
785 handler = globals().get('handle_' + cmd)
787 handler(form[cmd].value)
790 path_info = os.environ.get('PATH_INFO', '')
791 if len(path_info) and path_info[0] == '/':
792 query = path_info[1:] or 'FrontPage'
794 query = os.environ.get('QUERY_STRING', '') or 'FrontPage'
796 if file_re.match(query):
797 if word_re.match(query):
800 from mimetypes import MimeTypes
801 mimetype, encoding = MimeTypes().guess_type(query)
803 if mimetype.startswith('image/'):
804 Page(query).send_image(mimetype=mimetype, args=form)
806 Page(query).send_raw(mimetype=mimetype)
810 send_httperror("403 Forbidden", query)
813 execfile("geekigeeki.conf.py")
814 form = cgi.FieldStorage()
818 msg_text = traceback.format_exc()
820 send_guru(msg_text, "error")
822 send_title(None, msg_text=msg_text)