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