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', '')
42 def privileged_path():
43 return privileged_url or script_name()
46 return environ.get('REMOTE_USER', 'AnonymousCoward')
49 return environ.get('REMOTE_ADDR', '')
51 def get_hostname(addr):
53 from socket import gethostbyaddr
54 return gethostbyaddr(addr)[0] + ' (' + addr + ')'
58 # Formatting stuff --------------------------------------------------
60 def emit_header(type="text/html"):
61 print "Content-type: " + type + "; charset=utf-8"
64 def send_guru(msg, msg_type):
65 if msg is None or len(msg) == 0: return
66 print '<pre id="guru" onclick="this.style.display = \'none\'" class="' + msg_type + '">'
67 if msg_type == 'error':
68 print ' Software Failure. Press left mouse button to continue.\n'
70 if msg_type == 'error':
71 print ' Guru Meditation #DEADBEEF.ABADC0DE'
73 # FIXME: This simple JS snippet is harder to pass than ACID 3.0
75 <script language="JavaScript" type="text/javascript">
76 var guru = document.getElementById('guru');
77 // Firefox 2.0 doesn't take border-color, but returns border-top-color fine
78 var color = document.defaultView.getComputedStyle(guru,null).getPropertyValue('border-top-color');
81 guru.style.setProperty('border-color', color, '');
82 setTimeout('guruOff()', 1000);
85 guru.style.setProperty('border-color', '#000000', '');
86 setTimeout('guruOn()', 1000);
88 // Safari 2.0 returns this rgba crap
89 // Konqueror 3.5.6 doesn't seem to support computed properties
90 if (color && color != 'rgba(0, 0, 0, 0)') {
91 //window.alert("enabled! color='" + color + "'");
96 def send_title(name, text="Limbo", msg=None, msg_type='error'):
102 print """<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
103 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
104 <html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en">
106 print "<head><title>%s: %s</title>" % (site_name, text)
107 print ' <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />'
109 print ' <meta name="robots" content="noindex,nofollow" />'
111 print ' <link rel="stylesheet" type="text/css" href="%s" />' % css_url
115 if name and privileged_url is not None:
116 print '<body ondblclick="location.href=\'' + privileged_path() + '?edit=' + name + '\'">'
120 send_guru(msg, msg_type)
123 print '<div class="navigator">'
124 print ' <b>' + site_name + ': ',
126 print link_tag('?fullsearch=' + name, text) + '</b> '
129 print ' | ' + link_tag('FrontPage', 'Front Page', 'navlink')
130 print ' | ' + link_tag('FindPage', 'Find Page', 'navlink')
131 print ' | <a href="/wikigit/wiki.git" class="navlink">Recent Changes</a>'
134 print ' | <a href="/wikigit/wiki.git?a=history;f=' + name + '" class="navlink">Page History</a>'
135 print ' | ' + link_tag('?raw=' + name, 'Raw Text', 'navlink')
136 if privileged_url is not None:
137 print ' | ' + link_tag('?edit=' + name, 'Edit Page', 'navlink', authentication=True)
139 print ' | <i>Immutable Page</i>'
142 if user != 'AnonymousCoward':
143 print ' | <i>logged in as <b>' + cgi.escape(user) + '</b></i>'
149 def link_tag(params, text=None, ss_class=None, authentication=False):
151 text = params # default
154 classattr += 'class="%s" ' % ss_class
155 # Prevent crawlers from following links to generated pages
156 # and links added by potential spammers
157 if ss_class == 'external' or ss_class == 'navlink':
158 classattr += 'rel="nofollow" '
160 path = privileged_path()
163 return '<a %shref="%s/%s">%s</a>' % (classattr, path, params, text)
165 # Search ---------------------------------------------------
167 def do_fullsearch(needle):
168 send_title(None, 'Full text search for "%s"' % (needle))
170 needle_re = re.compile(needle, re.IGNORECASE)
172 all_pages = page_list()
173 for page_name in all_pages:
174 body = Page(page_name).get_raw_body()
175 count = len(needle_re.findall(body))
177 hits.append((count, page_name))
179 # The default comparison for tuples compares elements in order,
180 # so this sorts by number of hits
185 for (count, page_name) in hits:
186 print '<li><p>' + Page(page_name).link_to()
187 print ' . . . . ' + `count`
188 print ['match', 'matches'][count <> 1]
192 print_search_stats(len(hits), len(all_pages))
195 def do_titlesearch(needle):
196 # TODO: check needle is legal -- but probably we can just accept any RE
197 send_title(None, "Title search for \"" + needle + '"')
199 needle_re = re.compile(needle, re.IGNORECASE)
200 all_pages = page_list()
201 hits = filter(needle_re.search, all_pages)
204 for filename in hits:
205 print '<li><p>' + Page(filename).link_to() + "</p></li>"
208 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):
221 if privileged_url is None:
222 raise 'editing disallowed for ' + pagename
226 if 'preview' in form:
227 pg.send_editor(form['savetext'].value)
229 pg.save_text(form['savetext'].value)
231 elif 'cancel' in form:
232 pg.msg = 'Editing cancelled'
233 pg.msg_type = 'notice'
236 raise 'What did you press?'
238 def make_index_key():
240 links = map(lambda ch: '<a href="#%s">%s</a>' % (ch, ch),
242 s = s + string.join(links, ' | ')
243 s = s + '</center></p>'
248 return filter(word_re.match, os.listdir(text_dir))
251 def send_footer(name, mod_string=None):
253 cgi.print_arguments()
254 cgi.print_form(cgi.FieldStorage())
256 print '<div class="footer">'
258 print "last modified %s" % mod_string
259 print '</div></body></html>'
262 # ----------------------------------------------------------
264 def _macro_TitleSearch():
265 return _macro_search("titlesearch")
267 def _macro_FullSearch():
268 return _macro_search("fullsearch")
270 def _macro_search(type):
271 if form.has_key('value'):
272 default = form["value"].value
275 return """<form method="get"><input name="%s" size="30" value="%s"><input type="submit" value="Go" /></form>""" % (type, default)
277 def _macro_WordIndex():
279 pages = list(page_list())
281 word_re = re.compile('[A-Z][a-z]+')
283 for word in word_re.findall(name):
285 map[word].append(name)
289 all_words = map.keys()
293 for word in all_words:
294 letter = string.lower(word[0])
295 if letter <> last_letter:
296 s = s + '; <a name="%s"><h3>%s</h3></a>' % (letter, letter)
299 s = s + '<b>%s</b><ul>' % word
304 if name == last_page: continue
305 s = s + '<li>' + Page(name).link_to()
310 def _macro_TitleIndex():
312 pages = list(page_list())
314 current_letter = None
316 letter = string.lower(name[0])
317 if letter <> current_letter:
318 s = s + '<a name="%s"><h3>%s</h3></a>' % (letter, letter)
319 current_letter = letter
322 s = s + Page(name).link_to()
326 # ----------------------------------------------------------
328 """Object that turns Wiki markup into HTML.
330 All formatting commands can be parsed one line at a time, though
331 some state is carried over between lines.
333 def __init__(self, raw):
335 self.is_em = self.is_b = 0
337 self.list_indents = []
340 self.in_header = True
342 def _emph_repl(self, word):
344 self.is_b = not self.is_b
345 return ['</b>', '<b>'][self.is_b]
347 self.is_em = not self.is_em
348 return ['</em>', '<em>'][self.is_em]
350 def _tit_repl(self, word):
352 result = "</h%d>" % self.h_level
355 self.h_level = len(word) - 1
356 result = "<h%d>" % self.h_level
359 def _rule_repl(self, word):
362 s = s + "\n<hr size='1' noshade=\"noshade\" />\n"
364 s = s + "\n<hr size='%d' noshade=\"noshade\" />\n" % (len(word) - 2 )
367 def _word_repl(self, word):
368 return Page(word).link_to()
370 def _img_repl(self, word):
371 return '<img border="0" src="%s/%s" />' % (script_name(), word)
373 def _url_repl(self, word):
374 if img_re.match(word):
375 return '<img border="0" src="%s" />' % word
377 return '<a href="%s" rel="nofollow" class="external">%s</a>' % (word, word)
379 def _hurl_repl(self, word):
380 m = re.compile("\[\[(\S+)\ (.+)\]\]").match(word)
383 if img_re.match(anchor):
384 return '<img border="0" src="%s" alt="%s" />' % (anchor, descr)
385 elif url_re.match(anchor):
386 return '<a href="%s" rel="nofollow" class="external">%s</a>' % (anchor, descr)
387 elif anchor.startswith('/'):
388 return '<a href="%s">%s</a>' % (anchor, descr)
390 return link_tag(anchor, descr)
392 def _email_repl(self, word):
393 return '<a href="mailto:%s">%s</a>' % (word, word)
396 def _ent_repl(self, s):
397 return {'&': '&',
402 def _li_repl(self, match):
406 def _pre_repl(self, word):
407 if word == '{{{' and not self.in_pre:
416 def _var_repl(self, word):
417 if word == '{{' and not self.in_var:
425 def _macro_repl(self, word):
426 macro_name = word[2:-2]
427 # TODO: Somehow get the default value into the search field
428 return apply(globals()['_macro_' + macro_name], ())
430 def _indent_level(self):
431 return len(self.list_indents) and self.list_indents[-1]
433 def _indent_to(self, new_level):
434 if self._indent_level() == new_level:
437 while self._indent_level() > new_level:
438 del(self.list_indents[-1])
440 while self._indent_level() < new_level:
441 self.list_indents.append(new_level)
448 res += '</ul>' * len(self.list_indents)
450 self.list_indents = []
453 def replace(self, match):
454 for type, hit in match.groupdict().items():
456 return apply(getattr(self, '_' + type + '_repl'), (hit,))
458 raise "Can't handle match " + `match`
460 def print_html(self):
461 print "<div class='wiki'><p>"
463 # For each line, we scan through looking for magic
464 # strings, outputting verbatim any intervening text
465 scan_re = re.compile(
467 + r"(?P<emph>'{2,3})"
468 + r"|(?P<tit>\={2,6})"
470 + r"|(?P<img>\b[a-zA-Z0-9_-]+\.(png|gif|jpg|jpeg|bmp))"
471 + r"|(?P<word>\b(?:[A-Z][a-z]+){2,}\b)"
472 + r"|(?P<rule>^-{3,})"
473 + r"|(?P<hurl>\[\[\S+\s+.+\]\])"
474 + r"|(?P<url>(http|ftp|nntp|news|mailto)\:[^\s'\"]+\S)"
475 + r"|(?P<email>[-\w._+]+\@[\w.-]+)"
477 + r"|(?P<pre>(\{\{\{|\s*\}\}\}))"
478 + r"|(?P<var>(\{\{|\}\}))"
479 + r"|(?P<macro>\[\[(TitleSearch|FullSearch|WordIndex|TitleIndex)\]\])"
483 + r"(?P<pre>\s*\}\}\})"
485 blank_re = re.compile("^\s*$")
486 indent_re = re.compile("^\s*")
487 eol_re = re.compile(r'\r?\n')
488 raw = string.expandtabs(self.raw)
489 for line in eol_re.split(raw):
492 if line.startswith('#'):
494 self.in_header = False
496 print re.sub(pre_re, self.replace, line)
498 # XXX: Should we check these conditions in this order?
499 if blank_re.match(line):
502 indent = indent_re.match(line)
503 print self._indent_to(len(indent.group(0)))
504 print re.sub(scan_re, self.replace, line)
505 if self.in_pre: print '</pre>'
509 # ----------------------------------------------------------
511 def __init__(self, page_name):
512 self.page_name = page_name
514 self.msg_type = 'error'
517 def split_title(self):
518 # look for the end of words and the start of a new word,
519 # and insert a space there
520 return re.sub('([a-z])([A-Z])', r'\1 \2', self.page_name)
522 def _text_filename(self):
523 return path.join(text_dir, self.page_name)
525 def _tmp_filename(self):
526 return path.join(text_dir, ('#' + self.page_name + '.' + `os.getpid()` + '#'))
530 os.stat(self._text_filename())
533 if er.errno == errno.ENOENT:
539 word = self.page_name
541 return link_tag(word, word, 'wikilink')
544 return link_tag(word, '?', 'nonexistent') + word
546 return link_tag(word, word, 'nonexistent')
549 def get_raw_body(self):
551 return open(self._text_filename(), 'rt').read()
553 if er.errno == errno.ENOENT:
554 # just doesn't exist, use default
555 return 'Describe %s here.' % self.page_name
563 file = open(self._text_filename(), 'rt')
564 attr_re = re.compile(r"^#(\S*)(.*)$")
566 m = attr_re.match(line)
569 self.attrs[m.group(1)] = m.group(2).strip()
570 #print "bernie: attrs[" + m.group(1) + "] = " + m.group(2) + "<br>\n"
572 if er.errno != errno.ENOENT:
577 attrs = self.get_attrs()
579 # SomeUser:read,write All:read
581 for rule in acl.split():
582 (user,perms) = acl.split(':')
583 if user == remote_user() or user == "All":
584 if 'write' in perms.split(','):
594 page_name = self.page_name
595 send_title(page_name, self.split_title(), msg=self.msg, msg_type=self.msg_type)
596 PageFormatter(self.get_raw_body()).print_html()
597 send_footer(page_name, self._last_modified())
599 def _last_modified(self):
600 if not self.exists():
602 from time import localtime, strftime
603 modtime = localtime(os.stat(self._text_filename())[stat.ST_MTIME])
604 return strftime(datetime_fmt, modtime)
606 def send_editor(self, preview=None):
607 send_title(None, 'Edit ' + self.split_title(), msg=self.msg, msg_type=self.msg_type)
609 print ('<p><b>Editing ' + self.page_name
610 + ' for ' + cgi.escape(remote_user())
611 + ' from ' + cgi.escape(get_hostname(remote_host()))
613 print '<div class="editor"><form method="post" action="%s/%s">' % (script_name(), self.page_name)
614 print '<input type="hidden" name="savepage" value="%s">' % (self.page_name)
615 print """<textarea wrap="virtual" id="editor" name="savetext" rows="17" cols="80">%s</textarea>""" % (preview or self.get_raw_body())
618 <input type="submit" name="save" value="Save" />
619 <input type="submit" name="preview" value="Preview" />
620 <input type="reset" value="Reset" />
621 <input type="submit" name="cancel" value="Cancel" />
624 print "<p>" + Page('EditingTips').link_to() + "</p>"
626 print "<div class='preview'>"
627 PageFormatter(preview).print_html()
629 send_footer(self.page_name)
632 emit_header("text/plain")
633 print self.get_raw_body()
635 def _write_file(self, text):
636 tmp_filename = self._tmp_filename()
637 open(tmp_filename, 'wt').write(text.replace('\r\n', '\n'))
638 text = self._text_filename()
640 # Bad Bill! POSIX rename ought to replace. :-(
644 if er.errno <> errno.ENOENT: raise er
645 os.rename(tmp_filename, text)
647 def save_text(self, newtext):
648 self._write_file(newtext)
651 # FIXME: what's the std way to perform shell quoting in python?
652 cmd = ( post_edit_hook
653 + " '" + text_dir + '/' + self.page_name
654 + "' '" + remote_user()
655 + "' '" + remote_host() + "'"
661 self.msg += "Post-editing hook returned %d.\n" % rc
662 self.msg += 'Command was: ' + cmd + '\n'
664 self.msg += 'Output follows:\n' + msg
666 self.msg = 'Thankyou for your contribution. Your attention to detail is appreciated.'
667 self.msg_type = 'success'
669 def send_verbatim(filename, mime_type='application/octet-stream'):
670 pathname = path.join(text_dir, filename)
671 data = open(pathname, 'rb').read()
672 emit_header(mime_type)
673 sys.stdout.write(data)
675 # Main ---------------------------------------------------------------
677 # Configuration values
678 site_name = 'Codewiz'
680 # set to None for read-only sites
681 # leave empty ('') to allow anonymous edits
682 # otherwise, set to a URL that requires authentication
683 privileged_url = 'https://www.codewiz.org/~bernie/wiki'
685 data_dir = '/home/bernie/public_html/wiki'
686 text_dir = path.join(data_dir, 'text')
687 css_url = '../wikidata/geekigeeki.css' # optional stylesheet link
688 post_edit_hook = './post_edit_hook.sh'
689 datetime_fmt = '%a %d %b %Y %I:%M %p'
690 allow_edit = True # Is it possible to edit pages?
691 show_hosts = True # show hostnames?
692 nonexist_qm = False # show '?' for nonexistent?
693 debug_cgi = False # Set to True for CGI var dump
695 form = cgi.FieldStorage()
697 handlers = { 'fullsearch': do_fullsearch,
698 'titlesearch': do_titlesearch,
701 'savepage': do_savepage }
703 for cmd in handlers.keys():
704 if form.has_key(cmd):
705 apply(handlers[cmd], (form[cmd].value,))
708 path_info = environ.get('PATH_INFO', '')
709 if len(path_info) and path_info[0] == '/':
710 query = path_info[1:] or 'FrontPage'
712 query = environ.get('QUERY_STRING', '') or 'FrontPage'
714 if file_re.match(query):
715 if word_re.match(query):
716 Page(query).send_page()
717 elif img_re.match(query):
718 #FIXME: use correct mime type
719 send_verbatim(query, 'image/jpeg')
724 send_title(None, msg='Can\'t work out query: ' + query)
727 msg=traceback.format_exc()
729 send_guru(msg, "error")
731 send_title(None, msg=msg)