]> git.llucax.com Git - software/blitiri.git/blob - blitiri.cgi
0e2aea6da68051a1575281f5990c0f9904635b79
[software/blitiri.git] / blitiri.cgi
1 #!/usr/bin/env python
2 #coding: utf8
3
4 # blitiri - A single-file blog engine.
5 # Alberto Bertogli (albertito@gmail.com)
6
7 #
8 # Configuration section
9 #
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.
12 #
13
14 # Directory where entries are stored
15 data_path = "/tmp/blog/data"
16
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"
20
21 # URL to the blog, including the name. Can be a full URL or just the path.
22 blog_url = "/blog/blitiri.cgi"
23
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"
27
28 # Blog title
29 title = "I don't like blogs"
30
31 # Default author
32 author = "Hartmut Kegan"
33
34 # Article encoding
35 encoding = "utf8"
36
37 #
38 # End of configuration
39 # DO *NOT* EDIT ANYTHING PAST HERE
40 #
41
42
43 import sys
44 import os
45 import time
46 import datetime
47 import calendar
48 import zlib
49 import urllib
50 import cgi
51 from docutils.core import publish_parts
52
53 # Before importing the config, add our cwd to the Python path
54 sys.path.append(os.getcwd())
55
56 # Load the config file, if there is one
57 try:
58         from config import *
59 except:
60         pass
61
62
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)
66
67 # Default template
68
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">
73
74 <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
75 <head>
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>
80 </head>
81
82 <body>
83
84 <h1><a href="%(url)s">%(title)s</a></h1>
85
86 <div class="content">
87 """
88
89 default_main_footer = """
90 </div>
91 <div class="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/>
96 </div>
97
98 </body>
99 </html>
100 """
101
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">
107
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>
118 </span><br/>
119 <p/>
120 <div class="artbody">
121 """
122
123 default_article_footer = """
124 <p/>
125 </div>
126 </div>
127 """
128
129 # Default CSS
130 default_css = """
131 body {
132         font-family: sans-serif;
133         font-size: small;
134         width: 52em;
135 }
136
137 div.content {
138         width: 96%;
139 }
140
141 h1 {
142         font-size: large;
143         border-bottom: 2px solid #99F;
144         width: 100%;
145         margin-bottom: 1em;
146 }
147
148 h2 {
149         font-size: medium;
150         font-weigth: none;
151         margin-bottom: 1pt;
152         border-bottom: 1px solid #99C;
153 }
154
155 h1 a, h2 a {
156         text-decoration: none;
157         color: black;
158 }
159
160 span.artinfo {
161         font-size: xx-small;
162 }
163
164 span.artinfo a {
165         text-decoration: none;
166         color: #339;
167 }
168
169 span.artinfo a:hover {
170         text-decoration: none;
171         color: blue;
172 }
173
174 div.artbody {
175         margin-left: 1em;
176 }
177
178 div.article {
179         margin-bottom: 2em;
180 }
181
182 div.footer {
183         margin-top: 1em;
184         padding-top: 0.4em;
185         width: 100%;
186         border-top: 2px solid #99F;
187         font-size: x-small;
188 }
189
190 div.footer a {
191         text-decoration: none;
192 }
193
194 /* Articles are enclosed in <div class="section"> */
195 div.section h1 {
196         font-size: small;
197         font-weigth: none;
198         width: 100%;
199         margin-bottom: 1pt;
200         border-bottom: 1px dotted #99C;
201 }
202
203 """
204
205 # helper functions
206 def rst_to_html(rst):
207         settings = {
208                 'input_encoding': encoding,
209                 'output_encoding': 'utf8',
210         }
211         parts = publish_parts(rst, settings_overrides = settings,
212                                 writer_name = "html")
213         return parts['body'].encode('utf8')
214
215 def sanitize(obj):
216         if isinstance(obj, basestring):
217                 return cgi.escape(obj, True)
218         return obj
219
220
221 # find out our URL, needed for syndication
222 try:
223         n = os.environ['SERVER_NAME']
224         p = os.environ['SERVER_PORT']
225         s = os.environ['SCRIPT_NAME']
226         if p == '80': p = ''
227         else: p = ':' + p
228         full_url = 'http://%s%s%s' % (n, p, s)
229 except KeyError:
230         full_url = 'Not needed'
231
232
233 class Templates (object):
234         def __init__(self, tpath, db, showyear = None):
235                 self.tpath = tpath
236                 self.db = db
237                 now = datetime.datetime.now()
238                 if not showyear:
239                         showyear = now.year
240
241                 self.vars = {
242                         'css_url': css_url,
243                         'title': title,
244                         'url': blog_url,
245                         'fullurl': full_url,
246                         'year': now.year,
247                         'month': now.month,
248                         'day': now.day,
249                         'showyear': showyear,
250                         'monthlinks': ' '.join(db.get_month_links(showyear)),
251                         'yearlinks': ' '.join(db.get_year_links()),
252                 }
253
254         def get_template(self, page_name, default_template, extra_vars = None):
255                 if extra_vars is None:
256                         vars = self.vars
257                 else:
258                         vars = self.vars.copy()
259                         vars.update(extra_vars)
260
261                 p = '%s/%s.html' % (self.tpath, page_name)
262                 if os.path.isfile(p):
263                         return open(p).read() % vars
264                 return default_template % vars
265
266         def get_main_header(self):
267                 return self.get_template('header', default_main_header)
268
269         def get_main_footer(self):
270                 return self.get_template('footer', default_main_footer)
271
272         def get_article_header(self, article):
273                 return self.get_template(
274                         'art_header', default_article_header, article.to_vars())
275
276         def get_article_footer(self, article):
277                 return self.get_template(
278                         'art_footer', default_article_footer, article.to_vars())
279
280
281 class Article (object):
282         def __init__(self, path, created = None, updated = None):
283                 self.path = path
284                 self.created = created
285                 self.updated = updated
286                 self.uuid = "%08x" % zlib.crc32(self.path)
287
288                 self.loaded = False
289
290                 # loaded on demand
291                 self._title = 'Removed post'
292                 self._author = author
293                 self._tags = []
294                 self._raw_content = ''
295
296
297         def get_title(self):
298                 if not self.loaded:
299                         self.load()
300                 return self._title
301         title = property(fget = get_title)
302
303         def get_author(self):
304                 if not self.loaded:
305                         self.load()
306                 return self._author
307         author = property(fget = get_author)
308
309         def get_tags(self):
310                 if not self.loaded:
311                         self.load()
312                 return self._tags
313         tags = property(fget = get_tags)
314
315         def get_raw_content(self):
316                 if not self.loaded:
317                         self.load()
318                 return self._raw_content
319         raw_content = property(fget = get_raw_content)
320
321
322         def __cmp__(self, other):
323                 if self.path == other.path:
324                         return 0
325                 if not self.created:
326                         return 1
327                 if not other.created:
328                         return -1
329                 if self.created < other.created:
330                         return -1
331                 return 1
332
333         def title_cmp(self, other):
334                 return cmp(self.title, other.title)
335
336
337         def load(self):
338                 # XXX this tweak is only needed for old DB format, where
339                 # article's paths started with a slash
340                 path = self.path
341                 if path.startswith('/'):
342                         path = path[1:]
343                 filename = os.path.join(data_path, path)
344                 try:
345                         raw = open(filename).readlines()
346                 except:
347                         return
348
349                 count = 0
350                 for l in raw:
351                         if ':' in l:
352                                 name, value = l.split(':', 1)
353                                 if name.lower() == 'title':
354                                         self._title = value.strip()
355                                 elif name.lower() == 'author':
356                                         self._author = value.strip()
357                                 elif name.lower() == 'tags':
358                                         ts = value.split(',')
359                                         ts = [t.strip() for t in ts]
360                                         self._tags = set(ts)
361                         elif l == '\n':
362                                 # end of header
363                                 break
364                         count += 1
365                 self._raw_content = ''.join(raw[count + 1:])
366                 self.loaded = True
367
368         def to_html(self):
369                 return rst_to_html(self.raw_content)
370
371         def to_vars(self):
372                 return {
373                         'arttitle': sanitize(self.title),
374                         'author': sanitize(self.author),
375                         'date': self.created.isoformat(' '),
376                         'uuid': self.uuid,
377                         'tags': self.get_tags_links(),
378
379                         'created': self.created.isoformat(' '),
380                         'ciso': self.created.isoformat(),
381                         'cyear': self.created.year,
382                         'cmonth': self.created.month,
383                         'cday': self.created.day,
384                         'chour': self.created.hour,
385                         'cminute': self.created.minute,
386                         'csecond': self.created.second,
387
388                         'updated': self.updated.isoformat(' '),
389                         'uiso': self.updated.isoformat(),
390                         'uyear': self.updated.year,
391                         'umonth': self.updated.month,
392                         'uday': self.updated.day,
393                         'uhour': self.updated.hour,
394                         'uminute': self.updated.minute,
395                         'usecond': self.updated.second,
396                 }
397
398         def get_tags_links(self):
399                 l = []
400                 tags = list(self.tags)
401                 tags.sort()
402                 for t in tags:
403                         l.append('<a class="tag" href="%s/tag/%s">%s</a>' % \
404                                 (blog_url, urllib.quote(t), sanitize(t) ))
405                 return ', '.join(l)
406
407
408 class ArticleDB (object):
409         def __init__(self, dbpath):
410                 self.dbpath = dbpath
411                 self.articles = []
412                 self.uuids = {}
413                 self.actyears = set()
414                 self.actmonths = set()
415                 self.load()
416
417         def get_articles(self, year = 0, month = 0, day = 0, tags = None):
418                 l = []
419                 for a in self.articles:
420                         if year and a.created.year != year: continue
421                         if month and a.created.month != month: continue
422                         if day and a.created.day != day: continue
423                         if tags and not tags.issubset(a.tags): continue
424
425                         l.append(a)
426
427                 return l
428
429         def get_article(self, uuid):
430                 return self.uuids[uuid]
431
432         def load(self):
433                 try:
434                         f = open(self.dbpath)
435                 except:
436                         return
437
438                 for l in f:
439                         # Each line has the following comma separated format:
440                         # path (relative to data_path), \
441                         #       created (epoch), \
442                         #       updated (epoch)
443                         try:
444                                 l = l.split(',')
445                         except:
446                                 continue
447
448                         a = Article(l[0],
449                                 datetime.datetime.fromtimestamp(float(l[1])),
450                                 datetime.datetime.fromtimestamp(float(l[2])))
451                         self.uuids[a.uuid] = a
452                         self.actyears.add(a.created.year)
453                         self.actmonths.add((a.created.year, a.created.month))
454                         self.articles.append(a)
455
456         def save(self):
457                 f = open(self.dbpath + '.tmp', 'w')
458                 for a in self.articles:
459                         s = ''
460                         s += a.path + ', '
461                         s += str(time.mktime(a.created.timetuple())) + ', '
462                         s += str(time.mktime(a.updated.timetuple())) + '\n'
463                         f.write(s)
464                 f.close()
465                 os.rename(self.dbpath + '.tmp', self.dbpath)
466
467         def get_year_links(self):
468                 yl = list(self.actyears)
469                 yl.sort(reverse = True)
470                 return [ '<a href="%s/%d/">%d</a>' % (blog_url, y, y)
471                                 for y in yl ]
472
473         def get_month_links(self, year):
474                 am = [ i[1] for i in self.actmonths if i[0] == year ]
475                 ml = []
476                 for i in range(1, 13):
477                         name = calendar.month_name[i][:3]
478                         if i in am:
479                                 s = '<a href="%s/%d/%d/">%s</a>' % \
480                                         ( blog_url, year, i, name )
481                         else:
482                                 s = name
483                         ml.append(s)
484                 return ml
485
486 #
487 # Main
488 #
489
490
491 def render_html(articles, db, actyear = None):
492         template = Templates(templates_path, db, actyear)
493         print 'Content-type: text/html; charset=utf-8\n'
494         print template.get_main_header()
495         for a in articles:
496                 print template.get_article_header(a)
497                 print a.to_html()
498                 print template.get_article_footer(a)
499         print template.get_main_footer()
500
501 def render_artlist(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()
505         print '<h2>Articles</h2>'
506         for a in articles:
507                 print '<li><a href="%(url)s/uuid/%(uuid)s">%(title)s</a></li>' \
508                         % {     'url': blog_url,
509                                 'uuid': a.uuid,
510                                 'title': a.title,
511                                 'author': a.author,
512                         }
513         print template.get_main_footer()
514
515 def render_atom(articles):
516         if len(articles) > 0:
517                 updated = articles[0].updated.isoformat()
518         else:
519                 updated = datetime.datetime.now().isoformat()
520
521         print 'Content-type: application/atom+xml; charset=utf-8\n'
522         print """<?xml version="1.0" encoding="utf-8"?>
523
524 <feed xmlns="http://www.w3.org/2005/Atom">
525  <title>%(title)s</title>
526  <link rel="alternate" type="text/html" href="%(url)s"/>
527  <link rel="self" type="application/atom+xml" href="%(url)s/atom"/>
528  <id>%(url)s</id> <!-- TODO: find a better <id>, see RFC 4151 -->
529  <updated>%(updated)sZ</updated>
530
531         """ % {
532                 'title': title,
533                 'url': full_url,
534                 'updated': updated,
535         }
536
537         for a in articles:
538                 vars = a.to_vars()
539                 vars.update( {
540                         'url': full_url,
541                         'contents': a.to_html(),
542                 } )
543                 print """
544   <entry>
545     <title>%(arttitle)s</title>
546     <author><name>%(author)s</name></author>
547     <link href="%(url)s/post/%(uuid)s" />
548     <id>%(url)s/post/%(uuid)s</id>
549     <summary>%(arttitle)s</summary>
550     <published>%(ciso)sZ</published>
551     <updated>%(uiso)sZ</updated>
552     <content type="xhtml">
553       <div xmlns="http://www.w3.org/1999/xhtml"><p>
554 %(contents)s
555       </p></div>
556     </content>
557   </entry>
558                 """ % vars
559         print "</feed>"
560
561
562 def render_style():
563         print 'Content-type: text/css\r\n\r\n',
564         print default_css
565
566 def handle_cgi():
567         import cgitb; cgitb.enable()
568
569         form = cgi.FieldStorage()
570         year = int(form.getfirst("year", 0))
571         month = int(form.getfirst("month", 0))
572         day = int(form.getfirst("day", 0))
573         tags = set(form.getlist("tag"))
574         uuid = None
575         atom = False
576         style = False
577         post = False
578         artlist = False
579
580         if os.environ.has_key('PATH_INFO'):
581                 path_info = os.environ['PATH_INFO']
582                 style = path_info == '/style'
583                 atom = path_info == '/atom'
584                 tag = path_info.startswith('/tag/')
585                 post = path_info.startswith('/post/')
586                 artlist = path_info.startswith('/list')
587                 if not style and not atom and not post and not tag \
588                                 and not artlist:
589                         date = path_info.split('/')[1:]
590                         try:
591                                 if len(date) > 1 and date[0]:
592                                         year = int(date[0])
593                                 if len(date) > 2 and date[1]:
594                                         month = int(date[1])
595                                 if len(date) > 3 and date[2]:
596                                         day = int(date[2])
597                         except ValueError:
598                                 pass
599                 elif post:
600                         uuid = path_info.replace('/post/', '')
601                         uuid = uuid.replace('/', '')
602                 elif tag:
603                         t = path_info.replace('/tag/', '')
604                         t = t.replace('/', '')
605                         t = urllib.unquote_plus(t)
606                         tags = set((t,))
607
608         db = ArticleDB(os.path.join(data_path, 'db'))
609         if atom:
610                 articles = db.get_articles(tags = tags)
611                 articles.sort(reverse = True)
612                 render_atom(articles[:10])
613         elif style:
614                 render_style()
615         elif post:
616                 render_html( [db.get_article(uuid)], db, year )
617         elif artlist:
618                 articles = db.get_articles()
619                 articles.sort(cmp = Article.title_cmp)
620                 render_artlist(articles, db)
621         else:
622                 articles = db.get_articles(year, month, day, tags)
623                 articles.sort(reverse = True)
624                 if not year and not month and not day and not tags:
625                         articles = articles[:10]
626                 render_html(articles, db, year)
627
628
629 def usage():
630         print 'Usage: %s {add|rm|update} article_path' % sys.argv[0]
631
632 def handle_cmd():
633         if len(sys.argv) != 3:
634                 usage()
635                 return 1
636
637         cmd = sys.argv[1]
638         art_path = os.path.realpath(sys.argv[2])
639
640         if os.path.commonprefix([data_path, art_path]) != data_path:
641                 print "Error: article (%s) must be inside data_path (%s)" % \
642                                 (art_path, data_path)
643                 return 1
644         art_path = art_path[len(data_path)+1:]
645
646         db_filename = os.path.join(data_path, 'db')
647         if not os.path.isfile(db_filename):
648                 open(db_filename, 'w').write('')
649         db = ArticleDB(db_filename)
650
651         if cmd == 'add':
652                 article = Article(art_path, datetime.datetime.now(),
653                                         datetime.datetime.now())
654                 for a in db.articles:
655                         if a == article:
656                                 print 'Error: article already exists'
657                                 return 1
658                 db.articles.append(article)
659                 db.save()
660         elif cmd == 'rm':
661                 article = Article(art_path)
662                 for a in db.articles:
663                         if a == article:
664                                 break
665                 else:
666                         print "Error: no such article"
667                         return 1
668                 db.articles.remove(a)
669                 db.save()
670         elif cmd == 'update':
671                 article = Article(art_path)
672                 for a in db.articles:
673                         if a == article:
674                                 break
675                 else:
676                         print "Error: no such article"
677                         return 1
678                 a.updated = datetime.datetime.now()
679                 db.save()
680         else:
681                 usage()
682                 return 1
683
684         return 0
685
686
687 if os.environ.has_key('GATEWAY_INTERFACE'):
688         handle_cgi()
689 else:
690         sys.exit(handle_cmd())
691
692