Rework action dispatcher
[geekigeeki.git] / geekigeeki.py
1 #!/usr/bin/python
2 # -*- coding: utf-8 -*-
3 #
4 # Copyright 1999, 2000 Martin Pool <mbp@humbug.org.au>
5 # Copyright 2002 Gerardo Poggiali
6 # Copyright 2007, 2008, 2009 Bernie Innocenti <bernie@codewiz.org>
7 #
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.
12 #
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.
17 #
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/>.
20
21 __version__ = '$Id$'[4:12]
22
23 from time import clock
24 start_time = clock()
25
26 import cgi, sys, os, re, errno, stat
27
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 ext_re = re.compile(r"\.([^\./]+)$")
37
38 title_done = False
39
40 # CGI stuff ---------------------------------------------------------
41 def script_name():
42     return os.environ.get('SCRIPT_NAME', '')
43
44 def query_string():
45     path_info = os.environ.get('PATH_INFO', '')
46     if len(path_info) and path_info[0] == '/':
47         return path_info[1:] or 'FrontPage'
48     else:
49         return os.environ.get('QUERY_STRING', '') or 'FrontPage'
50
51 def privileged_path():
52     return privileged_url or script_name()
53
54 def remote_user():
55     user = os.environ.get('REMOTE_USER', '')
56     if user is None or user == '' or user == 'anonymous':
57         user = 'AnonymousCoward'
58     return user
59
60 def remote_host():
61     return os.environ.get('REMOTE_ADDR', '')
62
63 def get_hostname(addr):
64     try:
65         from socket import gethostbyaddr
66         return gethostbyaddr(addr)[0] + ' (' + addr + ')'
67     except Exception:
68         return addr
69
70 def is_external_url(pathname):
71     return (url_re.match(pathname) or pathname.startswith('/'))
72
73 def relative_url(pathname, privileged=False):
74     if not is_external_url(pathname):
75         if privileged:
76             url = privileged_path()
77         else:
78             url = script_name()
79         pathname = url + '/' + pathname
80     return cgi.escape(pathname, quote=True)
81
82 def permalink(s):
83     return re.sub(' ', '-', re.sub('[^a-z0-9_ ]', '', s.lower()).strip())
84
85 # Split arg lists like "blah| blah blah| width=100 | align = center",
86 # return a list containing anonymous arguments and a map containing the named arguments
87 def parse_args(s):
88     args = []
89     kwargs = {} 
90     for arg in s.strip('<[{}]>').split('|'):
91         try:
92             key, val = arg.split('=', 1)
93             kwargs[key.strip()] = val.strip()
94         except ValueError:
95             args.append(arg.strip())
96     return (args, kwargs)
97
98 def url_args(kvargs):
99     argv = []
100     for k, v in kvargs.items():
101         argv.append(k + '=' + v)
102     if argv:
103         return '?' + '&amp;'.join(argv)
104     return ''
105
106 # Formatting stuff --------------------------------------------------
107 def emit_header(mime_type="text/html"):
108     print("Content-type: " + mime_type + "; charset=utf-8\n")
109
110 def send_guru(msg_text, msg_type):
111     if not msg_text: return
112     print('<pre id="guru" onclick="this.style.display = \'none\'" class="' + msg_type + '">')
113     if msg_type == 'error':
114         print('    Software Failure.  Press left mouse button to continue.\n')
115     print(msg_text)
116     if msg_type == 'error':
117         print '\n           Guru Meditation #DEADBEEF.ABADC0DE'
118     print('</pre><script language="JavaScript" type="text/javascript" src="%s" defer="defer"></script>' \
119         % relative_url('sys/GuruMeditation.js'))
120
121 def send_title(name, text="Limbo", msg_text=None, msg_type='error', writable=False):
122     global title_done
123     if title_done: return
124
125     # Head
126     emit_header()
127     print('<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"')
128     print('  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">')
129     print('<html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en">')
130
131     print("<head><title>%s: %s</title>" % (site_name, text))
132     print(' <meta http-equiv="Content-Type" content="application/xhtml+xml; charset=utf-8" />')
133     if not name:
134         print(' <meta name="robots" content="noindex,nofollow" />')
135
136     for meta in meta_urls:
137         http_equiv, content = meta
138         print(' <meta http-equiv="%s" content="%s" />' % (http_equiv, relative_url(content)))
139
140     for link in link_urls:
141         rel, href = link
142         print(' <link rel="%s" href="%s" />' % (rel, relative_url(href)))
143
144     if name and writable and privileged_url is not None:
145         print(' <link rel="alternate" type="application/x-wiki" title="Edit this page" href="%s" />' \
146             % (privileged_path() + '?a=edit&q=' + name))
147
148     if history_url is not None:
149         print(' <link rel="alternate" type="application/rss+xml" title="RSS" href="%s" />' \
150             % relative_url(history_url + '?a=rss'))
151
152     print('</head>')
153
154     # Body
155     if name and writable and privileged_url is not None:
156         print('<body ondblclick="location.href=\'' + privileged_path() + '?a=edit&q=' + name + '\'">')
157     else:
158         print('<body>')
159
160     title_done = True
161     send_guru(msg_text, msg_type)
162
163     # Navbar
164     print('<div class="nav">')
165     print link_tag('FrontPage', site_icon or 'Home', 'navlink')
166     if name:
167         print('  <b>' + link_tag('?fullsearch=' + name, text, 'navlink') + '</b> ')
168     else:
169         print('  <b>' + text + '</b> ')
170     print(' | ' + link_tag('FindPage', 'Find Page', 'navlink'))
171     if 'history_url' in globals():
172         print(' | <a href="' + relative_url(history_url) + '" class="navlink">Recent Changes</a>')
173         if name:
174             print(' | <a href="' + relative_url(history_url + '?a=history;f=' + name) + '" class="navlink">Page History</a>')
175
176     if name:
177         print(' | ' + link_tag('?raw=' + name, 'Raw Text', 'navlink'))
178         if privileged_url is not None:
179             if writable:
180                 print(' | ' + link_tag('?a=edit&q=' + name, 'Edit', 'navlink', privileged=True))
181             else:
182                 print(' | ' + link_tag(name, 'Login', 'navlink', privileged=True))
183
184     else:
185         print(' | <i>Immutable Page</i>')
186
187     user = remote_user()
188     if user != 'AnonymousCoward':
189         print(' | <span class="login"><i><b>' + link_tag('User/' + user, user) + '</b></i></span>')
190
191     print('<hr /></div>')
192
193 def send_httperror(status="403 Not Found", query=""):
194     print("Status: %s" % status)
195     send_title(None, msg_text=("%s: on query '%s'" % (status, query)))
196     send_footer()
197
198 def link_tag(params, text=None, link_class=None, privileged=False, **kvargs):
199     if text is None:
200         text = params # default
201     elif img_re.match(text):
202         text = '<img border="0" src="' + relative_url(text) + '" alt="' + text + '" />'
203
204     if not link_class:
205         if is_external_url(params):
206             link_class = 'external'
207         elif file_re.match(params) and Page(params).exists():
208             link_class = 'wikilink'
209         else:
210             params = nonexist_pfx + params
211             link_class = 'nonexistent'
212
213     classattr = 'class="%s" ' % link_class
214     # Prevent crawlers from following links potentially added by spammers or to generated pages
215     if link_class == 'external' or link_class == 'navlink':
216         classattr += 'rel="nofollow"'
217
218     return '<a %shref="%s">%s</a>' % (classattr, relative_url(params, privileged=privileged), text)
219
220 def link_inline(name, descr=None, kvargs={}):
221     if not descr: descr = name
222     url = relative_url(name)
223     if video_re.match(name):
224         return '<video src="%s">Your browser does not support the HTML5 video tag</video>' % url
225     elif img_re.match(name):
226         return '<a href="%s"><img border="0" src="%s" alt="%s" /></a>' % (url, url + url_args(kvargs), descr)
227     elif file_re.match(name) and not ext_re.search(name): # FIXME: this guesses a wiki page
228         return Page(name).send_naked()
229     else:
230         return '<iframe width="100%%" scrolling="auto" frameborder="0" src="%s"><a href="%s">%s</a></iframe>' \
231             % (url, url, name)
232
233 # Search ---------------------------------------------------
234
235 def print_search_stats(hits, searched):
236     print("<p>%d hits out of %d pages searched.</p>" % (hits, searched))
237
238 def handle_fullsearch(query, form):
239     needle = form['q'].value
240     send_title(None, 'Full text search for "' + needle + '"')
241
242     needle_re = re.compile(needle, re.IGNORECASE)
243     hits = []
244     all_pages = page_list()
245     for page_name in all_pages:
246         body = Page(page_name).get_raw_body()
247         count = len(needle_re.findall(body))
248         if count:
249             hits.append((count, page_name))
250
251     # The default comparison for tuples compares elements in order,
252     # so this sorts by number of hits
253     hits.sort()
254     hits.reverse()
255
256     print("<ul>")
257     for (count, page_name) in hits:
258         print('<li><p>' + link_tag(page_name))
259         print(' . . . . ' + `count`)
260         print(['match', 'matches'][count != 1])
261         print('</p></li>')
262     print("</ul>")
263
264     print_search_stats(len(hits), len(all_pages))
265
266 def handle_titlesearch(query, form):
267     # TODO: check needle is legal -- but probably we can just accept any RE
268     needle = form['q'].value
269     send_title(None, 'Title search for "' + needle + '"')
270
271     needle_re = re.compile(needle, re.IGNORECASE)
272     all_pages = page_list()
273     hits = list(filter(needle_re.search, all_pages))
274
275     print("<ul>")
276     for filename in hits:
277         print('<li><p>' + link_tag(filename) + "</p></li>")
278     print("</ul>")
279
280     print_search_stats(len(hits), len(all_pages))
281
282 def handle_raw(pagename, form):
283     if not file_re.match(pagename):
284         send_httperror("403 Forbidden", pagename)
285         return
286
287     Page(pagename).send_raw()
288
289 def handle_edit(pagename, form):
290     if not file_re.match(pagename):
291         send_httperror("403 Forbidden", pagename)
292         return
293
294     pg = Page(form['q'].value)
295     if 'save' in form:
296         if form['file'].value:
297             pg.save(form['file'].file.read(), form['changelog'].value)
298         else:
299             pg.save(form['savetext'].value.replace('\r\n', '\n'), form['changelog'].value)
300         pg.format()
301     elif 'cancel' in form:
302         pg.msg_text = 'Editing canceled'
303         pg.msg_type = 'notice'
304         pg.format()
305     else: # preview or edit
306         text = None
307         if 'preview' in form:
308             text = form['savetext'].value
309         pg.send_editor(text)
310
311 def handle_get(pagename, form):
312         if file_re.match(pagename):
313             # FIMXE: this is all bullshit, MimeTypes bases its guess on the extension!
314             from mimetypes import MimeTypes
315             mimetype, encoding = MimeTypes().guess_type(pagename)
316             if mimetype:
317                 Page(pagename).send_raw(mimetype=mimetype, args=form)
318             else:
319                 Page(pagename).format()
320         else:
321             send_httperror("403 Forbidden", pagename)
322
323 # Used by macros/WordIndex and macros/TitleIndex
324 def make_index_key():
325     links = ['<a href="#%s">%s</a>' % (ch, ch) for ch in 'abcdefghijklmnopqrstuvwxyz']
326     return '<p style="text-align: center">' + ' | '.join(links) + '</p>'
327
328 def page_list(dirname = None, re = word_re):
329     return sorted(filter(re.match, os.listdir(dirname or data_dir)))
330
331 def send_footer(mod_string=None):
332     if globals().get('debug_cgi', False):
333         cgi.print_arguments()
334         cgi.print_form(form)
335         cgi.print_environ()
336     print('''
337 <div id="footer"><hr />
338 <p class="copyright">
339 <a rel="license" href="http://creativecommons.org/licenses/by-sa/3.0/"><img class="license" alt="Creative Commons License" src="%s" /></a>
340 <span class="benchmark">generated in %0.3fs</span> by <a href="http://www.codewiz.org/wiki/GeekiGeeki">GeekiGeeki</a> version %s
341 </p>
342 ''' % (relative_url('cc-by-sa.png'), clock() - start_time, __version__))
343     if mod_string:
344         print('<p class="modified">last modified %s</p>' % mod_string)
345     print('</div></body></html>')
346
347 class WikiFormatter:
348     """Object that turns Wiki markup into HTML.
349
350     All formatting commands can be parsed one line at a time, though
351     some state is carried over between lines.
352     """
353     def __init__(self, raw):
354         self.raw = raw
355         self.h_level = 0
356         self.in_pre = self.in_html = self.in_table = self.in_li = False
357         self.in_header = True
358         self.list_indents = []
359         self.tr_cnt = 0
360         self.styles = {
361             #wiki   html   enabled?
362             "//":  ["em",  False],
363             "**":  ["b",   False],
364             "##":  ["tt",  False],
365             "__":  ["u",   False],
366             "^^":  ["sup", False],
367             ",,":  ["sub", False],
368             "''":  ["em",  False], # LEGACY
369             "'''": ["b",   False], # LEGACY
370             "``":  ["tt",  False], # LEGACY
371         }
372
373     def _b_repl(self, word):
374         style = self.styles[word]
375         style[1] = not style[1]
376         return ['</', '<'][style[1]] + style[0] + '>'
377
378     def _tit_repl(self, word):
379         if self.h_level:
380             result = '</h%d><p>\n' % self.h_level
381             self.h_level = 0
382         else:
383             self.h_level = len(word) - 1
384             link = permalink(self.line)
385             result = '\n</p><h%d id="%s"><a class="heading" href="#%s">¶</a> ' % (self.h_level, link, link)
386         return result
387
388     def _br_repl(self, word):
389         return '<br />'
390
391     def _rule_repl(self, word):
392         return self._undent() + '\n<hr size="%d" noshade="noshade" />\n' % (len(word) - 2)
393
394     def _macro_repl(self, word):
395         try:
396             args, kwargs = parse_args(word)
397             macro = globals().get('_macro_' + args[0])
398             if not macro:
399                 exec(open("macros/" + name + ".py").read(), globals())
400                 macro = globals().get('_macro_' + name)
401             return macro(*args, **kwargs)
402         except Exception:
403             msg = cgi.escape(word)
404             if not self.in_html:
405                 msg = '<strong class="error">' + msg + '</strong>'
406             return msg
407
408     def _hurl_repl(self, word):
409         args, kvargs = parse_args(word)
410         return link_tag(*args, **kvargs)
411
412     def _inl_repl(self, word):
413         args, kvargs = parse_args(word)
414         name = args.pop(0)
415         if len(args):
416             descr = args.pop(0)
417             # The "extthumb" nonsense works around a limitation of the HTML block model
418             return '<div class="extthumb"><div class="thumb">' \
419                 + link_inline(name, descr, kvargs) \
420                 + '<div class="caption">' + descr + '</div></div></div>'
421         else:
422             return link_inline(name, None, kvargs)
423
424     def _html_repl(self, word):
425         if not self.in_html and word.startswith('<div'): word = '</p>' + word
426         self.in_html += 1
427         return word; # Pass through
428
429     def _htmle_repl(self, word):
430         self.in_html -= 1
431         if not self.in_html and word.startswith('</div'): word += '<p>'
432         return word; # Pass through
433
434     def _ent_repl(self, s):
435         if self.in_html:
436             return s; # Pass through
437         return {'&': '&amp;',
438                 '<': '&lt;',
439                 '>': '&gt;'}[s]
440
441     def _img_repl(self, word): # LEGACY
442         return self._inl_repl('{{' + word + '}}')
443
444     def _word_repl(self, word): # LEGACY
445         if self.in_html: return word # pass through
446         return link_tag(word)
447
448     def _url_repl(self, word): # LEGACY
449         if self.in_html: return word # pass through
450         return link_tag(word)
451
452     def _email_repl(self, word): # LEGACY
453         if self.in_html: return word # pass through
454         return '<a href="mailto:%s">%s</a>' % (word, word)
455
456     def _li_repl(self, match):
457         if self.in_li:
458             return '</li><li>'
459         else:
460             self.in_li = True
461             return '<li>'
462
463     def _pre_repl(self, word):
464         if word == '{{{' and not self.in_pre:
465             self.in_pre = True
466             return '<pre>'
467         elif self.in_pre:
468             self.in_pre = False
469             return '</pre>'
470         return ''
471
472     def _hi_repl(self, word):
473         return '<strong class="highlight ' + word + '">' + word + '</strong>'
474
475     def _tr_repl(self, word):
476         out = ''
477         if not self.in_table:
478             self.in_table = True
479             self.tr_cnt = 0
480             out = '</p><table><tbody>\n'
481         self.tr_cnt += 1
482         out = out + '<tr class="' + ['even', 'odd'][self.tr_cnt % 2] + '">'
483         return out + ['<td>', '<th>'][word.strip() == '||=']
484
485     def _td_repl(self, word):
486         if self.in_table:
487             return ['</td><td>', '</th><th>'][word.strip() == '||=']
488         return ''
489
490     def _tre_repl(self, word):
491         if self.in_table:
492             return ['</td></tr>', '</th></tr>'][word.strip() == '||=']
493         return ''
494
495     def _indent_level(self):
496         return len(self.list_indents) and self.list_indents[-1]
497
498     def _indent_to(self, new_level):
499         if self._indent_level() == new_level:
500             return ''
501         s = '</p>'
502         while self._indent_level() > new_level:
503             del(self.list_indents[-1])
504             if self.in_li:
505                 s += '</li>'
506                 self.in_li = False # FIXME
507             s += '</ul>\n'
508         while self._indent_level() < new_level:
509             self.list_indents.append(new_level)
510             s += '<ul>\n'
511         s += '<p>'
512         return s
513
514     def _undent(self):
515         res = '</p>'
516         res += '</ul>' * len(self.list_indents)
517         res += '<p>'
518         self.list_indents = []
519         return res
520
521     def replace(self, match):
522         for rule, hit in list(match.groupdict().items()):
523             if hit:
524                 return getattr(self, '_' + rule + '_repl')(hit)
525         else:
526             raise "Can't handle match " + repr(match)
527
528     def print_html(self):
529         print('<div class="wiki"><p>')
530
531         scan_re = re.compile(r"""(?:
532             # Styles and formatting
533               (?P<b>     \*\*|'''|//|''|\#\#|``|__|\^\^|,,)
534             | (?P<tit>   \={2,6})
535             | (?P<br>    \\\\)
536             | (?P<rule>  ^-{3,})
537             | (?P<hi>    \b( FIXME | TODO | DONE )\b )
538
539             # Links
540             | (?P<macro> \<\<([^\s\|\>]+)(?:\s*\|\s*([^\>]+)|)\>\>)
541             | (?P<hurl>  \[\[([^\s\|]+)(?:\s*\|\s*([^\]]+)|)\]\])
542
543             # Inline HTML
544             | (?P<html>  <(br|hr|div|span|form|iframe|input|textarea|a|img|h[1-5])\b )
545             | (?P<htmle> ( /\s*> | </(br|hr|div|span|form|iframe|input|textarea|a|img|h[1-5])> ) )
546             | (?P<ent>   [<>&] )
547
548             # Auto links (LEGACY)
549             | (?P<img>   \b[a-zA-Z0-9_/-]+\.(png|gif|jpg|jpeg|bmp|ico|ogm|ogg|mkv|mpg|mpeg|mp4|avi|asf|flv|wmv|qt))
550             | (?P<word>  \b(?:[A-Z][a-z]+){2,}\b)
551             | (?P<url>   (http|https|ftp|mailto)\:[^\s'\"]+\S)
552             | (?P<email> [-\w._+]+\@[\w.-]+)
553
554             # Lists, divs, spans
555             | (?P<li>    ^\s+[\*\#]\s+)
556             | (?P<pre>   \{\{\{|\s*\}\}\})
557             | (?P<inl>   \{\{([^\s\|]+)(?:\s*\|\s*([^\]]+)|)\}\})
558
559             # Tables
560             | (?P<tr>    ^\s*\|\|(=|)\s*)
561             | (?P<tre>   \s*\|\|(=|)\s*$)
562             | (?P<td>    \s*\|\|(=|)\s*)
563
564             # TODO: highlight search words (look at referrer)
565           )""", re.VERBOSE)
566         pre_re = re.compile("""(?:
567               (?P<pre>\s*\}\}\})
568             | (?P<ent>[<>&])"
569             )""", re.VERBOSE)
570         blank_re = re.compile(r"^\s*$")
571         indent_re = re.compile(r"^\s*")
572         tr_re = re.compile(r"^\s*\|\|")
573         eol_re = re.compile(r"\r?\n")
574         # For each line, we scan through looking for magic strings, outputting verbatim any intervening text
575         #3.0: for self.line in eol_re.split(str(self.raw.expandtabs(), 'utf-8')):
576         for self.line in eol_re.split(str(self.raw.expandtabs())):
577             # Skip pragmas
578             if self.in_header:
579                 if self.line.startswith('#'):
580                     continue
581                 self.in_header = False
582
583             if self.in_pre:
584                 print(re.sub(pre_re, self.replace, self.line))
585             else:
586                 if self.in_table and not tr_re.match(self.line):
587                     self.in_table = False
588                     print('</tbody></table><p>')
589
590                 if blank_re.match(self.line):
591                     print('</p><p>')
592                 else:
593                     indent = indent_re.match(self.line)
594                     #3.0: print(self._indent_to(len(indent.group(0))), end=' ')
595                     print(self._indent_to(len(indent.group(0))))
596                     print(re.sub(scan_re, self.replace, self.line))
597
598         if self.in_pre: print('</pre>')
599         if self.in_table: print('</tbody></table><p>')
600         print(self._undent())
601         print('</p></div>')
602
603 class Page:
604     def __init__(self, page_name):
605         self.page_name = page_name
606         self.msg_text = ''
607         self.msg_type = 'error'
608
609     def split_title(self):
610         # look for the end of words and the start of a new word and insert a space there
611         return re.sub('([a-z])([A-Z])', r'\1 \2', self.page_name)
612
613     def _filename(self):
614         return os.path.join(data_dir, self.page_name)
615
616     def _tmp_filename(self):
617         return os.path.join(data_dir, ('#' + self.page_name.replace('/','_') + '.' + str(os.getpid()) + '#'))
618
619     def exists(self):
620         try:
621             os.stat(self._filename())
622             return True
623         except OSError as err:
624             if err.errno == errno.ENOENT:
625                 return False
626             raise err
627
628     def get_raw_body(self, default=None):
629         try:
630             return open(self._filename(), 'rb').read()
631         except IOError as err:
632             if err.errno == errno.ENOENT:
633                 if default is None:
634                     default = '//[[%s|Describe %s|action=edit]]//' % (self.page_name, self.page_name)
635                 return default
636             if err.errno == errno.EISDIR:
637                 return self.format_dir()
638             raise err
639
640     def format_dir(self):
641         out = '== '
642         pathname = ''
643         for dirname in self.page_name.split('/'):
644             pathname = (pathname + '/' + dirname) if pathname else dirname
645             out += '[[' + pathname + '|' + dirname + ']]/'
646         out += ' ==\n'
647  
648         for filename in page_list(self._filename(), file_re):
649             if img_re.match(filename):
650                 if image_maxwidth:
651                     maxwidth_arg = '|maxwidth=' + str(image_maxwidth)
652                 out += '{{' + self.page_name + '/' + filename + '|' + filename + maxwidth_arg + '}}\n'
653             else:
654                 out += ' * [[' + self.page_name + '/' + filename + ']]\n'
655         return out
656
657     def pragmas(self):
658         if not '_pragmas' in self.__dict__:
659             self._pragmas = {}
660             try:
661                 file = open(self._filename(), 'rt')
662                 attr_re = re.compile(r"^#(\S*)(.*)$")
663                 for line in file:
664                     m = attr_re.match(line)
665                     if not m:
666                         break
667                     self._pragmas[m.group(1)] = m.group(2).strip()
668                     #print "bernie: pragmas[" + m.group(1) + "] = " + m.group(2) + "<br>\n"
669             except IOError as err:
670                 if err.errno != errno.ENOENT and err.errno != errno.EISDIR:
671                     raise er
672         return self._pragmas
673
674     def pragma(self, name, default):
675         return self.pragmas().get(name, default)
676
677     def can(self, action, default=True):
678         acl = None
679         try:
680             #acl SomeUser:read,write All:read
681             acl = self.pragma("acl", None)
682             for rule in acl.split():
683                 (user, perms) = rule.split(':')
684                 if user == remote_user() or user == "All":
685                     return action in perms.split(',')
686             return False
687         except Exception:
688             if acl:
689                 self.msg_text = 'Illegal acl line: ' + acl
690         return default
691
692     def can_write(self):
693         return self.can("write", True)
694
695     def can_read(self):
696         return self.can("read", True)
697
698     def send_naked(self):
699         if self.can_read():
700             WikiFormatter(self.get_raw_body()).print_html()
701         else:
702             send_guru("Read access denied by ACLs", "notice")
703
704     def format(self):
705         #css foo.css
706         value = self.pragma("css", None)
707         if value:
708             global link_urls
709             link_urls += [ [ "stylesheet", value ] ]
710
711         send_title(self.page_name, self.split_title(),
712             msg_text=self.msg_text, msg_type=self.msg_type, writable=self.can_write())
713         self.send_naked()
714         send_footer(self._last_modified())
715
716     def _last_modified(self):
717         try:
718             from time import localtime, strftime
719             modtime = localtime(os.stat(self._filename())[stat.ST_MTIME])
720         except OSError as err:
721             if err.errno != errno.ENOENT:
722                 raise err
723             return None
724         return strftime(datetime_fmt, modtime)
725
726     def send_editor(self, preview=None):
727         send_title(None, 'Edit ' + self.split_title(), msg_text=self.msg_text, msg_type=self.msg_type)
728         if not self.can_write():
729             send_guru("Write access denied by ACLs", "error")
730             return
731
732         filename = ''
733         if 'file' in form:
734             filename = form['file'].value
735
736         print(('<p><b>Editing ' + self.page_name
737             + ' for ' + cgi.escape(remote_user())
738             + ' from ' + cgi.escape(get_hostname(remote_host()))
739             + '</b></p>'))
740         print('<div class="editor"><form name="editform" method="post" enctype="multipart/form-data" action="%s">' % relative_url(self.page_name))
741         print('<input type="hidden" name="edit" value="%s">' % (self.page_name))
742         print('<input type="input" id="editor" name="changelog" value="Edit page %s" accesskey="c" /><br />' % (self.page_name))
743         print('<textarea wrap="off" spellcheck="true" id="editor" name="savetext" rows="17" cols="100" accesskey="e">%s</textarea>' \
744             % cgi.escape(preview or self.get_raw_body(default='')))
745         print('<label for="file" accesskey="u">Or Upload a file:</label> <input type="file" name="file" value="%s" />' % filename)
746         print("""
747             <br />
748             <input type="submit" name="save" value="Save" accesskey="s">
749             <input type="submit" name="preview" value="Preview" accesskey="p" />
750             <input type="reset" value="Reset" />
751             <input type="submit" name="cancel" value="Cancel" />
752             <br />
753             </form></div>
754             <script language="javascript">
755             <!--
756             document.editform.savetext.focus()
757             //-->
758             </script>
759             """)
760         print("<p>" + link_tag('EditingTips') + "</p>")
761         if preview:
762             print("<div class='preview'>")
763             WikiFormatter(preview).print_html()
764             print("</div>")
765         send_footer()
766
767     def send_raw(self, mimetype='text/plain', args=[]):
768         if not self.can_read():
769             send_title(None, msg_text='Read access denied by ACLs', msg_type='notice')
770             return
771
772         if 'maxwidth' in args:
773             import subprocess
774             emit_header(mimetype)
775             sys.stdout.flush()
776             subprocess.check_call(['gm', 'convert', self._filename(),
777                 '-scale', args['maxwidth'].value + ' >', '-'])
778         else:
779             body = self.get_raw_body()
780             emit_header(mimetype)
781             print(body)
782
783     def _write_file(self, data):
784         tmp_filename = self._tmp_filename()
785         open(tmp_filename, 'wb').write(data)
786         name = self._filename()
787         if os.name == 'nt':
788             # Bad Bill!  POSIX rename ought to replace. :-(
789             try:
790                 os.remove(name)
791             except OSError as err:
792                 if err.errno != errno.ENOENT: raise err
793         os.rename(tmp_filename, name)
794
795     def save(self, newdata, changelog):
796         if not self.can_write():
797             self.msg_text = 'Write access denied by ACLs'
798             self.msg_type = 'error'
799             return
800
801         self._write_file(newdata)
802         rc = 0
803         if post_edit_hook:
804             import subprocess
805             cmd = [ post_edit_hook, data_dir + '/' + self.page_name, remote_user(), remote_host(), changelog]
806             child = subprocess.Popen(cmd, stdout=subprocess.PIPE, close_fds=True)
807             output = child.stdout.read()
808             rc = child.wait()
809         if rc:
810             self.msg_text += "Post-editing hook returned %d. Command was:\n'%s'\n" % (rc, "' '".join(cmd))
811             if output:
812                 self.msg_text += 'Output follows:\n' + output
813         else:
814             self.msg_text = 'Thank you for your contribution.  Your attention to detail is appreciated.'
815             self.msg_type = 'success'
816
817 try:
818     exec(open("geekigeeki.conf.py").read())
819     form = cgi.FieldStorage()
820     action = form.getvalue('a', 'get')
821     handler = globals().get('handle_' + action)
822     if handler:
823         handler(query_string(), form)
824     else:
825         send_httperror("403 Forbidden", query_string())
826
827 except Exception:
828     import traceback
829     msg_text = traceback.format_exc()
830     if title_done:
831         send_guru(msg_text, "error")
832     else:
833         send_title(None, msg_text=msg_text)
834     send_footer()
835
836 sys.stdout.flush()