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