4 # blitiri - A single-file blog engine.
5 # Alberto Bertogli (albertito@gmail.com)
8 # Configuration section
10 # You can edit these values, or create a file named "config.py" and put them
11 # there to make updating easier. The ones in config.py take precedence.
14 # Directory where entries are stored
15 data_path = "/tmp/blog/data"
17 # Are comments allowed? (if False, comments_path option is not used)
18 enable_comments = False
20 # Directory where comments are stored (must be writeable by the web server)
21 comments_path = "/tmp/blog/comments"
23 # Path where templates are stored. Use an empty string for the built-in
24 # default templates. If they're not found, the built-in ones will be used.
25 templates_path = "/tmp/blog/templates"
27 # URL to the blog, including the name. Can be a full URL or just the path.
28 blog_url = "/blog/blitiri.cgi"
30 # Style sheet (CSS) URL. Can be relative or absolute. To use the built-in
31 # default, set it to blog_url + "/style".
32 css_url = blog_url + "/style"
35 title = "I don't like blogs"
38 author = "Hartmut Kegan"
44 # End of configuration
45 # DO *NOT* EDIT ANYTHING PAST HERE
59 from docutils.core import publish_parts
61 # Before importing the config, add our cwd to the Python path
62 sys.path.append(os.getcwd())
64 # Load the config file, if there is one
71 # Pimp *_path config variables to support relative paths
72 data_path = os.path.realpath(data_path)
73 templates_path = os.path.realpath(templates_path)
77 default_main_header = """\
78 <?xml version="1.0" encoding="utf-8"?>
79 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
80 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
82 <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
84 <link rel="alternate" title="%(title)s" href="%(fullurl)s/atom"
85 type="application/atom+xml" />
86 <link href="%(css_url)s" rel="stylesheet" type="text/css" />
87 <title>%(title)s</title>
92 <h1><a href="%(url)s">%(title)s</a></h1>
97 default_main_footer = """
100 %(showyear)s: %(monthlinks)s<br/>
101 years: %(yearlinks)s<br/>
102 subscribe: <a href="%(url)s/atom">atom</a><br/>
103 views: <a href="%(url)s/">blog</a> <a href="%(url)s/list">list</a><br/>
110 default_article_header = """
111 <div class="article">
112 <h2><a href="%(url)s/post/%(uuid)s">%(arttitle)s</a></h2>
113 <span class="artinfo">
114 by %(author)s on <span class="date">
116 <a class="date" href="%(url)s/%(cyear)d/">%(cyear)04d</a>-\
117 <a class="date" href="%(url)s/%(cyear)d/%(cmonth)d/">%(cmonth)02d</a>-\
118 <a class="date" href="%(url)s/%(cyear)d/%(cmonth)d/%(cday)d/">%(cday)02d</a>\
119 %(chour)02d:%(cminute)02d</span>
120 (updated on <span class="date">
121 <a class="date" href="%(url)s/%(uyear)d/">%(uyear)04d</a>-\
122 <a class="date" href="%(url)s/%(uyear)d/%(umonth)d/">%(umonth)02d</a>-\
123 <a class="date" href="%(url)s/%(uyear)d/%(umonth)d/%(uday)d/">%(uday)02d</a>\
124 %(uhour)02d:%(uminute)02d)</span><br/>
125 <span class="tags">tagged %(tags)s</span> -
126 <span class="comments">with %(comments)s
127 <a href="%(url)s/post/%(uuid)s#comments">comment(s)</a></span>
130 <div class="artbody">
133 default_article_footer = """
139 default_comment_header = """
140 <div class="comment">
141 <a name="comment-%(number)d" />
142 <h3><a href="#comment-%(number)d">Comment #%(number)d</a></h3>
143 <span class="cominfo">by %(linked_author)s
144 on %(year)04d-%(month)02d-%(day)02d %(hour)02d:%(minute)02d</span>
146 <div class="combody">
149 default_comment_footer = """
155 default_comment_form = """
156 <div class="comform">
158 <h3 class="comform"><a href="#comment">Your comment</a></h3>
159 <div class="comforminner">
160 <form method="%(form_method)s" action="%(form_action)s">
161 <div class="comformauthor">
162 <label for="comformauthor">Your name</label>
163 <input type="text" class="comformauthor" id="comformauthor"
164 name="comformauthor" />
166 <div class="comformlink">
167 <label for="comformlink">Your link
168 <span class="comformoptional">(optional, will be published)</span></label>
169 <input type="text" class="comformlink" id="comformlink"
170 name="comformlink" />
171 <div class="comformhelp">
172 like <span class="formurlexample">http://www.example.com/</span>
173 or <span class="formurlexample">mailto:you@example.com</span>
176 <div class="comformbody">
177 <label for="comformbody" class="comformbody">The comment</label>
178 <textarea class="comformbody" id="comformbody" name="comformbody" rows="15"
179 cols="80"></textarea>
180 <div class="comformhelp">
182 <a href="http://docutils.sourceforge.net/docs/user/rst/quickref.html">\
183 RestructuredText</a> format, please
186 <div class="comformsend">
187 <button type="submit" class="comformsend" id="comformsend" name="comformsend">
200 font-family: sans-serif;
211 border-bottom: 2px solid #99F;
220 border-bottom: 1px solid #99C;
227 border-bottom: 1px solid #99C;
231 text-decoration: none;
240 text-decoration: none;
244 span.artinfo a:hover {
245 text-decoration: none;
262 text-decoration: none;
266 span.cominfo a:hover {
267 text-decoration: none;
291 border-bottom: 1px solid #99C;
296 div.comform span.comformoptional {
312 span.formurlexample {
314 background-color: #EEF;
315 font-family: monospace;
317 padding-right: 0.2em;
320 textarea.comformbody {
321 font-family: monospace;
335 background-color: #99F;
343 border-top: 2px solid #99F;
348 text-decoration: none;
351 /* Articles are enclosed in <div class="section"> */
357 border-bottom: 1px dotted #99C;
363 def rst_to_html(rst):
365 'input_encoding': encoding,
366 'output_encoding': 'utf8',
370 parts = publish_parts(rst, settings_overrides = settings,
371 writer_name = "html")
372 return parts['body'].encode('utf8')
382 if isinstance(obj, basestring):
383 return cgi.escape(obj, True)
387 # find out our URL, needed for syndication
389 n = os.environ['SERVER_NAME']
390 p = os.environ['SERVER_PORT']
391 s = os.environ['SCRIPT_NAME']
394 full_url = 'http://%s%s%s' % (n, p, s)
396 full_url = 'Not needed'
399 class Templates (object):
400 def __init__(self, tpath, db, showyear = None):
403 now = datetime.datetime.now()
415 'showyear': showyear,
416 'monthlinks': ' '.join(db.get_month_links(showyear)),
417 'yearlinks': ' '.join(db.get_year_links()),
420 def get_template(self, page_name, default_template, extra_vars = None):
421 if extra_vars is None:
424 vars = self.vars.copy()
425 vars.update(extra_vars)
427 p = '%s/%s.html' % (self.tpath, page_name)
428 if os.path.isfile(p):
429 return open(p).read() % vars
430 return default_template % vars
432 def get_main_header(self):
433 return self.get_template('header', default_main_header)
435 def get_main_footer(self):
436 return self.get_template('footer', default_main_footer)
438 def get_article_header(self, article):
439 return self.get_template(
440 'art_header', default_article_header, article.to_vars())
442 def get_article_footer(self, article):
443 return self.get_template(
444 'art_footer', default_article_footer, article.to_vars())
446 def get_comment_header(self, comment):
447 vars = comment.to_vars()
449 vars['linked_author'] = '<a href="%s">%s</a>' \
450 % (comment.link, comment.author)
452 vars['linked_author'] = comment.author
453 return self.get_template(
454 'com_header', default_comment_header, vars)
456 def get_comment_footer(self, comment):
457 return self.get_template(
458 'com_footer', default_comment_footer, comment.to_vars())
460 def get_comment_form(self, article, method, action):
461 vars = article.to_vars()
462 vars['form_method'] = method
463 vars['form_action'] = action
464 return self.get_template(
465 'com_form', default_comment_form, vars)
468 class Comment (object):
469 def __init__(self, article, number, created = None):
470 self.article = article
473 self.created = datetime.datetime.now()
475 self.created = created
480 self._author = author
482 self._raw_content = 'Removed comment'
485 def get_author(self):
489 author = property(fget = get_author)
495 link = property(fget = get_link)
497 def get_raw_content(self):
500 return self._raw_content
501 raw_content = property(fget = get_raw_content)
504 def set(self, author, raw_content, link = '', created = None):
506 self._author = author
507 self._raw_content = raw_content
509 self.created = created or datetime.datetime.now()
513 filename = os.path.join(comments_path, self.article.uuid,
516 raw = open(filename).readlines()
523 name, value = l.split(':', 1)
524 if name.lower() == 'author':
525 self._author = value.strip()
526 elif name.lower() == 'link':
527 self._link = value.strip()
532 self._raw_content = ''.join(raw[count + 1:])
536 filename = os.path.join(comments_path, self.article.uuid,
539 f = open(filename, 'w')
540 f.write('Author: %s\n' % self.author)
541 f.write('Link: %s\n' % self.link)
543 f.write(self.raw_content)
549 return rst_to_html(self.raw_content)
553 'number': self.number,
554 'author': sanitize(self.author),
555 'link': sanitize(self.link),
556 'date': self.created.isoformat(' '),
557 'created': self.created.isoformat(' '),
559 'year': self.created.year,
560 'month': self.created.month,
561 'day': self.created.day,
562 'hour': self.created.hour,
563 'minute': self.created.minute,
564 'second': self.created.second,
567 class CommentDB (object):
568 def __init__(self, article):
569 self.path = os.path.join(comments_path, article.uuid)
573 def load(self, article):
575 f = open(os.path.join(self.path, 'db'))
580 # Each line has the following comma separated format:
581 # number, created (epoch)
582 # Empty lines are meaningful and represent removed
583 # comments (so we can preserve the comment number)
587 d = datetime.datetime.fromtimestamp(float(l[1]))
589 # Removed/invalid comment
590 self.comments.append(None)
592 self.comments.append(Comment(article, n, d))
595 old_db = os.path.join(self.path, 'db')
596 new_db = os.path.join(self.path, 'db.tmp')
597 f = open(new_db, 'w')
598 for c in self.comments:
602 s += str(c.number) + ', '
603 s += str(time.mktime(c.created.timetuple()))
607 os.rename(new_db, old_db)
610 class Article (object):
611 def __init__(self, path, created = None, updated = None):
613 self.created = created
614 self.updated = updated
615 self.uuid = "%08x" % zlib.crc32(self.path)
620 self._title = 'Removed post'
621 self._author = author
623 self._raw_content = ''
631 title = property(fget = get_title)
633 def get_author(self):
637 author = property(fget = get_author)
643 tags = property(fget = get_tags)
645 def get_raw_content(self):
648 return self._raw_content
649 raw_content = property(fget = get_raw_content)
651 def get_comments(self):
654 return self._comments
655 comments = property(fget = get_comments)
658 def __cmp__(self, other):
659 if self.path == other.path:
663 if not other.created:
665 if self.created < other.created:
669 def title_cmp(self, other):
670 return cmp(self.title, other.title)
673 def add_comment(self, author, raw_content, link = ''):
674 c = Comment(self, len(self.comments))
675 c.set(author, raw_content, link)
676 self.comments.append(c)
681 # XXX this tweak is only needed for old DB format, where
682 # article's paths started with a slash
684 if path.startswith('/'):
686 filename = os.path.join(data_path, path)
688 raw = open(filename).readlines()
695 name, value = l.split(':', 1)
696 if name.lower() == 'title':
697 self._title = value.strip()
698 elif name.lower() == 'author':
699 self._author = value.strip()
700 elif name.lower() == 'tags':
701 ts = value.split(',')
702 ts = [t.strip() for t in ts]
708 self._raw_content = ''.join(raw[count + 1:])
710 self._comments = db.comments
714 return rst_to_html(self.raw_content)
718 'arttitle': sanitize(self.title),
719 'author': sanitize(self.author),
720 'date': self.created.isoformat(' '),
722 'tags': self.get_tags_links(),
723 'comments': len(self.comments),
725 'created': self.created.isoformat(' '),
726 'ciso': self.created.isoformat(),
727 'cyear': self.created.year,
728 'cmonth': self.created.month,
729 'cday': self.created.day,
730 'chour': self.created.hour,
731 'cminute': self.created.minute,
732 'csecond': self.created.second,
734 'updated': self.updated.isoformat(' '),
735 'uiso': self.updated.isoformat(),
736 'uyear': self.updated.year,
737 'umonth': self.updated.month,
738 'uday': self.updated.day,
739 'uhour': self.updated.hour,
740 'uminute': self.updated.minute,
741 'usecond': self.updated.second,
744 def get_tags_links(self):
746 tags = list(self.tags)
749 l.append('<a class="tag" href="%s/tag/%s">%s</a>' % \
750 (blog_url, urllib.quote(t), sanitize(t) ))
754 class ArticleDB (object):
755 def __init__(self, dbpath):
759 self.actyears = set()
760 self.actmonths = set()
763 def get_articles(self, year = 0, month = 0, day = 0, tags = None):
765 for a in self.articles:
766 if year and a.created.year != year: continue
767 if month and a.created.month != month: continue
768 if day and a.created.day != day: continue
769 if tags and not tags.issubset(a.tags): continue
775 def get_article(self, uuid):
776 return self.uuids[uuid]
780 f = open(self.dbpath)
785 # Each line has the following comma separated format:
786 # path (relative to data_path), \
795 datetime.datetime.fromtimestamp(float(l[1])),
796 datetime.datetime.fromtimestamp(float(l[2])))
797 self.uuids[a.uuid] = a
798 self.actyears.add(a.created.year)
799 self.actmonths.add((a.created.year, a.created.month))
800 self.articles.append(a)
803 f = open(self.dbpath + '.tmp', 'w')
804 for a in self.articles:
807 s += str(time.mktime(a.created.timetuple())) + ', '
808 s += str(time.mktime(a.updated.timetuple())) + '\n'
811 os.rename(self.dbpath + '.tmp', self.dbpath)
813 def get_year_links(self):
814 yl = list(self.actyears)
815 yl.sort(reverse = True)
816 return [ '<a href="%s/%d/">%d</a>' % (blog_url, y, y)
819 def get_month_links(self, year):
820 am = [ i[1] for i in self.actmonths if i[0] == year ]
822 for i in range(1, 13):
823 name = calendar.month_name[i][:3]
825 s = '<a href="%s/%d/%d/">%s</a>' % \
826 ( blog_url, year, i, name )
837 def render_html(articles, db, actyear = None, show_comments = False,
839 if redirect is not None:
840 print 'Status: 303 See Other\r\n',
841 print 'Location: %s\r\n' % redirect,
842 print 'Content-type: text/html; charset=utf-8\r\n',
844 template = Templates(templates_path, db, actyear)
845 print template.get_main_header()
847 print template.get_article_header(a)
849 print template.get_article_footer(a)
851 print '<a name="comments" />'
855 print template.get_comment_header(c)
857 print template.get_comment_footer(c)
858 print template.get_comment_form(a, 'post',
859 blog_url + '/comment/' + a.uuid)
860 print template.get_main_footer()
862 def render_artlist(articles, db, actyear = None):
863 template = Templates(templates_path, db, actyear)
864 print 'Content-type: text/html; charset=utf-8\n'
865 print template.get_main_header()
866 print '<h2>Articles</h2>'
868 print '<li><a href="%(url)s/uuid/%(uuid)s">%(title)s</a></li>' \
874 print template.get_main_footer()
876 def render_atom(articles):
877 if len(articles) > 0:
878 updated = articles[0].updated.isoformat()
880 updated = datetime.datetime.now().isoformat()
882 print 'Content-type: application/atom+xml; charset=utf-8\n'
883 print """<?xml version="1.0" encoding="utf-8"?>
885 <feed xmlns="http://www.w3.org/2005/Atom">
886 <title>%(title)s</title>
887 <link rel="alternate" type="text/html" href="%(url)s"/>
888 <link rel="self" type="application/atom+xml" href="%(url)s/atom"/>
889 <id>%(url)s</id> <!-- TODO: find a better <id>, see RFC 4151 -->
890 <updated>%(updated)sZ</updated>
902 'contents': a.to_html(),
906 <title>%(arttitle)s</title>
907 <author><name>%(author)s</name></author>
908 <link href="%(url)s/post/%(uuid)s" />
909 <id>%(url)s/post/%(uuid)s</id>
910 <summary>%(arttitle)s</summary>
911 <published>%(ciso)sZ</published>
912 <updated>%(uiso)sZ</updated>
913 <content type="xhtml">
914 <div xmlns="http://www.w3.org/1999/xhtml"><p>
924 print 'Content-type: text/css\r\n\r\n',
928 import cgitb; cgitb.enable()
930 form = cgi.FieldStorage()
931 year = int(form.getfirst("year", 0))
932 month = int(form.getfirst("month", 0))
933 day = int(form.getfirst("day", 0))
934 tags = set(form.getlist("tag"))
942 if os.environ.has_key('PATH_INFO'):
943 path_info = os.environ['PATH_INFO']
944 style = path_info == '/style'
945 atom = path_info == '/atom'
946 tag = path_info.startswith('/tag/')
947 post = path_info.startswith('/post/')
948 artlist = path_info.startswith('/list')
949 comment = path_info.startswith('/comment/') and enable_comments
950 if not style and not atom and not post and not tag \
951 and not comment and not artlist:
952 date = path_info.split('/')[1:]
954 if len(date) > 1 and date[0]:
956 if len(date) > 2 and date[1]:
958 if len(date) > 3 and date[2]:
963 uuid = path_info.replace('/post/', '')
964 uuid = uuid.replace('/', '')
966 t = path_info.replace('/tag/', '')
967 t = t.replace('/', '')
968 t = urllib.unquote_plus(t)
971 uuid = path_info.replace('/comment/', '')
972 uuid = uuid.replace('/', '')
973 author = form.getfirst('comformauthor', '')
974 link = form.getfirst('comformlink', '')
975 body = form.getfirst('comformbody', '')
977 db = ArticleDB(os.path.join(data_path, 'db'))
979 articles = db.get_articles(tags = tags)
980 articles.sort(reverse = True)
981 render_atom(articles[:10])
985 render_html( [db.get_article(uuid)], db, year, enable_comments )
987 articles = db.get_articles()
988 articles.sort(cmp = Article.title_cmp)
989 render_artlist(articles, db)
991 author = author.strip().replace('\n', ' ')
992 link = link.strip().replace('\n', ' ')
994 article = db.get_article(uuid)
995 redirect = blog_url + '/post/' + uuid + '#comment'
996 if author and body and valid_rst(body):
997 c = article.add_comment(author, body, link)
999 cdb = CommentDB(article)
1000 cdb.comments = article.comments
1002 redirect += '-' + str(c.number)
1003 render_html( [article], db, year, enable_comments,
1004 redirect = redirect )
1006 articles = db.get_articles(year, month, day, tags)
1007 articles.sort(reverse = True)
1008 if not year and not month and not day and not tags:
1009 articles = articles[:10]
1010 render_html(articles, db, year)
1014 print 'Usage: %s {add|rm|update} article_path' % sys.argv[0]
1017 if len(sys.argv) != 3:
1022 art_path = os.path.realpath(sys.argv[2])
1024 if os.path.commonprefix([data_path, art_path]) != data_path:
1025 print "Error: article (%s) must be inside data_path (%s)" % \
1026 (art_path, data_path)
1028 art_path = art_path[len(data_path)+1:]
1030 db_filename = os.path.join(data_path, 'db')
1031 if not os.path.isfile(db_filename):
1032 open(db_filename, 'w').write('')
1033 db = ArticleDB(db_filename)
1036 article = Article(art_path, datetime.datetime.now(),
1037 datetime.datetime.now())
1038 for a in db.articles:
1040 print 'Error: article already exists'
1042 db.articles.append(article)
1045 comment_dir = os.path.join(comments_path, article.uuid)
1047 os.mkdir(comment_dir, 0775)
1049 if e.errno != errno.EEXIST:
1050 print "Error: can't create comments " \
1051 "directory %s (%s)" \
1053 # otherwise is probably a removed and re-added
1056 article = Article(art_path)
1057 for a in db.articles:
1061 print "Error: no such article"
1064 r = raw_input('Remove comments [y/N]? ')
1065 db.articles.remove(a)
1067 if enable_comments and r.lower() == 'y':
1068 shutil.rmtree(os.path.join(comments_path, a.uuid))
1069 elif cmd == 'update':
1070 article = Article(art_path)
1071 for a in db.articles:
1075 print "Error: no such article"
1077 a.updated = datetime.datetime.now()
1086 if os.environ.has_key('GATEWAY_INTERFACE'):
1089 sys.exit(handle_cmd())