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;
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 background-color: #99F;
195 text-decoration: none;
198 /* Articles are enclosed in <div class="section"> */
204 border-bottom: 1px dotted #99C;
209 # find out our URL, needed for syndication
211 n = os.environ['SERVER_NAME']
212 p = os.environ['SERVER_PORT']
213 s = os.environ['SCRIPT_NAME']
216 full_url = 'http://%s%s%s' % (n, p, s)
218 full_url = 'Not needed'
221 class Templates (object):
222 def __init__(self, tpath, db, showyear = None):
225 now = datetime.datetime.now()
237 'showyear': showyear,
238 'monthlinks': ' '.join(db.get_month_links(showyear)),
239 'yearlinks': ' '.join(db.get_year_links()),
242 def get_main_header(self):
243 p = self.tpath + '/header.html'
244 if os.path.isfile(p):
245 return open(p).read() % self.vars
246 return default_main_header % self.vars
248 def get_main_footer(self):
249 p = self.tpath + '/footer.html'
250 if os.path.isfile(p):
251 return open(p).read() % self.vars
252 return default_main_footer % self.vars
254 def get_article_header(self, article):
255 avars = self.vars.copy()
257 'arttitle': article.title,
258 'author': article.author,
259 'date': article.created.isoformat(' '),
260 'uuid': article.uuid,
261 'created': article.created.isoformat(' '),
262 'updated': article.updated.isoformat(' '),
263 'tags': article.get_tags_links(),
265 'cyear': article.created.year,
266 'cmonth': article.created.month,
267 'cday': article.created.day,
268 'chour': article.created.hour,
269 'cminute': article.created.minute,
270 'csecond': article.created.second,
272 'uyear': article.updated.year,
273 'umonth': article.updated.month,
274 'uday': article.updated.day,
275 'uhour': article.updated.hour,
276 'uminute': article.updated.minute,
277 'usecond': article.updated.second,
280 p = self.tpath + '/art_header.html'
281 if os.path.isfile(p):
282 return open(p).read() % avars
283 return default_article_header % avars
285 def get_article_footer(self, article):
286 avars = self.vars.copy()
288 'arttitle': article.title,
289 'author': article.author,
290 'date': article.created.isoformat(' '),
291 'uuid': article.uuid,
292 'created': article.created.isoformat(' '),
293 'updated': article.updated.isoformat(' '),
294 'tags': article.get_tags_links(),
296 'cyear': article.created.year,
297 'cmonth': article.created.month,
298 'cday': article.created.day,
299 'chour': article.created.hour,
300 'cminute': article.created.minute,
301 'csecond': article.created.second,
303 'uyear': article.updated.year,
304 'umonth': article.updated.month,
305 'uday': article.updated.day,
306 'uhour': article.updated.hour,
307 'uminute': article.updated.minute,
308 'usecond': article.updated.second,
311 p = self.tpath + '/art_footer.html'
312 if os.path.isfile(p):
313 return open(p).read() % avars
314 return default_article_footer % avars
317 class Article (object):
318 def __init__(self, path):
322 self.uuid = "%08x" % zlib.crc32(self.path)
327 self._title = 'Removed post'
328 self._author = author
330 self._raw_content = ''
337 title = property(fget = get_title)
339 def get_author(self):
343 author = property(fget = get_author)
349 tags = property(fget = get_tags)
351 def get_raw_content(self):
354 return self._raw_content
355 raw_content = property(fget = get_raw_content)
358 def __cmp__(self, other):
359 if self.path == other.path:
363 if not other.created:
365 if self.created < other.created:
369 def title_cmp(self, other):
370 return cmp(self.title, other.title)
375 raw = open(data_path + '/' + self.path).readlines()
382 name, value = l.split(':', 1)
383 if name.lower() == 'title':
385 elif name.lower() == 'author':
387 elif name.lower() == 'tags':
388 ts = value.split(',')
389 ts = [t.strip() for t in ts]
395 self._raw_content = ''.join(raw[count + 1:])
400 raw = open(data_path + '/' + self.path).readlines()
402 return "Can't open post file<p>"
403 raw = raw[raw.index('\n'):]
406 'input_encoding': encoding,
407 'output_encoding': 'utf8',
409 parts = publish_parts(self.raw_content,
410 settings_overrides = settings,
411 writer_name = "html")
412 return parts['body'].encode('utf8')
414 def get_tags_links(self):
416 tags = list(self.tags)
419 l.append('<a class="tag" href="%s/tag/%s">%s</a>' % \
420 (blog_url, urllib.quote(t), t) )
425 def __init__(self, dbpath):
429 self.actyears = set()
430 self.actmonths = set()
433 def get_articles(self, year = 0, month = 0, day = 0, tags = None):
435 for a in self.articles:
436 if year and a.created.year != year: continue
437 if month and a.created.month != month: continue
438 if day and a.created.day != day: continue
439 if tags and not tags.issubset(a.tags): continue
445 def get_article(self, uuid):
446 return self.uuids[uuid]
450 f = open(self.dbpath)
455 # Each line has the following comma separated format:
456 # path (relative to data_path), \
465 a.created = datetime.datetime.fromtimestamp(
467 a.updated = datetime.datetime.fromtimestamp(
469 self.uuids[a.uuid] = a
470 self.actyears.add(a.created.year)
471 self.actmonths.add((a.created.year, a.created.month))
472 self.articles.append(a)
475 f = open(self.dbpath + '.tmp', 'w')
476 for a in self.articles:
479 s += str(time.mktime(a.created.timetuple())) + ', '
480 s += str(time.mktime(a.updated.timetuple())) + '\n'
483 os.rename(self.dbpath + '.tmp', self.dbpath)
485 def get_year_links(self):
486 yl = list(self.actyears)
487 yl.sort(reverse = True)
488 return [ '<a href="%s/%d/">%d</a>' % (blog_url, y, y)
491 def get_month_links(self, year):
492 am = [ i[1] for i in self.actmonths if i[0] == year ]
494 for i in range(1, 13):
495 name = calendar.month_name[i][:3]
497 s = '<a href="%s/%d/%d/">%s</a>' % \
498 ( blog_url, year, i, name )
509 def render_html(articles, db, actyear = None):
510 template = Templates(templates_path, db, actyear)
511 print 'Content-type: text/html; charset=utf-8\n'
512 print template.get_main_header()
514 print template.get_article_header(a)
516 print template.get_article_footer(a)
517 print template.get_main_footer()
519 def render_artlist(articles, db, actyear = None):
520 template = Templates(templates_path, db, actyear)
521 print 'Content-type: text/html; charset=utf-8\n'
522 print template.get_main_header()
523 print '<h2>Articles</h2>'
525 print '<li><a href="%(url)s/uuid/%(uuid)s">%(title)s</a></li>' \
531 print template.get_main_footer()
533 def render_atom(articles):
534 if len(articles) > 0:
535 updated = articles[0].updated.isoformat()
537 updated = datetime.datetime.now().isoformat()
539 print 'Content-type: application/atom+xml; charset=utf-8\n'
540 print """<?xml version="1.0" encoding="utf-8"?>
542 <feed xmlns="http://www.w3.org/2005/Atom">
543 <title>%(title)s</title>
544 <link rel="alternate" type="text/html" href="%(url)s"/>
545 <link rel="self" type="application/atom+xml" href="%(url)s/atom"/>
546 <id>%(url)s</id> <!-- TODO: find a better <id>, see RFC 4151 -->
547 <updated>%(updated)sZ</updated>
558 <title>%(arttitle)s</title>
559 <author><name>%(author)s</name></author>
560 <link href="%(url)s/post/%(uuid)s" />
561 <id>%(url)s/post/%(uuid)s</id>
562 <summary>%(arttitle)s</summary>
563 <published>%(created)sZ</published>
564 <updated>%(updated)sZ</updated>
565 <content type="xhtml">
566 <div xmlns="http://www.w3.org/1999/xhtml"><p>
576 'created': a.created.isoformat(),
577 'updated': a.updated.isoformat(),
578 'contents': a.to_html(),
585 print 'Content-type: text/css\r\n\r\n',
589 import cgitb; cgitb.enable()
591 form = cgi.FieldStorage()
592 year = int(form.getfirst("year", 0))
593 month = int(form.getfirst("month", 0))
594 day = int(form.getfirst("day", 0))
595 tags = set(form.getlist("tag"))
602 if os.environ.has_key('PATH_INFO'):
603 path_info = os.environ['PATH_INFO']
604 style = path_info == '/style'
605 atom = path_info == '/atom'
606 tag = path_info.startswith('/tag/')
607 post = path_info.startswith('/post/')
608 artlist = path_info.startswith('/list')
609 if not style and not atom and not post and not tag \
611 date = path_info.split('/')[1:]
613 if len(date) > 1 and date[0]:
615 if len(date) > 2 and date[1]:
617 if len(date) > 3 and date[2]:
622 uuid = path_info.replace('/post/', '')
623 uuid = uuid.replace('/', '')
625 t = path_info.replace('/tag/', '')
626 t = t.replace('/', '')
627 t = urllib.unquote_plus(t)
630 db = DB(data_path + '/db')
632 articles = db.get_articles(tags = tags)
633 articles.sort(reverse = True)
634 render_atom(articles[:10])
638 render_html( [db.get_article(uuid)], db, year )
640 articles = db.get_articles()
641 articles.sort(cmp = Article.title_cmp)
642 render_artlist(articles, db)
644 articles = db.get_articles(year, month, day, tags)
645 articles.sort(reverse = True)
646 if not year and not month and not day and not tags:
647 articles = articles[:10]
648 render_html(articles, db, year)
652 print 'Usage: %s {add|rm|update} article_path' % sys.argv[0]
655 if len(sys.argv) != 3:
660 art_path = os.path.realpath(sys.argv[2])
662 if os.path.commonprefix([data_path, art_path]) != data_path:
663 print "Error: article (%s) must be inside data_path (%s)" % \
664 (art_path, data_path)
666 art_path = art_path[len(data_path):]
668 if not os.path.isfile(data_path + '/db'):
669 open(data_path + '/db', 'w').write('')
670 db = DB(data_path + '/db')
673 article = Article(art_path)
674 for a in db.articles:
676 print 'Error: article already exists'
678 db.articles.append(article)
679 article.created = datetime.datetime.now()
680 article.updated = datetime.datetime.now()
683 article = Article(art_path)
684 for a in db.articles:
688 print "Error: no such article"
690 db.articles.remove(a)
692 elif cmd == 'update':
693 article = Article(art_path)
694 for a in db.articles:
698 print "Error: no such article"
700 a.updated = datetime.datetime.now()
709 if os.environ.has_key('GATEWAY_INTERFACE'):
712 sys.exit(handle_cmd())