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*([^\]]+)|)(?:\]\]|}})")
40 # CGI stuff ---------------------------------------------------------
42 return os.environ.get('SCRIPT_NAME', '')
45 path_info = os.environ.get('PATH_INFO', '')
46 if len(path_info) and path_info[0] == '/':
47 return path_info[1:] or 'FrontPage'
49 return os.environ.get('QUERY_STRING', '') or 'FrontPage'
51 def privileged_path():
52 return privileged_url or script_name()
55 user = os.environ.get('REMOTE_USER', '')
56 if user is None or user == '' or user == 'anonymous':
57 user = 'AnonymousCoward'
61 return os.environ.get('REMOTE_ADDR', '')
63 def get_hostname(addr):
65 from socket import gethostbyaddr
66 return gethostbyaddr(addr)[0] + ' (' + addr + ')'
70 def is_external_url(pathname):
71 return (url_re.match(pathname) or pathname.startswith('/'))
73 def relative_url(pathname, privileged=False):
74 if not is_external_url(pathname):
76 url = privileged_path()
79 pathname = url + '/' + pathname
83 return re.sub(' ', '-', re.sub('[^a-z0-9_ ]', '', s.lower()).strip())
85 # Formatting stuff --------------------------------------------------
86 def emit_header(mime_type="text/html"):
87 print "Content-type: " + mime_type + "; charset=utf-8\n"
89 def sendfile(dest_file, src_file):
90 """Efficiently copy file data between file descriptors"""
92 data = src_file.read(65536)
96 def send_guru(msg_text, msg_type):
97 if not msg_text: return
98 print '<pre id="guru" onclick="this.style.display = \'none\'" class="' + msg_type + '">'
99 if msg_type == 'error':
100 print ' Software Failure. Press left mouse button to continue.\n'
102 if msg_type == 'error':
103 print '\n Guru Meditation #DEADBEEF.ABADC0DE'
106 sendfile(sys.stdout, open('gurumeditation.js', 'rb'))
110 def send_title(name, text="Limbo", msg_text=None, msg_type='error', writable=False):
112 if title_done: return
116 print '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"'
117 print ' "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">'
118 print '<html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en">'
120 print "<head><title>%s: %s</title>" % (site_name, text)
121 print ' <meta http-equiv="Content-Type" content="application/xhtml+xml; charset=utf-8" />'
123 print ' <meta name="robots" content="noindex,nofollow" />'
125 for meta in meta_urls:
126 http_equiv, content = meta
127 print ' <meta http-equiv="%s" content="%s" />' % (http_equiv, relative_url(content))
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, link_class=None, privileged=False):
189 text = params # default
190 elif img_re.match(text):
191 text = '<img border="0" src="' + text + '" />'
194 if is_external_url(params):
195 link_class = 'external'
196 elif file_re.match(params) and Page(params).exists():
197 link_class = 'wikilink'
199 params = nonexist_pfx + params
200 link_class = 'nonexistent'
202 classattr = 'class="%s" ' % link_class
203 # Prevent crawlers from following links potentially added by spammers or to generated pages
204 if link_class == 'external' or link_class == 'navlink':
205 classattr += 'rel="nofollow"'
207 return '<a %shref="%s">%s</a>' % (classattr, relative_url(params, privileged=privileged), text)
209 # Search ---------------------------------------------------
211 def handle_fullsearch(needle):
212 send_title(None, 'Full text search for "%s"' % (needle))
214 needle_re = re.compile(needle, re.IGNORECASE)
216 all_pages = page_list()
217 for page_name in all_pages:
218 body = Page(page_name).get_raw_body()
219 count = len(needle_re.findall(body))
221 hits.append((count, page_name))
223 # The default comparison for tuples compares elements in order,
224 # so this sorts by number of hits
229 for (count, page_name) in hits:
230 print '<li><p>' + link_tag(page_name)
231 print ' . . . . ' + `count`
232 print ['match', 'matches'][count != 1]
236 print_search_stats(len(hits), len(all_pages))
238 def handle_titlesearch(needle):
239 # TODO: check needle is legal -- but probably we can just accept any RE
240 send_title(None, "Title search for \"" + needle + '"')
242 needle_re = re.compile(needle, re.IGNORECASE)
243 all_pages = page_list()
244 hits = filter(needle_re.search, all_pages)
247 for filename in hits:
248 print '<li><p>' + link_tag(filename) + "</p></li>"
251 print_search_stats(len(hits), len(all_pages))
253 def print_search_stats(hits, searched):
254 print "<p>%d hits out of %d pages searched.</p>" % (hits, searched)
256 def handle_raw(pagename):
257 if not file_re.match(pagename):
258 send_httperror("403 Forbidden", pagename)
261 Page(pagename).send_raw()
263 def handle_edit(pagename):
264 if not file_re.match(pagename):
265 send_httperror("403 Forbidden", pagename)
270 if form['file'].value:
271 pg.save(form['file'].file.read(), form['changelog'].value)
273 pg.save(form['savetext'].value.replace('\r\n', '\n'), form['changelog'].value)
275 elif 'cancel' in form:
276 pg.msg_text = 'Editing canceled'
277 pg.msg_type = 'notice'
279 else: # preview or edit
281 if 'preview' in form:
282 text = form['savetext'].value
285 def make_index_key():
286 links = map(lambda ch: '<a href="#%s">%s</a>' % (ch, ch), 'abcdefghijklmnopqrstuvwxyz')
287 return '<p><center>'+ ' | '.join(links) + '</center></p>'
289 def page_list(dirname = None, re = word_re):
290 return sorted(filter(re.match, os.listdir(dirname or data_dir)))
292 def send_footer(mod_string=None):
293 if globals().get('debug_cgi', False):
294 cgi.print_arguments()
298 <div id="footer"><hr />
299 <p class="copyright">
300 <a rel="license" href="http://creativecommons.org/licenses/by-sa/3.0/"><img class="license" alt="Creative Commons License" src="%s" /></a>
301 <span class="benchmark">generated in %0.3fs</span> by <a href="http://www.codewiz.org/wiki/GeekiGeeki">GeekiGeeki</a> version %s
303 ''' % (relative_url('cc-by-sa.png'), clock() - start_time, __version__)
305 print '<p class="modified">last modified %s</p>' % mod_string
306 print '</div></body></html>'
309 """Object that turns Wiki markup into HTML.
311 All formatting commands can be parsed one line at a time, though
312 some state is carried over between lines.
314 def __init__(self, raw):
317 self.in_pre = self.in_html = self.in_table = self.in_li = False
318 self.in_header = True
319 self.list_indents = []
327 "^^": ["sup", False],
328 ",,": ["sub", False],
329 "''": ["em", False], # LEGACY
330 "'''": ["b", False], # LEGACY
331 "``": ["tt", False], # LEGACY
334 def _b_repl(self, word):
335 style = self.styles[word]
336 style[1] = not style[1]
337 return ['</', '<'][style[1]] + style[0] + '>'
339 def _tit_repl(self, word):
341 result = '</h%d><p>\n' % self.h_level
344 self.h_level = len(word) - 1
345 link = permalink(self.line)
346 result = '\n</p><h%d id="%s"><a class="heading" href="#%s">¶</a> ' % (self.h_level, link, link)
349 def _br_repl(self, word):
352 def _rule_repl(self, word):
353 return self._undent() + '\n<hr size="%d" noshade="noshade" />\n' % (len(word) - 2)
355 def _macro_repl(self, word):
356 m = re.compile("\<\<([^\s\|\>]+)(?:\s*\|\s*([^\>]+)|)\>\>").match(word)
360 argv.extend(m.group(2).split('|'))
361 argv = map(str.strip, argv)
363 macro = globals().get('_macro_' + name)
366 execfile("macros/" + name + ".py", globals())
368 if err.errno == errno.ENOENT: pass
369 macro = globals().get('_macro_' + name)
373 msg = '<<' + '|'.join(argv) + '>>'
375 msg = '<strong class="error">' + msg + '</strong>'
378 def _hurl_repl(self, word):
379 m = link_re.match(word)
380 return link_tag(m.group(1), m.group(2))
382 def _inl_repl(self, word):
383 m = link_re.match(word)
384 name = relative_url(m.group(1))
388 argv = descr.split('|')
392 args = '?' + '&'.join(argv)
394 # The "extthumb" nonsense works around a limitation of the HTML block model
395 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>' \
396 % (name, name + args, descr, descr)
397 elif video_re.match(name):
398 return '<video src="%s">Your browser does not support the HTML5 video tag</video>' % name
400 return '<a href="%s"><img border="0" src="%s" /></a>' % (name, name)
402 def _html_repl(self, word):
404 return word; # Pass through
406 def _htmle_repl(self, word):
408 return word; # Pass through
410 def _ent_repl(self, s):
412 return s; # Pass through
413 return {'&': '&',
417 def _img_repl(self, word): # LEGACY
418 return self._inl_repl('{{' + word + '}}')
420 def _word_repl(self, word): # LEGACY
421 if self.in_html: return word # pass through
422 return link_tag(word)
424 def _url_repl(self, word): # LEGACY
425 if self.in_html: return word # pass through
426 return link_tag(word)
428 def _email_repl(self, word): # LEGACY
429 if self.in_html: return word # pass through
430 return '<a href="mailto:%s">%s</a>' % (word, word)
432 def _li_repl(self, match):
439 def _pre_repl(self, word):
440 if word == '{{{' and not self.in_pre:
448 def _hi_repl(self, word):
449 return '<strong class="highlight ' + word + '">' + word + '</strong>'
451 def _tr_repl(self, word):
453 if not self.in_table:
456 out = '</p><table><tbody>\n'
458 out = out + '<tr class="' + ['even', 'odd'][self.tr_cnt % 2] + '">'
459 return out + ['<td>', '<th>'][word.strip() == '||=']
461 def _td_repl(self, word):
463 return ['</td><td>', '</th><th>'][word.strip() == '||=']
466 def _tre_repl(self, word):
468 return ['</td></tr>', '</th></tr>'][word.strip() == '||=']
471 def _indent_level(self):
472 return len(self.list_indents) and self.list_indents[-1]
474 def _indent_to(self, new_level):
475 if self._indent_level() == new_level:
478 while self._indent_level() > new_level:
479 del(self.list_indents[-1])
482 self.in_li = False # FIXME
484 while self._indent_level() < new_level:
485 self.list_indents.append(new_level)
492 res += '</ul>' * len(self.list_indents)
494 self.list_indents = []
497 def replace(self, match):
498 for rule, hit in match.groupdict().items():
500 return getattr(self, '_' + rule + '_repl')(hit)
502 raise "Can't handle match " + repr(match)
504 def print_html(self):
505 print '<div class="wiki"><p>'
507 scan_re = re.compile(r"""(?:
508 # Styles and formatting
509 (?P<b> \*\*|'''|//|''|\#\#|``|__|\^\^|,,)
513 | (?P<hi> \b( FIXME | TODO | DONE )\b )
516 | (?P<macro> \<\<([^\s\|\>]+)(?:\s*\|\s*([^\>]+)|)\>\>)
517 | (?P<hurl> \[\[([^\s\|]+)(?:\s*\|\s*([^\]]+)|)\]\])
520 | (?P<html> <(br|hr|div|span|form|iframe|input|textarea|a|img|h[1-5])\b )
521 | (?P<htmle> ( /\s*> | </(br|hr|div|span|form|iframe|input|textarea|a|img|h[1-5])> ) )
524 # Auto links (LEGACY)
525 | (?P<img> \b[a-zA-Z0-9_/-]+\.(png|gif|jpg|jpeg|bmp|ico|ogm|ogg|mkv|mpg|mpeg|mp4|avi|asf|flv|wmv|qt))
526 | (?P<word> \b(?:[A-Z][a-z]+){2,}\b)
527 | (?P<url> (http|https|ftp|mailto)\:[^\s'\"]+\S)
528 | (?P<email> [-\w._+]+\@[\w.-]+)
531 | (?P<li> ^\s+[\*\#]\s+)
532 | (?P<pre> \{\{\{|\s*\}\}\})
533 | (?P<inl> \{\{([^\s\|]+)(?:\s*\|\s*([^\]]+)|)\}\})
536 | (?P<tr> ^\s*\|\|(=|)\s*)
537 | (?P<tre> \s*\|\|(=|)\s*$)
538 | (?P<td> \s*\|\|(=|)\s*)
540 # TODO: highlight search words (look at referrer)
542 pre_re = re.compile("""(?:
546 blank_re = re.compile(r"^\s*$")
547 indent_re = re.compile(r"^\s*")
548 tr_re = re.compile(r"^\s*\|\|")
549 eol_re = re.compile(r"\r?\n")
551 # For each line, we scan through looking for magic strings, outputting verbatim any intervening text
552 for self.line in eol_re.split(self.raw.expandtabs()):
555 if self.line.startswith('#'):
557 self.in_header = False
560 print re.sub(pre_re, self.replace, self.line)
562 if self.in_table and not tr_re.match(self.line):
563 self.in_table = False
564 print '</tbody></table><p>'
566 if blank_re.match(self.line):
569 indent = indent_re.match(self.line)
570 print self._indent_to(len(indent.group(0))) ,
571 print re.sub(scan_re, self.replace, self.line)
573 if self.in_pre: print '</pre>'
574 if self.in_table: print '</tbody></table><p>'
579 def __init__(self, page_name):
580 self.page_name = page_name
582 self.msg_type = 'error'
584 def split_title(self):
585 # look for the end of words and the start of a new word and insert a space there
586 return re.sub('([a-z])([A-Z])', r'\1 \2', self.page_name)
589 return os.path.join(data_dir, self.page_name)
591 def _tmp_filename(self):
592 return os.path.join(data_dir, ('#' + self.page_name.replace('/','_') + '.' + `os.getpid()` + '#'))
596 os.stat(self._filename())
599 if err.errno == errno.ENOENT:
603 def get_raw_body(self):
605 return open(self._filename(), 'rb').read()
607 if err.errno == errno.ENOENT:
608 return '' # just doesn't exist, use default
609 if err.errno == errno.EISDIR:
610 return self.format_dir()
613 def format_dir(self):
616 for dirname in self.page_name.split('/'):
617 pathname = (pathname + '/' + dirname) if pathname else dirname
618 out += '[[' + pathname + '|' + dirname + ']]/'
621 for filename in page_list(self._filename(), file_re):
622 if img_re.match(filename):
624 maxwidth_arg = '|maxwidth=' + str(image_maxwidth)
625 out += '{{' + self.page_name + '/' + filename + '|' + filename + maxwidth_arg + '}}\n'
627 out += ' * [[' + self.page_name + '/' + filename + ']]\n'
631 if not '_pragmas' in self.__dict__:
634 f = open(self._filename(), 'rt')
635 attr_re = re.compile(r"^#(\S*)(.*)$")
637 m = attr_re.match(line)
640 self._pragmas[m.group(1)] = m.group(2).strip()
641 #print "bernie: _pragmas[" + m.group(1) + "] = " + m.group(2) + "<br>\n"
643 if err.errno != errno.ENOENT and err.errno != errno.EISDIR:
647 def pragma(self, name, default):
648 return self.pragmas().get(name, default)
650 def can(self, action, default=True):
653 #acl SomeUser:read,write All:read
654 acl = self.pragma("acl", None)
655 for rule in acl.split():
656 (user, perms) = rule.split(':')
657 if user == remote_user() or user == "All":
658 return action in perms.split(',')
662 self.msg_text = 'Illegal acl line: ' + acl
666 return self.can("write", True)
669 return self.can("read", True)
671 def send_naked(self):
673 WikiFormatter(self.get_raw_body()).print_html()
675 send_guru("Read access denied by ACLs", "notice")
679 value = self.pragma("css", None)
682 link_urls += [ [ "stylesheet", value ] ]
684 send_title(self.page_name, self.split_title(),
685 msg_text=self.msg_text, msg_type=self.msg_type, writable=self.can_write())
687 send_footer(self._last_modified())
689 def _last_modified(self):
691 from time import localtime, strftime
692 modtime = localtime(os.stat(self._filename())[stat.ST_MTIME])
694 if err.errno != errno.ENOENT:
697 return strftime(datetime_fmt, modtime)
699 def send_editor(self, preview=None):
700 send_title(None, 'Edit ' + self.split_title(), msg_text=self.msg_text, msg_type=self.msg_type)
701 if not self.can_write():
702 send_guru("Write access denied by ACLs", "error")
707 filename = form['file'].value
709 print ('<p><b>Editing ' + self.page_name
710 + ' for ' + cgi.escape(remote_user())
711 + ' from ' + cgi.escape(get_hostname(remote_host()))
713 print '<div class="editor"><form name="editform" method="post" enctype="multipart/form-data" action="%s">' % relative_url(self.page_name)
714 print '<input type="hidden" name="edit" value="%s">' % (self.page_name)
715 print '<input type="input" id="editor" name="changelog" value="Edit page %s" accesskey="c" /><br />' % (self.page_name)
716 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())
717 print '<label for="file" accesskey="u">Or Upload a file:</label> <input type="file" name="file" value="%s" />' % filename
720 <input type="submit" name="save" value="Save" accesskey="s">
721 <input type="submit" name="preview" value="Preview" accesskey="p" />
722 <input type="reset" value="Reset" />
723 <input type="submit" name="cancel" value="Cancel" />
726 <script language="javascript">
728 document.editform.savetext.focus()
732 print "<p>" + link_tag('EditingTips') + "</p>"
734 print "<div class='preview'>"
735 WikiFormatter(preview).print_html()
739 def send_raw(self, mimetype='text/plain'):
741 body = self.get_raw_body()
742 emit_header(mimetype)
745 send_title(None, msg_text='Read access denied by ACLs', msg_type='notice')
747 def send_image(self, mimetype, args=[]):
748 if 'maxwidth' in args:
750 emit_header(mimetype)
752 subprocess.check_call(['gm', 'convert', self._filename(),
753 '-scale', args['maxwidth'].value + ' >', '-'])
755 self.send_raw(mimetype)
757 def _write_file(self, data):
758 tmp_filename = self._tmp_filename()
759 open(tmp_filename, 'wb').write(data)
760 name = self._filename()
762 # Bad Bill! POSIX rename ought to replace. :-(
766 if err.errno != errno.ENOENT: raise err
767 os.rename(tmp_filename, name)
769 def save(self, newdata, changelog):
770 if not self.can_write():
771 self.msg_text = 'Write access denied by ACLs'
772 self.msg_type = 'error'
775 self._write_file(newdata)
778 # FIXME: what's the std way to perform shell quoting in python?
779 cmd = ( post_edit_hook
780 + " '" + data_dir + '/' + self.page_name
781 + "' '" + remote_user()
782 + "' '" + remote_host()
783 + "' '" + changelog + "'"
789 self.msg_text += "Post-editing hook returned %d.\n" % rc
790 self.msg_text += 'Command was: ' + cmd + '\n'
792 self.msg_text += 'Output follows:\n' + output
794 self.msg_text = 'Thank you for your contribution. Your attention to detail is appreciated.'
795 self.msg_type = 'success'
799 handler = globals().get('handle_' + cmd)
801 handler(form[cmd].value)
804 query = query_string()
805 if file_re.match(query):
806 if word_re.match(query):
809 from mimetypes import MimeTypes
810 mimetype, encoding = MimeTypes().guess_type(query)
812 if mimetype.startswith('image/'):
813 Page(query).send_image(mimetype=mimetype, args=form)
815 Page(query).send_raw(mimetype=mimetype)
819 send_httperror("403 Forbidden", query)
822 execfile("geekigeeki.conf.py")
823 form = cgi.FieldStorage()
827 msg_text = traceback.format_exc()
829 send_guru(msg_text, "error")
831 send_title(None, msg_text=msg_text)