2 # -*- coding: utf-8 -*-
4 # Copyright (C) 1999, 2000 Martin Pool <mbp@humbug.org.au>
5 # Copyright (C) 2002 Gerardo Poggiali
6 # Copyright (C) 2007, 2008, 2009, 2010, 2011 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 Affero General Public License as
10 # published by the Free Software Foundation, either version 3 of the
11 # License, or (at your option) any later version.
12 # You should have received a copy of the GNU Affero General Public License
13 # along with this program. If not, see <http://www.gnu.org/licenses/>.
15 __version__ = '4.0-' + '$Id$'[4:11]
17 from time import clock, localtime, gmtime, strftime
21 import cgi, sys, os, re, errno, stat, glob
23 image_ext = 'png|gif|jpg|jpeg|svg|bmp|ico'
24 video_ext = 'avi|webm|mkv|ogv'
25 image_re = re.compile(r".*\.(" + image_ext + ")$", re.IGNORECASE)
26 video_re = re.compile(r".*\.(" + video_ext + ")$", re.IGNORECASE)
27 # FIXME: we accept stuff like foo/../bar and we shouldn't
28 file_re = re.compile(r"([A-Za-z0-9_\-][A-Za-z0-9_\.\-/ ]*)$")
29 url_re = re.compile(r"[a-z]{3,8}://[^\s'\"]+\S$")
30 ext_re = re.compile(r"\.([^\./]+)$")
32 def config_get(key, default=None):
33 return globals().get(key, default)
36 return os.environ.get('SCRIPT_NAME', '')
38 #TODO: move post-edit hook into wiki, then kill this
40 return os.path.split(os.environ.get('SCRIPT_FILENAME', ''))[0]
43 path_info = os.environ.get('PATH_INFO', '')
44 if len(path_info) and path_info[0] == '/':
45 return path_info[1:] or 'FrontPage'
47 return os.environ.get('QUERY_STRING', '') or 'FrontPage'
50 purl = config_get('privileged_url')
51 return (purl is not None) and os.environ.get('SCRIPT_URI', '').startswith(purl)
54 user = os.environ.get('REMOTE_USER', '')
55 if user is None or user == '' or user == 'anonymous':
56 user = 'AnonymousCoward'
60 return os.environ.get('REMOTE_ADDR', '')
62 def get_hostname(addr):
64 from socket import gethostbyaddr
65 return gethostbyaddr(addr)[0] + ' (' + addr + ')'
69 def is_external_url(pathname):
70 return (url_re.match(pathname) or pathname.startswith('/'))
72 def relative_url(pathname, privileged=False):
73 if not is_external_url(pathname):
75 url = config_get('privileged_url') or script_name()
78 pathname = url + '/' + pathname
79 return cgi.escape(pathname, quote=True)
82 return re.sub(' ', '-', re.sub('[^a-z0-9_ ]', '', s.lower()).strip())
85 return re.sub(r'(?:.*[/:]|)([^:/\.]+)(?:\.[^/:]+|)$', r'\1', s.replace('_', ' '))
87 # Split arg lists like "blah|blah blah| width=100 | align = center",
88 # return a list containing anonymous arguments and a map containing the named arguments
92 for arg in s.strip('<[{}]>').split('|'):
93 m = re.match('\s*(\w+)\s*=\s*(.+)\s*', arg)
95 kvargs[m.group(1)] = m.group(2)
97 args.append(arg.strip())
100 def url_args(kvargs):
102 for k, v in kvargs.items():
103 argv.append(k + '=' + v)
105 return '?' + '&'.join(argv)
108 def emit_header(mtime=None, mime_type="text/html"):
110 # Prevent caching when the wiki engine gets updated
111 mtime = max(mtime, os.stat(__file__).st_mtime)
112 print("Last-Modified: " + strftime("%a, %d %b %Y %H:%M:%S GMT", gmtime(mtime)))
114 print("Cache-Control: must-revalidate, max-age=0")
115 print("Content-type: " + mime_type + "; charset=utf-8")
118 def send_guru(msg_text, msg_type):
119 if not msg_text: return
120 print('<pre id="guru" onclick="this.style.display = \'none\'" class="' + msg_type + '">')
121 if msg_type == 'error':
122 print(' Software Failure. Press left mouse button to continue.\n')
123 print(cgi.escape(msg_text))
124 if msg_type == 'error':
125 print '\n Guru Meditation #DEADBEEF.ABADC0DE'
126 print('</pre><script type="text/javascript" src="%s" defer="defer"></script>' \
127 % relative_url('sys/GuruMeditation.js'))
129 def send_httperror(status="404 Not Found", query="", trace=False):
130 print("Status: %s" % status)
131 msg_text = "%s: on query '%s'" % (status, query)
134 msg_text += '\n\n' + traceback.format_exc()
136 page.send_title(msg_text=msg_text)
139 def link_tag(dest, text=None, privileged=False, **kvargs):
141 text = humanlink(dest)
142 elif image_re.match(text):
143 text = '<img style="border: 0" src="' + relative_url(text) + '" alt="' + text + '" />'
145 link_class = kvargs.get('class', kvargs.get('cssclass', None))
147 if is_external_url(dest):
148 link_class = 'external'
149 elif file_re.match(dest) and Page(dest).exists():
150 link_class = 'wikilink'
152 text = config_get('nonexist_pfx', '') + text
153 link_class = 'nonexistent'
155 # Prevent crawlers from following links potentially added by spammers and to autogenerated pages
157 if link_class in ('external', 'navlink', 'nonexistent'):
158 nofollow = 'rel="nofollow" '
160 return '<a class="%s" %shref="%s">%s</a>' % (link_class, nofollow, relative_url(dest, privileged=privileged), text)
162 def link_inline(name, descr=None, kvargs={}):
163 if not descr: descr = humanlink(name)
164 url = relative_url(name)
165 if video_re.match(name):
166 return '<video controls="1" src="%s">Your browser does not support HTML5 video</video>' % url
167 elif image_re.match(name):
168 return '<a href="%s"><img border="0" src="%s" alt="%s" /></a>' % (url, url + url_args(kvargs), descr)
169 elif file_re.match(name) and not ext_re.search(name): # FIXME: this guesses a wiki page
170 Page(name).send_naked(kvargs) # FIXME: we should return the page as a string rather than print it
173 return '<iframe width="100%%" scrolling="auto" frameborder="0" src="%s"><a href="%s">%s</a></iframe>' \
176 def link_inline_glob(pattern, descr=None, kvargs={}):
177 if not url_re.match(pattern) and bool(set(pattern) & set('?*[')):
179 for name in sorted(glob.glob(pattern), reverse=bool(int(kvargs.get('reverse', '0'))) ):
180 s += link_inline(name, descr, kvargs)
183 return link_inline(pattern, descr, kvargs)
185 def search_stats(hits, searched):
186 return "%d hits out of %d pages searched.\n" % (hits, searched)
188 def handle_fullsearch(query, form):
189 needle = form['q'].value
190 Page().send_title(text='Full text search for "' + needle + '"')
192 needle_re = re.compile(needle, re.IGNORECASE)
194 all_pages = page_list()
195 for page_name in all_pages:
196 body = Page(page_name).get_raw_body()
197 count = len(needle_re.findall(body))
199 hits.append((count, page_name))
201 # The default comparison for tuples compares elements in order, so this sorts by number of hits
206 for (count, page_name) in hits:
207 out += ' * [[' + page_name + ']] . . . ' + str(count) + ' ' + ['match', 'matches'][count != 1] + '\n'
209 out += search_stats(len(hits), len(all_pages))
210 WikiFormatter(out).print_html()
212 def handle_titlesearch(query, form):
213 needle = form['q'].value
214 Page().send_title(text='Title search for "' + needle + '"')
216 needle_re = re.compile(needle, re.IGNORECASE)
217 all_pages = page_list()
218 hits = list(filter(needle_re.search, all_pages))
221 for filename in hits:
222 out += ' * [[' + filename + ']]\n'
224 out += search_stats(len(hits), len(all_pages))
225 WikiFormatter(out).print_html()
227 def handle_raw(pagename, form):
228 Page(pagename).send_raw()
230 def handle_atom(pagename, form):
231 Page(pagename).send_atom()
233 def handle_edit(pagename, form):
236 if form['file'].value:
237 pg.save(form['file'].file.read(), form['changelog'].value)
239 pg.save(form['savetext'].value.replace('\r\n', '\n'), form['changelog'].value)
241 elif 'cancel' in form:
242 pg.msg_text = 'Editing canceled'
243 pg.msg_type = 'notice'
245 else: # preview or edit
247 if 'preview' in form:
248 text = form['savetext'].value
251 def handle_get(pagename, form):
252 if not ext_re.search(pagename): # FIXME: no extension guesses a wiki page
253 Page(pagename).send()
255 # FIMXE: this is all bullshit, MimeTypes bases its guess on the extension!
256 from mimetypes import MimeTypes
257 mimetype, encoding = MimeTypes().guess_type(pagename)
258 Page(pagename).send_raw(mimetype=mimetype, args=form)
260 # Used by sys/macros/WordIndex and sys/macros/TitleIndex
261 def make_index_key():
262 links = ['<a href="#%s">%s</a>' % (ch, ch) for ch in 'abcdefghijklmnopqrstuvwxyz']
263 return '<p style="text-align: center">' + ' | '.join(links) + '</p>'
265 def page_list(dirname=None, search_re=None):
266 if search_re is None:
267 # FIXME: WikiWord is too restrictive now!
268 search_re = re.compile(r"^\b((([A-Z][a-z0-9]+){2,}/)*([A-Z][a-z0-9]+){2,})\b$")
269 return sorted(filter(search_re.match, os.listdir(dirname or '.')))
271 def _macro_ELAPSED_TIME(*args, **kvargs):
272 return "%03f" % (clock() - start_time)
274 def _macro_VERSION(*args, **kvargs):
278 """Object that turns Wiki markup into HTML."""
279 def __init__(self, raw, kvargs=None):
281 self.kvargs = kvargs or {}
283 self.in_pre = self.in_html = self.in_table = self.in_li = False
284 self.in_header = True
285 self.list_indents = [] # a list of pairs (indent_level, list_type) to track nested lists
293 "--": ["del", False],
294 "^^": ["sup", False],
295 ",,": ["sub", False],
296 "''": ["em", False], # LEGACY
297 "'''": ["b", False], # LEGACY
300 def _b_repl(self, word):
301 style = self.styles[word]
302 style[1] = not style[1]
303 return ['</', '<'][style[1]] + style[0] + '>'
305 def _glyph_repl(self, word):
308 def _tit_repl(self, word):
309 link = permalink(self.line)
311 result = '<a class="heading" href="#%s">¶</a></h%d><p>\n' % (link, self.h_level)
314 self.h_level = len(word) - 1
315 result = '\n</p><h%d id="%s">' % (self.h_level, link)
318 def _br_repl(self, word):
321 def _rule_repl(self, word):
322 return '\n<hr size="%d" noshade="noshade" />\n' % (len(word) - 2)
324 def _macro_repl(self, word):
326 args, macro_kvargs = parse_args(word)
327 # Is this a parameter given to the current page?
328 if args[0] in self.kvargs:
329 return self.kvargs[args[0]]
330 # Is this an internal macro?
331 macro = globals().get('_macro_' + args[0])
333 # Can we load (and cache) an external macro?
334 exec(open("sys/macros/" + args[0] + ".py").read(), globals())
335 macro = globals().get('_macro_' + args[0])
336 # Invoke macro passing both macro args augmented by page args
337 macro_kvargs.update(self.kvargs)
338 return macro(*args, **macro_kvargs)
340 msg = cgi.escape(word) + ": " + cgi.escape(str(e))
342 msg = '<strong class="error">' + msg + '</strong>'
345 def _hurl_repl(self, word):
346 args, kvargs = parse_args(word)
347 return link_tag(*args, **kvargs)
349 def _inl_repl(self, word):
350 args, kvargs = parse_args(word)
354 # This double div nonsense works around a limitation of the HTML block model
355 return '<div class="' + kvargs.get('class', 'thumb') + '">' \
356 + '<div class="innerthumb">' \
357 + link_inline_glob(name, descr, kvargs) \
358 + '<div class="caption">' + descr + '</div></div></div>'
360 return link_inline_glob(name, None, kvargs)
362 def _html_repl(self, word):
363 if not self.in_html and word.startswith('<div'): word = '</p>' + word
365 return word; # Pass through
367 def _htmle_repl(self, word):
369 if not self.in_html and word.startswith('</div'): word += '<p>'
370 return word; # Pass through
372 def _ent_repl(self, s):
374 return s; # Pass through
375 return {'&': '&',
379 def _img_repl(self, word): # LEGACY
380 return self._inl_repl('{{' + word + '}}')
382 def _word_repl(self, word): # LEGACY
383 if self.in_html: return word # pass through
384 return link_tag(word)
386 def _url_repl(self, word): # LEGACY
387 if self.in_html: return word # pass through
388 return link_tag(word)
390 def _email_repl(self, word): # LEGACY
391 if self.in_html: return word # pass through
392 return '<a href="mailto:%s">%s</a>' % (word, word)
394 def _li_repl(self, match):
401 def _pre_repl(self, word):
402 if word == '{{{' and not self.in_pre:
410 def _hi_repl(self, word):
411 return '<strong class="highlight ' + word + '">' + word + '</strong>'
413 def _tr_repl(self, word):
415 if not self.in_table:
418 out = '</p><table><tbody>\n'
420 out = out + '<tr class="' + ['even', 'odd'][self.tr_cnt % 2] + '">'
421 return out + ['<td>', '<th>'][word.strip() == '||=']
423 def _td_repl(self, word):
425 return ['</td><td>', '</th><th>'][word.strip() == '||=']
428 def _tre_repl(self, word):
430 return ['</td></tr>', '</th></tr>'][word.strip() == '||=']
433 def _indent_level(self):
434 return len(self.list_indents) and self.list_indents[-1][0]
436 def _indent_to(self, new_level, list_type=''):
437 if self._indent_level() == new_level:
440 while self._indent_level() > new_level:
443 self.in_li = False # FIXME
444 s += '</' + self.list_indents[-1][1] + '>\n'
445 del(self.list_indents[-1])
447 list_type = ('ul', 'ol')[list_type == '#']
448 while self._indent_level() < new_level:
449 self.list_indents.append((new_level, list_type))
450 s += '<' + list_type + '>\n'
454 def replace(self, match):
455 for rule, hit in list(match.groupdict().items()):
457 return getattr(self, '_' + rule + '_repl')(hit)
459 raise Exception("Can't handle match " + repr(match))
461 def print_html(self):
462 print('<div class="wiki"><p>')
464 scan_re = re.compile(r"""(?:
465 # Styles and formatting ("--" must cling to a word to disambiguate it from the dash)
466 (?P<b> \*\* | // | \#\# | __ | --\b | \b-- | \^\^ | ,, | ''' | '' )
470 | (?P<hi> \b( FIXME | TODO | DONE )\b )
474 | (?P<macro> \<\<[^\>]+\>\>)
475 | (?P<hurl> \[\[[^\]]+\]\])
478 | (?P<html> <(br|hr|small|div|span|form|iframe|input|textarea|a|img|h[1-5])\b )
479 | (?P<htmle> ( /\s*> | </(br|hr|small|div|span|form|iframe|input|textarea|a|img|h[1-5])> ) )
482 # Auto links (LEGACY)
483 | (?P<img> \b[a-zA-Z0-9_/-]+\.(""" + image_ext + "|" + video_ext + r"""))
484 | (?P<word> \b(?:[A-Z][a-z]+){2,}\b)
485 | (?P<url> (http|https|ftp|mailto)\:[^\s'\"]+\S)
486 | (?P<email> [-\w._+]+\@[\w.-]+)
488 # Lists, divs, spans and inline objects
489 | (?P<li> ^\s+[\*\#]\s+)
490 | (?P<pre> \{\{\{|\s*\}\}\})
491 | (?P<inl> \{\{[^\}]+\}\})
494 | (?P<tr> ^\s*\|\|(=|)\s*)
495 | (?P<tre> \s*\|\|(=|)\s*$)
496 | (?P<td> \s*\|\|(=|)\s*)
498 pre_re = re.compile("""(?:
502 blank_re = re.compile(r"^\s*$")
503 indent_re = re.compile(r"^(\s*)(\*|\#|)")
504 tr_re = re.compile(r"^\s*\|\|")
505 eol_re = re.compile(r"\r?\n")
506 # For each line, we scan through looking for magic strings, outputting verbatim any intervening text
507 #3.0: for self.line in eol_re.split(str(self.raw.expandtabs(), 'utf-8')):
508 for self.line in eol_re.split(str(self.raw.expandtabs())):
511 if self.line.startswith('#'):
513 self.in_header = False
516 print(re.sub(pre_re, self.replace, self.line))
518 if self.in_table and not tr_re.match(self.line):
519 self.in_table = False
520 print('</tbody></table><p>')
522 if blank_re.match(self.line):
525 indent = indent_re.match(self.line)
526 print(self._indent_to(len(indent.group(1)), indent.group(2)))
527 # Stand back! Here we apply the monster regex that does all the parsing
528 print(re.sub(scan_re, self.replace, self.line))
530 if self.in_pre: print('</pre>')
531 if self.in_table: print('</tbody></table><p>')
532 print(self._indent_to(0))
535 class HttpException(Exception):
536 def __init__(self, error, query):
541 def __init__(self, page_name="Limbo"):
542 self.page_name = page_name.rstrip('/');
544 self.msg_type = 'error'
545 if not file_re.match(self.page_name):
546 raise HttpException("403 Forbidden", self.page_name)
548 def split_title(self):
549 # look for the end of words and the start of a new word and insert a space there
550 return re.sub('([a-z])([A-Z])', r'\1 \2', self.page_name)
553 return self.page_name
555 def _tmp_filename(self):
556 return self.page_name + '.tmp' + str(os.getpid()) + '#'
560 return os.stat(self._filename()).st_mtime
562 if err.errno == errno.ENOENT:
571 def get_raw_body(self):
573 return open(self._filename(), 'rb').read()
575 if err.errno == errno.ENOENT:
577 if err.errno == errno.EISDIR:
578 return self.format_dir()
581 def format_dir(self):
584 for dirname in self.page_name.strip('/').split('/'):
585 pathname = (pathname and pathname + '/' ) + dirname
586 out += '[[' + pathname + '|' + dirname + ']]/'
590 for filename in page_list(self._filename(), file_re):
591 if image_re.match(filename):
592 maxwidth = config_get('image_maxwidth', '400')
594 maxwidth = ' | maxwidth=' + str(maxwidth)
595 images_out += '{{' + self.page_name + '/' + filename + ' | ' + humanlink(filename) + maxwidth + ' | class=thumbleft}}\n'
597 out += ' * [[' + self.page_name + '/' + filename + ']]\n'
598 return out + images_out
601 if not '_pragmas' in self.__dict__:
604 file = open(self._filename(), 'rt')
605 attr_re = re.compile(r"^#(\S*)(.*)$")
607 m = attr_re.match(line)
610 self._pragmas[m.group(1)] = m.group(2).strip()
611 #print "bernie: pragmas[" + m.group(1) + "] = " + m.group(2) + "<br>\n"
613 if err.errno != errno.ENOENT and err.errno != errno.EISDIR:
617 def pragma(self, name, default):
618 return self.pragmas().get(name, default)
620 def can(self, action, default=True):
623 #acl SomeUser:read,write All:read
624 acl = self.pragma("acl", None)
625 for rule in acl.split():
626 (user, perms) = rule.split(':')
627 if user == remote_user() or user == "All":
628 return action in perms.split(',')
632 self.msg_text = 'Illegal acl line: ' + acl
636 return self.can("write", True)
639 return self.can("read", True)
641 def send_title(self, name=None, text="Limbo", msg_text=None, msg_type='error'):
643 if title_done: return
646 emit_header(name and self._mtime())
647 print('<!doctype html>\n<html lang="en">')
648 print("<head><title>%s: %s</title>" % (config_get('site_name', "Unconfigured Wiki"), text))
649 print(' <meta charset="utf-8">')
650 print(' <meta name="viewport" content="width=device-width, initial-scale=1.0">')
652 print(' <meta name="robots" content="noindex,nofollow" />')
654 for http_equiv, content in config_get('meta_urls', {}):
655 print(' <meta http-equiv="%s" content="%s" />' % (http_equiv, relative_url(content)))
657 for link in config_get('link_urls', {}):
659 print(' <link rel="%s" href="%s" />' % (rel, relative_url(href)))
661 editable = name and self.can_write() and is_privileged()
663 print(' <link rel="alternate" type="application/x-wiki" title="Edit this page" href="%s" />' \
664 % relative_url(name + '?a=edit', privileged=True))
667 print(' <link rel="alternate" type="application/atom+xml" title="Atom feed" href="%s" />' \
668 % relative_url(name + '?a=atom'))
674 print('<body ondblclick="location.href=\'' + relative_url(name + '?a=edit', privileged=True) + '\'">')
679 send_guru(msg_text, msg_type)
681 if self.pragma("navbar", "on") != "on":
685 print('<nav><div class="nav">')
686 print link_tag('FrontPage', config_get('site_icon', 'Home'), cssclass='navlink')
688 print(' <b>' + link_tag('?a=titlesearch&q=' + name, text, cssclass='navlink') + '</b> ')
690 print(' <b>' + text + '</b> ')
691 print(' | ' + link_tag('FindPage', 'Find Page', cssclass='navlink'))
692 history = config_get('history_url')
694 print(' | <a href="' + relative_url(history) + '" class="navlink">Recent Changes</a>')
696 print(' | <a href="' + relative_url(history + '?a=history;f=' + name) + '" class="navlink">Page History</a>')
699 print(' | ' + link_tag(name + '?a=raw', 'Raw Text', cssclass='navlink'))
700 if config_get('privileged_url') is not None:
702 print(' | ' + link_tag(name + '?a=edit', 'Edit', cssclass='navlink', privileged=True))
704 print(' | ' + link_tag(name, 'Login', cssclass='login', privileged=True))
707 if user != 'AnonymousCoward':
708 print(' | ' + link_tag('user/' + user, user, cssclass='login'))
710 print('<hr /></div></nav>')
712 def send_footer(self):
713 if config_get('debug_cgi', False):
714 cgi.print_arguments()
717 footer = self.pragma("footer", "sys/footer")
719 link_inline(footer, kvargs = {
720 'LAST_MODIFIED': strftime(config_get('datetime_fmt', '%Y-%m-%dT%I:%M:%S%p'), localtime(self._mtime()))
722 print('</body></html>')
724 def send_naked(self, kvargs=None):
726 body = self.get_raw_body()
728 body = "//[[%s?a=edit|Describe %s]]//" % (self.page_name, self.page_name)
729 WikiFormatter(body, kvargs).print_html()
731 send_guru('Read access denied by ACLs', 'notice')
735 value = self.pragma("css", None)
738 link_urls += [ [ "stylesheet", value ] ]
740 self.send_title(name=self.page_name, text=self.split_title(), msg_text=self.msg_text, msg_type=self.msg_type)
745 emit_header(self._mtime(), 'application/atom+xml')
747 link_inline("sys/atom_header", kvargs = {
748 'LAST_MODIFIED': strftime(config_get('datetime_fmt', '%a, %d %b %Y %I:%M:%S %p'), localtime(self._mtime()))
753 link_inline("sys/atom_footer")
756 def send_editor(self, preview=None):
757 self.send_title(text='Edit ' + self.split_title(), msg_text=self.msg_text, msg_type=self.msg_type)
758 if not self.can_write():
759 send_guru("Write access denied by ACLs", "error")
763 preview = self.get_raw_body()
765 link_inline("sys/EditPage", kvargs = {
766 'EDIT_BODY': cgi.escape(preview),
767 #'EDIT_PREVIEW': WikiFormatter(preview).print_html(),
771 print("<div class='preview'>")
772 WikiFormatter(preview).print_html()
776 def send_raw(self, mimetype='text/plain', args=[]):
777 if not self.can_read():
778 self.send_title(msg_text='Read access denied by ACLs', msg_type='notice')
781 emit_header(self._mtime(), mimetype)
782 if 'maxwidth' in args:
785 subprocess.check_call(['convert', self._filename(),
786 '-auto-orient', '-orient', 'TopLeft',
787 '-scale', args['maxwidth'].value + ' >', '-'])
789 body = self.get_raw_body()
792 def _write_file(self, data):
793 tmp_filename = self._tmp_filename()
794 open(tmp_filename, 'wb').write(data)
795 name = self._filename()
797 # Bad Bill! POSIX rename ought to replace. :-(
801 if err.errno != errno.ENOENT: raise err
802 path = os.path.split(name)[0]
803 if path and not os.path.exists(path):
805 os.rename(tmp_filename, name)
807 def save(self, newdata, changelog):
808 if not self.can_write():
809 self.msg_text = 'Write access denied by Access Control List'
811 if not is_privileged():
812 self.msg_text = 'Unauthenticated access denied'
815 self._write_file(newdata)
817 if config_get('post_edit_hook'):
820 config_get('post_edit_hook'),
821 self.page_name, remote_user(),
822 remote_host(), changelog ]
823 child = subprocess.Popen(cmd, stdout=subprocess.PIPE, close_fds=True)
824 output = child.stdout.read()
827 self.msg_text += "Post-editing hook returned %d. Command was:\n'%s'\n" % (rc, "' '".join(cmd))
829 self.msg_text += 'Output follows:\n' + output
831 self.msg_text = 'Thank you for your contribution. Your attention to detail is appreciated.'
832 self.msg_type = 'success'
835 exec(open("geekigeeki.conf.py").read())
836 os.chdir(config_get('data_dir', 'data'))
837 form = cgi.FieldStorage()
838 action = form.getvalue('a', 'get')
839 handler = globals().get('handle_' + action)
841 handler(query_string(), form)
843 send_httperror("403 Forbidden", query_string())
845 except HttpException, e:
846 send_httperror(e.error, query=e.query)
848 send_httperror("500 Internal Server Error", query=query_string(), trace=True)