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