2 """Quick-quick implementation of WikiWikiWeb in Python
5 # Copyright (C) 1999, 2000 Martin Pool <mbp@humbug.org.au>
6 # This version includes additional changes by Gerardo Poggiali (2002)
7 # This version includes additional changes by Bernardo Innocenti (2007)
9 # This program is free software: you can redistribute it and/or modify
10 # it under the terms of the GNU General Public License as published by
11 # the Free Software Foundation, either version 3 of the License, or
12 # (at your option) any later version.
14 # This program is distributed in the hope that it will be useful, but
15 # WITHOUT ANY WARRANTY; without even the implied warranty of
16 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
17 # General Public License for more details.
19 # You should have received a copy of the GNU General Public License
20 # along with this program. If not, see <http://www.gnu.org/licenses/>.
22 __version__ = '$Revision: 1.63+gerry+bernie $'[11:-2];
24 import cgi, sys, string, os, re, errno, time, stat
25 from os import path, environ
27 # Regular expression defining a WikiWord
28 # (but this definition is also assumed in other places)
29 file_re = re.compile(r"^\b([A-Za-z0-9_\.\-]+)\b$")
30 word_re = re.compile(r"^\b([A-Z][a-z]+){2,}\b$")
31 img_re = re.compile(r"^.*\.(png|gif|jpg|jpeg)$", re.IGNORECASE)
32 url_re = re.compile(r"^[a-z]{3,8}://[^\s'\"]+\S$")
37 # CGI stuff ---------------------------------------------------------
40 return environ.get('SCRIPT_NAME', '')
43 return environ.get('REMOTE_USER', 'AnonymousCoward')
46 return environ.get('REMOTE_ADDR', '')
48 def get_hostname(addr):
50 from socket import gethostbyaddr
51 return gethostbyaddr(addr)[0] + ' (' + addr + ')'
55 # Formatting stuff --------------------------------------------------
57 def emit_header(type="text/html"):
58 print "Content-type: " + type + "; charset=utf-8"
61 def send_guru(msg, msg_type):
62 if msg is None or len(msg) == 0: return
63 print '<pre id="guru" onclick="this.style.display = \'none\'" class="' + msg_type + '">'
64 if msg_type == 'error':
65 print ' Software Failure. Press left mouse button to continue.\n'
67 if msg_type == 'error':
68 print ' Guru Meditation #DEADBEEF.ABADC0DE'
70 # FIXME: This simple JS code is harder to pass than ACID 3.0
72 <script language="JavaScript" type="text/javascript">
73 var guru = document.getElementById('guru');
74 // Firefox 2.0 doesn't take border-color, but returns border-top-color fine
75 var color = document.defaultView.getComputedStyle(guru,null).getPropertyValue('border-top-color');
78 guru.style.setProperty('border-color', color, '');
79 setTimeout('guruOff()', 1000);
82 guru.style.setProperty('border-color', '#000000', '');
83 setTimeout('guruOn()', 1000);
85 // Safari 2.0 returns this rgba crap
86 // Konqueror 3.5.6 doesn't seem to support computed properties
87 if (color && color != 'rgba(0, 0, 0, 0)') {
88 //window.alert("enabled! color='" + color + "'");
93 def send_title(name, text="Limbo", msg=None, msg_type = 'error'):
99 print """<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
100 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
101 <html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en">
103 print "<head><title>%s: %s</title>" % (site_name, text)
104 print ' <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />'
106 print ' <meta name="robots" content="noindex,nofollow">'
108 print ' <link rel="stylesheet" type="text/css" href="%s" />' % css_url
112 if name and allow_edit:
113 print '<body ondblclick="location.href=\'?edit=' + name + '\'">'
117 send_guru(msg, msg_type)
120 print '<div class="navigator">'
121 print ' <b>' + site_name + ': '
123 print link_tag('?fullsearch=' + name, text) + '</b> '
126 print ' | ' + link_tag('FrontPage', 'Front Page', 'navlink')
127 print ' | ' + link_tag('FindPage', 'Find Page', 'navlink')
128 print ' | <a href="/wikigit/wiki.git" class="navlink">Recent Changes</a>'
131 print ' | <a href="/wikigit/wiki.git?a=history;f=' + name + '" class="navlink">Page History</a>'
132 print ' | ' + link_tag('?raw=' + name, 'Raw Text', 'navlink')
134 print ' | ' + link_tag('?edit=' + name, 'Edit Page', 'navlink')
136 print ' | <i>Immutable Page</i>'
139 if user != 'AnonymousCoward':
140 print ' | <i>logged in as <b>' + cgi.escape(user) + '</b></i>'
146 def link_tag(params, text=None, ss_class=None):
148 text = params # default
150 # Prevent crawlers from following links to generated pages
151 # and links added by potential spammers
152 if ss_class == 'external' or ss_class == 'navlink':
153 classattr += 'rel="nofollow" '
155 classattr += 'class="%s" ' % ss_class
156 return '<a %shref="%s/%s">%s</a>' % (classattr, get_scriptname(),
159 # Search ---------------------------------------------------
161 def do_fullsearch(needle):
162 send_title(None, 'Full text search for "%s"' % (needle))
164 needle_re = re.compile(needle, re.IGNORECASE)
166 all_pages = page_list()
167 for page_name in all_pages:
168 body = Page(page_name).get_raw_body()
169 count = len(needle_re.findall(body))
171 hits.append((count, page_name))
173 # The default comparison for tuples compares elements in order,
174 # so this sorts by number of hits
179 for (count, page_name) in hits:
180 print '<li><p>' + Page(page_name).link_to()
181 print ' . . . . ' + `count`
182 print ['match', 'matches'][count <> 1]
186 print_search_stats(len(hits), len(all_pages))
189 def do_titlesearch(needle):
190 # TODO: check needle is legal -- but probably we can just accept any RE
191 send_title(None, "Title search for \"" + needle + '"')
193 needle_re = re.compile(needle, re.IGNORECASE)
194 all_pages = page_list()
195 hits = filter(needle_re.search, all_pages)
198 for filename in hits:
199 print '<li><p>' + Page(filename).link_to() + "</p></li>"
202 print_search_stats(len(hits), len(all_pages))
205 def print_search_stats(hits, searched):
206 print "<p>%d hits out of %d pages searched.</p>" % (hits, searched)
208 def do_edit(pagename):
209 Page(pagename).send_editor()
211 def do_raw(pagename):
212 Page(pagename).send_raw()
214 def do_savepage(pagename):
216 raise 'editing disallowed for ' + pagename
220 if 'preview' in form:
221 pg.send_editor(form['savetext'].value)
223 pg.save_text(form['savetext'].value)
225 elif 'cancel' in form:
226 pg.msg = 'Editing cancelled'
227 pg.msg_type = 'notice'
230 raise 'What did you press?'
232 def make_index_key():
234 links = map(lambda ch: '<a href="#%s">%s</a>' % (ch, ch),
236 s = s + string.join(links, ' | ')
237 s = s + '</center></p>'
242 return filter(word_re.match, os.listdir(text_dir))
245 def send_footer(name, mod_string=None):
246 print '<div class="footer">'
248 print "last modified %s" % mod_string
249 print '</div></body></html>'
252 # ----------------------------------------------------------
254 def _macro_TitleSearch():
255 return _macro_search("titlesearch")
257 def _macro_FullSearch():
258 return _macro_search("fullsearch")
260 def _macro_search(type):
261 if form.has_key('value'):
262 default = form["value"].value
265 return """<form method="get"><input name="%s" size="30" value="%s"><input type="submit" value="Go"></form>""" % (type, default)
267 def _macro_WordIndex():
269 pages = list(page_list())
271 word_re = re.compile('[A-Z][a-z]+')
273 for word in word_re.findall(name):
275 map[word].append(name)
279 all_words = map.keys()
283 for word in all_words:
284 letter = string.lower(word[0])
285 if letter <> last_letter:
286 s = s + '; <a name="%s"><h3>%s</h3></a>' % (letter, letter)
289 s = s + '<b>%s</b><ul>' % word
294 if name == last_page: continue
295 s = s + '<li>' + Page(name).link_to()
300 def _macro_TitleIndex():
302 pages = list(page_list())
304 current_letter = None
306 letter = string.lower(name[0])
307 if letter <> current_letter:
308 s = s + '<a name="%s"><h3>%s</h3></a>' % (letter, letter)
309 current_letter = letter
312 s = s + Page(name).link_to()
316 # ----------------------------------------------------------
318 """Object that turns Wiki markup into HTML.
320 All formatting commands can be parsed one line at a time, though
321 some state is carried over between lines.
323 def __init__(self, raw):
325 self.is_em = self.is_b = 0
327 self.list_indents = []
330 self.in_header = True
332 def _emph_repl(self, word):
334 self.is_b = not self.is_b
335 return ['</b>', '<b>'][self.is_b]
337 self.is_em = not self.is_em
338 return ['</em>', '<em>'][self.is_em]
340 def _tit_repl(self, word):
342 result = "</h%d>" % self.h_level
345 self.h_level = len(word) - 1
346 result = "<h%d>" % self.h_level
349 def _rule_repl(self, word):
352 s = s + "\n<hr size='1' noshade=\"noshade\" />\n"
354 s = s + "\n<hr size='%d' noshade=\"noshade\" />\n" % (len(word) - 2 )
357 def _word_repl(self, word):
358 return Page(word).link_to()
360 def _img_repl(self, word):
361 return '<img border="0" src="%s/%s" />' % (get_scriptname(), word)
363 def _url_repl(self, word):
364 if img_re.match(word):
365 return '<img border="0" src="%s" />' % word
367 return '<a href="%s" rel="nofollow" class="external">%s</a>' % (word, word)
369 def _hurl_repl(self, word):
370 m = re.compile("\[\[(\S+)\ (.+)\]\]").match(word)
373 if img_re.match(anchor):
374 return '<img border="0" src="%s" alt="%s" />' % (anchor, descr)
375 elif url_re.match(anchor):
376 return '<a href="%s" rel="nofollow" class="external">%s</a>' % (anchor, descr)
377 elif anchor.startswith('/'):
378 return '<a href="%s">%s</a>' % (anchor, descr)
380 return link_tag(anchor, descr)
382 def _email_repl(self, word):
383 return '<a href="mailto:%s">%s</a>' % (word, word)
386 def _ent_repl(self, s):
387 return {'&': '&',
392 def _li_repl(self, match):
396 def _pre_repl(self, word):
397 if word == '{{{' and not self.in_pre:
406 def _var_repl(self, word):
407 if word == '{{' and not self.in_var:
415 def _macro_repl(self, word):
416 macro_name = word[2:-2]
417 # TODO: Somehow get the default value into the search field
418 return apply(globals()['_macro_' + macro_name], ())
420 def _indent_level(self):
421 return len(self.list_indents) and self.list_indents[-1]
423 def _indent_to(self, new_level):
424 if self._indent_level() == new_level:
427 while self._indent_level() > new_level:
428 del(self.list_indents[-1])
430 while self._indent_level() < new_level:
431 self.list_indents.append(new_level)
438 res += '</ul>' * len(self.list_indents)
440 self.list_indents = []
443 def replace(self, match):
444 for type, hit in match.groupdict().items():
446 return apply(getattr(self, '_' + type + '_repl'), (hit,))
448 raise "Can't handle match " + `match`
450 def print_html(self):
451 print "<div class='wiki'><p>"
453 # For each line, we scan through looking for magic
454 # strings, outputting verbatim any intervening text
455 scan_re = re.compile(
457 + r"(?P<emph>'{2,3})"
458 + r"|(?P<tit>\={2,6})"
460 + r"|(?P<img>\b[a-zA-Z0-9_-]+\.(png|gif|jpg|jpeg|bmp))"
461 + r"|(?P<word>\b(?:[A-Z][a-z]+){2,}\b)"
462 + r"|(?P<rule>^-{3,})"
463 + r"|(?P<hurl>\[\[\S+\s+.+\]\])"
464 + r"|(?P<url>(http|ftp|nntp|news|mailto)\:[^\s'\"]+\S)"
465 + r"|(?P<email>[-\w._+]+\@[\w.-]+)"
467 + r"|(?P<pre>(\{\{\{|\s*\}\}\}))"
468 + r"|(?P<var>(\{\{|\}\}))"
469 + r"|(?P<macro>\[\[(TitleSearch|FullSearch|WordIndex|TitleIndex)\]\])"
473 + r"(?P<pre>\s*\}\}\})"
475 blank_re = re.compile("^\s*$")
476 indent_re = re.compile("^\s*")
477 eol_re = re.compile(r'\r?\n')
478 raw = string.expandtabs(self.raw)
479 for line in eol_re.split(raw):
482 if line.startswith('#'):
484 self.in_header = False
486 print re.sub(pre_re, self.replace, line)
488 # XXX: Should we check these conditions in this order?
489 if blank_re.match(line):
492 indent = indent_re.match(line)
493 print self._indent_to(len(indent.group(0)))
494 print re.sub(scan_re, self.replace, line)
495 if self.in_pre: print '</pre>'
499 # ----------------------------------------------------------
501 def __init__(self, page_name):
502 self.page_name = page_name
504 self.msg_type = 'error'
507 def split_title(self):
508 # look for the end of words and the start of a new word,
509 # and insert a space there
510 return re.sub('([a-z])([A-Z])', r'\1 \2', self.page_name)
512 def _text_filename(self):
513 return path.join(text_dir, self.page_name)
515 def _tmp_filename(self):
516 return path.join(text_dir, ('#' + self.page_name + '.' + `os.getpid()` + '#'))
520 os.stat(self._text_filename())
523 if er.errno == errno.ENOENT:
529 word = self.page_name
531 return link_tag(word, word, 'wikilink')
534 return link_tag(word, '?', 'nonexistent') + word
536 return link_tag(word, word, 'nonexistent')
539 def get_raw_body(self):
541 return open(self._text_filename(), 'rt').read()
543 if er.errno == errno.ENOENT:
544 # just doesn't exist, use default
545 return 'Describe %s here.' % self.page_name
553 file = open(self._text_filename(), 'rt')
554 attr_re = re.compile(r"^#(\S*)(.*)$")
556 m = attr_re.match(line)
559 self.attrs[m.group(1)] = m.group(2).strip()
560 #print "bernie: attrs[" + m.group(1) + "] = " + m.group(2) + "<br>\n"
562 if er.errno != errno.ENOENT:
567 attrs = self.get_attrs()
569 # SomeUser:read,write All:read
571 for rule in acl.split():
572 (user,perms) = acl.split(':')
573 if user == remote_user() or user == "All":
574 if 'write' in perms.split(','):
584 page_name = self.page_name
585 send_title(page_name, self.split_title(), msg=self.msg, msg_type=self.msg_type)
586 PageFormatter(self.get_raw_body()).print_html()
587 send_footer(page_name, self._last_modified())
589 def _last_modified(self):
590 if not self.exists():
592 from time import localtime, strftime
593 modtime = localtime(os.stat(self._text_filename())[stat.ST_MTIME])
594 return strftime(datetime_fmt, modtime)
596 def send_editor(self, preview=None):
597 send_title(None, 'Edit ' + self.split_title(), msg=self.msg, msg_type=self.msg_type)
599 print ('<p><b>Editing ' + self.page_name
600 + ' for ' + cgi.escape(remote_user())
601 + ' from ' + cgi.escape(get_hostname(remote_host()))
603 print '<div class="editor"><form method="post" action="%s/%s">' % (get_scriptname(), self.page_name)
604 print '<input type="hidden" name="savepage" value="%s">' % (self.page_name)
605 print """<textarea wrap="virtual" id="editor" name="savetext" rows="17" cols="80">%s</textarea>""" % (preview or self.get_raw_body())
608 <input type="submit" name="save" value="Save" />
609 <input type="submit" name="preview" value="Preview" />
610 <input type="reset" value="Reset" />
611 <input type="submit" name="cancel" value="Cancel" />
614 print "<p>" + Page('EditingTips').link_to() + "</p>"
616 print "<div class='preview'>"
617 PageFormatter(preview).print_html()
621 emit_header("text/plain")
622 print self.get_raw_body()
624 def _write_file(self, text):
625 tmp_filename = self._tmp_filename()
626 open(tmp_filename, 'wt').write(text.replace('\r\n', '\n'))
627 text = self._text_filename()
629 # Bad Bill! POSIX rename ought to replace. :-(
633 if er.errno <> errno.ENOENT: raise er
634 os.rename(tmp_filename, text)
636 def save_text(self, newtext):
637 self._write_file(newtext)
640 # FIXME: what's the std way to perform shell quoting in python?
641 cmd = ( post_edit_hook
642 + " '" + text_dir + '/' + self.page_name
643 + "' '" + remote_user()
644 + "' '" + remote_host() + "'"
650 self.msg += "Post-editing hook returned %d.\n" % rc
651 self.msg += 'Command was: ' + cmd + '\n'
653 self.msg += 'Output follows:\n' + msg
655 self.msg = 'Thankyou for your contribution. Your attention to detail is appreciated.'
656 self.msg_type = 'success'
658 def send_verbatim(filename, mime_type='application/octet-stream'):
659 pathname = path.join(text_dir, filename)
660 data = open(pathname, 'rb').read()
661 emit_header(mime_type)
662 sys.stdout.write(data)
664 # ---------------------------------------------------------------
666 # Configuration values
667 data_dir = '/home/bernie/public_html/wiki'
668 text_dir = path.join(data_dir, 'text')
669 allow_edit = True # Is it possible to edit pages?
670 site_name = 'codewiz.org'
671 changed_time_fmt = '[%I:%M %p] '
672 date_fmt = '%a %d %b %Y'
673 datetime_fmt = '%a %d %b %Y %I:%M %p'
674 show_hosts = True # show hostnames?
675 css_url = '../wikidata/geekigeeki.css' # optional stylesheet link
676 nonexist_qm = False # show '?' for nonexistent?
677 post_edit_hook = './post_edit_hook.sh'
679 form = cgi.FieldStorage()
681 handlers = { 'fullsearch': do_fullsearch,
682 'titlesearch': do_titlesearch,
685 'savepage': do_savepage }
687 for cmd in handlers.keys():
688 if form.has_key(cmd):
689 apply(handlers[cmd], (form[cmd].value,))
692 path_info = environ.get('PATH_INFO', '')
693 if len(path_info) and path_info[0] == '/':
694 query = path_info[1:] or 'FrontPage'
696 query = environ.get('QUERY_STRING', '') or 'FrontPage'
698 if file_re.match(query):
699 if word_re.match(query):
700 Page(query).send_page()
701 elif img_re.match(query):
702 send_verbatim(query, 'image/jpeg')
707 send_title(None, msg='Can\'t work out query: ' + query)
710 msg=traceback.format_exc()
712 send_guru(msg, "error")
714 send_title(None, msg=msg)