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