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):
167 if 'maxwidth' in kvargs:
168 args += 'width=' + kvargs['maxwidth']
169 return '<video controls="1" src="%s" %s/>' % (url, args)
170 elif image_re.match(name):
171 return '<a href="%s"><img border="0" src="%s" alt="%s" /></a>' % (url, url + url_args(kvargs), descr)
172 elif file_re.match(name) and not ext_re.search(name): # FIXME: this guesses a wiki page
173 Page(name).send_naked(kvargs) # FIXME: we should return the page as a string rather than print it
176 return '<iframe width="100%%" scrolling="auto" frameborder="0" src="%s"><a href="%s">%s</a></iframe>' \
179 def link_inline_glob(pattern, descr=None, kvargs={}):
180 if not url_re.match(pattern) and bool(set(pattern) & set('?*[')):
182 for name in sorted(glob.glob(pattern), reverse=bool(int(kvargs.get('reverse', '0'))) ):
183 s += link_inline(name, descr, kvargs)
186 return link_inline(pattern, descr, kvargs)
188 def search_stats(hits, searched):
189 return "%d hits out of %d pages searched.\n" % (hits, searched)
191 def handle_fullsearch(query, form):
192 needle = form['q'].value
193 Page().send_title(text='Full text search for "' + needle + '"')
195 needle_re = re.compile(needle, re.IGNORECASE)
197 all_pages = page_list()
198 for page_name in all_pages:
199 body = Page(page_name).get_raw_body()
200 count = len(needle_re.findall(body))
202 hits.append((count, page_name))
204 # The default comparison for tuples compares elements in order, so this sorts by number of hits
209 for (count, page_name) in hits:
210 out += ' * [[' + page_name + ']] . . . ' + str(count) + ' ' + ['match', 'matches'][count != 1] + '\n'
212 out += search_stats(len(hits), len(all_pages))
213 WikiFormatter(out).print_html()
215 def handle_titlesearch(query, form):
216 needle = form['q'].value
217 Page().send_title(text='Title search for "' + needle + '"')
219 needle_re = re.compile(needle, re.IGNORECASE)
220 all_pages = page_list()
221 hits = list(filter(needle_re.search, all_pages))
224 for filename in hits:
225 out += ' * [[' + filename + ']]\n'
227 out += search_stats(len(hits), len(all_pages))
228 WikiFormatter(out).print_html()
230 def handle_raw(pagename, form):
231 Page(pagename).send_raw()
233 def handle_atom(pagename, form):
234 Page(pagename).send_atom()
236 def handle_edit(pagename, form):
239 if form['file'].value:
240 pg.save(form['file'].file.read(), form['changelog'].value)
242 pg.save(form['savetext'].value.replace('\r\n', '\n'), form['changelog'].value)
244 elif 'cancel' in form:
245 pg.msg_text = 'Editing canceled'
246 pg.msg_type = 'notice'
248 else: # preview or edit
250 if 'preview' in form:
251 text = form['savetext'].value
254 def handle_get(pagename, form):
255 if not ext_re.search(pagename): # FIXME: no extension guesses a wiki page
256 Page(pagename).send()
258 # FIMXE: this is all bullshit, MimeTypes bases its guess on the extension!
259 from mimetypes import MimeTypes
260 mimetype, encoding = MimeTypes().guess_type(pagename)
261 Page(pagename).send_raw(mimetype=mimetype, args=form)
263 # Used by sys/macros/WordIndex and sys/macros/TitleIndex
264 def make_index_key():
265 links = ['<a href="#%s">%s</a>' % (ch, ch) for ch in 'abcdefghijklmnopqrstuvwxyz']
266 return '<p style="text-align: center">' + ' | '.join(links) + '</p>'
268 def page_list(dirname=None, search_re=None):
269 if search_re is None:
270 # FIXME: WikiWord is too restrictive now!
271 search_re = re.compile(r"^\b((([A-Z][a-z0-9]+){2,}/)*([A-Z][a-z0-9]+){2,})\b$")
272 return sorted(filter(search_re.match, os.listdir(dirname or '.')))
274 def _macro_ELAPSED_TIME(*args, **kvargs):
275 return "%03f" % (clock() - start_time)
277 def _macro_VERSION(*args, **kvargs):
281 """Object that turns Wiki markup into HTML."""
282 def __init__(self, raw, kvargs=None):
284 self.kvargs = kvargs or {}
286 self.in_pre = self.in_html = self.in_table = self.in_li = False
287 self.in_header = True
288 self.list_indents = [] # a list of pairs (indent_level, list_type) to track nested lists
296 "--": ["del", False],
297 "^^": ["sup", False],
298 ",,": ["sub", False],
299 "''": ["em", False], # LEGACY
300 "'''": ["b", False], # LEGACY
303 def _b_repl(self, word):
304 style = self.styles[word]
305 style[1] = not style[1]
306 return ['</', '<'][style[1]] + style[0] + '>'
308 def _glyph_repl(self, word):
311 def _tit_repl(self, word):
312 link = permalink(self.line)
314 result = '<a class="heading" href="#%s">¶</a></h%d><p>\n' % (link, self.h_level)
317 self.h_level = len(word) - 1
318 result = '\n</p><h%d id="%s">' % (self.h_level, link)
321 def _br_repl(self, word):
324 def _rule_repl(self, word):
325 return '\n<hr size="%d" noshade="noshade" />\n' % (len(word) - 2)
327 def _macro_repl(self, word):
329 args, macro_kvargs = parse_args(word)
330 # Is this a parameter given to the current page?
331 if args[0] in self.kvargs:
332 return self.kvargs[args[0]]
333 # Is this an internal macro?
334 macro = globals().get('_macro_' + args[0])
336 # Can we load (and cache) an external macro?
337 exec(open("sys/macros/" + args[0] + ".py").read(), globals())
338 macro = globals().get('_macro_' + args[0])
339 # Invoke macro passing both macro args augmented by page args
340 macro_kvargs.update(self.kvargs)
341 return macro(*args, **macro_kvargs)
343 msg = cgi.escape(word) + ": " + cgi.escape(str(e))
345 msg = '<strong class="error">' + msg + '</strong>'
348 def _hurl_repl(self, word):
349 args, kvargs = parse_args(word)
350 return link_tag(*args, **kvargs)
352 def _inl_repl(self, word):
353 args, kvargs = parse_args(word)
357 # This double div nonsense works around a limitation of the HTML block model
358 return '<div class="' + kvargs.get('class', 'thumb') + '">' \
359 + '<div class="innerthumb">' \
360 + link_inline_glob(name, descr, kvargs) \
361 + '<div class="caption">' + descr + '</div></div></div>'
363 return link_inline_glob(name, None, kvargs)
365 def _html_repl(self, word):
366 if not self.in_html and word.startswith('<div'): word = '</p>' + word
368 return word; # Pass through
370 def _htmle_repl(self, word):
372 if not self.in_html and word.startswith('</div'): word += '<p>'
373 return word; # Pass through
375 def _ent_repl(self, s):
377 return s; # Pass through
378 return {'&': '&',
382 def _img_repl(self, word): # LEGACY
383 return self._inl_repl('{{' + word + '}}')
385 def _word_repl(self, word): # LEGACY
386 if self.in_html: return word # pass through
387 return link_tag(word)
389 def _url_repl(self, word): # LEGACY
390 if self.in_html: return word # pass through
391 return link_tag(word)
393 def _email_repl(self, word): # LEGACY
394 if self.in_html: return word # pass through
395 return '<a href="mailto:%s">%s</a>' % (word, word)
397 def _li_repl(self, match):
404 def _pre_repl(self, word):
405 if word == '{{{' and not self.in_pre:
413 def _hi_repl(self, word):
414 return '<strong class="highlight ' + word + '">' + word + '</strong>'
416 def _tr_repl(self, word):
418 if not self.in_table:
421 out = '</p><table><tbody>\n'
423 out = out + '<tr class="' + ['even', 'odd'][self.tr_cnt % 2] + '">'
424 return out + ['<td>', '<th>'][word.strip() == '||=']
426 def _td_repl(self, word):
428 return ['</td><td>', '</th><th>'][word.strip() == '||=']
431 def _tre_repl(self, word):
433 return ['</td></tr>', '</th></tr>'][word.strip() == '||=']
436 def _indent_level(self):
437 return len(self.list_indents) and self.list_indents[-1][0]
439 def _indent_to(self, new_level, list_type=''):
440 if self._indent_level() == new_level:
443 while self._indent_level() > new_level:
446 self.in_li = False # FIXME
447 s += '</' + self.list_indents[-1][1] + '>\n'
448 del(self.list_indents[-1])
450 list_type = ('ul', 'ol')[list_type == '#']
451 while self._indent_level() < new_level:
452 self.list_indents.append((new_level, list_type))
453 s += '<' + list_type + '>\n'
457 def replace(self, match):
458 for rule, hit in list(match.groupdict().items()):
460 return getattr(self, '_' + rule + '_repl')(hit)
462 raise Exception("Can't handle match " + repr(match))
464 def print_html(self):
465 print('<div class="wiki"><p>')
467 scan_re = re.compile(r"""(?:
468 # Styles and formatting ("--" must cling to a word to disambiguate it from the dash)
469 (?P<b> \*\* | // | \#\# | __ | --\b | \b-- | \^\^ | ,, | ''' | '' )
473 | (?P<hi> \b( FIXME | TODO | DONE )\b )
477 | (?P<macro> \<\<[^\>]+\>\>)
478 | (?P<hurl> \[\[[^\]]+\]\])
481 | (?P<html> <(br|hr|small|div|span|form|iframe|input|textarea|a|img|h[1-5])\b )
482 | (?P<htmle> ( /\s*> | </(br|hr|small|div|span|form|iframe|input|textarea|a|img|h[1-5])> ) )
485 # Auto links (LEGACY)
486 | (?P<img> \b[a-zA-Z0-9_/-]+\.(""" + image_ext + "|" + video_ext + r"""))
487 | (?P<word> \b(?:[A-Z][a-z]+){2,}\b)
488 | (?P<url> (http|https|ftp|mailto)\:[^\s'\"]+\S)
489 | (?P<email> [-\w._+]+\@[\w.-]+)
491 # Lists, divs, spans and inline objects
492 | (?P<li> ^\s+[\*\#]\s+)
493 | (?P<pre> \{\{\{|\s*\}\}\})
494 | (?P<inl> \{\{[^\}]+\}\})
497 | (?P<tr> ^\s*\|\|(=|)\s*)
498 | (?P<tre> \s*\|\|(=|)\s*$)
499 | (?P<td> \s*\|\|(=|)\s*)
501 pre_re = re.compile("""(?:
505 blank_re = re.compile(r"^\s*$")
506 indent_re = re.compile(r"^(\s*)(\*|\#|)")
507 tr_re = re.compile(r"^\s*\|\|")
508 eol_re = re.compile(r"\r?\n")
509 # For each line, we scan through looking for magic strings, outputting verbatim any intervening text
510 #3.0: for self.line in eol_re.split(str(self.raw.expandtabs(), 'utf-8')):
511 for self.line in eol_re.split(str(self.raw.expandtabs())):
514 if self.line.startswith('#'):
516 self.in_header = False
519 print(re.sub(pre_re, self.replace, self.line))
521 if self.in_table and not tr_re.match(self.line):
522 self.in_table = False
523 print('</tbody></table><p>')
525 if blank_re.match(self.line):
528 indent = indent_re.match(self.line)
529 print(self._indent_to(len(indent.group(1)), indent.group(2)))
530 # Stand back! Here we apply the monster regex that does all the parsing
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>')
535 print(self._indent_to(0))
538 class HttpException(Exception):
539 def __init__(self, error, query):
544 def __init__(self, page_name="Limbo"):
545 self.page_name = page_name.rstrip('/');
547 self.msg_type = 'error'
548 if not file_re.match(self.page_name):
549 raise HttpException("403 Forbidden", self.page_name)
551 def split_title(self):
552 # look for the end of words and the start of a new word and insert a space there
553 return re.sub('([a-z])([A-Z])', r'\1 \2', self.page_name)
556 return self.page_name
558 def _tmp_filename(self):
559 return self.page_name + '.tmp' + str(os.getpid()) + '#'
563 return os.stat(self._filename()).st_mtime
565 if err.errno == errno.ENOENT:
574 def get_raw_body(self):
576 return open(self._filename(), 'rb').read()
578 if err.errno == errno.ENOENT:
580 if err.errno == errno.EISDIR:
581 return self.format_dir()
584 def format_dir(self):
587 for dirname in self.page_name.strip('/').split('/'):
588 pathname = (pathname and pathname + '/' ) + dirname
589 out += '[[' + pathname + '|' + dirname + ']]/'
593 for filename in page_list(self._filename(), file_re):
594 if image_re.match(filename) or video_re.match(filename):
595 maxwidth = config_get('image_maxwidth', '400')
597 maxwidth = ' | maxwidth=' + str(maxwidth)
598 images_out += '{{' + self.page_name + '/' + filename + ' | ' + humanlink(filename) + maxwidth + ' | class=thumbleft}}\n'
600 out += ' * [[' + self.page_name + '/' + filename + ']]\n'
601 return out + images_out
604 if not '_pragmas' in self.__dict__:
607 file = open(self._filename(), 'rt')
608 attr_re = re.compile(r"^#(\S*)(.*)$")
610 m = attr_re.match(line)
613 self._pragmas[m.group(1)] = m.group(2).strip()
614 #print "bernie: pragmas[" + m.group(1) + "] = " + m.group(2) + "<br>\n"
616 if err.errno != errno.ENOENT and err.errno != errno.EISDIR:
620 def pragma(self, name, default):
621 return self.pragmas().get(name, default)
623 def can(self, action, default=True):
626 #acl SomeUser:read,write All:read
627 acl = self.pragma("acl", None)
628 for rule in acl.split():
629 (user, perms) = rule.split(':')
630 if user == remote_user() or user == "All":
631 return action in perms.split(',')
635 self.msg_text = 'Illegal acl line: ' + acl
639 return self.can("write", True)
642 return self.can("read", True)
644 def send_title(self, name=None, text="Limbo", msg_text=None, msg_type='error'):
646 if title_done: return
649 emit_header(name and self._mtime())
650 print('<!doctype html>\n<html lang="en">')
651 print("<head><title>%s: %s</title>" % (config_get('site_name', "Unconfigured Wiki"), text))
652 print(' <meta charset="utf-8">')
653 print(' <meta name="viewport" content="width=device-width, initial-scale=1.0">')
655 print(' <meta name="robots" content="noindex,nofollow" />')
657 for http_equiv, content in config_get('meta_urls', {}):
658 print(' <meta http-equiv="%s" content="%s" />' % (http_equiv, relative_url(content)))
660 for link in config_get('link_urls', {}):
662 print(' <link rel="%s" href="%s" />' % (rel, relative_url(href)))
664 editable = name and self.can_write() and is_privileged()
666 print(' <link rel="alternate" type="application/x-wiki" title="Edit this page" href="%s" />' \
667 % relative_url(name + '?a=edit', privileged=True))
670 print(' <link rel="alternate" type="application/atom+xml" title="Atom feed" href="%s" />' \
671 % relative_url(name + '?a=atom'))
677 print('<body ondblclick="location.href=\'' + relative_url(name + '?a=edit', privileged=True) + '\'">')
682 send_guru(msg_text, msg_type)
684 if self.pragma("navbar", "on") != "on":
688 print('<nav><div class="nav">')
689 print link_tag('FrontPage', config_get('site_icon', 'Home'), cssclass='navlink')
691 print(' <b>' + link_tag('?a=titlesearch&q=' + name, text, cssclass='navlink') + '</b> ')
693 print(' <b>' + text + '</b> ')
694 print(' | ' + link_tag('FindPage', 'Find Page', cssclass='navlink'))
695 history = config_get('history_url')
697 print(' | <a href="' + relative_url(history) + '" class="navlink">Recent Changes</a>')
699 print(' | <a href="' + relative_url(history + '?a=history;f=' + name) + '" class="navlink">Page History</a>')
702 print(' | ' + link_tag(name + '?a=raw', 'Raw Text', cssclass='navlink'))
703 if config_get('privileged_url') is not None:
705 print(' | ' + link_tag(name + '?a=edit', 'Edit', cssclass='navlink', privileged=True))
707 print(' | ' + link_tag(name, 'Login', cssclass='login', privileged=True))
710 if user != 'AnonymousCoward':
711 print(' | ' + link_tag('user/' + user, user, cssclass='login'))
713 print('<hr /></div></nav>')
715 def send_footer(self):
716 if config_get('debug_cgi', False):
717 cgi.print_arguments()
720 footer = self.pragma("footer", "sys/footer")
722 link_inline(footer, kvargs = {
723 'LAST_MODIFIED': strftime(config_get('datetime_fmt', '%Y-%m-%dT%I:%M:%S%p'), localtime(self._mtime()))
725 print('</body></html>')
727 def send_naked(self, kvargs=None):
729 body = self.get_raw_body()
731 body = "//[[%s?a=edit|Describe %s]]//" % (self.page_name, self.page_name)
732 WikiFormatter(body, kvargs).print_html()
734 send_guru('Read access denied by ACLs', 'notice')
738 value = self.pragma("css", None)
741 link_urls += [ [ "stylesheet", value ] ]
743 self.send_title(name=self.page_name, text=self.split_title(), msg_text=self.msg_text, msg_type=self.msg_type)
748 emit_header(self._mtime(), 'application/atom+xml')
750 link_inline("sys/atom_header", kvargs = {
751 'LAST_MODIFIED': strftime(config_get('datetime_fmt', '%a, %d %b %Y %I:%M:%S %p'), localtime(self._mtime()))
756 link_inline("sys/atom_footer")
759 def send_editor(self, preview=None):
760 self.send_title(text='Edit ' + self.split_title(), msg_text=self.msg_text, msg_type=self.msg_type)
761 if not self.can_write():
762 send_guru("Write access denied by ACLs", "error")
766 preview = self.get_raw_body()
768 link_inline("sys/EditPage", kvargs = {
769 'EDIT_BODY': cgi.escape(preview),
770 #'EDIT_PREVIEW': WikiFormatter(preview).print_html(),
774 print("<div class='preview'>")
775 WikiFormatter(preview).print_html()
779 def send_raw(self, mimetype='text/plain', args=[]):
780 if not self.can_read():
781 self.send_title(msg_text='Read access denied by ACLs', msg_type='notice')
784 emit_header(self._mtime(), mimetype)
785 if 'maxwidth' in args:
788 subprocess.check_call(['convert', self._filename(),
789 '-auto-orient', '-orient', 'TopLeft',
790 '-scale', args['maxwidth'].value + ' >', '-'])
792 body = self.get_raw_body()
795 def _write_file(self, data):
796 tmp_filename = self._tmp_filename()
797 open(tmp_filename, 'wb').write(data)
798 name = self._filename()
800 # Bad Bill! POSIX rename ought to replace. :-(
804 if err.errno != errno.ENOENT: raise err
805 path = os.path.split(name)[0]
806 if path and not os.path.exists(path):
808 os.rename(tmp_filename, name)
810 def save(self, newdata, changelog):
811 if not self.can_write():
812 self.msg_text = 'Write access denied by Access Control List'
814 if not is_privileged():
815 self.msg_text = 'Unauthenticated access denied'
818 self._write_file(newdata)
820 if config_get('post_edit_hook'):
823 config_get('post_edit_hook'),
824 self.page_name, remote_user(),
825 remote_host(), changelog ]
826 child = subprocess.Popen(cmd, stdout=subprocess.PIPE, close_fds=True)
827 output = child.stdout.read()
830 self.msg_text += "Post-editing hook returned %d. Command was:\n'%s'\n" % (rc, "' '".join(cmd))
832 self.msg_text += 'Output follows:\n' + output
834 self.msg_text = 'Thank you for your contribution. Your attention to detail is appreciated.'
835 self.msg_type = 'success'
838 exec(open("geekigeeki.conf.py").read())
839 os.chdir(config_get('data_dir', 'data'))
840 form = cgi.FieldStorage()
841 action = form.getvalue('a', 'get')
842 handler = globals().get('handle_' + action)
844 handler(query_string(), form)
846 send_httperror("403 Forbidden", query_string())
848 except HttpException, e:
849 send_httperror(e.error, query=e.query)
851 send_httperror("500 Internal Server Error", query=query_string(), trace=True)