/[theodore]/bunnyblog/blog/blog.py


UCC Code Repository

Contents of /bunnyblog/blog/blog.py

Parent Directory Parent Directory | Revision Log Revision Log


Revision 1 - (hide annotations) (download) (as text)
Tue Jan 29 14:32:01 2008 UTC (12 years, 2 months ago) by svn-admin
File MIME type: text/x-python
File size: 12329 byte(s)
Re-import of repository after repository database corruption.

1 svn-admin 1 import re
2     import time
3     from os import sys
4    
5     """
6     Import modules from modules directory
7     """
8     sys.path.insert(0,'./modules')
9     import yaml
10     from logintools import isloggedin
11     del sys.path[0]
12    
13     class Blog:
14     def __init__(self, loadblog = False):
15     """
16     Setting loadblog to true will load all of the articles in the blog.
17     Setting it to false will not saving time when accessing the files isn't neccessary.
18     """
19     self.config = load('data/config.yaml')
20     self.htmlcode = "200"
21     if loadblog:
22     self.articles = load()
23     if not self.articles:
24     self.articles = []
25     self.stylename = "style/"+self.config['template'] + "/"
26     def addarticle(self, title, content, index):
27     newarticle = Article(title, content, index)
28     self.articles.append(newarticle)
29     return self.saveblog()
30     def delarticle(self, index):
31     article = self.findbyindex(index)
32     if article:
33     self.articles.remove(article)
34     return article.title and self.saveblog()
35     else:
36     return False
37     def findbyindex(self, index):
38     for article in self.articles:
39     if str(article.index) == str(index):
40     return article
41     return False
42     def findbytitle(self, title):
43     for article in self.articles:
44     if article.title == title:
45     return article
46     return False
47     def saveblog(self):
48     self.generaterss()
49     return save(yaml.dump(self.articles))
50     def display(self,title,header,main,sidebar, meta=""):
51     page = gethtmlheader(self.htmlcode) + gettemplate(self.stylename+"index")
52     page = page.replace("<@meta-data@>" , meta)
53     page = page.replace("<@style_dir@>" , "templates/"+self.stylename)
54     page = page.replace("<@page_title@>" , title)
55     page = page.replace("<@header@>" , header)
56     page = page.replace("<@main@>" , main)
57     page = page.replace("<@menu@>" , gettemplate("menu/mainmenu","data"))
58     page = page.replace("<@menu_noul@>" , gettemplate("menu/mainmenu","data").strip()[4:-5])
59     page = page.replace("<@sidebar@>" , sidebar)
60     page = page.replace("<@sidebar_noul@>" , sidebar.strip()[4:-5])
61     page = fixinternallinks(page)
62     for (key,value) in self.config.iteritems():
63     page = page.replace("<@"+key+"@>", value)
64     print page
65     def saveconfig(self):
66     save(yaml.dump(self.config),'data/config.yaml')
67     def generaterss(self):
68     rss = """Content-Type: text/xml
69    
70     <?xml version="1.0" ?>
71     <rss version="2.0">
72    
73     <channel>
74     """
75     config = self.config
76     url = config['site_url']
77     rss += "<title>%s RSS Feed</title>" % config['site_name']
78     rss += "<description>%s</description>" % config['site_blurb']
79     rss += "<link>%s</link>" % url
80    
81     if len(self.articles) > 10:
82     articles = self.articles[-10:]
83     else:
84     articles = self.articles
85     for article in articles[::-1]:
86     if len(article.content) > 60:
87     content = article.content[:40] + " ... " + article.content[-10:]
88     else:
89     content = article.content
90     rss += """
91     <item>
92     <title>%s</title>
93     <description>%s</description>
94     <link>%sindex.cgi?article=%d</link>
95     <pubDate>%s</pubDate>
96     <lastBuildDate>%s</lastBuildDate>
97     </item>
98     """ % (article.title, content, url, article.index, article.date, time.asctime())
99    
100     rss += """
101     </channel>
102    
103     </rss>
104     """
105    
106     save(rss,"blog.rss")
107    
108    
109     class Article(yaml.YAMLObject):
110     def __init__(self, title, content, index, comments = []):
111     self.comments = comments
112     self.content = cleanse(content)
113     self.date = time.asctime()
114     self.title = cleanse(title)
115     self.index = index
116    
117     def __rep__(self):
118     return self.htmlize()
119    
120     def htmlize(self):
121     deletearticle = ""
122     if isadmin():
123     deletearticle = " - <a href='<@site_url@>admin.cgi?action=deletearticle&amp;index=%s'>Delete this article</a>" % (self.index)
124     numcomments = len(self.comments)
125     html = "<div class = 'article'>\n"
126     html += "<a href='index.cgi?article=%s' class='articletitle'>%s</a> (%s Comment%s) %s" % (self.index,self.title, numcomments,(numcomments - 1 != 0 and 's' or ''), deletearticle)
127     html += "<p class='date'>Posted on: %s</p>" % (self.date)
128     html += tagify(self.content)
129     html += "</div>\n"
130     return html
131    
132     def showcomments(self):
133     deletecomment = ""
134     html = "<div class='commentarea'><h3>Comments:</h3>"
135     if isadmin():
136     deletecomment = " - <a href='<@site_url@>admin.cgi?deletecomment=%s&amp;articleindex=%s'>Delete this comment</a>" % ('<@commentindex@>',self.index)
137     if self.comments:
138     i = 0
139     for [author,comment, time] in self.comments:
140     comment = "<span class='commentauthor'>%s</span> had this to say: %s<br /><blockquote class='comment'>%s</blockquote><p class='date'>%s</p>" % (author,deletecomment, tagify(comment),time)
141     comment = comment.replace('<@commentindex@>',str(i))
142     html += comment
143     i += 1
144     else:
145     html += "No Comments"
146     html += "</div>"
147     html += gettemplate('blog/addcomment').replace('<@article_index@>',str(self.index))
148     return html
149    
150     def addcomment(self,author,comment):
151     if author != "" and comment != "":
152     self.comments.append([cleanse(author), cleanse(comment),time.asctime()] )
153    
154    
155     def cleanse(str):
156     str = str.replace('&', '&amp;')
157     str = str.replace('<', '&lt;')
158     str = str.replace('>', '&gt;')
159     return str
160    
161     def tagify(str):
162     str = str.replace('\n', '<br />')
163     """
164     Find all codeblocks, and replace them with a marker,
165     """
166     tags = re.compile(r"\[code\](.*?)\[/code\]")
167     codeblocks = tags.findall(str)
168     str = tags.sub("<@CODEBLOCK@>", str)
169    
170     """ Simple url tags"""
171    
172     tags = re.compile(r"\[url\](http://)*(.*?)\[/url\]")
173     tags.findall(str)
174     str = tags.sub('<a href="http://\g<2>">\g<2></a>', str)
175    
176     """Complex url tags"""
177     tags = re.compile(r"\[url=['|\"](http://)*(.*?)['|\"]\](.*?)\[/url\]")
178     tags.findall(str)
179     str = tags.sub('<a href="http://\g<2>">\g<3></a>', str)
180    
181     """Internal Links"""
182     tags = re.compile(r"\[blog=(page|title|index):(.*?)\](.*?)\[/blog\]")
183     tags.findall(str)
184     str = tags.sub('<a href = "<@site_url@>index.cgi?\g<1>=\g<2>"><span>\g<3></a>', str)
185    
186     """Rss feed"""
187     num_rss_tags = min(str.count('[rss]'),str.count('[/rss]'))
188     str = str.replace("[rss]", '<a href = "<@site_url@>blog.rss">', num_rss_tags)
189     str = str.replace("[/rss]", '</a>', num_rss_tags)
190     str = str.replace("[rss]", '\n<!-- Unmatched [rss] tag -->\n')
191     str = str.replace("[/rss]", '\n<!-- Unmatched [/rss] tag -->\n')
192     str = str.replace("[rss/]", '<a href = "<@site_url@>blog.rss">Link to <@site_name@> RSS Feed</a>')
193    
194     """ Image Tags """
195     str = str.replace('[img]','<img src="')
196     str = str.replace('[/img]','" alt="" />')
197    
198     """ Internal Image Tags """
199     # This links to an image in viewer mode
200     tags = re.compile(r"\[blog=image:(.*?)\](.*?)\[/blog\]")
201     str = tags.sub('<a href = "<@site_url@>gallery.cgi?\image=\g<1>"><span>\g<2></a>', str)
202    
203     # These insert images from the gallery into normal blog posts.
204     str = str.replace('[bimg]', '<img src="<@site_url@>data/images/')
205     str = str.replace('[bimg=preview]', '<img style="width: 100px;height: 75px;" src="<@site_url@>data/images/')
206     str = str.replace('[/bimg]', '" alt = "" >')
207    
208    
209     tags = re.compile(r"\[(/*[biu])\]")
210     tags.findall(str)
211     str = tags.sub("<\g<1>>", str)
212    
213     for code in codeblocks:
214     code = '<div style="border:1px black solid"><pre color="green;">Code:<hr/>%s<br /></pre></div><br />' % code
215     str = str.replace("<@CODEBLOCK@>", code, 1)
216    
217    
218     return "<p>%s</p>" % str
219    
220     def save(db, filetoload="data/blog.yaml"):
221     try:
222     file = open(filetoload, 'r+')
223     file.write(db)
224     file.truncate()
225     file.close()
226     return True
227     except:
228     return False
229    
230     def load(filetoload="data/blog.yaml"):
231     blog = ""
232     file = open(filetoload)
233     for line in file:
234     blog += line
235     return yaml.load(blog)
236    
237     def gettemplate(template="index", directory = "templates", tags=False):
238     page = "" # Create a string for our page
239     try:
240     file = open(directory + '/'+ template + '.pyhtml', 'r')
241     except:
242     return "Template Not Found - " + directory + "/" + template
243     for line in file:
244     page += line
245     file.close()
246     if tags:
247     page = cleanse(page)
248     page = tagify(page)
249     return page
250    
251     def gethtmlheader(code):
252     if code == "404":
253     status = "404 Not Found"
254     else:
255     status = "200 OK"
256     header = "Status: %s\nContent-Type: text/html\r\n\n" % status # HTML is following
257    
258     return header
259    
260     def error(errormessage):
261     return "<h1 style='color:red;'>" + errormessage + "</h1>"
262    
263     def isadmin():
264     if isloggedin('data/users/'):
265     return True
266     else:
267     return False
268    
269     def savenewpage(filename, content, pagetitle, filetype):
270     content = "--!pageconfig!--"+yaml.dump({'pagetitle':pagetitle,'filetype':filetype,'lastedit':time.asctime()}) + "\n--!pagecontent!--\n" + content
271     try:
272     file = open("data/cms/%s.pyhtml" % filename, 'w')
273     file.write(content)
274     file.close()
275     return True
276     except:
277     return False
278    
279     def getcmspage(template="index"):
280     cmspage = loadcmspage(template)
281     try:
282     (page, pagetitle, filetype, lastedited) = cmspage
283     except:
284     return (error(cmspage), 'Page not found')
285     if filetype == "bbcode":
286     page = cleanse(page)
287     page = tagify(page)
288     if isadmin():
289     editthispage = "Admin options for this page | <a href='<@site_url@>admin.cgi?delete=delete&amp;filename=%s'>Delete this page</a> | <a href='<@site_url@>admin.cgi?page=editcontent&filename=%s'>Edit this page</a>" % (template, template)
290     else:
291     editthispage = ""
292     page += "<br />%s<tt style='float:right;text-size:80%%;'>Last edited on %s</tt>" % (editthispage,lastedited)
293     return (page, pagetitle)
294    
295    
296     def loadcmspage(template="index"):
297     page = "" # Create a string for our page
298     filetype = "html"
299     lastedited = "Unknown"
300     try:
301     file = open('data/cms/'+ template + '.pyhtml', 'r')
302     except:
303     return "404 Page Not Found - " + template
304     for line in file:
305     page += line
306     file.close()
307     if page.startswith('--!pageconfig!--'):
308     (pageconfig,page) = page.split('--!pagecontent!--')
309     pageconfig = pageconfig.replace("--!pageconfig!--","")
310     pageconfig = yaml.load(pageconfig)
311    
312     filetype = pageconfig['filetype']
313     lastedited = pageconfig['lastedit']
314     pagetitle = pageconfig['pagetitle']
315     else:
316     pagetitle = template.replace('_',' ').title()
317     return (page, pagetitle, filetype, lastedited)
318    
319     def fixinternallinks(page):
320     tags = re.compile(r"<@(page|title|index):(.*?)@>")
321     links = tags.findall(page)
322     page = tags.sub("<@site_url@>index.cgi?\g<1>=\g<2>", page)
323     return page
324    
325     def savemenu(menu, file = "mainmenu.pyhtml"):
326     htmlmenu = "<ul>\n<li>"
327     blogtags = re.compile(r"\[blog=(page|title|index):(.*?)\](.*?)\[/blog\]")
328     urltags = re.compile(r"\[url=['|\"](http://)*(.*?)['|\"]\](.*?)\[/url\]")
329     imgtags = re.compile(r"\[blog=image:(.*?)\](.*?)\[/blog\]")
330     blogtags.findall(menu)
331     urltags.findall(menu)
332     imgtags.findall(menu)
333     menu = menu.replace("\n", "</li>\n<li>")
334     menu = blogtags.sub('<a href = "<@site_url@>index.cgi?\g<1>=\g<2>"><span>\g<3></span></a>', menu)
335     menu = urltags.sub('<a href="http://\g<2>"><span>\g<3></span></a>', menu)
336     menu = imgtags.sub('<a href = "<@site_url@>gallery.cgi?image=\g<1>"><span>\g<2></span></a>', menu)
337    
338     htmlmenu += menu+"</li>\n</ul>"
339     return save(htmlmenu, 'templates/blog/' + file)

Managed by UCC Webmasters ViewVC Help
Powered by ViewVC 1.1.26