3 # Copyright 1999, 2000 Martin Pool <mbp@humbug.org.au>
4 # Copyright 2002 Gerardo Poggiali
5 # Copyright 2007 Bernardo Innocenti
7 # This program is free software: you can redistribute it and/or modify
8 # it under the terms of the GNU General Public License as published by
9 # the Free Software Foundation, either version 3 of the License, or
10 # (at your option) any later version.
12 # This program is distributed in the hope that it will be useful, but
13 # WITHOUT ANY WARRANTY; without even the implied warranty of
14 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15 # General Public License for more details.
17 # You should have received a copy of the GNU General Public License
18 # along with this program. If not, see <http://www.gnu.org/licenses/>.
20 __version__ = '$Id$'[4:12]
22 from time import clock
25 import cgi, sys, string, os, re, errno, stat
26 from os import path, environ
28 # Regular expression defining a WikiWord
29 # (but this definition is also assumed in other places)
30 file_re = re.compile(r"^\b([A-Za-z0-9_\.\-]+)\b$")
31 word_re = re.compile(r"^\b([A-Z][a-z]+){2,}\b$")
32 img_re = re.compile(r"^.*\.(png|gif|jpg|jpeg)$", re.IGNORECASE)
33 url_re = re.compile(r"^[a-z]{3,8}://[^\s'\"]+\S$")
38 # CGI stuff ---------------------------------------------------------
41 return environ.get('SCRIPT_NAME', '')
43 def privileged_path():
44 return privileged_url or script_name()
47 user = environ.get('REMOTE_USER', '')
48 if user is None or user == '' or user == 'anonymous':
49 user = 'AnonymousCoward'
53 return environ.get('REMOTE_ADDR', '')
55 def get_hostname(addr):
57 from socket import gethostbyaddr
58 return gethostbyaddr(addr)[0] + ' (' + addr + ')'
62 # Formatting stuff --------------------------------------------------
64 def emit_header(type="text/html"):
65 print "Content-type: " + type + "; charset=utf-8"
68 def send_guru(msg, msg_type):
69 if msg is None or msg == '': return
70 print '<pre id="guru" onclick="this.style.display = \'none\'" class="' + msg_type + '">'
71 if msg_type == 'error':
72 print ' Software Failure. Press left mouse button to continue.\n'
74 if msg_type == 'error':
75 print ' Guru Meditation #DEADBEEF.ABADC0DE'
77 # FIXME: This simple JS snippet is harder to pass than ACID 3.0
79 <script language="JavaScript" type="text/javascript">
80 var guru = document.getElementById('guru');
81 // Firefox 2.0 doesn't take border-color, but returns border-top-color fine
82 var color = document.defaultView.getComputedStyle(guru,null).getPropertyValue('border-top-color');
85 guru.style.setProperty('border-color', color, '');
86 setTimeout('guruOff()', 1000);
89 guru.style.setProperty('border-color', '#000000', '');
90 setTimeout('guruOn()', 1000);
92 // Safari 2.0 returns this rgba crap
93 // Konqueror 3.5.6 doesn't seem to support computed properties
94 if (color && color != 'rgba(0, 0, 0, 0)') {
95 //window.alert("enabled! color='" + color + "'");
100 def send_title(name, text="Limbo", msg=None, msg_type='error'):
102 if title_done: return
106 print """<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
107 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
108 <html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en">
110 print "<head><title>%s: %s</title>" % (site_name, text)
111 print ' <meta http-equiv="Content-Type" content="application/xhtml+xml; charset=utf-8" />'
113 print ' <meta name="robots" content="noindex,nofollow" />'
115 print ' <link rel="stylesheet" type="text/css" href="%s" />' % css_url
119 if name and privileged_url is not None:
120 print '<body ondblclick="location.href=\'' + privileged_path() + '?edit=' + name + '\'">'
125 send_guru(msg, msg_type)
128 print '<div class="nav">'
129 print ' <b>' + site_name + ': ',
131 print link_tag('?fullsearch=' + name, text) + '</b> '
134 print ' | ' + link_tag('FrontPage', 'Front Page', 'navlink')
135 print ' | ' + link_tag('FindPage', 'Find Page', 'navlink')
136 print ' | <a href="' + history_url + '" class="navlink">Recent Changes</a>'
139 print ' | <a href="' + history_url + '?a=history;f=' + name + '" class="navlink">Page History</a>'
140 print ' | ' + link_tag('?raw=' + name, 'Raw Text', 'navlink')
141 if privileged_url is not None:
142 print ' | ' + link_tag('?edit=' + name, 'Edit Page', 'navlink', authentication=True)
144 print ' | <i>Immutable Page</i>'
147 if user != 'AnonymousCoward':
148 print ' | <span class="login"><i>logged in as <b>' + cgi.escape(user) + '</b></i></span>'
152 def link_tag(params, text=None, ss_class=None, authentication=False):
154 text = params # default
157 classattr += 'class="%s" ' % ss_class
158 # Prevent crawlers from following links potentially added by spammers or to generated pages
159 if ss_class == 'external' or ss_class == 'navlink':
160 classattr += 'rel="nofollow" '
162 path = privileged_path()
165 return '<a %shref="%s/%s">%s</a>' % (classattr, path, params, text)
167 # Search ---------------------------------------------------
169 def do_fullsearch(needle):
170 send_title(None, 'Full text search for "%s"' % (needle))
172 needle_re = re.compile(needle, re.IGNORECASE)
174 all_pages = page_list()
175 for page_name in all_pages:
176 body = Page(page_name).get_raw_body()
177 count = len(needle_re.findall(body))
179 hits.append((count, page_name))
181 # The default comparison for tuples compares elements in order,
182 # so this sorts by number of hits
187 for (count, page_name) in hits:
188 print '<li><p>' + Page(page_name).link_to()
189 print ' . . . . ' + `count`
190 print ['match', 'matches'][count <> 1]
194 print_search_stats(len(hits), len(all_pages))
196 def do_titlesearch(needle):
197 # TODO: check needle is legal -- but probably we can just accept any RE
198 send_title(None, "Title search for \"" + needle + '"')
200 needle_re = re.compile(needle, re.IGNORECASE)
201 all_pages = page_list()
202 hits = filter(needle_re.search, all_pages)
205 for filename in hits:
206 print '<li><p>' + Page(filename).link_to() + "</p></li>"
209 print_search_stats(len(hits), len(all_pages))
211 def print_search_stats(hits, searched):
212 print "<p>%d hits out of %d pages searched.</p>" % (hits, searched)
214 def do_edit(pagename):
215 Page(pagename).send_editor()
217 def do_raw(pagename):
218 Page(pagename).send_raw()
220 def do_savepage(pagename):
223 if 'preview' in form:
224 pg.send_editor(form['savetext'].value)
226 pg.save_text(form['savetext'].value)
228 elif 'cancel' in form:
229 pg.msg = 'Editing canceled'
230 pg.msg_type = 'notice'
233 raise 'What did you press?'
235 def make_index_key():
237 links = map(lambda ch: '<a href="#%s">%s</a>' % (ch, ch),
239 s = s + string.join(links, ' | ')
240 s = s + '</center></p>'
244 return filter(word_re.match, os.listdir(text_dir))
246 def send_footer(name, mod_string=None):
248 cgi.print_arguments()
249 cgi.print_form(cgi.FieldStorage())
252 print '<div id="footer"><hr />'
253 print ('<p class="copyright"><span class="benchmark">generated in %0.3fs</span>' +
254 ' by <a href="http://www.codewiz.org/wiki/GeekiGeeki">GeekiGeeki</a>' +
255 ' version %s</p>') % (clock() - start_time, __version__)
257 print '<p class="modified">last modified %s</p>' % mod_string
258 print '</div></body></html>'
260 # ----------------------------------------------------------
262 def _macro_TitleSearch(*vargs):
263 return _macro_search("titlesearch")
265 def _macro_FullSearch(*vargs):
266 return _macro_search("fullsearch")
268 def _macro_search(type):
269 if form.has_key('value'):
270 default = form["value"].value
273 return """<form method="get"><input name="%s" size="30" value="%s" /><input type="submit" value="Search" /></form>""" % (type, default)
275 def _macro_WordIndex(*vargs):
277 pages = list(page_list())
279 word_re = re.compile('[A-Z][a-z]+')
281 for word in word_re.findall(name):
283 map[word].append(name)
287 all_words = map.keys()
291 for word in all_words:
292 letter = string.lower(word[0])
293 if letter <> last_letter:
294 s = s + '; <a name="%s"><h3>%s</h3></a>' % (letter, letter)
297 s = s + '<b>%s</b><ul>' % word
302 if name == last_page: continue
303 s = s + '<li>' + Page(name).link_to()
308 def _macro_TitleIndex(*vargs):
310 pages = list(page_list())
312 current_letter = None
314 letter = string.lower(name[0])
315 if letter <> current_letter:
316 s = s + '<a name="%s"><h3>%s</h3></a>' % (letter, letter)
317 current_letter = letter
320 s = s + Page(name).link_to()
324 # ----------------------------------------------------------
326 """Object that turns Wiki markup into HTML.
328 All formatting commands can be parsed one line at a time, though
329 some state is carried over between lines.
331 def __init__(self, raw):
333 self.is_em = self.is_b = 0
336 self.list_indents = []
338 self.in_table = False
341 self.in_header = True
343 def _emph_repl(self, word):
345 self.is_b = not self.is_b
346 return ['</strong>', '<strong>'][self.is_b]
348 self.is_em = not self.is_em
349 return ['</em>', '<em>'][self.is_em]
351 def _tit_repl(self, word):
353 result = '</h%d>' % self.h_level
356 self.h_level = len(word) - 1
358 result = '<h%d id="%d"><a class="heading" href="#%d">*</a> ' % (self.h_level, self.h_count, self.h_count)
361 def _rule_repl(self, word):
362 return self._undent() + '\n<hr size="%d" noshade="noshade" />\n' % (len(word) - 2)
364 def _word_repl(self, word):
365 return Page(word).link_to()
367 def _img_repl(self, word):
368 path = script_name() + '/' + word;
369 return '<a href="%s"><img border="0" src="%s" /></a>' % (path, path)
371 def _url_repl(self, word):
372 if img_re.match(word):
373 return '<a href="%s"><img border="0" src="%s" /></a>' % (word, word)
375 return '<a href="%s" rel="nofollow" class="external">%s</a>' % (word, word)
377 def _hurl_repl(self, word):
378 m = re.compile("\[\[(\S+)([^\]]*)\]\]").match(word)
380 descr = m.group(2).strip() or name
382 macro = globals().get('_macro_' + name)
384 return apply(macro, (name, descr))
385 elif img_re.match(name):
386 return '<a href="%s"><img border="0" src="%s" alt="%s" /></a>' % (name, name, descr)
387 elif url_re.match(name):
388 return '<a href="%s" rel="nofollow" class="external">%s</a>' % (name, descr)
389 elif name.startswith('/'):
390 return '<a href="%s">%s</a>' % (name, descr)
392 return link_tag(name, descr)
394 def _email_repl(self, word):
395 return '<a href="mailto:%s">%s</a>' % (word, word)
397 def _html_repl(self, word):
398 return word; # Pass through
400 def _ent_repl(self, s):
401 return {'&': '&',
405 def _li_repl(self, match):
408 def _pre_repl(self, word):
409 if word == '{{{' and not self.in_pre:
417 def _hi_repl(self, word):
424 return '<strong class="highlight ' + cl + '">' + word + '</strong>'
426 def _var_repl(self, word):
427 if word == '{{' and not self.in_var:
435 def _tr_repl(self, word):
437 if not self.in_table:
440 out = '</p><table><tbody>\n'
442 return out + '<tr class="' + ['even', 'odd'][self.tr_cnt % 2] + '"><td>'
444 def _tre_repl(self, word):
449 def _td_repl(self, word):
454 def _indent_level(self):
455 return len(self.list_indents) and self.list_indents[-1]
457 def _indent_to(self, new_level):
458 if self._indent_level() == new_level:
461 while self._indent_level() > new_level:
462 del(self.list_indents[-1])
464 while self._indent_level() < new_level:
465 self.list_indents.append(new_level)
472 res += '</ul>' * len(self.list_indents)
474 self.list_indents = []
477 def replace(self, match):
478 for type, hit in match.groupdict().items():
480 return apply(getattr(self, '_' + type + '_repl'), (hit,))
482 raise "Can't handle match " + `match`
484 def print_html(self):
485 print '<div class="wiki"><p>'
487 # For each line, we scan through looking for magic
488 # strings, outputting verbatim any intervening text
489 # TODO: highlight search words (look at referer)
490 scan_re = re.compile(
493 + r"(?P<emph>'{2,3})"
494 + r"|(?P<tit>\={2,6})"
495 + r"|(?P<rule>^-{3,})"
496 + r"|(?P<html><(/|)(div|span|iframe)[^<>]*>)"
498 + r"|(?P<hi>\b(FIXME|TODO|DONE)\b)"
501 + r"|(?P<img>\b[a-zA-Z0-9_-]+\.(png|gif|jpg|jpeg|bmp))"
502 + r"|(?P<word>\b(?:[A-Z][a-z]+){2,}\b)"
503 + r"|(?P<hurl>\[\[\S+[^\]]*\]\])"
504 + r"|(?P<url>(http|https|ftp|mailto)\:[^\s'\"]+\S)"
505 + r"|(?P<email>[-\w._+]+\@[\w.-]+)"
509 + r"|(?P<pre>(\{\{\{|\s*\}\}\}))"
510 + r"|(?P<var>(\{\{|\}\}))"
513 + r"|(?P<tr>^\s*\|\|\s*)"
514 + r"|(?P<tre>\s*\|\|\s*$)"
515 + r"|(?P<td>\s*\|\|\s*)"
519 + r"(?P<pre>\s*\}\}\})"
521 blank_re = re.compile(r"^\s*$")
522 indent_re = re.compile(r"^\s*")
523 tr_re = re.compile(r"^\s*\|\|")
524 eol_re = re.compile(r"\r?\n")
525 raw = string.expandtabs(self.raw)
526 for line in eol_re.split(raw):
529 if line.startswith('#'):
531 self.in_header = False
534 print re.sub(pre_re, self.replace, line)
536 if self.in_table and not tr_re.match(line):
537 self.in_table = False
538 print '</tbody></table><p>'
540 if blank_re.match(line):
543 indent = indent_re.match(line)
544 print self._indent_to(len(indent.group(0)))
545 print re.sub(scan_re, self.replace, line)
547 if self.in_pre: print '</pre>'
548 if self.in_table: print '</tbody></table><p>'
552 # ----------------------------------------------------------
554 def __init__(self, page_name):
555 self.page_name = page_name
557 self.msg_type = 'error'
560 def split_title(self):
561 # look for the end of words and the start of a new word,
562 # and insert a space there
563 return re.sub('([a-z])([A-Z])', r'\1 \2', self.page_name)
565 def _text_filename(self):
566 return path.join(text_dir, self.page_name)
568 def _tmp_filename(self):
569 return path.join(text_dir, ('#' + self.page_name + '.' + `os.getpid()` + '#'))
573 os.stat(self._text_filename())
576 if er.errno == errno.ENOENT:
582 word = self.page_name
584 return link_tag(word, word, 'wikilink')
586 return link_tag(word, nonexist_pfx + word, 'nonexistent')
588 def get_raw_body(self):
590 return open(self._text_filename(), 'rt').read()
592 if er.errno == errno.ENOENT:
593 # just doesn't exist, use default
594 return 'Describe %s here.' % self.page_name
602 file = open(self._text_filename(), 'rt')
603 attr_re = re.compile(r"^#(\S*)(.*)$")
605 m = attr_re.match(line)
608 self.attrs[m.group(1)] = m.group(2).strip()
609 #print "bernie: attrs[" + m.group(1) + "] = " + m.group(2) + "<br>\n"
611 if er.errno != errno.ENOENT:
615 def can(self, action, default=True):
616 attrs = self.get_attrs()
618 # SomeUser:read,write All:read
620 for rule in acl.split():
621 (user,perms) = rule.split(':')
622 if user == remote_user() or user == "All":
623 if action in perms.split(','):
628 except Exception, er:
633 return self.can("write", True)
636 return self.can("read", True)
641 page_name = self.page_name
642 send_title(page_name, self.split_title(), msg=self.msg, msg_type=self.msg_type)
644 PageFormatter(self.get_raw_body()).print_html()
646 send_guru("Read access denied by ACLs", "notice")
647 send_footer(page_name, self._last_modified())
649 def _last_modified(self):
650 if not self.exists():
652 from time import localtime, strftime
653 modtime = localtime(os.stat(self._text_filename())[stat.ST_MTIME])
654 return strftime(datetime_fmt, modtime)
656 def send_editor(self, preview=None):
657 send_title(None, 'Edit ' + self.split_title(), msg=self.msg, msg_type=self.msg_type)
658 if not self.can_write():
659 send_guru("Write access denied by ACLs", "error")
662 print ('<p><b>Editing ' + self.page_name
663 + ' for ' + cgi.escape(remote_user())
664 + ' from ' + cgi.escape(get_hostname(remote_host()))
666 print '<div class="editor"><form method="post" action="%s/%s">' % (script_name(), self.page_name)
667 print '<input type="hidden" name="savepage" value="%s">' % (self.page_name)
668 print """<textarea wrap="virtual" id="editor" name="savetext" rows="17" cols="80">%s</textarea>""" % (preview or self.get_raw_body())
671 <input type="submit" name="save" value="Save" />
672 <input type="submit" name="preview" value="Preview" />
673 <input type="reset" value="Reset" />
674 <input type="submit" name="cancel" value="Cancel" />
677 print "<p>" + Page('EditingTips').link_to() + "</p>"
679 print "<div class='preview'>"
680 PageFormatter(preview).print_html()
682 send_footer(self.page_name)
685 if not self.can_read():
686 send_title(None, msg='Read access denied by ACLs', msg_type='notice')
688 emit_header("text/plain")
689 print self.get_raw_body()
691 def _write_file(self, text):
692 tmp_filename = self._tmp_filename()
693 open(tmp_filename, 'wt').write(text.replace('\r\n', '\n'))
694 text = self._text_filename()
696 # Bad Bill! POSIX rename ought to replace. :-(
700 if er.errno <> errno.ENOENT: raise er
701 os.rename(tmp_filename, text)
703 def save_text(self, newtext):
704 if not self.can_write():
705 self.msg = 'Write access denied by ACLs'
706 self.msg_type = 'error'
709 self._write_file(newtext)
712 # FIXME: what's the std way to perform shell quoting in python?
713 cmd = ( post_edit_hook
714 + " '" + text_dir + '/' + self.page_name
715 + "' '" + remote_user()
716 + "' '" + remote_host() + "'"
722 self.msg += "Post-editing hook returned %d.\n" % rc
723 self.msg += 'Command was: ' + cmd + '\n'
725 self.msg += 'Output follows:\n' + msg
727 self.msg = 'Thank you for your contribution. Your attention to detail is appreciated.'
728 self.msg_type = 'success'
730 def send_verbatim(filename, mime_type='application/octet-stream'):
731 pathname = path.join(text_dir, filename)
732 data = open(pathname, 'rb').read()
733 emit_header(mime_type)
734 sys.stdout.write(data)
736 # Main ---------------------------------------------------------------
738 # Configuration values
739 site_name = 'Codewiz'
741 # set to None for read-only sites, leave empty ('') to allow anonymous edits
742 # otherwise, set to a URL that requires authentication
743 privileged_url = 'https://www.codewiz.org/~bernie/wiki'
745 data_dir = '/home/bernie/public_html/wiki'
746 text_dir = path.join(data_dir, 'text')
747 css_url = '../wikidata/geekigeeki.css' # optional stylesheet link
748 history_url = '../wikigit/wiki.git'
749 post_edit_hook = './post_edit_hook.sh'
750 datetime_fmt = '%a %d %b %Y %I:%M %p'
751 allow_edit = True # Is it possible to edit pages?
752 show_hosts = True # show hostnames?
753 nonexist_pfx = '' # prefix before nonexistent link (usually '?')
754 debug_cgi = False # Set to True for CGI var dump
756 form = cgi.FieldStorage()
758 handlers = { 'fullsearch': do_fullsearch,
759 'titlesearch': do_titlesearch,
762 'savepage': do_savepage }
764 for cmd in handlers.keys():
765 if form.has_key(cmd):
766 apply(handlers[cmd], (form[cmd].value,))
769 path_info = environ.get('PATH_INFO', '')
770 if len(path_info) and path_info[0] == '/':
771 query = path_info[1:] or 'FrontPage'
773 query = environ.get('QUERY_STRING', '') or 'FrontPage'
775 if file_re.match(query):
776 if word_re.match(query):
777 Page(query).send_page()
778 elif img_re.match(query):
779 #FIXME: use correct mime type
780 send_verbatim(query, 'image/jpeg')
785 send_title(None, msg='Can\'t work out query: ' + query)
788 msg=traceback.format_exc()
790 send_guru(msg, "error")
792 send_title(None, msg=msg)