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