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 if m.group(2) is None:
350 elif img_re.match(m.group(2)):
351 descr = '<img border="0" src="' + descr + '" />'
355 return link_tag(name, descr, 'wikilink')
357 def _inl_repl(self, word):
358 m = link_re.match(word)
360 descr = m.group(2) or name
361 name = relative_url(name)
362 argv = descr.split('|')
366 args = '?' + '&'.join(argv)
371 # The "extthumb" nonsense works around a limitation of the HTML block model
372 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>' \
373 % (name, name + args, descr, descr)
375 return '<a href="%s"><img border="0" src="%s" /></a>' % (name, name + args)
377 def _email_repl(self, word):
378 return '<a href="mailto:%s">%s</a>' % (word, word)
380 def _html_repl(self, word):
382 return word; # Pass through
384 def _ent_repl(self, s):
385 if self.in_html and s == '>':
388 return {'&': '&',
392 def _li_repl(self, match):
399 def _pre_repl(self, word):
400 if word == '{{{' and not self.in_pre:
408 def _hi_repl(self, word):
409 return '<strong class="highlight ' + word + '">' + word + '</strong>'
411 def _tr_repl(self, word):
413 if not self.in_table:
416 out = '</p><table><tbody>\n'
418 out = out + '<tr class="' + ['even', 'odd'][self.tr_cnt % 2] + '">'
419 return out + ['<td>', '<th>'][word.strip() == '||=']
421 def _td_repl(self, word):
423 return ['</td><td>', '</th><th>'][word.strip() == '||=']
426 def _tre_repl(self, word):
428 return ['</td></tr>', '</th></tr>'][word.strip() == '||=']
431 def _indent_level(self):
432 return len(self.list_indents) and self.list_indents[-1]
434 def _indent_to(self, new_level):
435 if self._indent_level() == new_level:
438 while self._indent_level() > new_level:
439 del(self.list_indents[-1])
442 self.in_li = False # FIXME
444 while self._indent_level() < new_level:
445 self.list_indents.append(new_level)
452 res += '</ul>' * len(self.list_indents)
454 self.list_indents = []
457 def replace(self, match):
458 for type, hit in match.groupdict().items():
460 return getattr(self, '_' + type + '_repl')(hit)
462 raise "Can't handle match " + `match`
464 def print_html(self):
465 print '<div class="wiki"><p>'
467 # For each line, we scan through looking for magic
468 # strings, outputting verbatim any intervening text
469 # TODO: highlight search words (look at referrer)
470 scan_re = re.compile(
473 + r"(?P<b>\*\*|'''|//|''|##|``|__|\^\^|,,)"
474 + r"|(?P<tit>\={2,6})"
476 + r"|(?P<rule>^-{3,})"
477 + r"|(?P<hi>\b(FIXME|TODO|DONE)\b)"
480 + r"|(?P<macro>\<\<([^\s\|\>]+)(?:\s*\|\s*([^\>]+)|)\>\>)"
481 + r"|(?P<hurl>\[\[([^\s\|]+)(?:\s*\|\s*([^\]]+)|)\]\])"
484 + r"|(?P<html><(/|)(br|hr|div|form|iframe|input|span))"
488 + r"|(?P<img>\b[a-zA-Z0-9_/-]+\.(png|gif|jpg|jpeg|bmp))" # LEGACY
489 + r"|(?P<word>\b(?:[A-Z][a-z]+){2,}\b)" # LEGACY
490 + r"|(?P<url>(http|https|ftp|mailto)\:[^\s'\"]+\S)" # LEGACY
491 + r"|(?P<email>[-\w._+]+\@[\w.-]+)" # LEGACY
494 + r"|(?P<li>^\s+[\*#] +)"
495 + r"|(?P<pre>\{\{\{|\s*\}\}\})"
496 + r"|(?P<inl>\{\{([^\s\|]+)(?:\s*\|\s*([^\]]+)|)\}\})" #TODO
499 + r"|(?P<tr>^\s*\|\|(=|)\s*)"
500 + r"|(?P<tre>\s*\|\|(=|)\s*$)"
501 + r"|(?P<td>\s*\|\|(=|)\s*)"
505 + r"(?P<pre>\s*\}\}\})"
508 blank_re = re.compile(r"^\s*$")
509 indent_re = re.compile(r"^\s*")
510 tr_re = re.compile(r"^\s*\|\|")
511 eol_re = re.compile(r"\r?\n")
512 for self.line in eol_re.split(self.raw.expandtabs()):
515 if self.line.startswith('#'):
517 self.in_header = False
520 print re.sub(pre_re, self.replace, self.line)
522 if self.in_table and not tr_re.match(self.line):
523 self.in_table = False
524 print '</tbody></table><p>'
526 if blank_re.match(self.line):
529 indent = indent_re.match(self.line)
530 print self._indent_to(len(indent.group(0)))
531 print re.sub(scan_re, self.replace, self.line)
533 if self.in_pre: print '</pre>'
534 if self.in_table: print '</tbody></table><p>'
539 def __init__(self, page_name):
540 self.page_name = page_name
542 self.msg_type = 'error'
544 def split_title(self):
545 # look for the end of words and the start of a new word and insert a space there
546 return re.sub('([a-z])([A-Z])', r'\1 \2', self.page_name)
549 return path.join(data_dir, self.page_name)
551 def _tmp_filename(self):
552 return path.join(data_dir, ('#' + self.page_name.replace('/','_') + '.' + `os.getpid()` + '#'))
556 os.stat(self._filename())
559 if er.errno == errno.ENOENT:
564 word = self.page_name
566 return link_tag(word, word, 'wikilink')
568 return link_tag(word, nonexist_pfx + word, 'nonexistent')
570 def get_raw_body(self):
572 return open(self._filename(), 'rb').read()
574 if er.errno == errno.ENOENT:
575 return '' # just doesn't exist, use default
576 if er.errno == errno.EISDIR:
577 return self.format_dir()
580 def format_dir(self):
583 for dir in self.page_name.split('/'):
584 path = (path + '/' + dir) if path else dir
585 out += '[[' + path + '|' + dir + ']]/'
588 for file in page_list(self._filename(), file_re):
589 if img_re.match(file):
591 maxwidth_arg = '|maxwidth=' + str(image_maxwidth)
592 out += '{{' + self.page_name + '/' + file + '|' + file + maxwidth_arg + '}}\n'
594 out += ' * [[' + self.page_name + '/' + file + ']]\n'
597 if 'attrs' in self.__dict__:
601 file = open(self._filename(), 'rt')
602 attr_re = re.compile(r"^#(\S*)(.*)$")
604 m = attr_re.match(line)
607 self.attrs[m.group(1)] = m.group(2).strip()
608 #print "bernie: attrs[" + m.group(1) + "] = " + m.group(2) + "<br>\n"
610 if er.errno != errno.ENOENT:
614 def get_attr(self, name, default):
615 return self.get_attrs().get(name, default)
617 def can(self, action, default=True):
620 #acl SomeUser:read,write All:read
621 acl = self.get_attr("acl", None)
622 for rule in acl.split():
623 (user, perms) = rule.split(':')
624 if user == remote_user() or user == "All":
625 return action in perms.split(',')
627 except Exception, er:
629 self.msg_text = 'Illegal acl line: ' + acl
633 return self.can("write", True)
636 return self.can("read", True)
638 def send_naked(self):
640 WikiFormatter(self.get_raw_body()).print_html()
642 send_guru("Read access denied by ACLs", "notice")
647 page_name = self.page_name
651 css_url = self.get_attr("css", "").split() + css_url
653 send_title(page_name, self.split_title(), msg_text=self.msg_text, msg_type=self.msg_type)
655 send_footer(page_name, self._last_modified())
657 def _last_modified(self):
659 from time import localtime, strftime
660 modtime = localtime(os.stat(self._filename())[stat.ST_MTIME])
662 if er.errno != errno.ENOENT:
665 return strftime(datetime_fmt, modtime)
667 def send_editor(self, preview=None):
668 send_title(None, 'Edit ' + self.split_title(), msg_text=self.msg_text, msg_type=self.msg_type)
669 if not self.can_write():
670 send_guru("Write access denied by ACLs", "error")
675 file = form['file'].value
677 print ('<p><b>Editing ' + self.page_name
678 + ' for ' + cgi.escape(remote_user())
679 + ' from ' + cgi.escape(get_hostname(remote_host()))
681 print '<div class="editor"><form method="post" enctype="multipart/form-data" action="%s">' % relative_url(self.page_name)
682 print '<input type="hidden" name="edit" value="%s">' % (self.page_name)
683 print '<textarea wrap="off" spellcheck="true" id="editor" name="savetext" rows="17" cols="100">%s</textarea>' % (preview or self.get_raw_body())
684 print 'Or upload a file: <input type="file" name="file" value="%s" />' % file
687 <input type="submit" name="save" value="Save" />
688 <input type="submit" name="preview" value="Preview" />
689 <input type="reset" value="Reset" />
690 <input type="submit" name="cancel" value="Cancel" />
693 print "<p>" + Page('EditingTips').link_to() + "</p>"
695 print "<div class='preview'>"
696 WikiFormatter(preview).print_html()
698 send_footer(self.page_name)
700 def send_raw(self, mimetype='text/plain'):
702 body = self.get_raw_body()
703 emit_header(mimetype)
706 send_title(None, msg_text='Read access denied by ACLs', msg_type='notice')
708 def send_image(self, mimetype, args=[]):
709 if 'maxwidth' in args:
711 emit_header(mimetype)
713 subprocess.check_call(['gm', 'convert', self._filename(),
714 '-scale', args['maxwidth'].value + ' >', '-'])
716 self.send_raw(mimetype)
718 def _write_file(self, data):
719 tmp_filename = self._tmp_filename()
720 open(tmp_filename, 'wb').write(data)
721 name = self._filename()
723 # Bad Bill! POSIX rename ought to replace. :-(
727 if er.errno != errno.ENOENT: raise er
728 os.rename(tmp_filename, name)
730 def save(self, newdata):
731 if not self.can_write():
732 self.msg_text = 'Write access denied by ACLs'
733 self.msg_type = 'error'
736 self._write_file(newdata)
739 # FIXME: what's the std way to perform shell quoting in python?
740 cmd = ( post_edit_hook
741 + " '" + data_dir + '/' + self.page_name
742 + "' '" + remote_user()
743 + "' '" + remote_host() + "'"
749 self.msg_text += "Post-editing hook returned %d.\n" % rc
750 self.msg_text += 'Command was: ' + cmd + '\n'
752 self.msg_text += 'Output follows:\n' + output
754 self.msg_text = 'Thank you for your contribution. Your attention to detail is appreciated.'
755 self.msg_type = 'success'
757 # Main ---------------------------------------------------------------
759 execfile("geekigeeki.conf.py")
760 form = cgi.FieldStorage()
763 handler = globals().get('handle_' + cmd)
765 handler(form[cmd].value)
768 path_info = environ.get('PATH_INFO', '')
769 if len(path_info) and path_info[0] == '/':
770 query = path_info[1:] or 'FrontPage'
772 query = environ.get('QUERY_STRING', '') or 'FrontPage'
774 if file_re.match(query):
775 if word_re.match(query):
778 from mimetypes import MimeTypes
779 type, encoding = MimeTypes().guess_type(query)
780 #type = type or 'text/plain'
781 #Page(query).send_raw(mimetype=type)
783 if type.startswith('image/'):
784 Page(query).send_image(mimetype=type,args=form)
786 Page(query).send_raw(mimetype=type)
790 print "Status: 404 Not Found"
791 send_title(None, msg_text='Can\'t work out query: ' + query)
795 msg_text = traceback.format_exc()
797 send_guru(msg_text, "error")
799 send_title(None, msg_text=msg_text)