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