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:-2]
22 import cgi, sys, string, os, re, errno, time, stat
23 from os import path, environ
25 # Regular expression defining a WikiWord
26 # (but this definition is also assumed in other places)
27 file_re = re.compile(r"^\b([A-Za-z0-9_\.\-]+)\b$")
28 word_re = re.compile(r"^\b([A-Z][a-z]+){2,}\b$")
29 img_re = re.compile(r"^.*\.(png|gif|jpg|jpeg)$", re.IGNORECASE)
30 url_re = re.compile(r"^[a-z]{3,8}://[^\s'\"]+\S$")
35 # CGI stuff ---------------------------------------------------------
38 return environ.get('SCRIPT_NAME', '')
40 def privileged_path():
41 return privileged_url or script_name()
44 user = environ.get('REMOTE_USER', '')
45 if user is None or user == '' or user == 'anonymous':
46 user = 'AnonymousCoward'
50 return environ.get('REMOTE_ADDR', '')
52 def get_hostname(addr):
54 from socket import gethostbyaddr
55 return gethostbyaddr(addr)[0] + ' (' + addr + ')'
59 # Formatting stuff --------------------------------------------------
61 def emit_header(type="text/html"):
62 print "Content-type: " + type + "; charset=utf-8"
65 def send_guru(msg, msg_type):
66 if msg is None or msg == '': return
67 print '<pre id="guru" onclick="this.style.display = \'none\'" class="' + msg_type + '">'
68 if msg_type == 'error':
69 print ' Software Failure. Press left mouse button to continue.\n'
71 if msg_type == 'error':
72 print ' Guru Meditation #DEADBEEF.ABADC0DE'
74 # FIXME: This simple JS snippet is harder to pass than ACID 3.0
76 <script language="JavaScript" type="text/javascript">
77 var guru = document.getElementById('guru');
78 // Firefox 2.0 doesn't take border-color, but returns border-top-color fine
79 var color = document.defaultView.getComputedStyle(guru,null).getPropertyValue('border-top-color');
82 guru.style.setProperty('border-color', color, '');
83 setTimeout('guruOff()', 1000);
86 guru.style.setProperty('border-color', '#000000', '');
87 setTimeout('guruOn()', 1000);
89 // Safari 2.0 returns this rgba crap
90 // Konqueror 3.5.6 doesn't seem to support computed properties
91 if (color && color != 'rgba(0, 0, 0, 0)') {
92 //window.alert("enabled! color='" + color + "'");
97 def send_title(name, text="Limbo", msg=None, msg_type='error'):
103 print """<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
104 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
105 <html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en">
107 print "<head><title>%s: %s</title>" % (site_name, text)
108 print ' <meta http-equiv="Content-Type" content="application/xhtml+xml; charset=utf-8" />'
110 print ' <meta name="robots" content="noindex,nofollow" />'
112 print ' <link rel="stylesheet" type="text/css" href="%s" />' % css_url
116 if name and privileged_url is not None:
117 print '<body ondblclick="location.href=\'' + privileged_path() + '?edit=' + name + '\'">'
122 send_guru(msg, msg_type)
125 print '<div class="nav">'
126 print ' <b>' + site_name + ': ',
128 print link_tag('?fullsearch=' + name, text) + '</b> '
131 print ' | ' + link_tag('FrontPage', 'Front Page', 'navlink')
132 print ' | ' + link_tag('FindPage', 'Find Page', 'navlink')
133 print ' | <a href="' + history_url + '" class="navlink">Recent Changes</a>'
136 print ' | <a href="' + history_url + '?a=history;f=' + name + '" class="navlink">Page History</a>'
137 print ' | ' + link_tag('?raw=' + name, 'Raw Text', 'navlink')
138 if privileged_url is not None:
139 print ' | ' + link_tag('?edit=' + name, 'Edit Page', 'navlink', authentication=True)
141 print ' | <i>Immutable Page</i>'
144 if user != 'AnonymousCoward':
145 print ' | <span class="login"><i>logged in as <b>' + cgi.escape(user) + '</b></i></span>'
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 potentially added by spammers or to generated pages
156 if ss_class == 'external' or ss_class == 'navlink':
157 classattr += 'rel="nofollow" '
159 path = privileged_path()
162 return '<a %shref="%s/%s">%s</a>' % (classattr, path, params, text)
164 # Search ---------------------------------------------------
166 def do_fullsearch(needle):
167 send_title(None, 'Full text search for "%s"' % (needle))
169 needle_re = re.compile(needle, re.IGNORECASE)
171 all_pages = page_list()
172 for page_name in all_pages:
173 body = Page(page_name).get_raw_body()
174 count = len(needle_re.findall(body))
176 hits.append((count, page_name))
178 # The default comparison for tuples compares elements in order,
179 # so this sorts by number of hits
184 for (count, page_name) in hits:
185 print '<li><p>' + Page(page_name).link_to()
186 print ' . . . . ' + `count`
187 print ['match', 'matches'][count <> 1]
191 print_search_stats(len(hits), len(all_pages))
194 def do_titlesearch(needle):
195 # TODO: check needle is legal -- but probably we can just accept any RE
196 send_title(None, "Title search for \"" + needle + '"')
198 needle_re = re.compile(needle, re.IGNORECASE)
199 all_pages = page_list()
200 hits = filter(needle_re.search, all_pages)
203 for filename in hits:
204 print '<li><p>' + Page(filename).link_to() + "</p></li>"
207 print_search_stats(len(hits), len(all_pages))
210 def print_search_stats(hits, searched):
211 print "<p>%d hits out of %d pages searched.</p>" % (hits, searched)
213 def do_edit(pagename):
214 Page(pagename).send_editor()
216 def do_raw(pagename):
217 Page(pagename).send_raw()
219 def do_savepage(pagename):
222 if 'preview' in form:
223 pg.send_editor(form['savetext'].value)
225 pg.save_text(form['savetext'].value)
227 elif 'cancel' in form:
228 pg.msg = 'Editing canceled'
229 pg.msg_type = 'notice'
232 raise 'What did you press?'
234 def make_index_key():
236 links = map(lambda ch: '<a href="#%s">%s</a>' % (ch, ch),
238 s = s + string.join(links, ' | ')
239 s = s + '</center></p>'
244 return filter(word_re.match, os.listdir(text_dir))
247 def send_footer(name, mod_string=None):
249 cgi.print_arguments()
250 cgi.print_form(cgi.FieldStorage())
253 print '<div id="footer"><hr />'
254 print ('<p class="copyright">Powered by' +
255 ' <a href="http://www.codewiz.org/wiki/GeekiGeeki">GeekiGeeki</a>' +
256 ' version %s</p>' % __version__)
258 print '<p class="modified">last modified %s</p>' % mod_string
259 print '</div></body></html>'
262 # ----------------------------------------------------------
264 def _macro_TitleSearch(*vargs):
265 return _macro_search("titlesearch")
267 def _macro_FullSearch(*vargs):
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="Search" /></form>""" % (type, default)
277 def _macro_WordIndex(*vargs):
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(*vargs):
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
338 self.list_indents = []
340 self.in_table = False
343 self.in_header = True
345 def _emph_repl(self, word):
347 self.is_b = not self.is_b
348 return ['</strong>', '<strong>'][self.is_b]
350 self.is_em = not self.is_em
351 return ['</em>', '<em>'][self.is_em]
353 def _tit_repl(self, word):
355 result = '</h%d>' % self.h_level
358 self.h_level = len(word) - 1
360 result = '<h%d id="%d"><a class="heading" href="#%d">*</a> ' % (self.h_level, self.h_count, self.h_count)
363 def _rule_repl(self, word):
364 return self._undent() + '\n<hr size="%d" noshade="noshade" />\n' % (len(word) - 2)
366 def _word_repl(self, word):
367 return Page(word).link_to()
369 def _img_repl(self, word):
370 path = script_name() + '/' + word;
371 return '<a href="%s"><img border="0" src="%s" /></a>' % (path, path)
373 def _url_repl(self, word):
374 if img_re.match(word):
375 return '<a href="%s"><img border="0" src="%s" /></a>' % (word, 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)
382 descr = m.group(2).strip() or name
384 macro = globals().get('_macro_' + name)
386 return apply(macro, (name, descr))
387 elif img_re.match(name):
388 return '<a href="%s"><img border="0" src="%s" alt="%s" /></a>' % (name, name, descr)
389 elif url_re.match(name):
390 return '<a href="%s" rel="nofollow" class="external">%s</a>' % (name, descr)
391 elif name.startswith('/'):
392 return '<a href="%s">%s</a>' % (name, descr)
394 return link_tag(name, descr)
396 def _email_repl(self, word):
397 return '<a href="mailto:%s">%s</a>' % (word, word)
399 def _html_repl(self, word):
400 return word; # Pass through
402 def _ent_repl(self, s):
403 return {'&': '&',
407 def _li_repl(self, match):
410 def _pre_repl(self, word):
411 if word == '{{{' and not self.in_pre:
419 def _hi_repl(self, word):
426 return '<strong class="highlight ' + cl + '">' + word + '</strong>'
428 def _var_repl(self, word):
429 if word == '{{' and not self.in_var:
437 def _tr_repl(self, word):
439 if not self.in_table:
442 out = '</p><table><tbody>\n'
444 return out + '<tr class="' + ['even', 'odd'][self.tr_cnt % 2] + '"><td>'
446 def _tre_repl(self, word):
451 def _td_repl(self, word):
456 def _indent_level(self):
457 return len(self.list_indents) and self.list_indents[-1]
459 def _indent_to(self, new_level):
460 if self._indent_level() == new_level:
463 while self._indent_level() > new_level:
464 del(self.list_indents[-1])
466 while self._indent_level() < new_level:
467 self.list_indents.append(new_level)
474 res += '</ul>' * len(self.list_indents)
476 self.list_indents = []
479 def replace(self, match):
480 for type, hit in match.groupdict().items():
482 return apply(getattr(self, '_' + type + '_repl'), (hit,))
484 raise "Can't handle match " + `match`
486 def print_html(self):
487 print '<div class="wiki"><p>'
489 # For each line, we scan through looking for magic
490 # strings, outputting verbatim any intervening text
491 # TODO: highlight search words (look at referer)
492 scan_re = re.compile(
495 + r"(?P<emph>'{2,3})"
496 + r"|(?P<tit>\={2,6})"
497 + r"|(?P<rule>^-{3,})"
498 + r"|(?P<html><(/|)(div|span|iframe)[^<>]*>)"
500 + r"|(?P<hi>\b(FIXME|TODO|DONE)\b)"
503 + r"|(?P<img>\b[a-zA-Z0-9_-]+\.(png|gif|jpg|jpeg|bmp))"
504 + r"|(?P<word>\b(?:[A-Z][a-z]+){2,}\b)"
505 + r"|(?P<hurl>\[\[\S+[^\]]*\]\])"
506 + r"|(?P<url>(http|https|ftp|mailto)\:[^\s'\"]+\S)"
507 + r"|(?P<email>[-\w._+]+\@[\w.-]+)"
511 + r"|(?P<pre>(\{\{\{|\s*\}\}\}))"
512 + r"|(?P<var>(\{\{|\}\}))"
515 + r"|(?P<tr>^\s*\|\|\s*)"
516 + r"|(?P<tre>\s*\|\|\s*$)"
517 + r"|(?P<td>\s*\|\|\s*)"
521 + r"(?P<pre>\s*\}\}\})"
523 blank_re = re.compile(r"^\s*$")
524 indent_re = re.compile(r"^\s*")
525 tr_re = re.compile(r"^\s*\|\|")
526 eol_re = re.compile(r"\r?\n")
527 raw = string.expandtabs(self.raw)
528 for line in eol_re.split(raw):
531 if line.startswith('#'):
533 self.in_header = False
536 print re.sub(pre_re, self.replace, line)
538 if self.in_table and not tr_re.match(line):
539 self.in_table = False
540 print '</tbody></table><p>'
542 if blank_re.match(line):
545 indent = indent_re.match(line)
546 print self._indent_to(len(indent.group(0)))
547 print re.sub(scan_re, self.replace, line)
549 if self.in_pre: print '</pre>'
550 if self.in_table: print '</tbody></table><p>'
554 # ----------------------------------------------------------
556 def __init__(self, page_name):
557 self.page_name = page_name
559 self.msg_type = 'error'
562 def split_title(self):
563 # look for the end of words and the start of a new word,
564 # and insert a space there
565 return re.sub('([a-z])([A-Z])', r'\1 \2', self.page_name)
567 def _text_filename(self):
568 return path.join(text_dir, self.page_name)
570 def _tmp_filename(self):
571 return path.join(text_dir, ('#' + self.page_name + '.' + `os.getpid()` + '#'))
575 os.stat(self._text_filename())
578 if er.errno == errno.ENOENT:
584 word = self.page_name
586 return link_tag(word, word, 'wikilink')
588 return link_tag(word, nonexist_pfx + word, 'nonexistent')
590 def get_raw_body(self):
592 return open(self._text_filename(), 'rt').read()
594 if er.errno == errno.ENOENT:
595 # just doesn't exist, use default
596 return 'Describe %s here.' % self.page_name
604 file = open(self._text_filename(), 'rt')
605 attr_re = re.compile(r"^#(\S*)(.*)$")
607 m = attr_re.match(line)
610 self.attrs[m.group(1)] = m.group(2).strip()
611 #print "bernie: attrs[" + m.group(1) + "] = " + m.group(2) + "<br>\n"
613 if er.errno != errno.ENOENT:
617 def can(self, action, default=True):
618 attrs = self.get_attrs()
620 # SomeUser:read,write All:read
622 for rule in acl.split():
623 (user,perms) = rule.split(':')
624 if user == remote_user() or user == "All":
625 if action in perms.split(','):
630 except Exception, er:
635 return self.can("write", True)
638 return self.can("read", True)
643 page_name = self.page_name
644 send_title(page_name, self.split_title(), msg=self.msg, msg_type=self.msg_type)
646 PageFormatter(self.get_raw_body()).print_html()
648 send_guru("Read access denied by ACLs", "notice")
649 send_footer(page_name, self._last_modified())
651 def _last_modified(self):
652 if not self.exists():
654 from time import localtime, strftime
655 modtime = localtime(os.stat(self._text_filename())[stat.ST_MTIME])
656 return strftime(datetime_fmt, modtime)
658 def send_editor(self, preview=None):
659 send_title(None, 'Edit ' + self.split_title(), msg=self.msg, msg_type=self.msg_type)
660 if not self.can_write():
661 send_guru("Write access denied by ACLs", "error")
664 print ('<p><b>Editing ' + self.page_name
665 + ' for ' + cgi.escape(remote_user())
666 + ' from ' + cgi.escape(get_hostname(remote_host()))
668 print '<div class="editor"><form method="post" action="%s/%s">' % (script_name(), self.page_name)
669 print '<input type="hidden" name="savepage" value="%s">' % (self.page_name)
670 print """<textarea wrap="virtual" id="editor" name="savetext" rows="17" cols="80">%s</textarea>""" % (preview or self.get_raw_body())
673 <input type="submit" name="save" value="Save" />
674 <input type="submit" name="preview" value="Preview" />
675 <input type="reset" value="Reset" />
676 <input type="submit" name="cancel" value="Cancel" />
679 print "<p>" + Page('EditingTips').link_to() + "</p>"
681 print "<div class='preview'>"
682 PageFormatter(preview).print_html()
684 send_footer(self.page_name)
687 if not self.can_read():
688 send_title(None, msg='Read access denied by ACLs', msg_type='notice')
690 emit_header("text/plain")
691 print self.get_raw_body()
693 def _write_file(self, text):
694 tmp_filename = self._tmp_filename()
695 open(tmp_filename, 'wt').write(text.replace('\r\n', '\n'))
696 text = self._text_filename()
698 # Bad Bill! POSIX rename ought to replace. :-(
702 if er.errno <> errno.ENOENT: raise er
703 os.rename(tmp_filename, text)
705 def save_text(self, newtext):
706 if not self.can_write():
707 self.msg = 'Write access denied by ACLs'
708 self.msg_type = 'error'
711 self._write_file(newtext)
714 # FIXME: what's the std way to perform shell quoting in python?
715 cmd = ( post_edit_hook
716 + " '" + text_dir + '/' + self.page_name
717 + "' '" + remote_user()
718 + "' '" + remote_host() + "'"
724 self.msg += "Post-editing hook returned %d.\n" % rc
725 self.msg += 'Command was: ' + cmd + '\n'
727 self.msg += 'Output follows:\n' + msg
729 self.msg = 'Thank you for your contribution. Your attention to detail is appreciated.'
730 self.msg_type = 'success'
732 def send_verbatim(filename, mime_type='application/octet-stream'):
733 pathname = path.join(text_dir, filename)
734 data = open(pathname, 'rb').read()
735 emit_header(mime_type)
736 sys.stdout.write(data)
738 # Main ---------------------------------------------------------------
740 # Configuration values
741 site_name = 'Codewiz'
743 # set to None for read-only sites, leave empty ('') to allow anonymous edits
744 # otherwise, set to a URL that requires authentication
745 privileged_url = 'https://www.codewiz.org/~bernie/wiki'
747 data_dir = '/home/bernie/public_html/wiki'
748 text_dir = path.join(data_dir, 'text')
749 css_url = '../wikidata/geekigeeki.css' # optional stylesheet link
750 history_url = '../wikigit/wiki.git'
751 post_edit_hook = './post_edit_hook.sh'
752 datetime_fmt = '%a %d %b %Y %I:%M %p'
753 allow_edit = True # Is it possible to edit pages?
754 show_hosts = True # show hostnames?
755 nonexist_pfx = '' # prefix before nonexistent link (usually '?')
756 debug_cgi = False # Set to True for CGI var dump
758 form = cgi.FieldStorage()
760 handlers = { 'fullsearch': do_fullsearch,
761 'titlesearch': do_titlesearch,
764 'savepage': do_savepage }
766 for cmd in handlers.keys():
767 if form.has_key(cmd):
768 apply(handlers[cmd], (form[cmd].value,))
771 path_info = environ.get('PATH_INFO', '')
772 if len(path_info) and path_info[0] == '/':
773 query = path_info[1:] or 'FrontPage'
775 query = environ.get('QUERY_STRING', '') or 'FrontPage'
777 if file_re.match(query):
778 if word_re.match(query):
779 Page(query).send_page()
780 elif img_re.match(query):
781 #FIXME: use correct mime type
782 send_verbatim(query, 'image/jpeg')
787 send_title(None, msg='Can\'t work out query: ' + query)
790 msg=traceback.format_exc()
792 send_guru(msg, "error")
794 send_title(None, msg=msg)