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 # Directory where comments are stored (must be writeable by the web server)
18 comments_path = "/tmp/blog/comments"
20 # Path where templates are stored. Use an empty string for the built-in
21 # default templates. If they're not found, the built-in ones will be used.
22 templates_path = "/tmp/blog/templates"
24 # URL to the blog, including the name. Can be a full URL or just the path.
25 blog_url = "/blog/blitiri.cgi"
27 # Style sheet (CSS) URL. Can be relative or absolute. To use the built-in
28 # default, set it to blog_url + "/style".
29 css_url = blog_url + "/style"
32 title = "I don't like blogs"
35 author = "Hartmut Kegan"
41 # End of configuration
42 # DO *NOT* EDIT ANYTHING PAST HERE
54 from docutils.core import publish_parts
56 # Before importing the config, add our cwd to the Python path
57 sys.path.append(os.getcwd())
59 # Load the config file, if there is one
66 # Pimp *_path config variables to support relative paths
67 data_path = os.path.realpath(data_path)
68 templates_path = os.path.realpath(templates_path)
72 default_main_header = """\
73 <?xml version="1.0" encoding="utf-8"?>
74 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
75 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
77 <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
79 <link rel="alternate" title="%(title)s" href="%(fullurl)s/atom"
80 type="application/atom+xml" />
81 <link href="%(css_url)s" rel="stylesheet" type="text/css" />
82 <title>%(title)s</title>
87 <h1><a href="%(url)s">%(title)s</a></h1>
92 default_main_footer = """
95 %(showyear)s: %(monthlinks)s<br/>
96 years: %(yearlinks)s<br/>
97 subscribe: <a href="%(url)s/atom">atom</a><br/>
98 views: <a href="%(url)s/">blog</a> <a href="%(url)s/list">list</a><br/>
105 default_article_header = """
106 <div class="article">
107 <h2><a href="%(url)s/post/%(uuid)s">%(arttitle)s</a></h2>
108 <span class="artinfo">
109 by %(author)s on <span class="date">
111 <a class="date" href="%(url)s/%(cyear)d/">%(cyear)04d</a>-\
112 <a class="date" href="%(url)s/%(cyear)d/%(cmonth)d/">%(cmonth)02d</a>-\
113 <a class="date" href="%(url)s/%(cyear)d/%(cmonth)d/%(cday)d/">%(cday)02d</a>\
114 %(chour)02d:%(cminute)02d</span>
115 (updated on <span class="date">
116 <a class="date" href="%(url)s/%(uyear)d/">%(uyear)04d</a>-\
117 <a class="date" href="%(url)s/%(uyear)d/%(umonth)d/">%(umonth)02d</a>-\
118 <a class="date" href="%(url)s/%(uyear)d/%(umonth)d/%(uday)d/">%(uday)02d</a>\
119 %(uhour)02d:%(uminute)02d)</span><br/>
120 <span class="tags">tagged %(tags)s</span> -
121 <span class="comments">with %(comments)s comment(s)</span>
124 <div class="artbody">
127 default_article_footer = """
133 default_comment_header = """
134 <div class="comment">
135 <a name="comment-%(number)d" />
136 <h3><a href="#comment-%(number)d">Comment #%(number)d</a></h3>
137 <span class="cominfo">by <a href="%(link)s">%(author)s</a>
138 on %(year)04d-%(month)02d-%(day)02d %(hour)02d:%(minute)02d</span>
140 <div class="combody">
143 default_comment_footer = """
153 font-family: sans-serif;
164 border-bottom: 2px solid #99F;
173 border-bottom: 1px solid #99C;
180 border-bottom: 1px solid #99C;
184 text-decoration: none;
193 text-decoration: none;
197 span.artinfo a:hover {
198 text-decoration: none;
215 text-decoration: none;
219 span.cominfo a:hover {
220 text-decoration: none;
237 background-color: #99F;
245 border-top: 2px solid #99F;
250 text-decoration: none;
253 /* Articles are enclosed in <div class="section"> */
259 border-bottom: 1px dotted #99C;
265 def rst_to_html(rst):
267 'input_encoding': encoding,
268 'output_encoding': 'utf8',
270 parts = publish_parts(rst, settings_overrides = settings,
271 writer_name = "html")
272 return parts['body'].encode('utf8')
275 if isinstance(obj, basestring):
276 return cgi.escape(obj, True)
280 # find out our URL, needed for syndication
282 n = os.environ['SERVER_NAME']
283 p = os.environ['SERVER_PORT']
284 s = os.environ['SCRIPT_NAME']
287 full_url = 'http://%s%s%s' % (n, p, s)
289 full_url = 'Not needed'
292 class Templates (object):
293 def __init__(self, tpath, db, showyear = None):
296 now = datetime.datetime.now()
308 'showyear': showyear,
309 'monthlinks': ' '.join(db.get_month_links(showyear)),
310 'yearlinks': ' '.join(db.get_year_links()),
313 def get_template(self, page_name, default_template, extra_vars = None):
314 if extra_vars is None:
317 vars = self.vars.copy()
318 vars.update(extra_vars)
320 p = '%s/%s.html' % (self.tpath, page_name)
321 if os.path.isfile(p):
322 return open(p).read() % vars
323 return default_template % vars
325 def get_main_header(self):
326 return self.get_template('header', default_main_header)
328 def get_main_footer(self):
329 return self.get_template('footer', default_main_footer)
331 def get_article_header(self, article):
332 return self.get_template(
333 'art_header', default_article_header, article.to_vars())
335 def get_article_footer(self, article):
336 return self.get_template(
337 'art_footer', default_article_footer, article.to_vars())
339 def get_comment_header(self, comment):
340 return self.get_template(
341 'com_header', default_comment_header, comment.to_vars())
343 def get_comment_footer(self, comment):
344 return self.get_template(
345 'com_footer', default_comment_footer, comment.to_vars())
348 class Comment (object):
349 def __init__(self, article, number, created = None):
350 self.article = article
353 self.created = datetime.datetime.now()
355 self.created = created
360 self._author = author
362 self._raw_content = 'Removed comment'
365 def get_author(self):
369 author = property(fget = get_author)
375 link = property(fget = get_link)
377 def get_raw_content(self):
380 return self._raw_content
381 raw_content = property(fget = get_raw_content)
385 filename = os.path.join(comments_path, self.article.uuid,
388 raw = open(filename).readlines()
395 name, value = l.split(':', 1)
396 if name.lower() == 'author':
397 self._author = value.strip()
398 elif name.lower() == 'link':
399 self._link = value.strip()
404 self._raw_content = ''.join(raw[count + 1:])
408 return rst_to_html(self.raw_content)
412 'number': self.number,
413 'author': sanitize(self.author),
414 'link': sanitize(self.link),
415 'date': self.created.isoformat(' '),
416 'created': self.created.isoformat(' '),
418 'year': self.created.year,
419 'month': self.created.month,
420 'day': self.created.day,
421 'hour': self.created.hour,
422 'minute': self.created.minute,
423 'second': self.created.second,
426 class CommentDB (object):
427 def __init__(self, article):
428 self.path = os.path.join(comments_path, article.uuid)
432 def load(self, article):
434 f = open(os.path.join(self.path, 'db'))
439 # Each line has the following comma separated format:
440 # number, created (epoch)
441 # Empty lines are meaningful and represent removed
442 # comments (so we can preserve the comment number)
446 d = datetime.datetime.fromtimestamp(float(l[1]))
448 # Removed/invalid comment
449 self.comments.append(None)
451 self.comments.append(Comment(article, n, d))
454 old_db = os.path.join(self.path, 'db')
455 new_db = os.path.join(self.path, 'db.tmp')
456 f = open(new_db, 'w')
457 for c in self.comments:
461 s += str(c.number) + ', '
462 s += str(time.mktime(c.created.timetuple()))
466 os.rename(new_db, old_db)
469 class Article (object):
470 def __init__(self, path, created = None, updated = None):
472 self.created = created
473 self.updated = updated
474 self.uuid = "%08x" % zlib.crc32(self.path)
479 self._title = 'Removed post'
480 self._author = author
482 self._raw_content = ''
490 title = property(fget = get_title)
492 def get_author(self):
496 author = property(fget = get_author)
502 tags = property(fget = get_tags)
504 def get_raw_content(self):
507 return self._raw_content
508 raw_content = property(fget = get_raw_content)
510 def get_comments(self):
513 return self._comments
514 comments = property(fget = get_comments)
517 def __cmp__(self, other):
518 if self.path == other.path:
522 if not other.created:
524 if self.created < other.created:
528 def title_cmp(self, other):
529 return cmp(self.title, other.title)
533 # XXX this tweak is only needed for old DB format, where
534 # article's paths started with a slash
536 if path.startswith('/'):
538 filename = os.path.join(data_path, path)
540 raw = open(filename).readlines()
547 name, value = l.split(':', 1)
548 if name.lower() == 'title':
549 self._title = value.strip()
550 elif name.lower() == 'author':
551 self._author = value.strip()
552 elif name.lower() == 'tags':
553 ts = value.split(',')
554 ts = [t.strip() for t in ts]
560 self._raw_content = ''.join(raw[count + 1:])
562 self._comments = db.comments
566 return rst_to_html(self.raw_content)
570 'arttitle': sanitize(self.title),
571 'author': sanitize(self.author),
572 'date': self.created.isoformat(' '),
574 'tags': self.get_tags_links(),
575 'comments': len(self.comments),
577 'created': self.created.isoformat(' '),
578 'ciso': self.created.isoformat(),
579 'cyear': self.created.year,
580 'cmonth': self.created.month,
581 'cday': self.created.day,
582 'chour': self.created.hour,
583 'cminute': self.created.minute,
584 'csecond': self.created.second,
586 'updated': self.updated.isoformat(' '),
587 'uiso': self.updated.isoformat(),
588 'uyear': self.updated.year,
589 'umonth': self.updated.month,
590 'uday': self.updated.day,
591 'uhour': self.updated.hour,
592 'uminute': self.updated.minute,
593 'usecond': self.updated.second,
596 def get_tags_links(self):
598 tags = list(self.tags)
601 l.append('<a class="tag" href="%s/tag/%s">%s</a>' % \
602 (blog_url, urllib.quote(t), sanitize(t) ))
606 class ArticleDB (object):
607 def __init__(self, dbpath):
611 self.actyears = set()
612 self.actmonths = set()
615 def get_articles(self, year = 0, month = 0, day = 0, tags = None):
617 for a in self.articles:
618 if year and a.created.year != year: continue
619 if month and a.created.month != month: continue
620 if day and a.created.day != day: continue
621 if tags and not tags.issubset(a.tags): continue
627 def get_article(self, uuid):
628 return self.uuids[uuid]
632 f = open(self.dbpath)
637 # Each line has the following comma separated format:
638 # path (relative to data_path), \
647 datetime.datetime.fromtimestamp(float(l[1])),
648 datetime.datetime.fromtimestamp(float(l[2])))
649 self.uuids[a.uuid] = a
650 self.actyears.add(a.created.year)
651 self.actmonths.add((a.created.year, a.created.month))
652 self.articles.append(a)
655 f = open(self.dbpath + '.tmp', 'w')
656 for a in self.articles:
659 s += str(time.mktime(a.created.timetuple())) + ', '
660 s += str(time.mktime(a.updated.timetuple())) + '\n'
663 os.rename(self.dbpath + '.tmp', self.dbpath)
665 def get_year_links(self):
666 yl = list(self.actyears)
667 yl.sort(reverse = True)
668 return [ '<a href="%s/%d/">%d</a>' % (blog_url, y, y)
671 def get_month_links(self, year):
672 am = [ i[1] for i in self.actmonths if i[0] == year ]
674 for i in range(1, 13):
675 name = calendar.month_name[i][:3]
677 s = '<a href="%s/%d/%d/">%s</a>' % \
678 ( blog_url, year, i, name )
689 def render_html(articles, db, actyear = None, show_comments = False):
690 template = Templates(templates_path, db, actyear)
691 print 'Content-type: text/html; charset=utf-8\n'
692 print template.get_main_header()
694 print template.get_article_header(a)
696 print template.get_article_footer(a)
698 print '<a name="comments" />'
702 print template.get_comment_header(c)
704 print template.get_comment_footer(c)
705 print template.get_main_footer()
707 def render_artlist(articles, db, actyear = None):
708 template = Templates(templates_path, db, actyear)
709 print 'Content-type: text/html; charset=utf-8\n'
710 print template.get_main_header()
711 print '<h2>Articles</h2>'
713 print '<li><a href="%(url)s/uuid/%(uuid)s">%(title)s</a></li>' \
719 print template.get_main_footer()
721 def render_atom(articles):
722 if len(articles) > 0:
723 updated = articles[0].updated.isoformat()
725 updated = datetime.datetime.now().isoformat()
727 print 'Content-type: application/atom+xml; charset=utf-8\n'
728 print """<?xml version="1.0" encoding="utf-8"?>
730 <feed xmlns="http://www.w3.org/2005/Atom">
731 <title>%(title)s</title>
732 <link rel="alternate" type="text/html" href="%(url)s"/>
733 <link rel="self" type="application/atom+xml" href="%(url)s/atom"/>
734 <id>%(url)s</id> <!-- TODO: find a better <id>, see RFC 4151 -->
735 <updated>%(updated)sZ</updated>
747 'contents': a.to_html(),
751 <title>%(arttitle)s</title>
752 <author><name>%(author)s</name></author>
753 <link href="%(url)s/post/%(uuid)s" />
754 <id>%(url)s/post/%(uuid)s</id>
755 <summary>%(arttitle)s</summary>
756 <published>%(ciso)sZ</published>
757 <updated>%(uiso)sZ</updated>
758 <content type="xhtml">
759 <div xmlns="http://www.w3.org/1999/xhtml"><p>
769 print 'Content-type: text/css\r\n\r\n',
773 import cgitb; cgitb.enable()
775 form = cgi.FieldStorage()
776 year = int(form.getfirst("year", 0))
777 month = int(form.getfirst("month", 0))
778 day = int(form.getfirst("day", 0))
779 tags = set(form.getlist("tag"))
786 if os.environ.has_key('PATH_INFO'):
787 path_info = os.environ['PATH_INFO']
788 style = path_info == '/style'
789 atom = path_info == '/atom'
790 tag = path_info.startswith('/tag/')
791 post = path_info.startswith('/post/')
792 artlist = path_info.startswith('/list')
793 if not style and not atom and not post and not tag \
795 date = path_info.split('/')[1:]
797 if len(date) > 1 and date[0]:
799 if len(date) > 2 and date[1]:
801 if len(date) > 3 and date[2]:
806 uuid = path_info.replace('/post/', '')
807 uuid = uuid.replace('/', '')
809 t = path_info.replace('/tag/', '')
810 t = t.replace('/', '')
811 t = urllib.unquote_plus(t)
814 db = ArticleDB(os.path.join(data_path, 'db'))
816 articles = db.get_articles(tags = tags)
817 articles.sort(reverse = True)
818 render_atom(articles[:10])
822 render_html( [db.get_article(uuid)], db, year, True )
824 articles = db.get_articles()
825 articles.sort(cmp = Article.title_cmp)
826 render_artlist(articles, db)
828 articles = db.get_articles(year, month, day, tags)
829 articles.sort(reverse = True)
830 if not year and not month and not day and not tags:
831 articles = articles[:10]
832 render_html(articles, db, year)
836 print 'Usage: %s {add|rm|update} article_path' % sys.argv[0]
839 if len(sys.argv) != 3:
844 art_path = os.path.realpath(sys.argv[2])
846 if os.path.commonprefix([data_path, art_path]) != data_path:
847 print "Error: article (%s) must be inside data_path (%s)" % \
848 (art_path, data_path)
850 art_path = art_path[len(data_path)+1:]
852 db_filename = os.path.join(data_path, 'db')
853 if not os.path.isfile(db_filename):
854 open(db_filename, 'w').write('')
855 db = ArticleDB(db_filename)
858 article = Article(art_path, datetime.datetime.now(),
859 datetime.datetime.now())
860 for a in db.articles:
862 print 'Error: article already exists'
864 db.articles.append(article)
867 article = Article(art_path)
868 for a in db.articles:
872 print "Error: no such article"
874 db.articles.remove(a)
876 elif cmd == 'update':
877 article = Article(art_path)
878 for a in db.articles:
882 print "Error: no such article"
884 a.updated = datetime.datetime.now()
893 if os.environ.has_key('GATEWAY_INTERFACE'):
896 sys.exit(handle_cmd())