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