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 # Load the config file, if there is one
62 default_main_header = """
63 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
67 <link rel="alternate" title="%(title)s" href="%(fullurl)s/atom"
68 type="application/atom+xml" />
69 <link href="%(css_url)s" rel="stylesheet"
71 <title>%(title)s</title>
76 <h1><a href="%(url)s">%(title)s</a></h1>
81 default_main_footer = """
85 %(showyear)s: %(monthlinks)s<br/>
86 years: %(yearlinks)s<br/>
87 subscribe: <a href="%(url)s/atom">atom</a><br/>
94 default_article_header = """
96 <h2><a href="%(url)s/post/%(uuid)s">%(arttitle)s</a></h2>
97 <span class="artinfo">
98 by %(author)s on <span class="date">
100 <a class="date" href="%(url)s/%(cyear)d/">%(cyear)04d</a>-\
101 <a class="date" href="%(url)s/%(cyear)d/%(cmonth)d/">%(cmonth)02d</a>-\
102 <a class="date" href="%(url)s/%(cyear)d/%(cmonth)d/%(cday)d/">%(cday)02d</a>\
103 %(chour)02d:%(cminute)02d</span>
104 (updated on <span class="date">
105 <a class="date" href="%(url)s/%(uyear)d/">%(uyear)04d</a>-\
106 <a class="date" href="%(url)s/%(uyear)d/%(umonth)d/">%(umonth)02d</a>-\
107 <a class="date" href="%(url)s/%(uyear)d/%(umonth)d/%(uday)d/">%(uday)02d</a>\
108 %(uhour)02d:%(uminute)02d)</span><br/>
109 <span class="tags">tagged %(tags)s</span>
112 <div class="artbody">
115 default_article_footer = """
124 font-family: sans-serif;
134 border-bottom: 2px solid #99F;
143 border-bottom: 1px solid #99C;
147 text-decoration: none;
156 text-decoration: none;
160 span.artinfo a:hover {
161 text-decoration: none;
177 background-color: #99F;
186 text-decoration: none;
189 /* Articles are enclosed in <div class="section"> */
195 border-bottom: 1px dotted #99C;
200 # find out our URL, needed for syndication
202 n = os.environ['SERVER_NAME']
203 p = os.environ['SERVER_PORT']
204 s = os.environ['SCRIPT_NAME']
207 full_url = 'http://%s%s%s' % (n, p, s)
209 full_url = 'Not needed'
212 class Templates (object):
213 def __init__(self, tpath, db, showyear = None):
216 now = datetime.datetime.now()
228 'showyear': showyear,
229 'monthlinks': ' '.join(db.get_month_links(showyear)),
230 'yearlinks': ' '.join(db.get_year_links()),
233 def get_main_header(self):
234 p = self.tpath + '/header.html'
235 if os.path.isfile(p):
236 return open(p).read() % self.vars
237 return default_main_header % self.vars
239 def get_main_footer(self):
240 p = self.tpath + '/footer.html'
241 if os.path.isfile(p):
242 return open(p).read() % self.vars
243 return default_main_footer % self.vars
245 def get_article_header(self, article):
246 avars = self.vars.copy()
248 'arttitle': article.title,
249 'author': article.author,
250 'date': article.created.isoformat(' '),
251 'uuid': article.uuid,
252 'created': article.created.isoformat(' '),
253 'updated': article.updated.isoformat(' '),
254 'tags': article.get_tags_links(),
256 'cyear': article.created.year,
257 'cmonth': article.created.month,
258 'cday': article.created.day,
259 'chour': article.created.hour,
260 'cminute': article.created.minute,
261 'csecond': article.created.second,
263 'uyear': article.updated.year,
264 'umonth': article.updated.month,
265 'uday': article.updated.day,
266 'uhour': article.updated.hour,
267 'uminute': article.updated.minute,
268 'usecond': article.updated.second,
271 p = self.tpath + '/art_header.html'
272 if os.path.isfile(p):
273 return open(p).read() % avars
274 return default_article_header % avars
276 def get_article_footer(self, article):
277 avars = self.vars.copy()
279 'arttitle': article.title,
280 'author': article.author,
281 'date': article.created.isoformat(' '),
282 'uuid': article.uuid,
283 'created': article.created.isoformat(' '),
284 'updated': article.updated.isoformat(' '),
285 'tags': article.get_tags_links(),
287 'cyear': article.created.year,
288 'cmonth': article.created.month,
289 'cday': article.created.day,
290 'chour': article.created.hour,
291 'cminute': article.created.minute,
292 'csecond': article.created.second,
294 'uyear': article.updated.year,
295 'umonth': article.updated.month,
296 'uday': article.updated.day,
297 'uhour': article.updated.hour,
298 'uminute': article.updated.minute,
299 'usecond': article.updated.second,
302 p = self.tpath + '/art_footer.html'
303 if os.path.isfile(p):
304 return open(p).read() % avars
305 return default_article_footer % avars
308 class Article (object):
309 def __init__(self, path):
313 self.uuid = "%08x" % zlib.crc32(self.path)
318 self._title = 'Removed post'
319 self._author = author
321 self._raw_content = ''
328 title = property(fget = get_title)
330 def get_author(self):
334 author = property(fget = get_author)
340 tags = property(fget = get_tags)
342 def get_raw_content(self):
345 return self._raw_content
346 raw_content = property(fget = get_raw_content)
349 def __cmp__(self, other):
350 if self.path == other.path:
354 if not other.created:
356 if self.created < other.created:
362 raw = open(data_path + '/' + self.path).readlines()
369 name, value = l.split(':', 1)
370 if name.lower() == 'title':
372 elif name.lower() == 'author':
374 elif name.lower() == 'tags':
375 ts = value.split(',')
376 ts = [t.strip() for t in ts]
382 self._raw_content = ''.join(raw[count + 1:])
387 raw = open(data_path + '/' + self.path).readlines()
389 return "Can't open post file<p>"
390 raw = raw[raw.index('\n'):]
393 'input_encoding': encoding,
394 'output_encoding': 'utf8',
396 parts = publish_parts(self.raw_content,
397 settings_overrides = settings,
398 writer_name = "html")
399 return parts['body'].encode('utf8')
401 def get_tags_links(self):
403 tags = list(self.tags)
406 l.append('<a class="tag" href="%s/tag/%s">%s</a>' % \
407 (blog_url, urllib.quote(t), t) )
412 def __init__(self, dbpath):
416 self.actyears = set()
417 self.actmonths = set()
420 def get_articles(self, year = 0, month = 0, day = 0, tags = None):
422 for a in self.articles:
423 if year and a.created.year != year: continue
424 if month and a.created.month != month: continue
425 if day and a.created.day != day: continue
426 if tags and not tags.issubset(a.tags): continue
432 def get_article(self, uuid):
433 return self.uuids[uuid]
437 f = open(self.dbpath)
442 # Each line has the following comma separated format:
443 # path (relative to data_path), \
452 a.created = datetime.datetime.fromtimestamp(
454 a.updated = datetime.datetime.fromtimestamp(
456 self.uuids[a.uuid] = a
457 self.actyears.add(a.created.year)
458 self.actmonths.add((a.created.year, a.created.month))
459 self.articles.append(a)
462 f = open(self.dbpath + '.tmp', 'w')
463 for a in self.articles:
466 s += str(time.mktime(a.created.timetuple())) + ', '
467 s += str(time.mktime(a.updated.timetuple())) + '\n'
470 os.rename(self.dbpath + '.tmp', self.dbpath)
472 def get_year_links(self):
473 yl = list(self.actyears)
474 yl.sort(reverse = True)
475 return [ '<a href="%s/%d/">%d</a>' % (blog_url, y, y)
478 def get_month_links(self, year):
479 am = [ i[1] for i in self.actmonths if i[0] == year ]
481 for i in range(1, 13):
482 name = calendar.month_name[i][:3]
484 s = '<a href="%s/%d/%d/">%s</a>' % \
485 ( blog_url, year, i, name )
496 def render_html(articles, db, actyear = None):
497 template = Templates(templates_path, db, actyear)
498 print 'Content-type: text/html; charset=utf-8\n'
499 print template.get_main_header()
501 print template.get_article_header(a)
503 print template.get_article_footer(a)
504 print template.get_main_footer()
506 def render_atom(articles):
507 if len(articles) > 0:
508 updated = articles[0].updated.isoformat()
510 updated = datetime.datetime.now().isoformat()
512 print 'Content-type: application/atom+xml; charset=utf-8\n'
513 print """<?xml version="1.0" encoding="utf-8"?>
515 <feed xmlns="http://www.w3.org/2005/Atom">
516 <title>%(title)s</title>
517 <link rel="alternate" type="text/html" href="%(url)s"/>
518 <link rel="self" type="application/atom+xml" href="%(url)s/atom"/>
519 <id>%(url)s</id> <!-- TODO: find a better <id>, see RFC 4151 -->
520 <updated>%(updated)sZ</updated>
531 <title>%(arttitle)s</title>
532 <author><name>%(author)s</name></author>
533 <link href="%(url)s/post/%(uuid)s" />
534 <id>%(url)s/post/%(uuid)s</id>
535 <summary>%(arttitle)s</summary>
536 <published>%(created)sZ</published>
537 <updated>%(updated)sZ</updated>
538 <content type="xhtml">
539 <div xmlns="http://www.w3.org/1999/xhtml"><p>
549 'created': a.created.isoformat(),
550 'updated': a.updated.isoformat(),
551 'contents': a.to_html(),
558 print 'Content-type: text/plain\n'
562 import cgitb; cgitb.enable()
564 form = cgi.FieldStorage()
565 year = int(form.getfirst("year", 0))
566 month = int(form.getfirst("month", 0))
567 day = int(form.getfirst("day", 0))
568 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 if not style and not atom and not post and not tag:
581 date = path_info.split('/')[1:]
583 if len(date) > 1 and date[0]:
585 if len(date) > 2 and date[1]:
587 if len(date) > 3 and date[2]:
592 uuid = path_info.replace('/post/', '')
593 uuid = uuid.replace('/', '')
595 t = path_info.replace('/tag/', '')
596 t = t.replace('/', '')
597 t = urllib.unquote_plus(t)
600 db = DB(data_path + '/db')
602 articles = db.get_articles(tags = tags)
603 articles.sort(reverse = True)
604 render_atom(articles[:10])
608 render_html( [db.get_article(uuid)], year )
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)
640 for a in db.articles:
642 print 'Error: article already exists'
644 db.articles.append(article)
645 article.created = datetime.datetime.now()
646 article.updated = datetime.datetime.now()
649 article = Article(art_path)
650 for a in db.articles:
654 print "Error: no such article"
656 db.articles.remove(a)
658 elif cmd == 'update':
659 article = Article(art_path)
660 for a in db.articles:
664 print "Error: no such article"
666 a.updated = datetime.datetime.now()
675 if os.environ.has_key('GATEWAY_INTERFACE'):
678 sys.exit(handle_cmd())