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
57 from docutils.core import publish_parts
59 # Before importing the config, add our cwd to the Python path
60 sys.path.append(os.getcwd())
62 # Load the config file, if there is one
69 # Pimp *_path config variables to support relative paths
70 data_path = os.path.realpath(data_path)
71 templates_path = os.path.realpath(templates_path)
75 default_main_header = """\
76 <?xml version="1.0" encoding="utf-8"?>
77 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
78 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
80 <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
82 <link rel="alternate" title="%(title)s" href="%(fullurl)s/atom"
83 type="application/atom+xml" />
84 <link href="%(css_url)s" rel="stylesheet" type="text/css" />
85 <title>%(title)s</title>
90 <h1><a href="%(url)s">%(title)s</a></h1>
95 default_main_footer = """
98 %(showyear)s: %(monthlinks)s<br/>
99 years: %(yearlinks)s<br/>
100 subscribe: <a href="%(url)s/atom">atom</a><br/>
101 views: <a href="%(url)s/">blog</a> <a href="%(url)s/list">list</a><br/>
108 default_article_header = """
109 <div class="article">
110 <h2><a href="%(url)s/post/%(uuid)s">%(arttitle)s</a></h2>
111 <span class="artinfo">
112 by %(author)s on <span class="date">
114 <a class="date" href="%(url)s/%(cyear)d/">%(cyear)04d</a>-\
115 <a class="date" href="%(url)s/%(cyear)d/%(cmonth)d/">%(cmonth)02d</a>-\
116 <a class="date" href="%(url)s/%(cyear)d/%(cmonth)d/%(cday)d/">%(cday)02d</a>\
117 %(chour)02d:%(cminute)02d</span>
118 (updated on <span class="date">
119 <a class="date" href="%(url)s/%(uyear)d/">%(uyear)04d</a>-\
120 <a class="date" href="%(url)s/%(uyear)d/%(umonth)d/">%(umonth)02d</a>-\
121 <a class="date" href="%(url)s/%(uyear)d/%(umonth)d/%(uday)d/">%(uday)02d</a>\
122 %(uhour)02d:%(uminute)02d)</span><br/>
123 <span class="tags">tagged %(tags)s</span> -
124 <span class="comments">with %(comments)s
125 <a href="%(url)s/post/%(uuid)s#comments">comment(s)</a></span>
128 <div class="artbody">
131 default_article_footer = """
137 default_comment_header = """
138 <div class="comment">
139 <a name="comment-%(number)d" />
140 <h3><a href="#comment-%(number)d">Comment #%(number)d</a></h3>
141 <span class="cominfo">by <a href="%(link)s">%(author)s</a>
142 on %(year)04d-%(month)02d-%(day)02d %(hour)02d:%(minute)02d</span>
144 <div class="combody">
147 default_comment_footer = """
157 font-family: sans-serif;
168 border-bottom: 2px solid #99F;
177 border-bottom: 1px solid #99C;
184 border-bottom: 1px solid #99C;
188 text-decoration: none;
197 text-decoration: none;
201 span.artinfo a:hover {
202 text-decoration: none;
219 text-decoration: none;
223 span.cominfo a:hover {
224 text-decoration: none;
241 background-color: #99F;
249 border-top: 2px solid #99F;
254 text-decoration: none;
257 /* Articles are enclosed in <div class="section"> */
263 border-bottom: 1px dotted #99C;
269 def rst_to_html(rst):
271 'input_encoding': encoding,
272 'output_encoding': 'utf8',
274 parts = publish_parts(rst, settings_overrides = settings,
275 writer_name = "html")
276 return parts['body'].encode('utf8')
279 if isinstance(obj, basestring):
280 return cgi.escape(obj, True)
284 # find out our URL, needed for syndication
286 n = os.environ['SERVER_NAME']
287 p = os.environ['SERVER_PORT']
288 s = os.environ['SCRIPT_NAME']
291 full_url = 'http://%s%s%s' % (n, p, s)
293 full_url = 'Not needed'
296 class Templates (object):
297 def __init__(self, tpath, db, showyear = None):
300 now = datetime.datetime.now()
312 'showyear': showyear,
313 'monthlinks': ' '.join(db.get_month_links(showyear)),
314 'yearlinks': ' '.join(db.get_year_links()),
317 def get_template(self, page_name, default_template, extra_vars = None):
318 if extra_vars is None:
321 vars = self.vars.copy()
322 vars.update(extra_vars)
324 p = '%s/%s.html' % (self.tpath, page_name)
325 if os.path.isfile(p):
326 return open(p).read() % vars
327 return default_template % vars
329 def get_main_header(self):
330 return self.get_template('header', default_main_header)
332 def get_main_footer(self):
333 return self.get_template('footer', default_main_footer)
335 def get_article_header(self, article):
336 return self.get_template(
337 'art_header', default_article_header, article.to_vars())
339 def get_article_footer(self, article):
340 return self.get_template(
341 'art_footer', default_article_footer, article.to_vars())
343 def get_comment_header(self, comment):
344 return self.get_template(
345 'com_header', default_comment_header, comment.to_vars())
347 def get_comment_footer(self, comment):
348 return self.get_template(
349 'com_footer', default_comment_footer, comment.to_vars())
352 class Comment (object):
353 def __init__(self, article, number, created = None):
354 self.article = article
357 self.created = datetime.datetime.now()
359 self.created = created
364 self._author = author
366 self._raw_content = 'Removed comment'
369 def get_author(self):
373 author = property(fget = get_author)
379 link = property(fget = get_link)
381 def get_raw_content(self):
384 return self._raw_content
385 raw_content = property(fget = get_raw_content)
389 filename = os.path.join(comments_path, self.article.uuid,
392 raw = open(filename).readlines()
399 name, value = l.split(':', 1)
400 if name.lower() == 'author':
401 self._author = value.strip()
402 elif name.lower() == 'link':
403 self._link = value.strip()
408 self._raw_content = ''.join(raw[count + 1:])
412 return rst_to_html(self.raw_content)
416 'number': self.number,
417 'author': sanitize(self.author),
418 'link': sanitize(self.link),
419 'date': self.created.isoformat(' '),
420 'created': self.created.isoformat(' '),
422 'year': self.created.year,
423 'month': self.created.month,
424 'day': self.created.day,
425 'hour': self.created.hour,
426 'minute': self.created.minute,
427 'second': self.created.second,
430 class CommentDB (object):
431 def __init__(self, article):
432 self.path = os.path.join(comments_path, article.uuid)
436 def load(self, article):
438 f = open(os.path.join(self.path, 'db'))
443 # Each line has the following comma separated format:
444 # number, created (epoch)
445 # Empty lines are meaningful and represent removed
446 # comments (so we can preserve the comment number)
450 d = datetime.datetime.fromtimestamp(float(l[1]))
452 # Removed/invalid comment
453 self.comments.append(None)
455 self.comments.append(Comment(article, n, d))
458 old_db = os.path.join(self.path, 'db')
459 new_db = os.path.join(self.path, 'db.tmp')
460 f = open(new_db, 'w')
461 for c in self.comments:
465 s += str(c.number) + ', '
466 s += str(time.mktime(c.created.timetuple()))
470 os.rename(new_db, old_db)
473 class Article (object):
474 def __init__(self, path, created = None, updated = None):
476 self.created = created
477 self.updated = updated
478 self.uuid = "%08x" % zlib.crc32(self.path)
483 self._title = 'Removed post'
484 self._author = author
486 self._raw_content = ''
494 title = property(fget = get_title)
496 def get_author(self):
500 author = property(fget = get_author)
506 tags = property(fget = get_tags)
508 def get_raw_content(self):
511 return self._raw_content
512 raw_content = property(fget = get_raw_content)
514 def get_comments(self):
517 return self._comments
518 comments = property(fget = get_comments)
521 def __cmp__(self, other):
522 if self.path == other.path:
526 if not other.created:
528 if self.created < other.created:
532 def title_cmp(self, other):
533 return cmp(self.title, other.title)
537 # XXX this tweak is only needed for old DB format, where
538 # article's paths started with a slash
540 if path.startswith('/'):
542 filename = os.path.join(data_path, path)
544 raw = open(filename).readlines()
551 name, value = l.split(':', 1)
552 if name.lower() == 'title':
553 self._title = value.strip()
554 elif name.lower() == 'author':
555 self._author = value.strip()
556 elif name.lower() == 'tags':
557 ts = value.split(',')
558 ts = [t.strip() for t in ts]
564 self._raw_content = ''.join(raw[count + 1:])
566 self._comments = db.comments
570 return rst_to_html(self.raw_content)
574 'arttitle': sanitize(self.title),
575 'author': sanitize(self.author),
576 'date': self.created.isoformat(' '),
578 'tags': self.get_tags_links(),
579 'comments': len(self.comments),
581 'created': self.created.isoformat(' '),
582 'ciso': self.created.isoformat(),
583 'cyear': self.created.year,
584 'cmonth': self.created.month,
585 'cday': self.created.day,
586 'chour': self.created.hour,
587 'cminute': self.created.minute,
588 'csecond': self.created.second,
590 'updated': self.updated.isoformat(' '),
591 'uiso': self.updated.isoformat(),
592 'uyear': self.updated.year,
593 'umonth': self.updated.month,
594 'uday': self.updated.day,
595 'uhour': self.updated.hour,
596 'uminute': self.updated.minute,
597 'usecond': self.updated.second,
600 def get_tags_links(self):
602 tags = list(self.tags)
605 l.append('<a class="tag" href="%s/tag/%s">%s</a>' % \
606 (blog_url, urllib.quote(t), sanitize(t) ))
610 class ArticleDB (object):
611 def __init__(self, dbpath):
615 self.actyears = set()
616 self.actmonths = set()
619 def get_articles(self, year = 0, month = 0, day = 0, tags = None):
621 for a in self.articles:
622 if year and a.created.year != year: continue
623 if month and a.created.month != month: continue
624 if day and a.created.day != day: continue
625 if tags and not tags.issubset(a.tags): continue
631 def get_article(self, uuid):
632 return self.uuids[uuid]
636 f = open(self.dbpath)
641 # Each line has the following comma separated format:
642 # path (relative to data_path), \
651 datetime.datetime.fromtimestamp(float(l[1])),
652 datetime.datetime.fromtimestamp(float(l[2])))
653 self.uuids[a.uuid] = a
654 self.actyears.add(a.created.year)
655 self.actmonths.add((a.created.year, a.created.month))
656 self.articles.append(a)
659 f = open(self.dbpath + '.tmp', 'w')
660 for a in self.articles:
663 s += str(time.mktime(a.created.timetuple())) + ', '
664 s += str(time.mktime(a.updated.timetuple())) + '\n'
667 os.rename(self.dbpath + '.tmp', self.dbpath)
669 def get_year_links(self):
670 yl = list(self.actyears)
671 yl.sort(reverse = True)
672 return [ '<a href="%s/%d/">%d</a>' % (blog_url, y, y)
675 def get_month_links(self, year):
676 am = [ i[1] for i in self.actmonths if i[0] == year ]
678 for i in range(1, 13):
679 name = calendar.month_name[i][:3]
681 s = '<a href="%s/%d/%d/">%s</a>' % \
682 ( blog_url, year, i, name )
693 def render_html(articles, db, actyear = None, show_comments = False):
694 template = Templates(templates_path, db, actyear)
695 print 'Content-type: text/html; charset=utf-8\n'
696 print template.get_main_header()
698 print template.get_article_header(a)
700 print template.get_article_footer(a)
702 print '<a name="comments" />'
706 print template.get_comment_header(c)
708 print template.get_comment_footer(c)
709 print template.get_main_footer()
711 def render_artlist(articles, db, actyear = None):
712 template = Templates(templates_path, db, actyear)
713 print 'Content-type: text/html; charset=utf-8\n'
714 print template.get_main_header()
715 print '<h2>Articles</h2>'
717 print '<li><a href="%(url)s/uuid/%(uuid)s">%(title)s</a></li>' \
723 print template.get_main_footer()
725 def render_atom(articles):
726 if len(articles) > 0:
727 updated = articles[0].updated.isoformat()
729 updated = datetime.datetime.now().isoformat()
731 print 'Content-type: application/atom+xml; charset=utf-8\n'
732 print """<?xml version="1.0" encoding="utf-8"?>
734 <feed xmlns="http://www.w3.org/2005/Atom">
735 <title>%(title)s</title>
736 <link rel="alternate" type="text/html" href="%(url)s"/>
737 <link rel="self" type="application/atom+xml" href="%(url)s/atom"/>
738 <id>%(url)s</id> <!-- TODO: find a better <id>, see RFC 4151 -->
739 <updated>%(updated)sZ</updated>
751 'contents': a.to_html(),
755 <title>%(arttitle)s</title>
756 <author><name>%(author)s</name></author>
757 <link href="%(url)s/post/%(uuid)s" />
758 <id>%(url)s/post/%(uuid)s</id>
759 <summary>%(arttitle)s</summary>
760 <published>%(ciso)sZ</published>
761 <updated>%(uiso)sZ</updated>
762 <content type="xhtml">
763 <div xmlns="http://www.w3.org/1999/xhtml"><p>
773 print 'Content-type: text/css\r\n\r\n',
777 import cgitb; cgitb.enable()
779 form = cgi.FieldStorage()
780 year = int(form.getfirst("year", 0))
781 month = int(form.getfirst("month", 0))
782 day = int(form.getfirst("day", 0))
783 tags = set(form.getlist("tag"))
790 if os.environ.has_key('PATH_INFO'):
791 path_info = os.environ['PATH_INFO']
792 style = path_info == '/style'
793 atom = path_info == '/atom'
794 tag = path_info.startswith('/tag/')
795 post = path_info.startswith('/post/')
796 artlist = path_info.startswith('/list')
797 if not style and not atom and not post and not tag \
799 date = path_info.split('/')[1:]
801 if len(date) > 1 and date[0]:
803 if len(date) > 2 and date[1]:
805 if len(date) > 3 and date[2]:
810 uuid = path_info.replace('/post/', '')
811 uuid = uuid.replace('/', '')
813 t = path_info.replace('/tag/', '')
814 t = t.replace('/', '')
815 t = urllib.unquote_plus(t)
818 db = ArticleDB(os.path.join(data_path, 'db'))
820 articles = db.get_articles(tags = tags)
821 articles.sort(reverse = True)
822 render_atom(articles[:10])
826 render_html( [db.get_article(uuid)], db, year, enable_comments )
828 articles = db.get_articles()
829 articles.sort(cmp = Article.title_cmp)
830 render_artlist(articles, db)
832 articles = db.get_articles(year, month, day, tags)
833 articles.sort(reverse = True)
834 if not year and not month and not day and not tags:
835 articles = articles[:10]
836 render_html(articles, db, year)
840 print 'Usage: %s {add|rm|update} article_path' % sys.argv[0]
843 if len(sys.argv) != 3:
848 art_path = os.path.realpath(sys.argv[2])
850 if os.path.commonprefix([data_path, art_path]) != data_path:
851 print "Error: article (%s) must be inside data_path (%s)" % \
852 (art_path, data_path)
854 art_path = art_path[len(data_path)+1:]
856 db_filename = os.path.join(data_path, 'db')
857 if not os.path.isfile(db_filename):
858 open(db_filename, 'w').write('')
859 db = ArticleDB(db_filename)
862 article = Article(art_path, datetime.datetime.now(),
863 datetime.datetime.now())
864 for a in db.articles:
866 print 'Error: article already exists'
868 db.articles.append(article)
871 article = Article(art_path)
872 for a in db.articles:
876 print "Error: no such article"
878 db.articles.remove(a)
880 elif cmd == 'update':
881 article = Article(art_path)
882 for a in db.articles:
886 print "Error: no such article"
888 a.updated = datetime.datetime.now()
897 if os.environ.has_key('GATEWAY_INTERFACE'):
900 sys.exit(handle_cmd())