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