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 # Are comments allowed? (if False, comments_path option is not used)
18 enable_comments = False
20 # Directory where comments are stored (must be writeable by the web server)
21 comments_path = "/tmp/blog/comments"
23 # Path where templates are stored. Use an empty string for the built-in
24 # default templates. If they're not found, the built-in ones will be used.
25 templates_path = "/tmp/blog/templates"
27 # Path where the cache is stored (must be writeable by the web server);
28 # set to None to disable. When enabled, you must take care of cleaning it up
29 # every once in a while.
30 #cache_path = "/tmp/blog/cache"
33 # URL to the blog, including the name. Can be a full URL or just the path.
34 blog_url = "/blog/blitiri.cgi"
36 # Style sheet (CSS) URL. Can be relative or absolute. To use the built-in
37 # default, set it to blog_url + "/style".
38 css_url = blog_url + "/style"
41 title = "I don't like blogs"
44 author = "Hartmut Kegan"
49 # Captcha method to use. At the moment only "title" is supported, but if you
50 # are keen with Python you can provide your own captcha implementation, see
52 captcha_method = "title"
54 # How many articles to show in the index
59 # End of configuration
60 # DO *NOT* EDIT ANYTHING PAST HERE
74 from docutils.core import publish_parts
75 from docutils.utils import SystemMessage
77 # Before importing the config, add our cwd to the Python path
78 sys.path.append(os.getcwd())
80 # Load the config file, if there is one
87 # Pimp *_path config variables to support relative paths
88 data_path = os.path.realpath(data_path)
89 templates_path = os.path.realpath(templates_path)
95 # They must follow the interface described below.
98 # Captcha(article) -> constructor, takes an article[1] as argument
100 # puzzle -> a string with the puzzle the user must solve to prove he is
101 # not a bot (can be raw HTML)
102 # help -> a string with extra instructions, shown only when the user
103 # failed to solve the puzzle
105 # validate(form_data) -> based on the form data[2], returns True if
106 # the user has solved the puzzle uccessfully
109 # Note you must ensure that the puzzle attribute and validate() method can
110 # "communicate" because they are executed in different requests. You can pass a
111 # cookie or just calculate the answer based on the article's data, for example.
113 # [1] article is an object with all the article's information:
115 # created -> datetime
116 # updated -> datetime
117 # uuid -> string (unique ID)
120 # tags -> list of strings
121 # raw_contents -> string in rst format
122 # comments -> list of Comment objects (not too relevant here)
123 # [2] form_data is an object with the form fields (all strings):
124 # author, author_error
126 # catpcha, captcha_error
130 class TitleCaptcha (object):
131 "Captcha that uses the article's title for the puzzle"
132 def __init__(self, article):
133 self.article = article
134 words = article.title.split()
135 self.nword = hash(article.title) % len(words) % 5
136 self.answer = words[self.nword]
137 self.help = 'gotcha, damn spam bot!'
141 nword = self.nword + 1
149 n = str(nword) + 'th'
150 return "enter the %s word of the article's title" % n
152 def validate(self, form_data):
153 if form_data.captcha.lower() == self.answer.lower():
157 known_captcha_methods = {
158 'title': TitleCaptcha,
161 # If the configured captcha method was a known string, replace it by the
162 # matching class; otherwise assume it's already a class and leave it
163 # alone. This way the user can either use one of our methods, or provide one
165 if captcha_method in known_captcha_methods:
166 captcha_method = known_captcha_methods[captcha_method]
171 default_main_header = """\
172 <?xml version="1.0" encoding="utf-8"?>
173 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
174 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
176 <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
178 <link rel="alternate" title="%(title)s" href="%(fullurl)s/atom"
179 type="application/atom+xml" />
180 <link href="%(css_url)s" rel="stylesheet" type="text/css" />
181 <title>%(title)s</title>
186 <h1><a href="%(url)s">%(title)s</a></h1>
188 <div class="content">
191 default_main_footer = """
194 %(showyear)s: %(monthlinks)s<br/>
195 years: %(yearlinks)s<br/>
196 subscribe: <a href="%(url)s/atom">atom</a><br/>
197 views: <a href="%(url)s/">blog</a> <a href="%(url)s/list">list</a><br/>
198 tags: %(taglinks)s<br/>
205 default_article_header = """
206 <div class="article">
207 <h2><a href="%(url)s/post/%(uuid)s">%(arttitle)s</a></h2>
208 <span class="artinfo">
209 by %(author)s on <span class="date">
211 <a class="date" href="%(url)s/%(cyear)d/">%(cyear)04d</a>-\
212 <a class="date" href="%(url)s/%(cyear)d/%(cmonth)d/">%(cmonth)02d</a>-\
213 <a class="date" href="%(url)s/%(cyear)d/%(cmonth)d/%(cday)d/">%(cday)02d</a>\
214 %(chour)02d:%(cminute)02d</span>
215 (updated on <span class="date">
216 <a class="date" href="%(url)s/%(uyear)d/">%(uyear)04d</a>-\
217 <a class="date" href="%(url)s/%(uyear)d/%(umonth)d/">%(umonth)02d</a>-\
218 <a class="date" href="%(url)s/%(uyear)d/%(umonth)d/%(uday)d/">%(uday)02d</a>\
219 %(uhour)02d:%(uminute)02d)</span><br/>
220 <span class="tags">tagged %(tags)s</span> -
221 <span class="comments">with %(comments)s
222 <a href="%(url)s/post/%(uuid)s#comments">comment(s)</a></span>
225 <div class="artbody">
228 default_article_footer = """
234 default_comment_header = """
235 <div class="comment">
236 <a name="comment-%(number)d" />
237 <h3><a href="#comment-%(number)d">Comment #%(number)d</a></h3>
238 <span class="cominfo">by %(linked_author)s
239 on %(year)04d-%(month)02d-%(day)02d %(hour)02d:%(minute)02d</span>
241 <div class="combody">
244 default_comment_footer = """
250 default_comment_form = """
251 <div class="comform">
253 <h3 class="comform"><a href="#comment">Your comment</a></h3>
254 <div class="comforminner">
255 <form method="%(form_method)s" action="%(form_action)s">
256 <div class="comformauthor">
257 <label for="comformauthor">Your name %(form_author_error)s</label>
258 <input type="text" class="comformauthor" id="comformauthor"
259 name="comformauthor" value="%(form_author)s" />
261 <div class="comformlink">
262 <label for="comformlink">Your link
263 <span class="comformoptional">(optional, will be published)</span>
264 %(form_link_error)s</label>
265 <input type="text" class="comformlink" id="comformlink"
266 name="comformlink" value="%(form_link)s" />
267 <div class="comformhelp">
268 like <span class="formurlexample">http://www.example.com/</span>
269 or <span class="formurlexample">mailto:you@example.com</span>
272 <div class="comformcaptcha">
273 <label for="comformcaptcha">Your humanity proof %(form_captcha_error)s</label>
274 <input type="text" class="comformcaptcha" id="comformcaptcha"
275 name="comformcaptcha" value="%(form_captcha)s" />
276 <div class="comformhelp">%(captcha_puzzle)s</div>
278 <div class="comformbody">
279 <label for="comformbody" class="comformbody">The comment
280 %(form_body_error)s</label>
281 <textarea class="comformbody" id="comformbody" name="comformbody" rows="15"
282 cols="80">%(form_body)s</textarea>
283 <div class="comformhelp">
285 <a href="http://docutils.sourceforge.net/docs/user/rst/quickref.html">\
286 RestructuredText</a> format, please
289 <div class="comformsend">
290 <button type="submit" class="comformsend" id="comformsend" name="comformsend">
299 default_comment_error = '<span class="comformerror">(%(error)s)</span>'
305 font-family: sans-serif;
316 border-bottom: 2px solid #99F;
325 border-bottom: 1px solid #99C;
332 border-bottom: 1px solid #99C;
336 text-decoration: none;
345 text-decoration: none;
349 span.artinfo a:hover {
350 text-decoration: none;
367 text-decoration: none;
371 span.cominfo a:hover {
372 text-decoration: none;
396 border-bottom: 1px solid #99C;
401 div.comform span.comformoptional {
417 span.formurlexample {
419 background-color: #EEF;
420 font-family: monospace;
422 padding-right: 0.2em;
425 textarea.comformbody {
426 font-family: monospace;
446 background-color: #99F;
454 border-top: 2px solid #99F;
459 text-decoration: none;
462 /* Articles are enclosed in <div class="section"> */
468 border-bottom: 1px dotted #99C;
475 # It only works if the function is pure (that is, its return value depends
476 # only on its arguments), and if all the arguments are hash()eable.
478 # do not decorate if the cache is disabled
479 if cache_path is None:
482 def decorate(*args, **kwargs):
483 hashes = '-'.join( str(hash(x)) for x in args +
484 tuple(kwargs.items()) )
485 fname = 'blitiri.%s.%s.cache' % (f.__name__, hashes)
486 cache_file = os.path.join(cache_path, fname)
488 s = open(cache_file).read()
490 s = f(*args, **kwargs)
491 open(cache_file, 'w').write(s)
499 def rst_to_html(rst, secure = True):
501 'input_encoding': encoding,
502 'output_encoding': 'utf8',
505 'file_insertion_enabled': secure,
506 'raw_enabled': secure,
508 parts = publish_parts(rst, settings_overrides = settings,
509 writer_name = "html")
510 return parts['body'].encode('utf8')
512 def validate_rst(rst, secure = True):
514 rst_to_html(rst, secure)
516 except SystemMessage, e:
517 desc = e.args[0].encode('utf-8') # the error string
518 desc = desc[9:] # remove "<string>:"
519 line = int(desc[:desc.find(':')] or 0) # get the line number
520 desc = desc[desc.find(')')+2:-1] # remove (LEVEL/N)
522 desc, context = desc.split('\n', 1)
525 if desc.endswith('.'):
527 return (line, desc, context)
529 def valid_link(link):
531 scheme_re = r'^[a-zA-Z]+:'
532 mail_re = r"^[^ \t\n\r@<>()]+@[a-z0-9][a-z0-9\.\-_]*\.[a-z]+$"
533 url_re = r'^(?:[a-z0-9\-]+|[a-z0-9][a-z0-9\-\.\_]*\.[a-z]+)' \
534 r'(?::[0-9]+)?(?:/.*)?$'
536 if re.match(scheme_re, link, re.I):
537 scheme, rest = link.split(':', 1)
538 # if we have an scheme and a rest, assume the link is valid
539 # and return it as-is; otherwise (having just the scheme) is
545 # at this point, we don't have a scheme; we will try to recognize some
546 # common addresses (mail and http at the moment) and complete them to
547 # form a valid link, if we fail we will just claim it's invalid
548 if re.match(mail_re, link, re.I):
549 return 'mailto:' + link
550 elif re.match(url_re, link, re.I):
551 return 'http://' + link
556 return cgi.escape(obj, quote = True)
559 # find out our URL, needed for syndication
561 n = os.environ['SERVER_NAME']
562 p = os.environ['SERVER_PORT']
563 s = os.environ['SCRIPT_NAME']
566 full_url = 'http://%s%s%s' % (n, p, s)
568 full_url = 'Not needed'
571 class Templates (object):
572 def __init__(self, tpath, db, showyear = None):
575 now = datetime.datetime.now()
587 'showyear': showyear,
588 'monthlinks': ' '.join(db.get_month_links(showyear)),
589 'yearlinks': ' '.join(db.get_year_links()),
590 'taglinks': ' '.join(db.get_tag_links()),
593 def get_template(self, page_name, default_template, extra_vars = None):
594 if extra_vars is None:
597 vars = self.vars.copy()
598 vars.update(extra_vars)
600 p = '%s/%s.html' % (self.tpath, page_name)
601 if os.path.isfile(p):
602 return open(p).read() % vars
603 return default_template % vars
605 def get_main_header(self):
606 return self.get_template('header', default_main_header)
608 def get_main_footer(self):
609 return self.get_template('footer', default_main_footer)
611 def get_article_header(self, article):
612 return self.get_template(
613 'art_header', default_article_header, article.to_vars())
615 def get_article_footer(self, article):
616 return self.get_template(
617 'art_footer', default_article_footer, article.to_vars())
619 def get_comment_header(self, comment):
620 vars = comment.to_vars()
622 vars['linked_author'] = '<a href="%s">%s</a>' \
623 % (vars['link'], vars['author'])
625 vars['linked_author'] = vars['author']
626 return self.get_template(
627 'com_header', default_comment_header, vars)
629 def get_comment_footer(self, comment):
630 return self.get_template(
631 'com_footer', default_comment_footer, comment.to_vars())
633 def get_comment_form(self, article, form_data, captcha_puzzle):
634 vars = article.to_vars()
635 vars.update(form_data.to_vars(self))
636 vars['captcha_puzzle'] = captcha_puzzle
637 return self.get_template(
638 'com_form', default_comment_form, vars)
640 def get_comment_error(self, error):
641 return self.get_template(
642 'com_error', default_comment_error, dict(error=error))
645 class CommentFormData (object):
646 def __init__(self, author = '', link = '', captcha = '', body = ''):
649 self.captcha = captcha
651 self.author_error = ''
653 self.captcha_error = ''
658 def to_vars(self, template):
659 render_error = template.get_comment_error
660 a_error = self.author_error and render_error(self.author_error)
661 l_error = self.link_error and render_error(self.link_error)
662 c_error = self.captcha_error \
663 and render_error(self.captcha_error)
664 b_error = self.body_error and render_error(self.body_error)
666 'form_author': sanitize(self.author),
667 'form_link': sanitize(self.link),
668 'form_captcha': sanitize(self.captcha),
669 'form_body': sanitize(self.body),
671 'form_author_error': a_error,
672 'form_link_error': l_error,
673 'form_captcha_error': c_error,
674 'form_body_error': b_error,
676 'form_action': self.action,
677 'form_method': self.method,
681 class Comment (object):
682 def __init__(self, article, number, created = None):
683 self.article = article
686 self.created = datetime.datetime.now()
688 self.created = created
693 self._author = author
695 self._raw_content = 'Removed comment'
710 def raw_content(self):
713 return self._raw_content
715 def set(self, author, raw_content, link = '', created = None):
717 self._author = author
718 self._raw_content = raw_content
720 self.created = created or datetime.datetime.now()
724 filename = os.path.join(comments_path, self.article.uuid,
727 raw = open(filename).readlines()
734 name, value = l.split(':', 1)
735 if name.lower() == 'author':
736 self._author = value.strip()
737 elif name.lower() == 'link':
738 self._link = value.strip()
743 self._raw_content = ''.join(raw[count + 1:])
747 filename = os.path.join(comments_path, self.article.uuid,
750 f = open(filename, 'w')
751 f.write('Author: %s\n' % self.author)
752 f.write('Link: %s\n' % self.link)
754 f.write(self.raw_content)
760 return rst_to_html(self.raw_content)
764 'number': self.number,
765 'author': sanitize(self.author),
766 'link': sanitize(self.link),
767 'date': self.created.isoformat(' '),
768 'created': self.created.isoformat(' '),
770 'year': self.created.year,
771 'month': self.created.month,
772 'day': self.created.day,
773 'hour': self.created.hour,
774 'minute': self.created.minute,
775 'second': self.created.second,
778 class CommentDB (object):
779 def __init__(self, article):
780 self.path = os.path.join(comments_path, article.uuid)
781 # if comments were enabled after the article was added, we
782 # will need to create the directory
783 if not os.path.exists(self.path):
784 os.mkdir(self.path, 0777)
789 def load(self, article):
791 f = open(os.path.join(self.path, 'db'))
796 # Each line has the following comma separated format:
797 # number, created (epoch)
798 # Empty lines are meaningful and represent removed
799 # comments (so we can preserve the comment number)
803 d = datetime.datetime.fromtimestamp(float(l[1]))
805 # Removed/invalid comment
806 self.comments.append(None)
808 self.comments.append(Comment(article, n, d))
811 old_db = os.path.join(self.path, 'db')
812 new_db = os.path.join(self.path, 'db.tmp')
813 f = open(new_db, 'w')
814 for c in self.comments:
818 s += str(c.number) + ', '
819 s += str(time.mktime(c.created.timetuple()))
823 os.rename(new_db, old_db)
826 class Article (object):
827 def __init__(self, path, created = None, updated = None):
829 self.created = created
830 self.updated = updated
831 self.uuid = "%08x" % zlib.crc32(self.path)
836 self._title = 'Removed post'
837 self._author = author
839 self._raw_content = ''
861 def raw_content(self):
864 return self._raw_content
870 return self._comments
873 def __eq__(self, other):
874 if self.path == other.path:
879 def add_comment(self, author, raw_content, link = ''):
880 c = Comment(self, len(self.comments))
881 c.set(author, raw_content, link)
882 self.comments.append(c)
887 # XXX this tweak is only needed for old DB format, where
888 # article's paths started with a slash
890 if path.startswith('/'):
892 filename = os.path.join(data_path, path)
894 raw = open(filename).readlines()
901 name, value = l.split(':', 1)
902 if name.lower() == 'title':
903 self._title = value.strip()
904 elif name.lower() == 'author':
905 self._author = value.strip()
906 elif name.lower() == 'tags':
907 ts = value.split(',')
908 ts = [t.strip() for t in ts]
914 self._raw_content = ''.join(raw[count + 1:])
916 self._comments = db.comments
920 dirname = os.path.dirname
921 post_url = '/'.join([dirname(full_url), 'posts',
923 post_dir = '/'.join([data_path, dirname(self.path)])
924 rst = self.raw_content.replace('##POST_URL##', post_url)
925 rst = rst.replace('##POST_DIR##', post_dir)
926 # TODO: make it better!
928 rst = re.sub(r'.. youtube:: (.*)', r'''.. raw:: html
930 <div style="text-align: center; margin-bottom: 8pt">
931 <object width="500" height="375">
933 value="http://www.youtube.com/v/\1&hl=en&fs=1"
935 <param name="allowFullScreen" value="true"></param>
936 <param name="allowscriptaccess" value="always"></param>
937 <embed src="http://www.youtube.com/v/\1&hl=en&fs=1"
938 type="application/x-shockwave-flash" allowscriptaccess="always"
939 allowfullscreen="true" width="500" height="375"></embed>
942 rst = re.sub(r'.. vimeo:: (\w*)', r'''.. raw:: html
944 <div style="text-align: center; margin-bottom: 8pt">
945 <object width="500" height="375">
946 <param name="allowfullscreen" value="true" />
947 <param name="allowscriptaccess" value="always" />
948 <param name="movie" value="http://vimeo.com/moogaloop.swf?clip_id=\1&server=vimeo.com&show_title=1&show_byline=1&show_portrait=0&color=00ADEF&fullscreen=1" />
949 <embed src="http://vimeo.com/moogaloop.swf?clip_id=\1&server=vimeo.com&show_title=1&show_byline=1&show_portrait=0&color=00ADEF&fullscreen=1"
950 type="application/x-shockwave-flash"
951 allowfullscreen="true"
952 allowscriptaccess="always"
958 rst = re.sub(r'.. grooveshark:: (\w*)', r'''.. raw:: html
960 <div class="grooveshark">
961 <object width="220" height="300">
963 value="http://listen.grooveshark.com/widget.swf" />
964 <param name="wmode" value="window" />
965 <param name="allowScriptAccess" value="always" />
966 <param name="flashvars"
967 value="hostname=cowbell.grooveshark.com&playlistID=\1&style=metal&p=0" />
968 <embed src="http://listen.grooveshark.com/widget.swf"
969 type="application/x-shockwave-flash"
970 width="220" height="300"
971 flashvars="hostname=cowbell.grooveshark.com&playlistID=\1&style=metal&p=0"
972 allowScriptAccess="always" wmode="window" />
975 return rst_to_html(rst)
979 'arttitle': sanitize(self.title),
980 'author': sanitize(self.author),
981 'date': self.created.isoformat(' '),
983 'tags': self.get_tags_links(),
984 'comments': len(self.comments),
986 'created': self.created.isoformat(' '),
987 'ciso': self.created.isoformat(),
988 'cyear': self.created.year,
989 'cmonth': self.created.month,
990 'cday': self.created.day,
991 'chour': self.created.hour,
992 'cminute': self.created.minute,
993 'csecond': self.created.second,
995 'updated': self.updated.isoformat(' '),
996 'uiso': self.updated.isoformat(),
997 'uyear': self.updated.year,
998 'umonth': self.updated.month,
999 'uday': self.updated.day,
1000 'uhour': self.updated.hour,
1001 'uminute': self.updated.minute,
1002 'usecond': self.updated.second,
1005 def get_tags_links(self):
1007 tags = list(self.tags)
1010 l.append('<a class="tag" href="%s/tag/%s">%s</a>' % \
1011 (blog_url, urllib.quote(t), sanitize(t) ))
1015 class ArticleDB (object):
1016 def __init__(self, dbpath):
1017 self.dbpath = dbpath
1020 self.actyears = set()
1021 self.actmonths = set()
1022 self.acttags = set()
1025 def get_articles(self, year = 0, month = 0, day = 0, tags = None):
1027 for a in self.articles:
1028 if year and a.created.year != year: continue
1029 if month and a.created.month != month: continue
1030 if day and a.created.day != day: continue
1031 if tags and not tags.issubset(a.tags): continue
1037 def get_article(self, uuid):
1038 return self.uuids[uuid]
1042 f = open(self.dbpath)
1047 # Each line has the following comma separated format:
1048 # path (relative to data_path), \
1049 # created (epoch), \
1057 datetime.datetime.fromtimestamp(float(l[1])),
1058 datetime.datetime.fromtimestamp(float(l[2])))
1059 self.uuids[a.uuid] = a
1060 self.acttags.update(a.tags)
1061 self.actyears.add(a.created.year)
1062 self.actmonths.add((a.created.year, a.created.month))
1063 self.articles.append(a)
1066 f = open(self.dbpath + '.tmp', 'w')
1067 for a in self.articles:
1070 s += str(time.mktime(a.created.timetuple())) + ', '
1071 s += str(time.mktime(a.updated.timetuple())) + '\n'
1074 os.rename(self.dbpath + '.tmp', self.dbpath)
1076 def get_year_links(self):
1077 yl = list(self.actyears)
1078 yl.sort(reverse = True)
1079 return [ '<a href="%s/%d/">%d</a>' % (blog_url, y, y)
1082 def get_month_links(self, year):
1083 am = [ i[1] for i in self.actmonths if i[0] == year ]
1085 for i in range(1, 13):
1086 name = calendar.month_name[i][:3]
1088 s = '<a href="%s/%d/%d/">%s</a>' % \
1089 ( blog_url, year, i, name )
1095 def get_tag_links(self):
1096 tl = list(self.acttags)
1098 return [ '<a href="%s/tag/%s">%s</a>' % (blog_url,
1099 sanitize(t), sanitize(t)) for t in tl ]
1105 def render_comments(article, template, form_data):
1106 print '<a name="comments" />'
1107 for c in article.comments:
1110 print template.get_comment_header(c)
1112 print template.get_comment_footer(c)
1114 form_data = CommentFormData()
1115 form_data.action = blog_url + '/comment/' + article.uuid + '#comment'
1116 captcha = captcha_method(article)
1117 print template.get_comment_form(article, form_data, captcha.puzzle)
1119 def render_html(articles, db, actyear = None, show_comments = False,
1120 redirect = None, form_data = None):
1122 print 'Status: 303 See Other\r\n',
1123 print 'Location: %s\r\n' % redirect,
1124 print 'Content-type: text/html; charset=utf-8\r\n',
1126 template = Templates(templates_path, db, actyear)
1127 print template.get_main_header()
1129 print template.get_article_header(a)
1131 print template.get_article_footer(a)
1133 render_comments(a, template, form_data)
1134 print template.get_main_footer()
1136 def render_artlist(articles, db, actyear = None):
1137 template = Templates(templates_path, db, actyear)
1138 print 'Content-type: text/html; charset=utf-8\n'
1139 print template.get_main_header()
1140 print '<h2>Articles</h2>'
1142 print '<li><a href="%(url)s/post/%(uuid)s">%(title)s</a></li>' \
1143 % { 'url': blog_url,
1148 print template.get_main_footer()
1150 def render_atom(articles):
1151 if len(articles) > 0:
1152 updated = articles[0].updated.isoformat()
1154 updated = datetime.datetime.now().isoformat()
1156 print 'Content-type: application/atom+xml; charset=utf-8\n'
1157 print """<?xml version="1.0" encoding="utf-8"?>
1159 <feed xmlns="http://www.w3.org/2005/Atom">
1160 <title>%(title)s</title>
1161 <link rel="alternate" type="text/html" href="%(url)s"/>
1162 <link rel="self" type="application/atom+xml" href="%(url)s/atom"/>
1163 <id>%(url)s</id> <!-- TODO: find a better <id>, see RFC 4151 -->
1164 <updated>%(updated)sZ</updated>
1176 'contents': a.to_html(),
1180 <title>%(arttitle)s</title>
1181 <author><name>%(author)s</name></author>
1182 <link href="%(url)s/post/%(uuid)s" />
1183 <id>%(url)s/post/%(uuid)s</id>
1184 <summary>%(arttitle)s</summary>
1185 <published>%(ciso)sZ</published>
1186 <updated>%(uiso)sZ</updated>
1187 <content type="xhtml">
1188 <div xmlns="http://www.w3.org/1999/xhtml">
1198 print 'Content-type: text/css\r\n\r\n',
1201 # Get a dictionary with sort() arguments (key and reverse) by parsing the sort
1202 # specification format:
1204 # Where "-" is used to specify reverse order, while "+" is regular, ascending,
1205 # order (reverse = False). The key value is an Article's attribute name (title,
1206 # author, created, updated and uuid are accepted), and will be used as key for
1207 # sorting. If a value is omitted, that value is taken from the default, which
1208 # should be provided using the same format specification, with the difference
1209 # that all values must be provided for the default.
1210 def get_sort_args(sort_str, default):
1217 # accept ' ' as an alias of '+' since '+' is translated
1219 if s[0] in ('+', ' ', '-'):
1221 d['reverse'] = (s[0] == '-')
1224 if key in ('title', 'author', 'created', 'updated', 'uuid'):
1225 d['key'] = lambda a: getattr(a, key)
1227 args = parse(default)
1228 assert args['key'] is not None and args['reverse'] is not None
1229 args.update(parse(sort_str))
1233 import cgitb; cgitb.enable()
1235 form = cgi.FieldStorage()
1236 year = int(form.getfirst("year", 0))
1237 month = int(form.getfirst("month", 0))
1238 day = int(form.getfirst("day", 0))
1239 tags = set(form.getlist("tag"))
1240 sort_str = form.getfirst("sort", None)
1245 post_preview = False
1249 if os.environ.has_key('PATH_INFO'):
1250 path_info = os.environ['PATH_INFO']
1251 style = path_info == '/style'
1252 atom = path_info == '/atom'
1253 tag = path_info.startswith('/tag/')
1254 post = path_info.startswith('/post/')
1255 post_preview = path_info.startswith('/preview/post/')
1256 artlist = path_info.startswith('/list')
1257 comment = path_info.startswith('/comment/') and enable_comments
1258 if not style and not atom and not post and not post_preview \
1259 and not tag and not comment and not artlist:
1260 date = path_info.split('/')[1:]
1262 if len(date) > 1 and date[0]:
1264 if len(date) > 2 and date[1]:
1265 month = int(date[1])
1266 if len(date) > 3 and date[2]:
1271 uuid = path_info.replace('/post/', '')
1272 uuid = uuid.replace('/', '')
1274 art_path = path_info.replace('/preview/post/', '')
1275 art_path = urllib.unquote_plus(art_path)
1276 art_path = os.path.join(data_path, art_path)
1277 art_path = os.path.realpath(art_path)
1278 common = os.path.commonprefix([data_path, art_path])
1279 if common != data_path: # something nasty happened
1280 post_preview = False
1281 art_path = art_path[len(data_path)+1:]
1283 t = path_info.replace('/tag/', '')
1284 t = t.replace('/', '')
1285 t = urllib.unquote_plus(t)
1288 uuid = path_info.replace('/comment/', '')
1289 uuid = uuid.replace('#comment', '')
1290 uuid = uuid.replace('/', '')
1291 author = form.getfirst('comformauthor', '')
1292 link = form.getfirst('comformlink', '')
1293 captcha = form.getfirst('comformcaptcha', '')
1294 body = form.getfirst('comformbody', '')
1296 db = ArticleDB(os.path.join(data_path, 'db'))
1298 articles = db.get_articles(tags = tags)
1299 articles.sort(**get_sort_args(sort_str, '-created'))
1300 render_atom(articles[:index_articles])
1304 render_html( [db.get_article(uuid)], db, year, enable_comments )
1306 article = Article(art_path, datetime.datetime.now(),
1307 datetime.datetime.now())
1308 render_html( [article], db, year, enable_comments )
1310 articles = db.get_articles()
1311 articles.sort(**get_sort_args(sort_str, '+title'))
1312 render_artlist(articles, db)
1313 elif comment and enable_comments:
1314 form_data = CommentFormData(author.strip().replace('\n', ' '),
1315 link.strip().replace('\n', ' '), captcha,
1316 body.replace('\r', ''))
1317 article = db.get_article(uuid)
1318 captcha = captcha_method(article)
1321 if not form_data.author:
1322 form_data.author_error = 'please, enter your name'
1325 link = valid_link(form_data.link)
1327 form_data.link = link
1329 form_data.link_error = 'please, enter a ' \
1332 if not captcha.validate(form_data):
1333 form_data.captcha_error = captcha.help
1335 if not form_data.body:
1336 form_data.body_error = 'please, write a comment'
1339 error = validate_rst(form_data.body, secure=False)
1340 if error is not None:
1341 (line, desc, ctx) = error
1344 at = ' at line %d' % line
1345 form_data.body_error = 'error%s: %s' \
1349 c = article.add_comment(form_data.author,
1350 form_data.body, form_data.link)
1352 cdb = CommentDB(article)
1353 cdb.comments = article.comments
1355 redirect = blog_url + '/post/' + uuid + '#comment-' \
1357 render_html( [article], db, year, enable_comments, redirect,
1360 articles = db.get_articles(year, month, day, tags)
1361 articles.sort(**get_sort_args(sort_str, '-created'))
1362 if not year and not month and not day and not tags:
1363 articles = articles[:index_articles]
1364 render_html(articles, db, year)
1368 print 'Usage: %s {add|rm|update} article_path' % sys.argv[0]
1371 if len(sys.argv) != 3:
1376 art_path = os.path.realpath(sys.argv[2])
1378 if os.path.commonprefix([data_path, art_path]) != data_path:
1379 print "Error: article (%s) must be inside data_path (%s)" % \
1380 (art_path, data_path)
1382 art_path = art_path[len(data_path)+1:]
1384 db_filename = os.path.join(data_path, 'db')
1385 if not os.path.isfile(db_filename):
1386 open(db_filename, 'w').write('')
1387 db = ArticleDB(db_filename)
1390 article = Article(art_path, datetime.datetime.now(),
1391 datetime.datetime.now())
1392 for a in db.articles:
1394 print 'Error: article already exists'
1396 db.articles.append(article)
1399 comment_dir = os.path.join(comments_path, article.uuid)
1401 os.mkdir(comment_dir, 0775)
1403 if e.errno != errno.EEXIST:
1404 print "Error: can't create comments " \
1405 "directory %s (%s)" \
1407 # otherwise is probably a removed and re-added
1410 article = Article(art_path)
1411 for a in db.articles:
1415 print "Error: no such article"
1418 r = raw_input('Remove comments [y/N]? ')
1419 db.articles.remove(a)
1421 if enable_comments and r.lower() == 'y':
1422 shutil.rmtree(os.path.join(comments_path, a.uuid))
1423 elif cmd == 'update':
1424 article = Article(art_path)
1425 for a in db.articles:
1429 print "Error: no such article"
1431 a.updated = datetime.datetime.now()
1440 if os.environ.has_key('GATEWAY_INTERFACE'):
1441 i = datetime.datetime.now()
1443 f = datetime.datetime.now()
1444 print '<!-- render time: %s -->' % (f-i)
1446 sys.exit(handle_cmd())