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
54 if os.path.isfile("config.py"):
63 default_main_header = """
64 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
68 <link rel="alternate" title="%(title)s" href="%(fullurl)s/atom"
69 type="application/atom+xml" />
70 <link href="%(css_url)s" rel="stylesheet"
72 <title>%(title)s</title>
77 <h1><a href="%(url)s">%(title)s</a></h1>
82 default_main_footer = """
86 %(showyear)s: %(monthlinks)s<br/>
87 years: %(yearlinks)s<br/>
88 subscribe: <a href="%(url)s/atom">atom</a><br/>
95 default_article_header = """
97 <h2><a href="%(url)s/post/%(uuid)s">%(arttitle)s</a></h2>
98 <span class="artinfo">
99 by %(author)s on <span class="date">
101 <a class="date" href="%(url)s/%(cyear)d/">%(cyear)04d</a>-\
102 <a class="date" href="%(url)s/%(cyear)d/%(cmonth)d/">%(cmonth)02d</a>-\
103 <a class="date" href="%(url)s/%(cyear)d/%(cmonth)d/%(cday)d/">%(cday)02d</a>\
104 %(chour)02d:%(cminute)02d</span>
105 (updated on <span class="date">
106 <a class="date" href="%(url)s/%(uyear)d/">%(uyear)04d</a>-\
107 <a class="date" href="%(url)s/%(uyear)d/%(umonth)d/">%(umonth)02d</a>-\
108 <a class="date" href="%(url)s/%(uyear)d/%(umonth)d/%(uday)d/">%(uday)02d</a>\
109 %(uhour)02d:%(uminute)02d)</span><br/>
110 <span class="tags">tagged %(tags)s</span>
113 <div class="artbody">
116 default_article_footer = """
125 font-family: sans-serif;
135 border-bottom: 2px solid #99F;
144 border-bottom: 1px solid #99C;
148 text-decoration: none;
157 text-decoration: none;
161 span.artinfo a:hover {
162 text-decoration: none;
178 background-color: #99F;
187 text-decoration: none;
190 /* Articles are enclosed in <div class="section"> */
196 border-bottom: 1px dotted #99C;
201 # find out our URL, needed for syndication
203 n = os.environ['SERVER_NAME']
204 p = os.environ['SERVER_PORT']
205 s = os.environ['SCRIPT_NAME']
208 full_url = 'http://%s%s%s' % (n, p, s)
210 full_url = 'Not needed'
213 class Templates (object):
214 def __init__(self, tpath, db, showyear = None):
217 now = datetime.datetime.now()
229 'showyear': showyear,
230 'monthlinks': ' '.join(db.get_month_links(showyear)),
231 'yearlinks': ' '.join(db.get_year_links()),
234 def get_main_header(self):
235 p = self.tpath + '/header.html'
236 if os.path.isfile(p):
237 return open(p).read() % self.vars
238 return default_main_header % self.vars
240 def get_main_footer(self):
241 p = self.tpath + '/footer.html'
242 if os.path.isfile(p):
243 return open(p).read() % self.vars
244 return default_main_footer % self.vars
246 def get_article_header(self, article):
247 avars = self.vars.copy()
249 'arttitle': article.title,
250 'author': article.author,
251 'date': article.created.isoformat(' '),
252 'uuid': article.uuid,
253 'created': article.created.isoformat(' '),
254 'updated': article.updated.isoformat(' '),
255 'tags': article.get_tags_links(),
257 'cyear': article.created.year,
258 'cmonth': article.created.month,
259 'cday': article.created.day,
260 'chour': article.created.hour,
261 'cminute': article.created.minute,
262 'csecond': article.created.second,
264 'uyear': article.updated.year,
265 'umonth': article.updated.month,
266 'uday': article.updated.day,
267 'uhour': article.updated.hour,
268 'uminute': article.updated.minute,
269 'usecond': article.updated.second,
272 p = self.tpath + '/art_header.html'
273 if os.path.isfile(p):
274 return open(p).read() % avars
275 return default_article_header % avars
277 def get_article_footer(self, article):
278 avars = self.vars.copy()
280 'arttitle': article.title,
281 'author': article.author,
282 'date': article.created.isoformat(' '),
283 'uuid': article.uuid,
284 'created': article.created.isoformat(' '),
285 'updated': article.updated.isoformat(' '),
286 'tags': article.get_tags_links(),
288 'cyear': article.created.year,
289 'cmonth': article.created.month,
290 'cday': article.created.day,
291 'chour': article.created.hour,
292 'cminute': article.created.minute,
293 'csecond': article.created.second,
295 'uyear': article.updated.year,
296 'umonth': article.updated.month,
297 'uday': article.updated.day,
298 'uhour': article.updated.hour,
299 'uminute': article.updated.minute,
300 'usecond': article.updated.second,
303 p = self.tpath + '/art_footer.html'
304 if os.path.isfile(p):
305 return open(p).read() % avars
306 return default_article_footer % avars
309 class Article (object):
310 def __init__(self, path):
314 self.uuid = "%08x" % zlib.crc32(self.path)
319 self._title = 'Removed post'
320 self._author = author
322 self._raw_content = ''
329 title = property(fget = get_title)
331 def get_author(self):
335 author = property(fget = get_author)
341 tags = property(fget = get_tags)
343 def get_raw_content(self):
346 return self._raw_content
347 raw_content = property(fget = get_raw_content)
350 def __cmp__(self, other):
351 if self.path == other.path:
355 if not other.created:
357 if self.created < other.created:
363 raw = open(data_path + '/' + self.path).readlines()
370 name, value = l.split(':', 1)
371 if name.lower() == 'title':
373 elif name.lower() == 'author':
375 elif name.lower() == 'tags':
376 ts = value.split(',')
377 ts = [t.strip() for t in ts]
383 self._raw_content = ''.join(raw[count + 1:])
388 raw = open(data_path + '/' + self.path).readlines()
390 return "Can't open post file<p>"
391 raw = raw[raw.index('\n'):]
394 'input_encoding': encoding,
395 'output_encoding': 'utf8',
397 parts = publish_parts(self.raw_content,
398 settings_overrides = settings,
399 writer_name = "html")
400 return parts['body'].encode('utf8')
402 def get_tags_links(self):
404 tags = list(self.tags)
407 l.append('<a class="tag" href="%s/tag/%s">%s</a>' % \
408 (blog_url, urllib.quote(t), t) )
413 def __init__(self, dbpath):
417 self.actyears = set()
418 self.actmonths = set()
421 def get_articles(self, year = 0, month = 0, day = 0, tags = None):
423 for a in self.articles:
424 if year and a.created.year != year: continue
425 if month and a.created.month != month: continue
426 if day and a.created.day != day: continue
427 if tags and not tags.issubset(a.tags): continue
433 def get_article(self, uuid):
434 return self.uuids[uuid]
438 f = open(self.dbpath)
443 # Each line has the following comma separated format:
444 # path (relative to data_path), \
453 a.created = datetime.datetime.fromtimestamp(
455 a.updated = datetime.datetime.fromtimestamp(
457 self.uuids[a.uuid] = a
458 self.actyears.add(a.created.year)
459 self.actmonths.add((a.created.year, a.created.month))
460 self.articles.append(a)
463 f = open(self.dbpath + '.tmp', 'w')
464 for a in self.articles:
467 s += str(time.mktime(a.created.timetuple())) + ', '
468 s += str(time.mktime(a.updated.timetuple())) + '\n'
471 os.rename(self.dbpath + '.tmp', self.dbpath)
473 def get_year_links(self):
474 yl = list(self.actyears)
475 yl.sort(reverse = True)
476 return [ '<a href="%s/%d/">%d</a>' % (blog_url, y, y)
479 def get_month_links(self, year):
480 am = [ i[1] for i in self.actmonths if i[0] == year ]
482 for i in range(1, 13):
483 name = calendar.month_name[i][:3]
485 s = '<a href="%s/%d/%d/">%s</a>' % \
486 ( blog_url, year, i, name )
497 def render_html(articles, db, actyear = None):
498 template = Templates(templates_path, db, actyear)
499 print 'Content-type: text/html; charset=utf-8\n'
500 print template.get_main_header()
502 print template.get_article_header(a)
504 print template.get_article_footer(a)
505 print template.get_main_footer()
507 def render_atom(articles):
508 if len(articles) > 0:
509 updated = articles[0].updated.isoformat()
511 updated = datetime.datetime.now().isoformat()
513 print 'Content-type: application/atom+xml; charset=utf-8\n'
514 print """<?xml version="1.0" encoding="utf-8"?>
516 <feed xmlns="http://www.w3.org/2005/Atom">
517 <title>%(title)s</title>
518 <link rel="alternate" type="text/html" href="%(url)s"/>
519 <link rel="self" type="application/atom+xml" href="%(url)s/atom"/>
520 <id>%(url)s</id> <!-- TODO: find a better <id>, see RFC 4151 -->
521 <updated>%(updated)sZ</updated>
532 <title>%(arttitle)s</title>
533 <author><name>%(author)s</name></author>
534 <link href="%(url)s/post/%(uuid)s" />
535 <id>%(url)s/post/%(uuid)s</id>
536 <summary>%(arttitle)s</summary>
537 <published>%(created)sZ</published>
538 <updated>%(updated)sZ</updated>
539 <content type="xhtml">
540 <div xmlns="http://www.w3.org/1999/xhtml"><p>
550 'created': a.created.isoformat(),
551 'updated': a.updated.isoformat(),
552 'contents': a.to_html(),
559 print 'Content-type: text/plain\n'
563 import cgitb; cgitb.enable()
565 form = cgi.FieldStorage()
566 year = int(form.getfirst("year", 0))
567 month = int(form.getfirst("month", 0))
568 day = int(form.getfirst("day", 0))
569 tags = set(form.getlist("tag"))
575 if os.environ.has_key('PATH_INFO'):
576 path_info = os.environ['PATH_INFO']
577 style = path_info == '/style'
578 atom = path_info == '/atom'
579 tag = path_info.startswith('/tag/')
580 post = path_info.startswith('/post/')
581 if not style and not atom and not post and not tag:
582 date = path_info.split('/')[1:]
584 if len(date) > 1 and date[0]:
586 if len(date) > 2 and date[1]:
588 if len(date) > 3 and date[2]:
593 uuid = path_info.replace('/post/', '')
594 uuid = uuid.replace('/', '')
596 t = path_info.replace('/tag/', '')
597 t = t.replace('/', '')
598 t = urllib.unquote_plus(t)
601 db = DB(data_path + '/db')
603 articles = db.get_articles(tags = tags)
604 articles.sort(reverse = True)
605 render_atom(articles[:10])
609 render_html( [db.get_article(uuid)], year )
611 articles = db.get_articles(year, month, day, tags)
612 articles.sort(reverse = True)
613 if not year and not month and not day and not tags:
614 articles = articles[:10]
615 render_html(articles, db, year)
619 print 'Usage: %s {add|rm|update} article_path' % sys.argv[0]
622 if len(sys.argv) != 3:
627 art_path = os.path.realpath(sys.argv[2])
629 if os.path.commonprefix([data_path, art_path]) != data_path:
630 print "Error: article must be inside data dir"
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())