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 <a href="%(link)s">%(author)s</a>
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 return self.get_template(
448 'com_header', default_comment_header, comment.to_vars())
450 def get_comment_footer(self, comment):
451 return self.get_template(
452 'com_footer', default_comment_footer, comment.to_vars())
454 def get_comment_form(self, article, method, action):
455 vars = article.to_vars()
456 vars['form_method'] = method
457 vars['form_action'] = action
458 return self.get_template(
459 'com_footer', default_comment_form, vars)
462 class Comment (object):
463 def __init__(self, article, number, created = None):
464 self.article = article
467 self.created = datetime.datetime.now()
469 self.created = created
474 self._author = author
476 self._raw_content = 'Removed comment'
479 def get_author(self):
483 author = property(fget = get_author)
489 link = property(fget = get_link)
491 def get_raw_content(self):
494 return self._raw_content
495 raw_content = property(fget = get_raw_content)
498 def set(self, author, raw_content, link = '', created = None):
500 self._author = author
501 self._raw_content = raw_content
503 self.created = created or datetime.datetime.now()
507 filename = os.path.join(comments_path, self.article.uuid,
510 raw = open(filename).readlines()
517 name, value = l.split(':', 1)
518 if name.lower() == 'author':
519 self._author = value.strip()
520 elif name.lower() == 'link':
521 self._link = value.strip()
526 self._raw_content = ''.join(raw[count + 1:])
530 filename = os.path.join(comments_path, self.article.uuid,
533 f = open(filename, 'w')
534 f.write('Author: %s\n' % self.author)
535 f.write('Link: %s\n' % self.link)
537 f.write(self.raw_content)
543 return rst_to_html(self.raw_content)
547 'number': self.number,
548 'author': sanitize(self.author),
549 'link': sanitize(self.link),
550 'date': self.created.isoformat(' '),
551 'created': self.created.isoformat(' '),
553 'year': self.created.year,
554 'month': self.created.month,
555 'day': self.created.day,
556 'hour': self.created.hour,
557 'minute': self.created.minute,
558 'second': self.created.second,
561 class CommentDB (object):
562 def __init__(self, article):
563 self.path = os.path.join(comments_path, article.uuid)
567 def load(self, article):
569 f = open(os.path.join(self.path, 'db'))
574 # Each line has the following comma separated format:
575 # number, created (epoch)
576 # Empty lines are meaningful and represent removed
577 # comments (so we can preserve the comment number)
581 d = datetime.datetime.fromtimestamp(float(l[1]))
583 # Removed/invalid comment
584 self.comments.append(None)
586 self.comments.append(Comment(article, n, d))
589 old_db = os.path.join(self.path, 'db')
590 new_db = os.path.join(self.path, 'db.tmp')
591 f = open(new_db, 'w')
592 for c in self.comments:
596 s += str(c.number) + ', '
597 s += str(time.mktime(c.created.timetuple()))
601 os.rename(new_db, old_db)
604 class Article (object):
605 def __init__(self, path, created = None, updated = None):
607 self.created = created
608 self.updated = updated
609 self.uuid = "%08x" % zlib.crc32(self.path)
614 self._title = 'Removed post'
615 self._author = author
617 self._raw_content = ''
625 title = property(fget = get_title)
627 def get_author(self):
631 author = property(fget = get_author)
637 tags = property(fget = get_tags)
639 def get_raw_content(self):
642 return self._raw_content
643 raw_content = property(fget = get_raw_content)
645 def get_comments(self):
648 return self._comments
649 comments = property(fget = get_comments)
652 def __cmp__(self, other):
653 if self.path == other.path:
657 if not other.created:
659 if self.created < other.created:
663 def title_cmp(self, other):
664 return cmp(self.title, other.title)
667 def add_comment(self, author, raw_content, link = ''):
668 c = Comment(self, len(self.comments))
669 c.set(author, raw_content, link)
670 self.comments.append(c)
675 # XXX this tweak is only needed for old DB format, where
676 # article's paths started with a slash
678 if path.startswith('/'):
680 filename = os.path.join(data_path, path)
682 raw = open(filename).readlines()
689 name, value = l.split(':', 1)
690 if name.lower() == 'title':
691 self._title = value.strip()
692 elif name.lower() == 'author':
693 self._author = value.strip()
694 elif name.lower() == 'tags':
695 ts = value.split(',')
696 ts = [t.strip() for t in ts]
702 self._raw_content = ''.join(raw[count + 1:])
704 self._comments = db.comments
708 return rst_to_html(self.raw_content)
712 'arttitle': sanitize(self.title),
713 'author': sanitize(self.author),
714 'date': self.created.isoformat(' '),
716 'tags': self.get_tags_links(),
717 'comments': len(self.comments),
719 'created': self.created.isoformat(' '),
720 'ciso': self.created.isoformat(),
721 'cyear': self.created.year,
722 'cmonth': self.created.month,
723 'cday': self.created.day,
724 'chour': self.created.hour,
725 'cminute': self.created.minute,
726 'csecond': self.created.second,
728 'updated': self.updated.isoformat(' '),
729 'uiso': self.updated.isoformat(),
730 'uyear': self.updated.year,
731 'umonth': self.updated.month,
732 'uday': self.updated.day,
733 'uhour': self.updated.hour,
734 'uminute': self.updated.minute,
735 'usecond': self.updated.second,
738 def get_tags_links(self):
740 tags = list(self.tags)
743 l.append('<a class="tag" href="%s/tag/%s">%s</a>' % \
744 (blog_url, urllib.quote(t), sanitize(t) ))
748 class ArticleDB (object):
749 def __init__(self, dbpath):
753 self.actyears = set()
754 self.actmonths = set()
757 def get_articles(self, year = 0, month = 0, day = 0, tags = None):
759 for a in self.articles:
760 if year and a.created.year != year: continue
761 if month and a.created.month != month: continue
762 if day and a.created.day != day: continue
763 if tags and not tags.issubset(a.tags): continue
769 def get_article(self, uuid):
770 return self.uuids[uuid]
774 f = open(self.dbpath)
779 # Each line has the following comma separated format:
780 # path (relative to data_path), \
789 datetime.datetime.fromtimestamp(float(l[1])),
790 datetime.datetime.fromtimestamp(float(l[2])))
791 self.uuids[a.uuid] = a
792 self.actyears.add(a.created.year)
793 self.actmonths.add((a.created.year, a.created.month))
794 self.articles.append(a)
797 f = open(self.dbpath + '.tmp', 'w')
798 for a in self.articles:
801 s += str(time.mktime(a.created.timetuple())) + ', '
802 s += str(time.mktime(a.updated.timetuple())) + '\n'
805 os.rename(self.dbpath + '.tmp', self.dbpath)
807 def get_year_links(self):
808 yl = list(self.actyears)
809 yl.sort(reverse = True)
810 return [ '<a href="%s/%d/">%d</a>' % (blog_url, y, y)
813 def get_month_links(self, year):
814 am = [ i[1] for i in self.actmonths if i[0] == year ]
816 for i in range(1, 13):
817 name = calendar.month_name[i][:3]
819 s = '<a href="%s/%d/%d/">%s</a>' % \
820 ( blog_url, year, i, name )
831 def render_html(articles, db, actyear = None, show_comments = False,
833 if redirect is not None:
834 print 'Status: 303 See Other\r\n',
835 print 'Location: %s\r\n' % redirect,
836 print 'Content-type: text/html; charset=utf-8\r\n',
838 template = Templates(templates_path, db, actyear)
839 print template.get_main_header()
841 print template.get_article_header(a)
843 print template.get_article_footer(a)
845 print '<a name="comments" />'
849 print template.get_comment_header(c)
851 print template.get_comment_footer(c)
852 print template.get_comment_form(a, 'post',
853 blog_url + '/comment/' + a.uuid)
854 print template.get_main_footer()
856 def render_artlist(articles, db, actyear = None):
857 template = Templates(templates_path, db, actyear)
858 print 'Content-type: text/html; charset=utf-8\n'
859 print template.get_main_header()
860 print '<h2>Articles</h2>'
862 print '<li><a href="%(url)s/uuid/%(uuid)s">%(title)s</a></li>' \
868 print template.get_main_footer()
870 def render_atom(articles):
871 if len(articles) > 0:
872 updated = articles[0].updated.isoformat()
874 updated = datetime.datetime.now().isoformat()
876 print 'Content-type: application/atom+xml; charset=utf-8\n'
877 print """<?xml version="1.0" encoding="utf-8"?>
879 <feed xmlns="http://www.w3.org/2005/Atom">
880 <title>%(title)s</title>
881 <link rel="alternate" type="text/html" href="%(url)s"/>
882 <link rel="self" type="application/atom+xml" href="%(url)s/atom"/>
883 <id>%(url)s</id> <!-- TODO: find a better <id>, see RFC 4151 -->
884 <updated>%(updated)sZ</updated>
896 'contents': a.to_html(),
900 <title>%(arttitle)s</title>
901 <author><name>%(author)s</name></author>
902 <link href="%(url)s/post/%(uuid)s" />
903 <id>%(url)s/post/%(uuid)s</id>
904 <summary>%(arttitle)s</summary>
905 <published>%(ciso)sZ</published>
906 <updated>%(uiso)sZ</updated>
907 <content type="xhtml">
908 <div xmlns="http://www.w3.org/1999/xhtml"><p>
918 print 'Content-type: text/css\r\n\r\n',
922 import cgitb; cgitb.enable()
924 form = cgi.FieldStorage()
925 year = int(form.getfirst("year", 0))
926 month = int(form.getfirst("month", 0))
927 day = int(form.getfirst("day", 0))
928 tags = set(form.getlist("tag"))
936 if os.environ.has_key('PATH_INFO'):
937 path_info = os.environ['PATH_INFO']
938 style = path_info == '/style'
939 atom = path_info == '/atom'
940 tag = path_info.startswith('/tag/')
941 post = path_info.startswith('/post/')
942 artlist = path_info.startswith('/list')
943 comment = path_info.startswith('/comment/') and enable_comments
944 if not style and not atom and not post and not tag \
945 and not comment and not artlist:
946 date = path_info.split('/')[1:]
948 if len(date) > 1 and date[0]:
950 if len(date) > 2 and date[1]:
952 if len(date) > 3 and date[2]:
957 uuid = path_info.replace('/post/', '')
958 uuid = uuid.replace('/', '')
960 t = path_info.replace('/tag/', '')
961 t = t.replace('/', '')
962 t = urllib.unquote_plus(t)
965 uuid = path_info.replace('/comment/', '')
966 uuid = uuid.replace('/', '')
967 author = form.getfirst('comformauthor', '')
968 link = form.getfirst('comformlink', '')
969 body = form.getfirst('comformbody', '')
971 db = ArticleDB(os.path.join(data_path, 'db'))
973 articles = db.get_articles(tags = tags)
974 articles.sort(reverse = True)
975 render_atom(articles[:10])
979 render_html( [db.get_article(uuid)], db, year, enable_comments )
981 articles = db.get_articles()
982 articles.sort(cmp = Article.title_cmp)
983 render_artlist(articles, db)
985 author = author.strip().replace('\n', ' ')
986 link = link.strip().replace('\n', ' ')
988 article = db.get_article(uuid)
989 redirect = blog_url + '/post/' + uuid + '#comment'
990 if author and body and valid_rst(body):
991 c = article.add_comment(author, body, link)
993 cdb = CommentDB(article)
994 cdb.comments = article.comments
996 redirect += '-' + str(c.number)
997 render_html( [article], db, year, enable_comments,
998 redirect = redirect )
1000 articles = db.get_articles(year, month, day, tags)
1001 articles.sort(reverse = True)
1002 if not year and not month and not day and not tags:
1003 articles = articles[:10]
1004 render_html(articles, db, year)
1008 print 'Usage: %s {add|rm|update} article_path' % sys.argv[0]
1011 if len(sys.argv) != 3:
1016 art_path = os.path.realpath(sys.argv[2])
1018 if os.path.commonprefix([data_path, art_path]) != data_path:
1019 print "Error: article (%s) must be inside data_path (%s)" % \
1020 (art_path, data_path)
1022 art_path = art_path[len(data_path)+1:]
1024 db_filename = os.path.join(data_path, 'db')
1025 if not os.path.isfile(db_filename):
1026 open(db_filename, 'w').write('')
1027 db = ArticleDB(db_filename)
1030 article = Article(art_path, datetime.datetime.now(),
1031 datetime.datetime.now())
1032 for a in db.articles:
1034 print 'Error: article already exists'
1036 db.articles.append(article)
1039 comment_dir = os.path.join(comments_path, article.uuid)
1041 os.mkdir(comment_dir, 0775)
1043 if e.errno != errno.EEXIST:
1044 print "Error: can't create comments " \
1045 "directory %s (%s)" \
1047 # otherwise is probably a removed and re-added
1050 article = Article(art_path)
1051 for a in db.articles:
1055 print "Error: no such article"
1058 r = raw_input('Remove comments [y/N]? ')
1059 db.articles.remove(a)
1061 if enable_comments and r.lower() == 'y':
1062 shutil.rmtree(os.path.join(comments_path, a.uuid))
1063 elif cmd == 'update':
1064 article = Article(art_path)
1065 for a in db.articles:
1069 print "Error: no such article"
1071 a.updated = datetime.datetime.now()
1080 if os.environ.has_key('GATEWAY_INTERFACE'):
1083 sys.exit(handle_cmd())