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')
216 if isinstance(obj, basestring):
217 return cgi.escape(obj, True)
221 # find out our URL, needed for syndication
223 n = os.environ['SERVER_NAME']
224 p = os.environ['SERVER_PORT']
225 s = os.environ['SCRIPT_NAME']
228 full_url = 'http://%s%s%s' % (n, p, s)
230 full_url = 'Not needed'
233 class Templates (object):
234 def __init__(self, tpath, db, showyear = None):
237 now = datetime.datetime.now()
249 'showyear': showyear,
250 'monthlinks': ' '.join(db.get_month_links(showyear)),
251 'yearlinks': ' '.join(db.get_year_links()),
254 def get_template(self, page_name, default_template, extra_vars = None):
255 if extra_vars is None:
258 vars = self.vars.copy()
259 vars.update(extra_vars)
261 p = '%s/%s.html' % (self.tpath, page_name)
262 if os.path.isfile(p):
263 return open(p).read() % vars
264 return default_template % vars
266 def get_main_header(self):
267 return self.get_template('header', default_main_header)
269 def get_main_footer(self):
270 return self.get_template('footer', default_main_footer)
272 def get_article_header(self, article):
273 return self.get_template(
274 'art_header', default_article_header, article.to_vars())
276 def get_article_footer(self, article):
277 return self.get_template(
278 'art_footer', default_article_footer, article.to_vars())
281 class Article (object):
282 def __init__(self, path, created = None, updated = None):
284 self.created = created
285 self.updated = updated
286 self.uuid = "%08x" % zlib.crc32(self.path)
291 self._title = 'Removed post'
292 self._author = author
294 self._raw_content = ''
301 title = property(fget = get_title)
303 def get_author(self):
307 author = property(fget = get_author)
313 tags = property(fget = get_tags)
315 def get_raw_content(self):
318 return self._raw_content
319 raw_content = property(fget = get_raw_content)
322 def __cmp__(self, other):
323 if self.path == other.path:
327 if not other.created:
329 if self.created < other.created:
333 def title_cmp(self, other):
334 return cmp(self.title, other.title)
339 raw = open(data_path + '/' + self.path).readlines()
346 name, value = l.split(':', 1)
347 if name.lower() == 'title':
348 self._title = value.strip()
349 elif name.lower() == 'author':
350 self._author = value.strip()
351 elif name.lower() == 'tags':
352 ts = value.split(',')
353 ts = [t.strip() for t in ts]
359 self._raw_content = ''.join(raw[count + 1:])
363 return rst_to_html(self.raw_content)
367 'arttitle': sanitize(self.title),
368 'author': sanitize(self.author),
369 'date': self.created.isoformat(' '),
371 'tags': self.get_tags_links(),
373 'created': self.created.isoformat(' '),
374 'ciso': self.created.isoformat(),
375 'cyear': self.created.year,
376 'cmonth': self.created.month,
377 'cday': self.created.day,
378 'chour': self.created.hour,
379 'cminute': self.created.minute,
380 'csecond': self.created.second,
382 'updated': self.updated.isoformat(' '),
383 'uiso': self.updated.isoformat(),
384 'uyear': self.updated.year,
385 'umonth': self.updated.month,
386 'uday': self.updated.day,
387 'uhour': self.updated.hour,
388 'uminute': self.updated.minute,
389 'usecond': self.updated.second,
392 def get_tags_links(self):
394 tags = list(self.tags)
397 l.append('<a class="tag" href="%s/tag/%s">%s</a>' % \
398 (blog_url, urllib.quote(t), sanitize(t) ))
403 def __init__(self, dbpath):
407 self.actyears = set()
408 self.actmonths = set()
411 def get_articles(self, year = 0, month = 0, day = 0, tags = None):
413 for a in self.articles:
414 if year and a.created.year != year: continue
415 if month and a.created.month != month: continue
416 if day and a.created.day != day: continue
417 if tags and not tags.issubset(a.tags): continue
423 def get_article(self, uuid):
424 return self.uuids[uuid]
428 f = open(self.dbpath)
433 # Each line has the following comma separated format:
434 # path (relative to data_path), \
443 datetime.datetime.fromtimestamp(float(l[1])),
444 datetime.datetime.fromtimestamp(float(l[2])))
445 self.uuids[a.uuid] = a
446 self.actyears.add(a.created.year)
447 self.actmonths.add((a.created.year, a.created.month))
448 self.articles.append(a)
451 f = open(self.dbpath + '.tmp', 'w')
452 for a in self.articles:
455 s += str(time.mktime(a.created.timetuple())) + ', '
456 s += str(time.mktime(a.updated.timetuple())) + '\n'
459 os.rename(self.dbpath + '.tmp', self.dbpath)
461 def get_year_links(self):
462 yl = list(self.actyears)
463 yl.sort(reverse = True)
464 return [ '<a href="%s/%d/">%d</a>' % (blog_url, y, y)
467 def get_month_links(self, year):
468 am = [ i[1] for i in self.actmonths if i[0] == year ]
470 for i in range(1, 13):
471 name = calendar.month_name[i][:3]
473 s = '<a href="%s/%d/%d/">%s</a>' % \
474 ( blog_url, year, i, name )
485 def render_html(articles, db, actyear = None):
486 template = Templates(templates_path, db, actyear)
487 print 'Content-type: text/html; charset=utf-8\n'
488 print template.get_main_header()
490 print template.get_article_header(a)
492 print template.get_article_footer(a)
493 print template.get_main_footer()
495 def render_artlist(articles, db, actyear = None):
496 template = Templates(templates_path, db, actyear)
497 print 'Content-type: text/html; charset=utf-8\n'
498 print template.get_main_header()
499 print '<h2>Articles</h2>'
501 print '<li><a href="%(url)s/uuid/%(uuid)s">%(title)s</a></li>' \
507 print template.get_main_footer()
509 def render_atom(articles):
510 if len(articles) > 0:
511 updated = articles[0].updated.isoformat()
513 updated = datetime.datetime.now().isoformat()
515 print 'Content-type: application/atom+xml; charset=utf-8\n'
516 print """<?xml version="1.0" encoding="utf-8"?>
518 <feed xmlns="http://www.w3.org/2005/Atom">
519 <title>%(title)s</title>
520 <link rel="alternate" type="text/html" href="%(url)s"/>
521 <link rel="self" type="application/atom+xml" href="%(url)s/atom"/>
522 <id>%(url)s</id> <!-- TODO: find a better <id>, see RFC 4151 -->
523 <updated>%(updated)sZ</updated>
535 'contents': a.to_html(),
539 <title>%(arttitle)s</title>
540 <author><name>%(author)s</name></author>
541 <link href="%(url)s/post/%(uuid)s" />
542 <id>%(url)s/post/%(uuid)s</id>
543 <summary>%(arttitle)s</summary>
544 <published>%(ciso)sZ</published>
545 <updated>%(uiso)sZ</updated>
546 <content type="xhtml">
547 <div xmlns="http://www.w3.org/1999/xhtml"><p>
557 print 'Content-type: text/css\r\n\r\n',
561 import cgitb; cgitb.enable()
563 form = cgi.FieldStorage()
564 year = int(form.getfirst("year", 0))
565 month = int(form.getfirst("month", 0))
566 day = int(form.getfirst("day", 0))
567 tags = set(form.getlist("tag"))
574 if os.environ.has_key('PATH_INFO'):
575 path_info = os.environ['PATH_INFO']
576 style = path_info == '/style'
577 atom = path_info == '/atom'
578 tag = path_info.startswith('/tag/')
579 post = path_info.startswith('/post/')
580 artlist = path_info.startswith('/list')
581 if not style and not atom and not post and not tag \
583 date = path_info.split('/')[1:]
585 if len(date) > 1 and date[0]:
587 if len(date) > 2 and date[1]:
589 if len(date) > 3 and date[2]:
594 uuid = path_info.replace('/post/', '')
595 uuid = uuid.replace('/', '')
597 t = path_info.replace('/tag/', '')
598 t = t.replace('/', '')
599 t = urllib.unquote_plus(t)
602 db = DB(data_path + '/db')
604 articles = db.get_articles(tags = tags)
605 articles.sort(reverse = True)
606 render_atom(articles[:10])
610 render_html( [db.get_article(uuid)], db, year )
612 articles = db.get_articles()
613 articles.sort(cmp = Article.title_cmp)
614 render_artlist(articles, db)
616 articles = db.get_articles(year, month, day, tags)
617 articles.sort(reverse = True)
618 if not year and not month and not day and not tags:
619 articles = articles[:10]
620 render_html(articles, db, year)
624 print 'Usage: %s {add|rm|update} article_path' % sys.argv[0]
627 if len(sys.argv) != 3:
632 art_path = os.path.realpath(sys.argv[2])
634 if os.path.commonprefix([data_path, art_path]) != data_path:
635 print "Error: article (%s) must be inside data_path (%s)" % \
636 (art_path, data_path)
638 art_path = art_path[len(data_path):]
640 if not os.path.isfile(data_path + '/db'):
641 open(data_path + '/db', 'w').write('')
642 db = DB(data_path + '/db')
645 article = Article(art_path, datetime.datetime.now(),
646 datetime.datetime.now())
647 for a in db.articles:
649 print 'Error: article already exists'
651 db.articles.append(article)
654 article = Article(art_path)
655 for a in db.articles:
659 print "Error: no such article"
661 db.articles.remove(a)
663 elif cmd == 'update':
664 article = Article(art_path)
665 for a in db.articles:
669 print "Error: no such article"
671 a.updated = datetime.datetime.now()
680 if os.environ.has_key('GATEWAY_INTERFACE'):
683 sys.exit(handle_cmd())