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"
50 class Captcha (object):
51 def __init__(self, article):
52 self.article = article
53 words = article.title.split()
54 self.nword = hash(article.title) % len(words) % 5
55 self.answer = words[self.nword]
56 self.help = 'gotcha, damn spam bot!'
59 nword = self.nword + 1
68 return "enter the %s word of the article's title" % n
69 puzzle = property(fget = get_puzzle)
71 def validate(self, form_data):
72 if form_data.captcha.lower() == self.answer.lower():
78 # End of configuration
79 # DO *NOT* EDIT ANYTHING PAST HERE
93 from docutils.core import publish_parts
94 from docutils.utils import SystemMessage
96 # Before importing the config, add our cwd to the Python path
97 sys.path.append(os.getcwd())
99 # Load the config file, if there is one
106 # Pimp *_path config variables to support relative paths
107 data_path = os.path.realpath(data_path)
108 templates_path = os.path.realpath(templates_path)
112 default_main_header = """\
113 <?xml version="1.0" encoding="utf-8"?>
114 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
115 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
117 <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
119 <link rel="alternate" title="%(title)s" href="%(fullurl)s/atom"
120 type="application/atom+xml" />
121 <link href="%(css_url)s" rel="stylesheet" type="text/css" />
122 <title>%(title)s</title>
127 <h1><a href="%(url)s">%(title)s</a></h1>
129 <div class="content">
132 default_main_footer = """
135 %(showyear)s: %(monthlinks)s<br/>
136 years: %(yearlinks)s<br/>
137 subscribe: <a href="%(url)s/atom">atom</a><br/>
138 views: <a href="%(url)s/">blog</a> <a href="%(url)s/list">list</a><br/>
145 default_article_header = """
146 <div class="article">
147 <h2><a href="%(url)s/post/%(uuid)s">%(arttitle)s</a></h2>
148 <span class="artinfo">
149 by %(author)s on <span class="date">
151 <a class="date" href="%(url)s/%(cyear)d/">%(cyear)04d</a>-\
152 <a class="date" href="%(url)s/%(cyear)d/%(cmonth)d/">%(cmonth)02d</a>-\
153 <a class="date" href="%(url)s/%(cyear)d/%(cmonth)d/%(cday)d/">%(cday)02d</a>\
154 %(chour)02d:%(cminute)02d</span>
155 (updated on <span class="date">
156 <a class="date" href="%(url)s/%(uyear)d/">%(uyear)04d</a>-\
157 <a class="date" href="%(url)s/%(uyear)d/%(umonth)d/">%(umonth)02d</a>-\
158 <a class="date" href="%(url)s/%(uyear)d/%(umonth)d/%(uday)d/">%(uday)02d</a>\
159 %(uhour)02d:%(uminute)02d)</span><br/>
160 <span class="tags">tagged %(tags)s</span> -
161 <span class="comments">with %(comments)s
162 <a href="%(url)s/post/%(uuid)s#comments">comment(s)</a></span>
165 <div class="artbody">
168 default_article_footer = """
174 default_comment_header = """
175 <div class="comment">
176 <a name="comment-%(number)d" />
177 <h3><a href="#comment-%(number)d">Comment #%(number)d</a></h3>
178 <span class="cominfo">by %(linked_author)s
179 on %(year)04d-%(month)02d-%(day)02d %(hour)02d:%(minute)02d</span>
181 <div class="combody">
184 default_comment_footer = """
190 default_comment_form = """
191 <div class="comform">
193 <h3 class="comform"><a href="#comment">Your comment</a></h3>
194 <div class="comforminner">
195 <form method="%(form_method)s" action="%(form_action)s">
196 <div class="comformauthor">
197 <label for="comformauthor">Your name %(form_author_error)s</label>
198 <input type="text" class="comformauthor" id="comformauthor"
199 name="comformauthor" value="%(form_author)s" />
201 <div class="comformlink">
202 <label for="comformlink">Your link
203 <span class="comformoptional">(optional, will be published)</span>
204 %(form_link_error)s</label>
205 <input type="text" class="comformlink" id="comformlink"
206 name="comformlink" value="%(form_link)s" />
207 <div class="comformhelp">
208 like <span class="formurlexample">http://www.example.com/</span>
209 or <span class="formurlexample">mailto:you@example.com</span>
212 <div class="comformcaptcha">
213 <label for="comformcaptcha">Your humanity proof %(form_captcha_error)s</label>
214 <input type="text" class="comformcaptcha" id="comformcaptcha"
215 name="comformcaptcha" value="%(form_captcha)s" />
216 <div class="comformhelp">%(captcha_puzzle)s</div>
218 <div class="comformbody">
219 <label for="comformbody" class="comformbody">The comment
220 %(form_body_error)s</label>
221 <textarea class="comformbody" id="comformbody" name="comformbody" rows="15"
222 cols="80">%(form_body)s</textarea>
223 <div class="comformhelp">
225 <a href="http://docutils.sourceforge.net/docs/user/rst/quickref.html">\
226 RestructuredText</a> format, please
229 <div class="comformsend">
230 <button type="submit" class="comformsend" id="comformsend" name="comformsend">
239 default_comment_error = '<span class="comformerror">(%(error)s)</span>'
245 font-family: sans-serif;
256 border-bottom: 2px solid #99F;
265 border-bottom: 1px solid #99C;
272 border-bottom: 1px solid #99C;
276 text-decoration: none;
285 text-decoration: none;
289 span.artinfo a:hover {
290 text-decoration: none;
307 text-decoration: none;
311 span.cominfo a:hover {
312 text-decoration: none;
336 border-bottom: 1px solid #99C;
341 div.comform span.comformoptional {
357 span.formurlexample {
359 background-color: #EEF;
360 font-family: monospace;
362 padding-right: 0.2em;
365 textarea.comformbody {
366 font-family: monospace;
386 background-color: #99F;
394 border-top: 2px solid #99F;
399 text-decoration: none;
402 /* Articles are enclosed in <div class="section"> */
408 border-bottom: 1px dotted #99C;
415 # It only works if the function is pure (that is, its return value depends
416 # only on its arguments), and if all the arguments are hash()eable.
418 # do not decorate if the cache is disabled
419 if cache_path is None:
422 def decorate(*args, **kwargs):
423 hashes = '-'.join( str(hash(x)) for x in args +
424 tuple(kwargs.items()) )
425 fname = 'blitiri.%s.%s.cache' % (f.__name__, hashes)
426 cache_file = os.path.join(cache_path, fname)
428 s = open(cache_file).read()
430 s = f(*args, **kwargs)
431 open(cache_file, 'w').write(s)
438 def rst_to_html(rst, secure = True):
440 'input_encoding': encoding,
441 'output_encoding': 'utf8',
444 'file_insertion_enabled': secure,
445 'raw_enabled': secure,
447 parts = publish_parts(rst, settings_overrides = settings,
448 writer_name = "html")
449 return parts['body'].encode('utf8')
450 rst_to_html = cached(rst_to_html)
452 def validate_rst(rst, secure = True):
454 rst_to_html(rst, secure)
456 except SystemMessage, e:
457 desc = e.args[0].encode('utf-8') # the error string
458 desc = desc[9:] # remove "<string>:"
459 line = int(desc[:desc.find(':')] or 0) # get the line number
460 desc = desc[desc.find(')')+2:-1] # remove (LEVEL/N)
462 desc, context = desc.split('\n', 1)
465 if desc.endswith('.'):
467 return (line, desc, context)
469 def valid_link(link):
471 mail_re = r"^[^ \t\n\r@<>()]+@[a-z0-9][a-z0-9\.\-_]*\.[a-z]+$"
472 scheme_re = r'^[a-zA-Z]+:'
473 url_re = r'^(?:[a-z0-9\-]+|[a-z0-9][a-z0-9\-\.\_]*\.[a-z]+)' \
474 r'(?::[0-9]+)?(?:/.*)?$'
477 if re.match(scheme_re, link, re.I):
478 scheme, rest = link.split(':', 1)
479 if (not scheme or scheme == 'mailto') and re.match(mail_re, rest, re.I):
480 return 'mailto:' + link
481 if not scheme and re.match(url_re, rest, re.I):
482 return 'http://' + rest
488 if isinstance(obj, basestring):
489 return cgi.escape(obj, True)
493 # find out our URL, needed for syndication
495 n = os.environ['SERVER_NAME']
496 p = os.environ['SERVER_PORT']
497 s = os.environ['SCRIPT_NAME']
500 full_url = 'http://%s%s%s' % (n, p, s)
502 full_url = 'Not needed'
505 class Templates (object):
506 def __init__(self, tpath, db, showyear = None):
509 now = datetime.datetime.now()
521 'showyear': showyear,
522 'monthlinks': ' '.join(db.get_month_links(showyear)),
523 'yearlinks': ' '.join(db.get_year_links()),
526 def get_template(self, page_name, default_template, extra_vars = None):
527 if extra_vars is None:
530 vars = self.vars.copy()
531 vars.update(extra_vars)
533 p = '%s/%s.html' % (self.tpath, page_name)
534 if os.path.isfile(p):
535 return open(p).read() % vars
536 return default_template % vars
538 def get_main_header(self):
539 return self.get_template('header', default_main_header)
541 def get_main_footer(self):
542 return self.get_template('footer', default_main_footer)
544 def get_article_header(self, article):
545 return self.get_template(
546 'art_header', default_article_header, article.to_vars())
548 def get_article_footer(self, article):
549 return self.get_template(
550 'art_footer', default_article_footer, article.to_vars())
552 def get_comment_header(self, comment):
553 vars = comment.to_vars()
555 vars['linked_author'] = '<a href="%s">%s</a>' \
556 % (comment.link, comment.author)
558 vars['linked_author'] = comment.author
559 return self.get_template(
560 'com_header', default_comment_header, vars)
562 def get_comment_footer(self, comment):
563 return self.get_template(
564 'com_footer', default_comment_footer, comment.to_vars())
566 def get_comment_form(self, article, form_data, captcha_puzzle):
567 vars = article.to_vars()
568 vars.update(form_data.to_vars(self))
569 vars['captcha_puzzle'] = captcha_puzzle
570 return self.get_template(
571 'com_form', default_comment_form, vars)
573 def get_comment_error(self, error):
574 return self.get_template(
575 'com_error', default_comment_error, dict(error=error))
578 class CommentFormData (object):
579 def __init__(self, author = '', link = '', captcha = '', body = ''):
582 self.captcha = captcha
584 self.author_error = ''
586 self.captcha_error = ''
591 def to_vars(self, template):
592 render_error = template.get_comment_error
593 a_error = self.author_error and render_error(self.author_error)
594 l_error = self.link_error and render_error(self.link_error)
595 c_error = self.captcha_error \
596 and render_error(self.captcha_error)
597 b_error = self.body_error and render_error(self.body_error)
599 'form_author': sanitize(self.author),
600 'form_link': sanitize(self.link),
601 'form_captcha': sanitize(self.captcha),
602 'form_body': sanitize(self.body),
604 'form_author_error': a_error,
605 'form_link_error': l_error,
606 'form_captcha_error': c_error,
607 'form_body_error': b_error,
609 'form_action': self.action,
610 'form_method': self.method,
614 class Comment (object):
615 def __init__(self, article, number, created = None):
616 self.article = article
619 self.created = datetime.datetime.now()
621 self.created = created
626 self._author = author
628 self._raw_content = 'Removed comment'
631 def get_author(self):
635 author = property(fget = get_author)
641 link = property(fget = get_link)
643 def get_raw_content(self):
646 return self._raw_content
647 raw_content = property(fget = get_raw_content)
650 def set(self, author, raw_content, link = '', created = None):
652 self._author = author
653 self._raw_content = raw_content
655 self.created = created or datetime.datetime.now()
659 filename = os.path.join(comments_path, self.article.uuid,
662 raw = open(filename).readlines()
669 name, value = l.split(':', 1)
670 if name.lower() == 'author':
671 self._author = value.strip()
672 elif name.lower() == 'link':
673 self._link = value.strip()
678 self._raw_content = ''.join(raw[count + 1:])
682 filename = os.path.join(comments_path, self.article.uuid,
685 f = open(filename, 'w')
686 f.write('Author: %s\n' % self.author)
687 f.write('Link: %s\n' % self.link)
689 f.write(self.raw_content)
695 return rst_to_html(self.raw_content)
699 'number': self.number,
700 'author': sanitize(self.author),
701 'link': sanitize(self.link),
702 'date': self.created.isoformat(' '),
703 'created': self.created.isoformat(' '),
705 'year': self.created.year,
706 'month': self.created.month,
707 'day': self.created.day,
708 'hour': self.created.hour,
709 'minute': self.created.minute,
710 'second': self.created.second,
713 class CommentDB (object):
714 def __init__(self, article):
715 self.path = os.path.join(comments_path, article.uuid)
719 def load(self, article):
721 f = open(os.path.join(self.path, 'db'))
726 # Each line has the following comma separated format:
727 # number, created (epoch)
728 # Empty lines are meaningful and represent removed
729 # comments (so we can preserve the comment number)
733 d = datetime.datetime.fromtimestamp(float(l[1]))
735 # Removed/invalid comment
736 self.comments.append(None)
738 self.comments.append(Comment(article, n, d))
741 old_db = os.path.join(self.path, 'db')
742 new_db = os.path.join(self.path, 'db.tmp')
743 f = open(new_db, 'w')
744 for c in self.comments:
748 s += str(c.number) + ', '
749 s += str(time.mktime(c.created.timetuple()))
753 os.rename(new_db, old_db)
756 class Article (object):
757 def __init__(self, path, created = None, updated = None):
759 self.created = created
760 self.updated = updated
761 self.uuid = "%08x" % zlib.crc32(self.path)
766 self._title = 'Removed post'
767 self._author = author
769 self._raw_content = ''
777 title = property(fget = get_title)
779 def get_author(self):
783 author = property(fget = get_author)
789 tags = property(fget = get_tags)
791 def get_raw_content(self):
794 return self._raw_content
795 raw_content = property(fget = get_raw_content)
797 def get_comments(self):
800 return self._comments
801 comments = property(fget = get_comments)
804 def __cmp__(self, other):
805 if self.path == other.path:
809 if not other.created:
811 if self.created < other.created:
815 def title_cmp(self, other):
816 return cmp(self.title, other.title)
819 def add_comment(self, author, raw_content, link = ''):
820 c = Comment(self, len(self.comments))
821 c.set(author, raw_content, link)
822 self.comments.append(c)
827 # XXX this tweak is only needed for old DB format, where
828 # article's paths started with a slash
830 if path.startswith('/'):
832 filename = os.path.join(data_path, path)
834 raw = open(filename).readlines()
841 name, value = l.split(':', 1)
842 if name.lower() == 'title':
843 self._title = value.strip()
844 elif name.lower() == 'author':
845 self._author = value.strip()
846 elif name.lower() == 'tags':
847 ts = value.split(',')
848 ts = [t.strip() for t in ts]
854 self._raw_content = ''.join(raw[count + 1:])
856 self._comments = db.comments
860 return rst_to_html(self.raw_content)
864 'arttitle': sanitize(self.title),
865 'author': sanitize(self.author),
866 'date': self.created.isoformat(' '),
868 'tags': self.get_tags_links(),
869 'comments': len(self.comments),
871 'created': self.created.isoformat(' '),
872 'ciso': self.created.isoformat(),
873 'cyear': self.created.year,
874 'cmonth': self.created.month,
875 'cday': self.created.day,
876 'chour': self.created.hour,
877 'cminute': self.created.minute,
878 'csecond': self.created.second,
880 'updated': self.updated.isoformat(' '),
881 'uiso': self.updated.isoformat(),
882 'uyear': self.updated.year,
883 'umonth': self.updated.month,
884 'uday': self.updated.day,
885 'uhour': self.updated.hour,
886 'uminute': self.updated.minute,
887 'usecond': self.updated.second,
890 def get_tags_links(self):
892 tags = list(self.tags)
895 l.append('<a class="tag" href="%s/tag/%s">%s</a>' % \
896 (blog_url, urllib.quote(t), sanitize(t) ))
900 class ArticleDB (object):
901 def __init__(self, dbpath):
905 self.actyears = set()
906 self.actmonths = set()
909 def get_articles(self, year = 0, month = 0, day = 0, tags = None):
911 for a in self.articles:
912 if year and a.created.year != year: continue
913 if month and a.created.month != month: continue
914 if day and a.created.day != day: continue
915 if tags and not tags.issubset(a.tags): continue
921 def get_article(self, uuid):
922 return self.uuids[uuid]
926 f = open(self.dbpath)
931 # Each line has the following comma separated format:
932 # path (relative to data_path), \
941 datetime.datetime.fromtimestamp(float(l[1])),
942 datetime.datetime.fromtimestamp(float(l[2])))
943 self.uuids[a.uuid] = a
944 self.actyears.add(a.created.year)
945 self.actmonths.add((a.created.year, a.created.month))
946 self.articles.append(a)
949 f = open(self.dbpath + '.tmp', 'w')
950 for a in self.articles:
953 s += str(time.mktime(a.created.timetuple())) + ', '
954 s += str(time.mktime(a.updated.timetuple())) + '\n'
957 os.rename(self.dbpath + '.tmp', self.dbpath)
959 def get_year_links(self):
960 yl = list(self.actyears)
961 yl.sort(reverse = True)
962 return [ '<a href="%s/%d/">%d</a>' % (blog_url, y, y)
965 def get_month_links(self, year):
966 am = [ i[1] for i in self.actmonths if i[0] == year ]
968 for i in range(1, 13):
969 name = calendar.month_name[i][:3]
971 s = '<a href="%s/%d/%d/">%s</a>' % \
972 ( blog_url, year, i, name )
982 def render_comments(article, template, form_data):
983 print '<a name="comments" />'
984 for c in article.comments:
987 print template.get_comment_header(c)
989 print template.get_comment_footer(c)
991 form_data = CommentFormData()
992 form_data.action = blog_url + '/comment/' + article.uuid + '#comment'
993 captcha = Captcha(article)
994 print template.get_comment_form(article, form_data, captcha.puzzle)
996 def render_html(articles, db, actyear = None, show_comments = False,
997 redirect = None, form_data = None):
999 print 'Status: 303 See Other\r\n',
1000 print 'Location: %s\r\n' % redirect,
1001 print 'Content-type: text/html; charset=utf-8\r\n',
1003 template = Templates(templates_path, db, actyear)
1004 print template.get_main_header()
1006 print template.get_article_header(a)
1008 print template.get_article_footer(a)
1010 render_comments(a, template, form_data)
1011 print template.get_main_footer()
1013 def render_artlist(articles, db, actyear = None):
1014 template = Templates(templates_path, db, actyear)
1015 print 'Content-type: text/html; charset=utf-8\n'
1016 print template.get_main_header()
1017 print '<h2>Articles</h2>'
1019 print '<li><a href="%(url)s/uuid/%(uuid)s">%(title)s</a></li>' \
1020 % { 'url': blog_url,
1025 print template.get_main_footer()
1027 def render_atom(articles):
1028 if len(articles) > 0:
1029 updated = articles[0].updated.isoformat()
1031 updated = datetime.datetime.now().isoformat()
1033 print 'Content-type: application/atom+xml; charset=utf-8\n'
1034 print """<?xml version="1.0" encoding="utf-8"?>
1036 <feed xmlns="http://www.w3.org/2005/Atom">
1037 <title>%(title)s</title>
1038 <link rel="alternate" type="text/html" href="%(url)s"/>
1039 <link rel="self" type="application/atom+xml" href="%(url)s/atom"/>
1040 <id>%(url)s</id> <!-- TODO: find a better <id>, see RFC 4151 -->
1041 <updated>%(updated)sZ</updated>
1053 'contents': a.to_html(),
1057 <title>%(arttitle)s</title>
1058 <author><name>%(author)s</name></author>
1059 <link href="%(url)s/post/%(uuid)s" />
1060 <id>%(url)s/post/%(uuid)s</id>
1061 <summary>%(arttitle)s</summary>
1062 <published>%(ciso)sZ</published>
1063 <updated>%(uiso)sZ</updated>
1064 <content type="xhtml">
1065 <div xmlns="http://www.w3.org/1999/xhtml"><p>
1075 print 'Content-type: text/css\r\n\r\n',
1079 import cgitb; cgitb.enable()
1081 form = cgi.FieldStorage()
1082 year = int(form.getfirst("year", 0))
1083 month = int(form.getfirst("month", 0))
1084 day = int(form.getfirst("day", 0))
1085 tags = set(form.getlist("tag"))
1090 post_preview = False
1094 if os.environ.has_key('PATH_INFO'):
1095 path_info = os.environ['PATH_INFO']
1096 style = path_info == '/style'
1097 atom = path_info == '/atom'
1098 tag = path_info.startswith('/tag/')
1099 post = path_info.startswith('/post/')
1100 post_preview = path_info.startswith('/preview/post/')
1101 artlist = path_info.startswith('/list')
1102 comment = path_info.startswith('/comment/') and enable_comments
1103 if not style and not atom and not post and not post_preview \
1104 and not tag and not comment and not artlist:
1105 date = path_info.split('/')[1:]
1107 if len(date) > 1 and date[0]:
1109 if len(date) > 2 and date[1]:
1110 month = int(date[1])
1111 if len(date) > 3 and date[2]:
1116 uuid = path_info.replace('/post/', '')
1117 uuid = uuid.replace('/', '')
1119 art_path = path_info.replace('/preview/post/', '')
1120 art_path = urllib.unquote_plus(art_path)
1121 art_path = os.path.join(data_path, art_path)
1122 art_path = os.path.realpath(art_path)
1123 common = os.path.commonprefix([data_path, art_path])
1124 if common != data_path: # something nasty happened
1125 post_preview = False
1126 art_path = art_path[len(data_path)+1:]
1128 t = path_info.replace('/tag/', '')
1129 t = t.replace('/', '')
1130 t = urllib.unquote_plus(t)
1133 uuid = path_info.replace('/comment/', '')
1134 uuid = uuid.replace('#comment', '')
1135 uuid = uuid.replace('/', '')
1136 author = form.getfirst('comformauthor', '')
1137 link = form.getfirst('comformlink', '')
1138 captcha = form.getfirst('comformcaptcha', '')
1139 body = form.getfirst('comformbody', '')
1141 db = ArticleDB(os.path.join(data_path, 'db'))
1143 articles = db.get_articles(tags = tags)
1144 articles.sort(reverse = True)
1145 render_atom(articles[:10])
1149 render_html( [db.get_article(uuid)], db, year, enable_comments )
1151 article = Article(art_path, datetime.datetime.now(),
1152 datetime.datetime.now())
1153 render_html( [article], db, year, enable_comments )
1155 articles = db.get_articles()
1156 articles.sort(cmp = Article.title_cmp)
1157 render_artlist(articles, db)
1159 form_data = CommentFormData(author.strip().replace('\n', ' '),
1160 link.strip().replace('\n', ' '), captcha,
1161 body.replace('\r', ''))
1162 article = db.get_article(uuid)
1163 captcha = Captcha(article)
1166 if not form_data.author:
1167 form_data.author_error = 'please, enter your name'
1170 link = valid_link(form_data.link)
1172 form_data.link = link
1174 form_data.link_error = 'please, enter a ' \
1177 if not captcha.validate(form_data):
1178 form_data.captcha_error = captcha.help
1180 if not form_data.body:
1181 form_data.body_error = 'please, write a comment'
1184 error = validate_rst(form_data.body, secure=False)
1185 if error is not None:
1186 (line, desc, ctx) = error
1189 at = ' at line %d' % line
1190 form_data.body_error = 'error%s: %s' \
1194 c = article.add_comment(form_data.author,
1195 form_data.body, form_data.link)
1197 cdb = CommentDB(article)
1198 cdb.comments = article.comments
1200 redirect = blog_url + '/post/' + uuid + '#comment-' \
1202 render_html( [article], db, year, enable_comments, redirect,
1205 articles = db.get_articles(year, month, day, tags)
1206 articles.sort(reverse = True)
1207 if not year and not month and not day and not tags:
1208 articles = articles[:10]
1209 render_html(articles, db, year)
1213 print 'Usage: %s {add|rm|update} article_path' % sys.argv[0]
1216 if len(sys.argv) != 3:
1221 art_path = os.path.realpath(sys.argv[2])
1223 if os.path.commonprefix([data_path, art_path]) != data_path:
1224 print "Error: article (%s) must be inside data_path (%s)" % \
1225 (art_path, data_path)
1227 art_path = art_path[len(data_path)+1:]
1229 db_filename = os.path.join(data_path, 'db')
1230 if not os.path.isfile(db_filename):
1231 open(db_filename, 'w').write('')
1232 db = ArticleDB(db_filename)
1235 article = Article(art_path, datetime.datetime.now(),
1236 datetime.datetime.now())
1237 for a in db.articles:
1239 print 'Error: article already exists'
1241 db.articles.append(article)
1244 comment_dir = os.path.join(comments_path, article.uuid)
1246 os.mkdir(comment_dir, 0775)
1248 if e.errno != errno.EEXIST:
1249 print "Error: can't create comments " \
1250 "directory %s (%s)" \
1252 # otherwise is probably a removed and re-added
1255 article = Article(art_path)
1256 for a in db.articles:
1260 print "Error: no such article"
1263 r = raw_input('Remove comments [y/N]? ')
1264 db.articles.remove(a)
1266 if enable_comments and r.lower() == 'y':
1267 shutil.rmtree(os.path.join(comments_path, a.uuid))
1268 elif cmd == 'update':
1269 article = Article(art_path)
1270 for a in db.articles:
1274 print "Error: no such article"
1276 a.updated = datetime.datetime.now()
1285 if os.environ.has_key('GATEWAY_INTERFACE'):
1286 i = datetime.datetime.now()
1288 f = datetime.datetime.now()
1289 print '<!-- render time: %s -->' % (f-i)
1291 sys.exit(handle_cmd())