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/>
88 views: <a href="%(url)s/">blog</a> <a href="%(url)s/list">list</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:
361 def title_cmp(self, other):
362 return cmp(self.title, other.title)
367 raw = open(data_path + '/' + self.path).readlines()
374 name, value = l.split(':', 1)
375 if name.lower() == 'title':
377 elif name.lower() == 'author':
379 elif name.lower() == 'tags':
380 ts = value.split(',')
381 ts = [t.strip() for t in ts]
387 self._raw_content = ''.join(raw[count + 1:])
392 raw = open(data_path + '/' + self.path).readlines()
394 return "Can't open post file<p>"
395 raw = raw[raw.index('\n'):]
398 'input_encoding': encoding,
399 'output_encoding': 'utf8',
401 parts = publish_parts(self.raw_content,
402 settings_overrides = settings,
403 writer_name = "html")
404 return parts['body'].encode('utf8')
406 def get_tags_links(self):
408 tags = list(self.tags)
411 l.append('<a class="tag" href="%s/tag/%s">%s</a>' % \
412 (blog_url, urllib.quote(t), t) )
417 def __init__(self, dbpath):
421 self.actyears = set()
422 self.actmonths = set()
425 def get_articles(self, year = 0, month = 0, day = 0, tags = None):
427 for a in self.articles:
428 if year and a.created.year != year: continue
429 if month and a.created.month != month: continue
430 if day and a.created.day != day: continue
431 if tags and not tags.issubset(a.tags): continue
437 def get_article(self, uuid):
438 return self.uuids[uuid]
442 f = open(self.dbpath)
447 # Each line has the following comma separated format:
448 # path (relative to data_path), \
457 a.created = datetime.datetime.fromtimestamp(
459 a.updated = datetime.datetime.fromtimestamp(
461 self.uuids[a.uuid] = a
462 self.actyears.add(a.created.year)
463 self.actmonths.add((a.created.year, a.created.month))
464 self.articles.append(a)
467 f = open(self.dbpath + '.tmp', 'w')
468 for a in self.articles:
471 s += str(time.mktime(a.created.timetuple())) + ', '
472 s += str(time.mktime(a.updated.timetuple())) + '\n'
475 os.rename(self.dbpath + '.tmp', self.dbpath)
477 def get_year_links(self):
478 yl = list(self.actyears)
479 yl.sort(reverse = True)
480 return [ '<a href="%s/%d/">%d</a>' % (blog_url, y, y)
483 def get_month_links(self, year):
484 am = [ i[1] for i in self.actmonths if i[0] == year ]
486 for i in range(1, 13):
487 name = calendar.month_name[i][:3]
489 s = '<a href="%s/%d/%d/">%s</a>' % \
490 ( blog_url, year, i, name )
501 def render_html(articles, db, actyear = None):
502 template = Templates(templates_path, db, actyear)
503 print 'Content-type: text/html; charset=utf-8\n'
504 print template.get_main_header()
506 print template.get_article_header(a)
508 print template.get_article_footer(a)
509 print template.get_main_footer()
511 def render_artlist(articles, db, actyear = None):
512 template = Templates(templates_path, db, actyear)
513 print 'Content-type: text/html; charset=utf-8\n'
514 print template.get_main_header()
515 print '<h2>Articles</h2>'
517 print '<li><a href="%(url)s/uuid/%(uuid)s">%(title)s</a></li>' \
523 print template.get_main_footer()
525 def render_atom(articles):
526 if len(articles) > 0:
527 updated = articles[0].updated.isoformat()
529 updated = datetime.datetime.now().isoformat()
531 print 'Content-type: application/atom+xml; charset=utf-8\n'
532 print """<?xml version="1.0" encoding="utf-8"?>
534 <feed xmlns="http://www.w3.org/2005/Atom">
535 <title>%(title)s</title>
536 <link rel="alternate" type="text/html" href="%(url)s"/>
537 <link rel="self" type="application/atom+xml" href="%(url)s/atom"/>
538 <id>%(url)s</id> <!-- TODO: find a better <id>, see RFC 4151 -->
539 <updated>%(updated)sZ</updated>
550 <title>%(arttitle)s</title>
551 <author><name>%(author)s</name></author>
552 <link href="%(url)s/post/%(uuid)s" />
553 <id>%(url)s/post/%(uuid)s</id>
554 <summary>%(arttitle)s</summary>
555 <published>%(created)sZ</published>
556 <updated>%(updated)sZ</updated>
557 <content type="xhtml">
558 <div xmlns="http://www.w3.org/1999/xhtml"><p>
568 'created': a.created.isoformat(),
569 'updated': a.updated.isoformat(),
570 'contents': a.to_html(),
577 print 'Content-type: text/plain\n'
581 import cgitb; cgitb.enable()
583 form = cgi.FieldStorage()
584 year = int(form.getfirst("year", 0))
585 month = int(form.getfirst("month", 0))
586 day = int(form.getfirst("day", 0))
587 tags = set(form.getlist("tag"))
594 if os.environ.has_key('PATH_INFO'):
595 path_info = os.environ['PATH_INFO']
596 style = path_info == '/style'
597 atom = path_info == '/atom'
598 tag = path_info.startswith('/tag/')
599 post = path_info.startswith('/post/')
600 artlist = path_info.startswith('/list')
601 if not style and not atom and not post and not tag \
603 date = path_info.split('/')[1:]
605 if len(date) > 1 and date[0]:
607 if len(date) > 2 and date[1]:
609 if len(date) > 3 and date[2]:
614 uuid = path_info.replace('/post/', '')
615 uuid = uuid.replace('/', '')
617 t = path_info.replace('/tag/', '')
618 t = t.replace('/', '')
619 t = urllib.unquote_plus(t)
622 db = DB(data_path + '/db')
624 articles = db.get_articles(tags = tags)
625 articles.sort(reverse = True)
626 render_atom(articles[:10])
630 render_html( [db.get_article(uuid)], db, year )
632 articles = db.get_articles()
633 articles.sort(cmp = Article.title_cmp)
634 render_artlist(articles, db)
636 articles = db.get_articles(year, month, day, tags)
637 articles.sort(reverse = True)
638 if not year and not month and not day and not tags:
639 articles = articles[:10]
640 render_html(articles, db, year)
644 print 'Usage: %s {add|rm|update} article_path' % sys.argv[0]
647 if len(sys.argv) != 3:
652 art_path = os.path.realpath(sys.argv[2])
654 if os.path.commonprefix([data_path, art_path]) != data_path:
655 print "Error: article (%s) must be inside data_path (%s)" % \
656 (art_path, data_path)
658 art_path = art_path[len(data_path):]
660 if not os.path.isfile(data_path + '/db'):
661 open(data_path + '/db', 'w').write('')
662 db = DB(data_path + '/db')
665 article = Article(art_path)
666 for a in db.articles:
668 print 'Error: article already exists'
670 db.articles.append(article)
671 article.created = datetime.datetime.now()
672 article.updated = datetime.datetime.now()
675 article = Article(art_path)
676 for a in db.articles:
680 print "Error: no such article"
682 db.articles.remove(a)
684 elif cmd == 'update':
685 article = Article(art_path)
686 for a in db.articles:
690 print "Error: no such article"
692 a.updated = datetime.datetime.now()
701 if os.environ.has_key('GATEWAY_INTERFACE'):
704 sys.exit(handle_cmd())