Separate images from subdirs in directory listing
[geekigeeki.git] / geekigeeki.py
1 #!/usr/bin/python
2 # -*- coding: utf-8 -*-
3 #
4 # Copyright (C) 1999, 2000 Martin Pool <mbp@humbug.org.au>
5 # Copyright (C) 2002 Gerardo Poggiali
6 # Copyright (C) 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 Affero General Public License as
10 # published by the Free Software Foundation, either version 3 of the
11 # License, or (at your option) any later version.
12 # You should have received a copy of the GNU Affero General Public License
13 # along with this program.  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 #TODO: move post-edit hook into wiki, then kill this
40 def script_path():
41     return os.path.split(os.environ.get('SCRIPT_FILENAME', ''))[0]
42
43 def query_string():
44     path_info = os.environ.get('PATH_INFO', '')
45     if len(path_info) and path_info[0] == '/':
46         return path_info[1:] or 'FrontPage'
47     else:
48         return os.environ.get('QUERY_STRING', '') or 'FrontPage'
49
50 def is_privileged():
51     purl = config_get('privileged_url')
52     return (purl is not None) and os.environ.get('SCRIPT_URI', '').startswith(purl)
53
54 def remote_user():
55     user = os.environ.get('REMOTE_USER', '')
56     if user is None or user == '' or user == 'anonymous':
57         user = 'AnonymousCoward'
58     return user
59
60 def remote_host():
61     return os.environ.get('REMOTE_ADDR', '')
62
63 def get_hostname(addr):
64     try:
65         from socket import gethostbyaddr
66         return gethostbyaddr(addr)[0] + ' (' + addr + ')'
67     except Exception:
68         return addr
69
70 def is_external_url(pathname):
71     return (url_re.match(pathname) or pathname.startswith('/'))
72
73 def relative_url(pathname, privileged=False):
74     if not is_external_url(pathname):
75         if privileged:
76             url = config_get('privileged_url') or script_name()
77         else:
78             url = script_name()
79         pathname = url + '/' + pathname
80     return cgi.escape(pathname, quote=True)
81
82 def permalink(s):
83     return re.sub(' ', '-', re.sub('[^a-z0-9_ ]', '', s.lower()).strip())
84
85 def humanlink(s):
86     return re.sub(r'(?:.*[/:]|)([^:/\.]+)(?:\.[^/:]+|)$', r'\1', s.replace('_', ' '))
87
88 # Split arg lists like "blah|blah blah| width=100 | align = center",
89 # return a list containing anonymous arguments and a map containing the named arguments
90 def parse_args(s):
91     args = []
92     kvargs = {}
93     for arg in s.strip('<[{}]>').split('|'):
94         m = re.match('\s*(\w+)\s*=\s*(.+)\s*', arg)
95         if m is not None:
96             kvargs[m.group(1)] = m.group(2)
97         else:
98             args.append(arg.strip())
99     return (args, kvargs)
100
101 def url_args(kvargs):
102     argv = []
103     for k, v in kvargs.items():
104         argv.append(k + '=' + v)
105     if argv:
106         return '?' + '&amp;'.join(argv)
107     return ''
108
109 # Formatting stuff --------------------------------------------------
110 def emit_header(mtime=None, mime_type="text/html"):
111     if mtime:
112         print("Last-Modified: " + strftime("%a, %d %b %Y %H:%M:%S GMT", gmtime(mtime)))
113     print("Content-type: " + mime_type + "; charset=utf-8\n")
114
115 def send_guru(msg_text, msg_type):
116     if not msg_text: return
117     print('<pre id="guru" onclick="this.style.display = \'none\'" class="' + msg_type + '">')
118     if msg_type == 'error':
119         print('    Software Failure.  Press left mouse button to continue.\n')
120     print(cgi.escape(msg_text))
121     if msg_type == 'error':
122         print '\n           Guru Meditation #DEADBEEF.ABADC0DE'
123     print('</pre><script type="text/javascript" src="%s" defer="defer"></script>' \
124         % relative_url('sys/GuruMeditation.js'))
125
126 def send_title(name, text="Limbo", msg_text=None, msg_type='error', writable=False, mtime=None):
127     global title_done
128     if title_done: return
129
130     # HEAD
131     emit_header(mtime)
132     print('<!doctype html>\n<html lang="en">')
133     print("<head><title>%s: %s</title>" % (config_get('site_name', "Unconfigured Wiki"), text))
134     print(' <meta charset="UTF-8">')
135     if not name:
136         print(' <meta name="robots" content="noindex,nofollow" />')
137
138     for http_equiv, content in config_get('meta_urls', {}):
139         print(' <meta http-equiv="%s" content="%s" />' % (http_equiv, relative_url(content)))
140
141     for link in config_get('link_urls', {}):
142         rel, href = link
143         print(' <link rel="%s" href="%s" />' % (rel, relative_url(href)))
144
145     editable = name and writable and is_privileged()
146     if editable:
147         print(' <link rel="alternate" type="application/x-wiki" title="Edit this page" href="%s" />' \
148             % relative_url('?a=edit&q=' + name, privileged=True))
149
150     history = config_get('history_url')
151     if history is not None:
152         print(' <link rel="alternate" type="application/rss+xml" title="RSS" href="%s" />' \
153             % relative_url(history + '?a=rss'))
154
155     print('</head>')
156
157     # BODY
158     if editable:
159         print('<body ondblclick="location.href=\'' + relative_url('?a=edit&q=' + name, privileged=True) + '\'">')
160     else:
161         print('<body>')
162
163     title_done = True
164     send_guru(msg_text, msg_type)
165
166     # NAVBAR
167     print('<nav><div class="nav">')
168     print link_tag('FrontPage', config_get('site_icon', 'Home'), cssclass='navlink')
169     if name:
170         print('  <b>' + link_tag('?fullsearch=' + name, text, cssclass='navlink') + '</b> ')
171     else:
172         print('  <b>' + text + '</b> ')
173     print(' | ' + link_tag('FindPage', 'Find Page', cssclass='navlink'))
174     if history:
175         print(' | <a href="' + relative_url(history) + '" class="navlink">Recent Changes</a>')
176         if name:
177             print(' | <a href="' + relative_url(history + '?a=history;f=' + name) + '" class="navlink">Page History</a>')
178
179     if name:
180         print(' | ' + link_tag(name + '?a=raw', 'Raw Text', cssclass='navlink'))
181         if config_get('privileged_url') is not None:
182             if writable:
183                 print(' | ' + link_tag('?a=edit&q=' + name, 'Edit', cssclass='navlink', privileged=True))
184             else:
185                 print(' | ' + link_tag(name, 'Login', cssclass='navlink', privileged=True))
186
187     else:
188         print(' | <i>Immutable Page</i>')
189
190     user = remote_user()
191     if user != 'AnonymousCoward':
192         print(' | <span class="login"><i><b>' + link_tag('User/' + user, user) + '</b></i></span>')
193
194     print('<hr /></div></nav>')
195
196 def send_httperror(status="403 Not Found", query=""):
197     print("Status: %s" % status)
198     send_title(None, msg_text=("%s: on query '%s'" % (status, query)))
199     send_footer()
200
201 def link_tag(dest, text=None, privileged=False, **kvargs):
202     if text is None:
203         text = humanlink(dest)
204     elif image_re.match(text):
205         text = '<img style="border: 0" src="' + relative_url(text) + '" alt="' + text + '" />'
206
207     link_class = kvargs.get('class', kvargs.get('cssclass', None))
208     if not link_class:
209         if is_external_url(dest):
210             link_class = 'external'
211         elif file_re.match(dest) and Page(dest).exists():
212             link_class = 'wikilink'
213         else:
214             text = config_get('nonexist_pfx', '') + text
215             link_class = 'nonexistent'
216
217     # Prevent crawlers from following links potentially added by spammers or to generated pages
218     nofollow = ''
219     if link_class == 'external' or link_class == 'navlink':
220         nofollow = 'rel="nofollow" '
221
222     return '<a class="%s" %shref="%s">%s</a>' % (link_class, nofollow, relative_url(dest, privileged=privileged), text)
223
224 def link_inline(name, descr=None, kvargs={}):
225     if not descr: descr = humanlink(name)
226     url = relative_url(name)
227     if video_re.match(name):
228         return '<video controls="1" src="%s">Your browser does not support HTML5 video</video>' % url
229     elif image_re.match(name):
230         return '<a href="%s"><img border="0" src="%s" alt="%s" /></a>' % (url, url + url_args(kvargs), descr)
231     elif file_re.match(name) and not ext_re.search(name): # FIXME: this guesses a wiki page
232         Page(name).send_naked(kvargs) # FIXME: we should return the page as a string rather than print it
233         return ''
234     else:
235         return '<iframe width="100%%" scrolling="auto" frameborder="0" src="%s"><a href="%s">%s</a></iframe>' \
236             % (url, url, name)
237
238 def link_inline_glob(pattern, descr=None, kvargs={}):
239     if not url_re.match(pattern) and bool(set(pattern) & set('?*[')):
240         s = ''
241         for name in glob.glob(pattern):
242             s += link_inline(name, descr, kvargs)
243         return s
244     else:
245         return link_inline(pattern, descr, kvargs)
246
247 # Search ---------------------------------------------------
248
249 def print_search_stats(hits, searched):
250     print("<p>%d hits out of %d pages searched.</p>" % (hits, searched))
251
252 def handle_fullsearch(query, form):
253     needle = form['q'].value
254     send_title(None, 'Full text search for "' + needle + '"')
255
256     needle_re = re.compile(needle, re.IGNORECASE)
257     hits = []
258     all_pages = page_list()
259     for page_name in all_pages:
260         body = Page(page_name).get_raw_body()
261         count = len(needle_re.findall(body))
262         if count:
263             hits.append((count, page_name))
264
265     # The default comparison for tuples compares elements in order,
266     # so this sorts by number of hits
267     hits.sort()
268     hits.reverse()
269
270     print("<ul>")
271     for (count, page_name) in hits:
272         print('<li><p>' + link_tag(page_name))
273         print(' . . . . ' + `count`)
274         print(['match', 'matches'][count != 1])
275         print('</p></li>')
276     print("</ul>")
277
278     print_search_stats(len(hits), len(all_pages))
279
280 def handle_titlesearch(query, form):
281     needle = form['q'].value
282     send_title(None, 'Title search for "' + needle + '"')
283
284     needle_re = re.compile(needle, re.IGNORECASE)
285     all_pages = page_list()
286     hits = list(filter(needle_re.search, all_pages))
287
288     print("<ul>")
289     for filename in hits:
290         print('<li><p>' + link_tag(filename) + "</p></li>")
291     print("</ul>")
292
293     print_search_stats(len(hits), len(all_pages))
294
295 def handle_raw(pagename, form):
296     if not file_re.match(pagename):
297         send_httperror("403 Forbidden", pagename)
298         return
299
300     Page(pagename).send_raw()
301
302 def handle_edit(pagename, form):
303     if not file_re.match(pagename):
304         send_httperror("403 Forbidden", pagename)
305         return
306
307     pg = Page(form['q'].value)
308     if 'save' in form:
309         if form['file'].value:
310             pg.save(form['file'].file.read(), form['changelog'].value)
311         else:
312             pg.save(form['savetext'].value.replace('\r\n', '\n'), form['changelog'].value)
313         pg.format()
314     elif 'cancel' in form:
315         pg.msg_text = 'Editing canceled'
316         pg.msg_type = 'notice'
317         pg.format()
318     else: # preview or edit
319         text = None
320         if 'preview' in form:
321             text = form['savetext'].value
322         pg.send_editor(text)
323
324 def handle_get(pagename, form):
325         if file_re.match(pagename):
326             # FIMXE: this is all bullshit, MimeTypes bases its guess on the extension!
327             from mimetypes import MimeTypes
328             mimetype, encoding = MimeTypes().guess_type(pagename)
329             if mimetype:
330                 Page(pagename).send_raw(mimetype=mimetype, args=form)
331             else:
332                 Page(pagename).format()
333         else:
334             send_httperror("403 Forbidden", pagename)
335
336 # Used by sys/macros/WordIndex and sys/macros/TitleIndex
337 def make_index_key():
338     links = ['<a href="#%s">%s</a>' % (ch, ch) for ch in 'abcdefghijklmnopqrstuvwxyz']
339     return '<p style="text-align: center">' + ' | '.join(links) + '</p>'
340
341 def page_list(dirname=None, search_re=None):
342     if search_re is None:
343         # FIXME: WikiWord is too restrictive now!
344         search_re = re.compile(r"^\b((([A-Z][a-z0-9]+){2,}/)*([A-Z][a-z0-9]+){2,})\b$")
345     return sorted(filter(search_re.match, os.listdir(dirname or '.')))
346
347 def send_footer(mtime=None):
348     if config_get('debug_cgi', False):
349         cgi.print_arguments()
350         cgi.print_form(form)
351         cgi.print_environ()
352     link_inline("sys/footer", kvargs = {
353         'LAST_MODIFIED': strftime(config_get('datetime_fmt', '%a %d %b %Y %I:%M %p'), localtime(mtime))
354     })
355     print("</body></html>")
356
357 def _macro_ELAPSED_TIME(*args, **kvargs):
358     return "%03f" % (clock() - start_time)
359
360 def _macro_VERSION(*args, **kvargs):
361     return __version__
362
363 class WikiFormatter:
364     """Object that turns Wiki markup into HTML.
365
366     All formatting commands can be parsed one line at a time, though
367     some state is carried over between lines.
368     """
369     def __init__(self, raw, kvargs=None):
370         self.raw = raw
371         self.kvargs = kvargs or {}
372         self.h_level = 0
373         self.in_pre = self.in_html = self.in_table = self.in_li = False
374         self.in_header = True
375         self.list_indents = [] # a list of pairs (indent_level, list_type) to track nested lists
376         self.tr_cnt = 0
377         self.styles = {
378             #wiki   html   enabled?
379             "//":  ["em",  False],
380             "**":  ["b",   False],
381             "##":  ["tt",  False],
382             "__":  ["u",   False],
383             "--":  ["del", False],
384             "^^":  ["sup", False],
385             ",,":  ["sub", False],
386             "''":  ["em",  False], # LEGACY
387             "'''": ["b",   False], # LEGACY
388         }
389
390     def _b_repl(self, word):
391         style = self.styles[word]
392         style[1] = not style[1]
393         return ['</', '<'][style[1]] + style[0] + '>'
394
395     def _glyph_repl(self, word):
396         return '&mdash;'
397
398     def _tit_repl(self, word):
399         if self.h_level:
400             result = '</h%d><p>\n' % self.h_level
401             self.h_level = 0
402         else:
403             self.h_level = len(word) - 1
404             link = permalink(self.line)
405             result = '\n</p><h%d id="%s"><a class="heading" href="#%s">¶</a> ' % (self.h_level, link, link)
406         return result
407
408     def _br_repl(self, word):
409         return '<br />'
410
411     def _rule_repl(self, word):
412         return '\n<hr size="%d" noshade="noshade" />\n' % (len(word) - 2)
413
414     def _macro_repl(self, word):
415         try:
416             args, kvargs = parse_args(word)
417             if args[0] in self.kvargs:
418                 return self.kvargs[args[0]]
419             macro = globals().get('_macro_' + args[0])
420             if not macro:
421                 exec(open("sys/macros/" + args[0] + ".py").read(), globals())
422                 macro = globals().get('_macro_' + args[0])
423             return macro(*args, **kvargs)
424         except Exception, e:
425             msg = cgi.escape(word) + ": " + cgi.escape(str(e))
426             if not self.in_html:
427                 msg = '<strong class="error">' + msg + '</strong>'
428             return msg
429
430     def _hurl_repl(self, word):
431         args, kvargs = parse_args(word)
432         return link_tag(*args, **kvargs)
433
434     def _inl_repl(self, word):
435         args, kvargs = parse_args(word)
436         name = args.pop(0)
437         if len(args):
438             descr = args.pop(0)
439             # This double div nonsense works around a limitation of the HTML block model
440             return '<div class="' + kvargs.get('class', 'thumb') + '">' \
441                 + '<div class="innerthumb">' \
442                 + link_inline_glob(name, descr, kvargs) \
443                 + '<div class="caption">' + descr + '</div></div></div>'
444         else:
445             return link_inline_glob(name, None, kvargs)
446
447     def _html_repl(self, word):
448         if not self.in_html and word.startswith('<div'): word = '</p>' + word
449         self.in_html += 1
450         return word; # Pass through
451
452     def _htmle_repl(self, word):
453         self.in_html -= 1
454         if not self.in_html and word.startswith('</div'): word += '<p>'
455         return word; # Pass through
456
457     def _ent_repl(self, s):
458         if self.in_html:
459             return s; # Pass through
460         return {'&': '&amp;',
461                 '<': '&lt;',
462                 '>': '&gt;'}[s]
463
464     def _img_repl(self, word): # LEGACY
465         return self._inl_repl('{{' + word + '}}')
466
467     def _word_repl(self, word): # LEGACY
468         if self.in_html: return word # pass through
469         return link_tag(word)
470
471     def _url_repl(self, word): # LEGACY
472         if self.in_html: return word # pass through
473         return link_tag(word)
474
475     def _email_repl(self, word): # LEGACY
476         if self.in_html: return word # pass through
477         return '<a href="mailto:%s">%s</a>' % (word, word)
478
479     def _li_repl(self, match):
480         if self.in_li:
481             return '</li><li>'
482         else:
483             self.in_li = True
484             return '<li>'
485
486     def _pre_repl(self, word):
487         if word == '{{{' and not self.in_pre:
488             self.in_pre = True
489             return '<pre>'
490         elif self.in_pre:
491             self.in_pre = False
492             return '</pre>'
493         return ''
494
495     def _hi_repl(self, word):
496         return '<strong class="highlight ' + word + '">' + word + '</strong>'
497
498     def _tr_repl(self, word):
499         out = ''
500         if not self.in_table:
501             self.in_table = True
502             self.tr_cnt = 0
503             out = '</p><table><tbody>\n'
504         self.tr_cnt += 1
505         out = out + '<tr class="' + ['even', 'odd'][self.tr_cnt % 2] + '">'
506         return out + ['<td>', '<th>'][word.strip() == '||=']
507
508     def _td_repl(self, word):
509         if self.in_table:
510             return ['</td><td>', '</th><th>'][word.strip() == '||=']
511         return ''
512
513     def _tre_repl(self, word):
514         if self.in_table:
515             return ['</td></tr>', '</th></tr>'][word.strip() == '||=']
516         return ''
517
518     def _indent_level(self):
519         return len(self.list_indents) and self.list_indents[-1][0]
520
521     def _indent_to(self, new_level, list_type=''):
522         if self._indent_level() == new_level:
523             return ''
524         s = '</p>'
525         while self._indent_level() > new_level:
526             if self.in_li:
527                 s += '</li>'
528                 self.in_li = False # FIXME
529             s += '</' + self.list_indents[-1][1] + '>\n'
530             del(self.list_indents[-1])
531
532         list_type = ('ul', 'ol')[list_type == '#']
533         while self._indent_level() < new_level:
534             self.list_indents.append((new_level, list_type))
535             s += '<' + list_type + '>\n'
536         s += '<p>'
537         return s
538
539     def replace(self, match):
540         for rule, hit in list(match.groupdict().items()):
541             if hit:
542                 return getattr(self, '_' + rule + '_repl')(hit)
543         else:
544             raise Exception("Can't handle match " + repr(match))
545
546     def print_html(self):
547         print('<div class="wiki"><p>')
548
549         scan_re = re.compile(r"""(?:
550             # Styles and formatting ("--" must cling to a word to disambiguate it from the dash)
551               (?P<b>     \*\* | // | \#\# | __ | --\b | \b-- | \^\^ | ,, | ''' | '' )
552             | (?P<tit>   \={2,6})
553             | (?P<br>    \\\\)
554             | (?P<rule>  ^-{3,})
555             | (?P<hi>    \b( FIXME | TODO | DONE )\b )
556             | (?P<glyph> --)
557
558             # Links
559             | (?P<macro> \<\<([^\s\|\>]+)(?:\s*\|\s*([^\>]+)|)\>\>)
560             | (?P<hurl>  \[\[([^\s\|]+)(?:\s*\|\s*([^\]]+)|)\]\])
561
562             # Inline HTML
563             | (?P<html>             <(br|hr|div|span|form|iframe|input|textarea|a|img|h[1-5])\b )
564             | (?P<htmle> ( /\s*> | </(br|hr|div|span|form|iframe|input|textarea|a|img|h[1-5])> ) )
565             | (?P<ent>   [<>&] )
566
567             # Auto links (LEGACY)
568             | (?P<img>   \b[a-zA-Z0-9_/-]+\.(""" + image_ext + "|" + video_ext + r"""))
569             | (?P<word>  \b(?:[A-Z][a-z]+){2,}\b)
570             | (?P<url>   (http|https|ftp|mailto)\:[^\s'\"]+\S)
571             | (?P<email> [-\w._+]+\@[\w.-]+)
572
573             # Lists, divs, spans and inline objects
574             | (?P<li>    ^\s+[\*\#]\s+)
575             | (?P<pre>   \{\{\{|\s*\}\}\})
576             | (?P<inl>   \{\{([^\s\|]+)(?:\s*\|\s*([^\]]+)|)\}\})
577
578             # Tables
579             | (?P<tr>    ^\s*\|\|(=|)\s*)
580             | (?P<tre>   \s*\|\|(=|)\s*$)
581             | (?P<td>    \s*\|\|(=|)\s*)
582
583             # TODO: highlight search words (look at referrer)
584           )""", re.VERBOSE)
585         pre_re = re.compile("""(?:
586               (?P<pre>\s*\}\}\})
587             | (?P<ent>[<>&])"
588             )""", re.VERBOSE)
589         blank_re = re.compile(r"^\s*$")
590         indent_re = re.compile(r"^(\s*)(\*|\#|)")
591         tr_re = re.compile(r"^\s*\|\|")
592         eol_re = re.compile(r"\r?\n")
593         # For each line, we scan through looking for magic strings, outputting verbatim any intervening text
594         #3.0: for self.line in eol_re.split(str(self.raw.expandtabs(), 'utf-8')):
595         for self.line in eol_re.split(str(self.raw.expandtabs())):
596             # Skip pragmas
597             if self.in_header:
598                 if self.line.startswith('#'):
599                     continue
600                 self.in_header = False
601
602             if self.in_pre:
603                 print(re.sub(pre_re, self.replace, self.line))
604             else:
605                 if self.in_table and not tr_re.match(self.line):
606                     self.in_table = False
607                     print('</tbody></table><p>')
608
609                 if blank_re.match(self.line):
610                     print('</p><p>')
611                 else:
612                     indent = indent_re.match(self.line)
613                     print(self._indent_to(len(indent.group(1)), indent.group(2)))
614                     # Stand back! Here we apply the monster regex that does all the parsing
615                     print(re.sub(scan_re, self.replace, self.line))
616
617         if self.in_pre: print('</pre>')
618         if self.in_table: print('</tbody></table><p>')
619         print(self._indent_to(0))
620         print('</p></div>')
621
622 class Page:
623     def __init__(self, page_name):
624         self.page_name = page_name.rstrip('/');
625         self.msg_text = ''
626         self.msg_type = 'error'
627
628     def split_title(self):
629         # look for the end of words and the start of a new word and insert a space there
630         return re.sub('([a-z])([A-Z])', r'\1 \2', self.page_name)
631
632     def _filename(self):
633         return self.page_name
634
635     def _tmp_filename(self):
636         return self.page_name + '.tmp' + str(os.getpid()) + '#'
637
638     def _mtime(self):
639         try:
640             return os.stat(self._filename()).st_mtime
641         except OSError, err:
642             if err.errno == errno.ENOENT:
643                 return None
644             raise err
645
646     def exists(self):
647         if self._mtime():
648             return True
649         return False
650
651     def get_raw_body(self, default=None):
652         try:
653             return open(self._filename(), 'rb').read()
654         except IOError, err:
655             if err.errno == errno.ENOENT:
656                 if default is None:
657                     default = '//[[?a=edit&q=%s|Describe %s]]//' % (self.page_name, self.page_name)
658                 return default
659             if err.errno == errno.EISDIR:
660                 return self.format_dir()
661             raise err
662
663     def format_dir(self):
664         out = '== '
665         pathname = ''
666         for dirname in self.page_name.strip('/').split('/'):
667             pathname = (pathname and pathname + '/' ) + dirname
668             out += '[[' + pathname + '|' + dirname + ']]/'
669         out += ' ==\n'
670         images_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                 images_out += '{{' + self.page_name + '/' + filename + ' | ' + humanlink(filename) + maxwidth + ' | class=thumbleft}}\n'
678             else:
679                 out += ' * [[' + self.page_name + '/' + filename + ']]\n'
680         return out + images_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 err
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 Access Control List'
794             return
795         if not is_privileged():
796             self.msg_text = 'Unauthenticated access denied'
797             return
798
799         self._write_file(newdata)
800         rc = 0
801         if config_get('post_edit_hook'):
802             import subprocess
803             cmd = [
804                 config_get('post_edit_hook'),
805                 self.page_name, remote_user(),
806                 remote_host(), changelog ]
807             child = subprocess.Popen(cmd, stdout=subprocess.PIPE, close_fds=True)
808             output = child.stdout.read()
809             rc = child.wait()
810         if rc:
811             self.msg_text += "Post-editing hook returned %d. Command was:\n'%s'\n" % (rc, "' '".join(cmd))
812             if output:
813                 self.msg_text += 'Output follows:\n' + output
814         else:
815             self.msg_text = 'Thank you for your contribution.  Your attention to detail is appreciated.'
816             self.msg_type = 'success'
817
818 try:
819     exec(open("geekigeeki.conf.py").read())
820     os.chdir(config_get('data_dir', 'data'))
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()