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 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
74 <link rel="alternate" title="%(title)s" href="%(fullurl)s/atom"
75 type="application/atom+xml" />
76 <link href="%(css_url)s" rel="stylesheet"
78 <title>%(title)s</title>
83 <h1><a href="%(url)s">%(title)s</a></h1>
88 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;
142 border-bottom: 2px solid #99F;
151 border-bottom: 1px solid #99C;
155 text-decoration: none;
164 text-decoration: none;
168 span.artinfo a:hover {
169 text-decoration: none;
185 background-color: #99F;
194 text-decoration: none;
197 /* Articles are enclosed in <div class="section"> */
203 border-bottom: 1px dotted #99C;
208 # find out our URL, needed for syndication
210 n = os.environ['SERVER_NAME']
211 p = os.environ['SERVER_PORT']
212 s = os.environ['SCRIPT_NAME']
215 full_url = 'http://%s%s%s' % (n, p, s)
217 full_url = 'Not needed'
220 class Templates (object):
221 def __init__(self, tpath, db, showyear = None):
224 now = datetime.datetime.now()
236 'showyear': showyear,
237 'monthlinks': ' '.join(db.get_month_links(showyear)),
238 'yearlinks': ' '.join(db.get_year_links()),
241 def get_main_header(self):
242 p = self.tpath + '/header.html'
243 if os.path.isfile(p):
244 return open(p).read() % self.vars
245 return default_main_header % self.vars
247 def get_main_footer(self):
248 p = self.tpath + '/footer.html'
249 if os.path.isfile(p):
250 return open(p).read() % self.vars
251 return default_main_footer % self.vars
253 def get_article_header(self, article):
254 avars = self.vars.copy()
256 'arttitle': article.title,
257 'author': article.author,
258 'date': article.created.isoformat(' '),
259 'uuid': article.uuid,
260 'created': article.created.isoformat(' '),
261 'updated': article.updated.isoformat(' '),
262 'tags': article.get_tags_links(),
264 'cyear': article.created.year,
265 'cmonth': article.created.month,
266 'cday': article.created.day,
267 'chour': article.created.hour,
268 'cminute': article.created.minute,
269 'csecond': article.created.second,
271 'uyear': article.updated.year,
272 'umonth': article.updated.month,
273 'uday': article.updated.day,
274 'uhour': article.updated.hour,
275 'uminute': article.updated.minute,
276 'usecond': article.updated.second,
279 p = self.tpath + '/art_header.html'
280 if os.path.isfile(p):
281 return open(p).read() % avars
282 return default_article_header % avars
284 def get_article_footer(self, article):
285 avars = self.vars.copy()
287 'arttitle': article.title,
288 'author': article.author,
289 'date': article.created.isoformat(' '),
290 'uuid': article.uuid,
291 'created': article.created.isoformat(' '),
292 'updated': article.updated.isoformat(' '),
293 'tags': article.get_tags_links(),
295 'cyear': article.created.year,
296 'cmonth': article.created.month,
297 'cday': article.created.day,
298 'chour': article.created.hour,
299 'cminute': article.created.minute,
300 'csecond': article.created.second,
302 'uyear': article.updated.year,
303 'umonth': article.updated.month,
304 'uday': article.updated.day,
305 'uhour': article.updated.hour,
306 'uminute': article.updated.minute,
307 'usecond': article.updated.second,
310 p = self.tpath + '/art_footer.html'
311 if os.path.isfile(p):
312 return open(p).read() % avars
313 return default_article_footer % avars
316 class Article (object):
317 def __init__(self, path):
321 self.uuid = "%08x" % zlib.crc32(self.path)
326 self._title = 'Removed post'
327 self._author = author
329 self._raw_content = ''
336 title = property(fget = get_title)
338 def get_author(self):
342 author = property(fget = get_author)
348 tags = property(fget = get_tags)
350 def get_raw_content(self):
353 return self._raw_content
354 raw_content = property(fget = get_raw_content)
357 def __cmp__(self, other):
358 if self.path == other.path:
362 if not other.created:
364 if self.created < other.created:
368 def title_cmp(self, other):
369 return cmp(self.title, other.title)
374 raw = open(data_path + '/' + self.path).readlines()
381 name, value = l.split(':', 1)
382 if name.lower() == 'title':
384 elif name.lower() == 'author':
386 elif name.lower() == 'tags':
387 ts = value.split(',')
388 ts = [t.strip() for t in ts]
394 self._raw_content = ''.join(raw[count + 1:])
399 raw = open(data_path + '/' + self.path).readlines()
401 return "Can't open post file<p>"
402 raw = raw[raw.index('\n'):]
405 'input_encoding': encoding,
406 'output_encoding': 'utf8',
408 parts = publish_parts(self.raw_content,
409 settings_overrides = settings,
410 writer_name = "html")
411 return parts['body'].encode('utf8')
413 def get_tags_links(self):
415 tags = list(self.tags)
418 l.append('<a class="tag" href="%s/tag/%s">%s</a>' % \
419 (blog_url, urllib.quote(t), t) )
424 def __init__(self, dbpath):
428 self.actyears = set()
429 self.actmonths = set()
432 def get_articles(self, year = 0, month = 0, day = 0, tags = None):
434 for a in self.articles:
435 if year and a.created.year != year: continue
436 if month and a.created.month != month: continue
437 if day and a.created.day != day: continue
438 if tags and not tags.issubset(a.tags): continue
444 def get_article(self, uuid):
445 return self.uuids[uuid]
449 f = open(self.dbpath)
454 # Each line has the following comma separated format:
455 # path (relative to data_path), \
464 a.created = datetime.datetime.fromtimestamp(
466 a.updated = datetime.datetime.fromtimestamp(
468 self.uuids[a.uuid] = a
469 self.actyears.add(a.created.year)
470 self.actmonths.add((a.created.year, a.created.month))
471 self.articles.append(a)
474 f = open(self.dbpath + '.tmp', 'w')
475 for a in self.articles:
478 s += str(time.mktime(a.created.timetuple())) + ', '
479 s += str(time.mktime(a.updated.timetuple())) + '\n'
482 os.rename(self.dbpath + '.tmp', self.dbpath)
484 def get_year_links(self):
485 yl = list(self.actyears)
486 yl.sort(reverse = True)
487 return [ '<a href="%s/%d/">%d</a>' % (blog_url, y, y)
490 def get_month_links(self, year):
491 am = [ i[1] for i in self.actmonths if i[0] == year ]
493 for i in range(1, 13):
494 name = calendar.month_name[i][:3]
496 s = '<a href="%s/%d/%d/">%s</a>' % \
497 ( blog_url, year, i, name )
508 def render_html(articles, db, actyear = None):
509 template = Templates(templates_path, db, actyear)
510 print 'Content-type: text/html; charset=utf-8\n'
511 print template.get_main_header()
513 print template.get_article_header(a)
515 print template.get_article_footer(a)
516 print template.get_main_footer()
518 def render_artlist(articles, db, actyear = None):
519 template = Templates(templates_path, db, actyear)
520 print 'Content-type: text/html; charset=utf-8\n'
521 print template.get_main_header()
522 print '<h2>Articles</h2>'
524 print '<li><a href="%(url)s/uuid/%(uuid)s">%(title)s</a></li>' \
530 print template.get_main_footer()
532 def render_atom(articles):
533 if len(articles) > 0:
534 updated = articles[0].updated.isoformat()
536 updated = datetime.datetime.now().isoformat()
538 print 'Content-type: application/atom+xml; charset=utf-8\n'
539 print """<?xml version="1.0" encoding="utf-8"?>
541 <feed xmlns="http://www.w3.org/2005/Atom">
542 <title>%(title)s</title>
543 <link rel="alternate" type="text/html" href="%(url)s"/>
544 <link rel="self" type="application/atom+xml" href="%(url)s/atom"/>
545 <id>%(url)s</id> <!-- TODO: find a better <id>, see RFC 4151 -->
546 <updated>%(updated)sZ</updated>
557 <title>%(arttitle)s</title>
558 <author><name>%(author)s</name></author>
559 <link href="%(url)s/post/%(uuid)s" />
560 <id>%(url)s/post/%(uuid)s</id>
561 <summary>%(arttitle)s</summary>
562 <published>%(created)sZ</published>
563 <updated>%(updated)sZ</updated>
564 <content type="xhtml">
565 <div xmlns="http://www.w3.org/1999/xhtml"><p>
575 'created': a.created.isoformat(),
576 'updated': a.updated.isoformat(),
577 'contents': a.to_html(),
584 print 'Content-type: text/plain\n'
588 import cgitb; cgitb.enable()
590 form = cgi.FieldStorage()
591 year = int(form.getfirst("year", 0))
592 month = int(form.getfirst("month", 0))
593 day = int(form.getfirst("day", 0))
594 tags = set(form.getlist("tag"))
601 if os.environ.has_key('PATH_INFO'):
602 path_info = os.environ['PATH_INFO']
603 style = path_info == '/style'
604 atom = path_info == '/atom'
605 tag = path_info.startswith('/tag/')
606 post = path_info.startswith('/post/')
607 artlist = path_info.startswith('/list')
608 if not style and not atom and not post and not tag \
610 date = path_info.split('/')[1:]
612 if len(date) > 1 and date[0]:
614 if len(date) > 2 and date[1]:
616 if len(date) > 3 and date[2]:
621 uuid = path_info.replace('/post/', '')
622 uuid = uuid.replace('/', '')
624 t = path_info.replace('/tag/', '')
625 t = t.replace('/', '')
626 t = urllib.unquote_plus(t)
629 db = DB(data_path + '/db')
631 articles = db.get_articles(tags = tags)
632 articles.sort(reverse = True)
633 render_atom(articles[:10])
637 render_html( [db.get_article(uuid)], db, year )
639 articles = db.get_articles()
640 articles.sort(cmp = Article.title_cmp)
641 render_artlist(articles, db)
643 articles = db.get_articles(year, month, day, tags)
644 articles.sort(reverse = True)
645 if not year and not month and not day and not tags:
646 articles = articles[:10]
647 render_html(articles, db, year)
651 print 'Usage: %s {add|rm|update} article_path' % sys.argv[0]
654 if len(sys.argv) != 3:
659 art_path = os.path.realpath(sys.argv[2])
661 if os.path.commonprefix([data_path, art_path]) != data_path:
662 print "Error: article (%s) must be inside data_path (%s)" % \
663 (art_path, data_path)
665 art_path = art_path[len(data_path):]
667 if not os.path.isfile(data_path + '/db'):
668 open(data_path + '/db', 'w').write('')
669 db = DB(data_path + '/db')
672 article = Article(art_path)
673 for a in db.articles:
675 print 'Error: article already exists'
677 db.articles.append(article)
678 article.created = datetime.datetime.now()
679 article.updated = datetime.datetime.now()
682 article = Article(art_path)
683 for a in db.articles:
687 print "Error: no such article"
689 db.articles.remove(a)
691 elif cmd == 'update':
692 article = Article(art_path)
693 for a in db.articles:
697 print "Error: no such article"
699 a.updated = datetime.datetime.now()
708 if os.environ.has_key('GATEWAY_INTERFACE'):
711 sys.exit(handle_cmd())