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;
205 # find out our URL, needed for syndication
207 n = os.environ['SERVER_NAME']
208 p = os.environ['SERVER_PORT']
209 s = os.environ['SCRIPT_NAME']
212 full_url = 'http://%s%s%s' % (n, p, s)
214 full_url = 'Not needed'
217 class Templates (object):
218 def __init__(self, tpath, db, showyear = None):
221 now = datetime.datetime.now()
233 'showyear': showyear,
234 'monthlinks': ' '.join(db.get_month_links(showyear)),
235 'yearlinks': ' '.join(db.get_year_links()),
238 def get_main_header(self):
239 p = self.tpath + '/header.html'
240 if os.path.isfile(p):
241 return open(p).read() % self.vars
242 return default_main_header % self.vars
244 def get_main_footer(self):
245 p = self.tpath + '/footer.html'
246 if os.path.isfile(p):
247 return open(p).read() % self.vars
248 return default_main_footer % self.vars
250 def get_article_header(self, article):
251 avars = self.vars.copy()
253 'arttitle': article.title,
254 'author': article.author,
255 'date': article.created.isoformat(' '),
256 'uuid': article.uuid,
257 'created': article.created.isoformat(' '),
258 'updated': article.updated.isoformat(' '),
259 'tags': article.get_tags_links(),
261 'cyear': article.created.year,
262 'cmonth': article.created.month,
263 'cday': article.created.day,
264 'chour': article.created.hour,
265 'cminute': article.created.minute,
266 'csecond': article.created.second,
268 'uyear': article.updated.year,
269 'umonth': article.updated.month,
270 'uday': article.updated.day,
271 'uhour': article.updated.hour,
272 'uminute': article.updated.minute,
273 'usecond': article.updated.second,
276 p = self.tpath + '/art_header.html'
277 if os.path.isfile(p):
278 return open(p).read() % avars
279 return default_article_header % avars
281 def get_article_footer(self, article):
282 avars = self.vars.copy()
284 'arttitle': article.title,
285 'author': article.author,
286 'date': article.created.isoformat(' '),
287 'uuid': article.uuid,
288 'created': article.created.isoformat(' '),
289 'updated': article.updated.isoformat(' '),
290 'tags': article.get_tags_links(),
292 'cyear': article.created.year,
293 'cmonth': article.created.month,
294 'cday': article.created.day,
295 'chour': article.created.hour,
296 'cminute': article.created.minute,
297 'csecond': article.created.second,
299 'uyear': article.updated.year,
300 'umonth': article.updated.month,
301 'uday': article.updated.day,
302 'uhour': article.updated.hour,
303 'uminute': article.updated.minute,
304 'usecond': article.updated.second,
307 p = self.tpath + '/art_footer.html'
308 if os.path.isfile(p):
309 return open(p).read() % avars
310 return default_article_footer % avars
313 class Article (object):
314 def __init__(self, path):
318 self.uuid = "%08x" % zlib.crc32(self.path)
323 self._title = 'Removed post'
324 self._author = author
326 self._raw_content = ''
333 title = property(fget = get_title)
335 def get_author(self):
339 author = property(fget = get_author)
345 tags = property(fget = get_tags)
347 def get_raw_content(self):
350 return self._raw_content
351 raw_content = property(fget = get_raw_content)
354 def __cmp__(self, other):
355 if self.path == other.path:
359 if not other.created:
361 if self.created < other.created:
365 def title_cmp(self, other):
366 return cmp(self.title, other.title)
371 raw = open(data_path + '/' + self.path).readlines()
378 name, value = l.split(':', 1)
379 if name.lower() == 'title':
381 elif name.lower() == 'author':
383 elif name.lower() == 'tags':
384 ts = value.split(',')
385 ts = [t.strip() for t in ts]
391 self._raw_content = ''.join(raw[count + 1:])
396 raw = open(data_path + '/' + self.path).readlines()
398 return "Can't open post file<p>"
399 raw = raw[raw.index('\n'):]
402 'input_encoding': encoding,
403 'output_encoding': 'utf8',
405 parts = publish_parts(self.raw_content,
406 settings_overrides = settings,
407 writer_name = "html")
408 return parts['body'].encode('utf8')
410 def get_tags_links(self):
412 tags = list(self.tags)
415 l.append('<a class="tag" href="%s/tag/%s">%s</a>' % \
416 (blog_url, urllib.quote(t), t) )
421 def __init__(self, dbpath):
425 self.actyears = set()
426 self.actmonths = set()
429 def get_articles(self, year = 0, month = 0, day = 0, tags = None):
431 for a in self.articles:
432 if year and a.created.year != year: continue
433 if month and a.created.month != month: continue
434 if day and a.created.day != day: continue
435 if tags and not tags.issubset(a.tags): continue
441 def get_article(self, uuid):
442 return self.uuids[uuid]
446 f = open(self.dbpath)
451 # Each line has the following comma separated format:
452 # path (relative to data_path), \
461 a.created = datetime.datetime.fromtimestamp(
463 a.updated = datetime.datetime.fromtimestamp(
465 self.uuids[a.uuid] = a
466 self.actyears.add(a.created.year)
467 self.actmonths.add((a.created.year, a.created.month))
468 self.articles.append(a)
471 f = open(self.dbpath + '.tmp', 'w')
472 for a in self.articles:
475 s += str(time.mktime(a.created.timetuple())) + ', '
476 s += str(time.mktime(a.updated.timetuple())) + '\n'
479 os.rename(self.dbpath + '.tmp', self.dbpath)
481 def get_year_links(self):
482 yl = list(self.actyears)
483 yl.sort(reverse = True)
484 return [ '<a href="%s/%d/">%d</a>' % (blog_url, y, y)
487 def get_month_links(self, year):
488 am = [ i[1] for i in self.actmonths if i[0] == year ]
490 for i in range(1, 13):
491 name = calendar.month_name[i][:3]
493 s = '<a href="%s/%d/%d/">%s</a>' % \
494 ( blog_url, year, i, name )
505 def render_html(articles, db, actyear = None):
506 template = Templates(templates_path, db, actyear)
507 print 'Content-type: text/html; charset=utf-8\n'
508 print template.get_main_header()
510 print template.get_article_header(a)
512 print template.get_article_footer(a)
513 print template.get_main_footer()
515 def render_artlist(articles, db, actyear = None):
516 template = Templates(templates_path, db, actyear)
517 print 'Content-type: text/html; charset=utf-8\n'
518 print template.get_main_header()
519 print '<h2>Articles</h2>'
521 print '<li><a href="%(url)s/uuid/%(uuid)s">%(title)s</a></li>' \
527 print template.get_main_footer()
529 def render_atom(articles):
530 if len(articles) > 0:
531 updated = articles[0].updated.isoformat()
533 updated = datetime.datetime.now().isoformat()
535 print 'Content-type: application/atom+xml; charset=utf-8\n'
536 print """<?xml version="1.0" encoding="utf-8"?>
538 <feed xmlns="http://www.w3.org/2005/Atom">
539 <title>%(title)s</title>
540 <link rel="alternate" type="text/html" href="%(url)s"/>
541 <link rel="self" type="application/atom+xml" href="%(url)s/atom"/>
542 <id>%(url)s</id> <!-- TODO: find a better <id>, see RFC 4151 -->
543 <updated>%(updated)sZ</updated>
554 <title>%(arttitle)s</title>
555 <author><name>%(author)s</name></author>
556 <link href="%(url)s/post/%(uuid)s" />
557 <id>%(url)s/post/%(uuid)s</id>
558 <summary>%(arttitle)s</summary>
559 <published>%(created)sZ</published>
560 <updated>%(updated)sZ</updated>
561 <content type="xhtml">
562 <div xmlns="http://www.w3.org/1999/xhtml"><p>
572 'created': a.created.isoformat(),
573 'updated': a.updated.isoformat(),
574 'contents': a.to_html(),
581 print 'Content-type: text/css\r\n\r\n',
585 import cgitb; cgitb.enable()
587 form = cgi.FieldStorage()
588 year = int(form.getfirst("year", 0))
589 month = int(form.getfirst("month", 0))
590 day = int(form.getfirst("day", 0))
591 tags = set(form.getlist("tag"))
598 if os.environ.has_key('PATH_INFO'):
599 path_info = os.environ['PATH_INFO']
600 style = path_info == '/style'
601 atom = path_info == '/atom'
602 tag = path_info.startswith('/tag/')
603 post = path_info.startswith('/post/')
604 artlist = path_info.startswith('/list')
605 if not style and not atom and not post and not tag \
607 date = path_info.split('/')[1:]
609 if len(date) > 1 and date[0]:
611 if len(date) > 2 and date[1]:
613 if len(date) > 3 and date[2]:
618 uuid = path_info.replace('/post/', '')
619 uuid = uuid.replace('/', '')
621 t = path_info.replace('/tag/', '')
622 t = t.replace('/', '')
623 t = urllib.unquote_plus(t)
626 db = DB(data_path + '/db')
628 articles = db.get_articles(tags = tags)
629 articles.sort(reverse = True)
630 render_atom(articles[:10])
634 render_html( [db.get_article(uuid)], db, year )
636 articles = db.get_articles()
637 articles.sort(cmp = Article.title_cmp)
638 render_artlist(articles, db)
640 articles = db.get_articles(year, month, day, tags)
641 articles.sort(reverse = True)
642 if not year and not month and not day and not tags:
643 articles = articles[:10]
644 render_html(articles, db, year)
648 print 'Usage: %s {add|rm|update} article_path' % sys.argv[0]
651 if len(sys.argv) != 3:
656 art_path = os.path.realpath(sys.argv[2])
658 if os.path.commonprefix([data_path, art_path]) != data_path:
659 print "Error: article (%s) must be inside data_path (%s)" % \
660 (art_path, data_path)
662 art_path = art_path[len(data_path):]
664 if not os.path.isfile(data_path + '/db'):
665 open(data_path + '/db', 'w').write('')
666 db = DB(data_path + '/db')
669 article = Article(art_path)
670 for a in db.articles:
672 print 'Error: article already exists'
674 db.articles.append(article)
675 article.created = datetime.datetime.now()
676 article.updated = datetime.datetime.now()
679 article = Article(art_path)
680 for a in db.articles:
684 print "Error: no such article"
686 db.articles.remove(a)
688 elif cmd == 'update':
689 article = Article(art_path)
690 for a in db.articles:
694 print "Error: no such article"
696 a.updated = datetime.datetime.now()
705 if os.environ.has_key('GATEWAY_INTERFACE'):
708 sys.exit(handle_cmd())