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