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 # Path where templates are stored. Use an empty string for the built-in
18 # default templates. If they're not found, the built-in ones will be used.
19 templates_path = "/tmp/blog/templates"
21 # URL to the blog, including the name. Can be a full URL or just the path.
22 blog_url = "/blog/blitiri.cgi"
24 # Style sheet (CSS) URL. Can be relative or absolute. To use the built-in
25 # default, set it to blog_url + "/style".
26 css_url = blog_url + "/style"
29 title = "I don't like blogs"
32 author = "Hartmut Kegan"
38 # End of configuration
39 # DO *NOT* EDIT ANYTHING PAST HERE
51 from docutils.core import publish_parts
53 # Before importing the config, add our cwd to the Python path
54 sys.path.append(os.getcwd())
56 # Load the config file, if there is one
63 # Pimp *_path config variables to support relative paths
64 data_path = os.path.realpath(data_path)
65 templates_path = os.path.realpath(templates_path)
69 default_main_header = """\
70 <?xml version="1.0" encoding="utf-8"?>
71 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
72 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
74 <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
76 <link rel="alternate" title="%(title)s" href="%(fullurl)s/atom"
77 type="application/atom+xml" />
78 <link href="%(css_url)s" rel="stylesheet" type="text/css" />
79 <title>%(title)s</title>
84 <h1><a href="%(url)s">%(title)s</a></h1>
89 default_main_footer = """
92 %(showyear)s: %(monthlinks)s<br/>
93 years: %(yearlinks)s<br/>
94 subscribe: <a href="%(url)s/atom">atom</a><br/>
95 views: <a href="%(url)s/">blog</a> <a href="%(url)s/list">list</a><br/>
102 default_article_header = """
103 <div class="article">
104 <h2><a href="%(url)s/post/%(uuid)s">%(arttitle)s</a></h2>
105 <span class="artinfo">
106 by %(author)s on <span class="date">
108 <a class="date" href="%(url)s/%(cyear)d/">%(cyear)04d</a>-\
109 <a class="date" href="%(url)s/%(cyear)d/%(cmonth)d/">%(cmonth)02d</a>-\
110 <a class="date" href="%(url)s/%(cyear)d/%(cmonth)d/%(cday)d/">%(cday)02d</a>\
111 %(chour)02d:%(cminute)02d</span>
112 (updated on <span class="date">
113 <a class="date" href="%(url)s/%(uyear)d/">%(uyear)04d</a>-\
114 <a class="date" href="%(url)s/%(uyear)d/%(umonth)d/">%(umonth)02d</a>-\
115 <a class="date" href="%(url)s/%(uyear)d/%(umonth)d/%(uday)d/">%(uday)02d</a>\
116 %(uhour)02d:%(uminute)02d)</span><br/>
117 <span class="tags">tagged %(tags)s</span>
120 <div class="artbody">
123 default_article_footer = """
132 font-family: sans-serif;
143 border-bottom: 2px solid #99F;
152 border-bottom: 1px solid #99C;
156 text-decoration: none;
165 text-decoration: none;
169 span.artinfo a:hover {
170 text-decoration: none;
186 border-top: 2px solid #99F;
191 text-decoration: none;
194 /* Articles are enclosed in <div class="section"> */
200 border-bottom: 1px dotted #99C;
206 def rst_to_html(rst):
208 'input_encoding': encoding,
209 'output_encoding': 'utf8',
211 parts = publish_parts(rst, settings_overrides = settings,
212 writer_name = "html")
213 return parts['body'].encode('utf8')
215 # find out our URL, needed for syndication
217 n = os.environ['SERVER_NAME']
218 p = os.environ['SERVER_PORT']
219 s = os.environ['SCRIPT_NAME']
222 full_url = 'http://%s%s%s' % (n, p, s)
224 full_url = 'Not needed'
227 class Templates (object):
228 def __init__(self, tpath, db, showyear = None):
231 now = datetime.datetime.now()
243 'showyear': showyear,
244 'monthlinks': ' '.join(db.get_month_links(showyear)),
245 'yearlinks': ' '.join(db.get_year_links()),
248 def get_template(self, page_name, default_template, extra_vars = None):
249 if extra_vars is None:
252 vars = self.vars.copy()
253 vars.update(extra_vars)
255 p = '%s/%s.html' % (self.tpath, page_name)
256 if os.path.isfile(p):
257 return open(p).read() % vars
258 return default_template % vars
260 def get_main_header(self):
261 return self.get_template('header', default_main_header)
263 def get_main_footer(self):
264 return self.get_template('footer', default_main_footer)
266 def get_article_header(self, article):
267 return self.get_template(
268 'art_header', default_article_header, article.to_vars())
270 def get_article_footer(self, article):
271 return self.get_template(
272 'art_footer', default_article_footer, article.to_vars())
275 class Article (object):
276 def __init__(self, path, created = None, updated = None):
278 self.created = created
279 self.updated = updated
280 self.uuid = "%08x" % zlib.crc32(self.path)
285 self._title = 'Removed post'
286 self._author = author
288 self._raw_content = ''
295 title = property(fget = get_title)
297 def get_author(self):
301 author = property(fget = get_author)
307 tags = property(fget = get_tags)
309 def get_raw_content(self):
312 return self._raw_content
313 raw_content = property(fget = get_raw_content)
316 def __cmp__(self, other):
317 if self.path == other.path:
321 if not other.created:
323 if self.created < other.created:
327 def title_cmp(self, other):
328 return cmp(self.title, other.title)
333 raw = open(data_path + '/' + self.path).readlines()
340 name, value = l.split(':', 1)
341 if name.lower() == 'title':
343 elif name.lower() == 'author':
345 elif name.lower() == 'tags':
346 ts = value.split(',')
347 ts = [t.strip() for t in ts]
353 self._raw_content = ''.join(raw[count + 1:])
357 return rst_to_html(self.raw_content)
361 'arttitle': self.title,
362 'author': self.author,
363 'date': self.created.isoformat(' '),
365 'tags': self.get_tags_links(),
367 'created': self.created.isoformat(' '),
368 'ciso': self.created.isoformat(),
369 'cyear': self.created.year,
370 'cmonth': self.created.month,
371 'cday': self.created.day,
372 'chour': self.created.hour,
373 'cminute': self.created.minute,
374 'csecond': self.created.second,
376 'updated': self.updated.isoformat(' '),
377 'uiso': self.updated.isoformat(),
378 'uyear': self.updated.year,
379 'umonth': self.updated.month,
380 'uday': self.updated.day,
381 'uhour': self.updated.hour,
382 'uminute': self.updated.minute,
383 'usecond': self.updated.second,
386 def get_tags_links(self):
388 tags = list(self.tags)
391 l.append('<a class="tag" href="%s/tag/%s">%s</a>' % \
392 (blog_url, urllib.quote(t), t) )
397 def __init__(self, dbpath):
401 self.actyears = set()
402 self.actmonths = set()
405 def get_articles(self, year = 0, month = 0, day = 0, tags = None):
407 for a in self.articles:
408 if year and a.created.year != year: continue
409 if month and a.created.month != month: continue
410 if day and a.created.day != day: continue
411 if tags and not tags.issubset(a.tags): continue
417 def get_article(self, uuid):
418 return self.uuids[uuid]
422 f = open(self.dbpath)
427 # Each line has the following comma separated format:
428 # path (relative to data_path), \
437 datetime.datetime.fromtimestamp(float(l[1])),
438 datetime.datetime.fromtimestamp(float(l[2])))
439 self.uuids[a.uuid] = a
440 self.actyears.add(a.created.year)
441 self.actmonths.add((a.created.year, a.created.month))
442 self.articles.append(a)
445 f = open(self.dbpath + '.tmp', 'w')
446 for a in self.articles:
449 s += str(time.mktime(a.created.timetuple())) + ', '
450 s += str(time.mktime(a.updated.timetuple())) + '\n'
453 os.rename(self.dbpath + '.tmp', self.dbpath)
455 def get_year_links(self):
456 yl = list(self.actyears)
457 yl.sort(reverse = True)
458 return [ '<a href="%s/%d/">%d</a>' % (blog_url, y, y)
461 def get_month_links(self, year):
462 am = [ i[1] for i in self.actmonths if i[0] == year ]
464 for i in range(1, 13):
465 name = calendar.month_name[i][:3]
467 s = '<a href="%s/%d/%d/">%s</a>' % \
468 ( blog_url, year, i, name )
479 def render_html(articles, db, actyear = None):
480 template = Templates(templates_path, db, actyear)
481 print 'Content-type: text/html; charset=utf-8\n'
482 print template.get_main_header()
484 print template.get_article_header(a)
486 print template.get_article_footer(a)
487 print template.get_main_footer()
489 def render_artlist(articles, db, actyear = None):
490 template = Templates(templates_path, db, actyear)
491 print 'Content-type: text/html; charset=utf-8\n'
492 print template.get_main_header()
493 print '<h2>Articles</h2>'
495 print '<li><a href="%(url)s/uuid/%(uuid)s">%(title)s</a></li>' \
501 print template.get_main_footer()
503 def render_atom(articles):
504 if len(articles) > 0:
505 updated = articles[0].updated.isoformat()
507 updated = datetime.datetime.now().isoformat()
509 print 'Content-type: application/atom+xml; charset=utf-8\n'
510 print """<?xml version="1.0" encoding="utf-8"?>
512 <feed xmlns="http://www.w3.org/2005/Atom">
513 <title>%(title)s</title>
514 <link rel="alternate" type="text/html" href="%(url)s"/>
515 <link rel="self" type="application/atom+xml" href="%(url)s/atom"/>
516 <id>%(url)s</id> <!-- TODO: find a better <id>, see RFC 4151 -->
517 <updated>%(updated)sZ</updated>
529 'contents': a.to_html(),
533 <title>%(arttitle)s</title>
534 <author><name>%(author)s</name></author>
535 <link href="%(url)s/post/%(uuid)s" />
536 <id>%(url)s/post/%(uuid)s</id>
537 <summary>%(arttitle)s</summary>
538 <published>%(ciso)sZ</published>
539 <updated>%(uiso)sZ</updated>
540 <content type="xhtml">
541 <div xmlns="http://www.w3.org/1999/xhtml"><p>
551 print 'Content-type: text/css\r\n\r\n',
555 import cgitb; cgitb.enable()
557 form = cgi.FieldStorage()
558 year = int(form.getfirst("year", 0))
559 month = int(form.getfirst("month", 0))
560 day = int(form.getfirst("day", 0))
561 tags = set(form.getlist("tag"))
568 if os.environ.has_key('PATH_INFO'):
569 path_info = os.environ['PATH_INFO']
570 style = path_info == '/style'
571 atom = path_info == '/atom'
572 tag = path_info.startswith('/tag/')
573 post = path_info.startswith('/post/')
574 artlist = path_info.startswith('/list')
575 if not style and not atom and not post and not tag \
577 date = path_info.split('/')[1:]
579 if len(date) > 1 and date[0]:
581 if len(date) > 2 and date[1]:
583 if len(date) > 3 and date[2]:
588 uuid = path_info.replace('/post/', '')
589 uuid = uuid.replace('/', '')
591 t = path_info.replace('/tag/', '')
592 t = t.replace('/', '')
593 t = urllib.unquote_plus(t)
596 db = DB(data_path + '/db')
598 articles = db.get_articles(tags = tags)
599 articles.sort(reverse = True)
600 render_atom(articles[:10])
604 render_html( [db.get_article(uuid)], db, year )
606 articles = db.get_articles()
607 articles.sort(cmp = Article.title_cmp)
608 render_artlist(articles, db)
610 articles = db.get_articles(year, month, day, tags)
611 articles.sort(reverse = True)
612 if not year and not month and not day and not tags:
613 articles = articles[:10]
614 render_html(articles, db, year)
618 print 'Usage: %s {add|rm|update} article_path' % sys.argv[0]
621 if len(sys.argv) != 3:
626 art_path = os.path.realpath(sys.argv[2])
628 if os.path.commonprefix([data_path, art_path]) != data_path:
629 print "Error: article (%s) must be inside data_path (%s)" % \
630 (art_path, data_path)
632 art_path = art_path[len(data_path):]
634 if not os.path.isfile(data_path + '/db'):
635 open(data_path + '/db', 'w').write('')
636 db = DB(data_path + '/db')
639 article = Article(art_path, datetime.datetime.now(),
640 datetime.datetime.now())
641 for a in db.articles:
643 print 'Error: article already exists'
645 db.articles.append(article)
648 article = Article(art_path)
649 for a in db.articles:
653 print "Error: no such article"
655 db.articles.remove(a)
657 elif cmd == 'update':
658 article = Article(art_path)
659 for a in db.articles:
663 print "Error: no such article"
665 a.updated = datetime.datetime.now()
674 if os.environ.has_key('GATEWAY_INTERFACE'):
677 sys.exit(handle_cmd())