Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
branch: master
Fetching contributors…

Cannot retrieve contributors at this time

471 lines (432 sloc) 16.164 kb
# -*- coding: utf-8 -*-
import web
import urllib
import json
import sys
import datetime
from re import sub
from unicodedata import normalize
from siteconfig import *
urls = (
'/', 'index',
'/post', 'post',
'/admin', 'admin',
'/admin/editor', 'editor',
'/admin/drafts', 'drafts',
'/admin/delete', 'delete',
'/about', 'about',
'/(.+)', 'view',
'/(.*)', 'index',
)
app = web.application(urls, globals())
render = web.template.render('themes/default/', base='base', globals={'session': 'session'})
def session_hook():
web.ctx.session = session
web.template.Template.globals['session'] = session
app.add_processor(web.loadhook(session_hook))
db = web.database(dbn='sqlite', db='sqlitedb')
session = web.session.Session(app, web.session.DiskStore('sessions'),
initializer={
'active': False,
'admin': False,
'email': 'unknown',
'postid': 'new',
'blogtitle': blogtitle,
'blogtagline': blogtagline,
'name': "unknown",
})
web.config.session_parameters['cookie_domain'] = servername
web.config.session_parameters['cookie_path'] = "/"
web.config.session_parameters['secret_key'] = secretkey
web.config.session_parameters['httponly'] = True
web.config.session_parameters['secure'] = False
web.config.debug = False
def gettime():
now = datetime.datetime.now()
return now
def dateurl(url):
now = datetime.datetime.now()
#year = now.year
#month = now.month
url = str(url)
#year = str(year)
#month = str(month)
dt = now.strftime("%Y/%m/")
dt = str(dt)
#newurl = year + "-" + month + "-" + url
newurl = dt + url
return newurl
def format_post(post):
post = post.replace('\r\n\r\n', '</p><p>')
post = post.replace('\r\n', '<br>')
return post
def unformat_post(post):
post = post.replace('<br>', '\r\n')
post = post.replace('</p><p>', '\r\n\r\n')
#post = post.replace("&lt;", "<")
#post = post.replace("&gt;", ">")
#post = post.replace("&amp;", "&")
return post
def format_url(title):
url = normalize('NFKD', title).encode('ascii', 'ignore').replace(' ', '-').lower()
url= sub('[^a-zA-Z0-9_-]', '', url)
url = sub('-+', '-', url)
return url
def getlastid():
try:
postid = db.query("SELECT id FROM posts ORDER BY id DESC LIMIT 1")
for i in postid:
postid = i.id
return postid
except:
return "fail"
def addpost(post, publish):
if publish:
published = 1
else:
published = 0
#print "post title:", post.title
whattimeitis = gettime()
print "whattimeitis:", whattimeitis
print "unformatted db entry:", post
post.content = format_post(post.content)
post.url = format_url(post.title)
post.dateurl = post.url
print "url:", post.url
#print "formatted post:", post.content
try:
if (published == 1) and (urldate == True):
post.url = dateurl(post.url)
ins = db.insert('posts', title=post.title, date=whattimeitis, url=post.url, content=post.content, published=published, author=web.ctx.session.name)
print "inserted post with id:", ins
print "published?", published
return True
except:
return False
def updatepost(post, publish):
print "updatepost(): trying to update post"
print "id:", post.id
whattimeitis = gettime()
print "--- contents ---"
print "title:", post.title
print "content:", post.content
print "url", post.url
print "------"
post.content= format_post(post.content)
try:
db.update('posts', where="id = $post.id", title = post.title, vars=locals())
db.update('posts', where="id = $post.id", date = whattimeitis, vars=locals())
db.update('posts', where="id = $post.id", url = post.url, vars=locals())
db.update('posts', where="id = $post.id", content = post.content, vars=locals())
if publish == True:
db.update('posts', where="id = $post.id", published = 1, vars=locals())
print "Published post ID", post.id
else:
db.update('posts', where="id = $post.id", published = 0, vars=locals())
print "Saved post ID", post.id
return True
except:
return False
def getposts(status):
if status == "published":
try:
posts = db.select('posts', where="published=1", order='date DESC')
return posts
except:
return "none"
if status == "drafts":
try:
posts = db.select('posts', where="published=0", order='date DESC')
return posts
except:
return "none"
if status == "recent":
try:
posts = db.select('posts', where="published=1", order='date DESC', limit=5)
return posts
except:
return "none"
def getpost(postid):
print "getting post from db"
print "post id:", postid
try:
tmp = db.query("SELECT title FROM posts where id=$postid", vars=locals())
for i in tmp:
post.title = i.title
tmp = db.query("SELECT content FROM posts where id=$postid", vars=locals())
for i in tmp:
post.content = i.content
tmp = db.query("SELECT date FROM posts where id=$postid", vars=locals())
for i in tmp:
post.date = i.date
tmp = db.query("SELECT url FROM posts where id=$postid", vars=locals())
for i in tmp:
post.url = i.url
tmp = db.query("SELECT author FROM posts where id=$postid", vars=locals())
for i in tmp:
post.author = i.author
print "debug: getpost() extracted this from the db:", post
post.id = postid
return post
except:
return False
def getpostbyurl(url):
print "getting post from db"
print "post url:", url
try:
tmp = db.query("SELECT title FROM posts where url=$url", vars=locals())
for i in tmp:
post.title = i.title
print "got title", post.title
tmp = db.query("SELECT content FROM posts where url=$url", vars=locals())
for i in tmp:
post.content = i.content
tmp = db.query("SELECT date FROM posts where url=$url", vars=locals())
for i in tmp:
post.date = i.date
tmp = db.query("SELECT id FROM posts where url=$url", vars=locals())
for i in tmp:
post.id = i.id
tmp = db.query("SELECT author FROM posts where url=$url", vars=locals())
for i in tmp:
post.author = i.author
print "debug: getpost() extracted this from the db:", post
post.url = url
return post
except:
return False
def deletepost(postid):
print "deleting post.."
db.delete('posts', where="id = $postid", vars=locals())
return
def addcomment(postid, name, comment):
curtime = gettime()
#try:
print "trying to add comment:"
#print "name:", name
#print "comment:", comment
db.insert('comments', email=web.ctx.session.email, name=name, date=curtime, comment=comment, pid=postid)
return True
#except:
# return False
def getcomments(postid):
print "getting comments.."
try:
comments = db.select('comments', where="pid = $postid", order="date ASC", vars=locals())
return comments
except:
return "none"
def reset_session():
print "resetting session"
web.ctx.session.active = False
web.ctx.session.admin = False
web.ctx.session.email = "unknown"
web.ctx.session.postid = "new"
web.ctx.session.blogtitle = blogtitle
web.ctx.session.blogtagline = blogtagline
web.ctx.session.name = "unknown"
return
class FalseStorage(web.storage):
def __nonzero__(self): return False
def browserid():
c = web.cookies()
if c.get('browserid_assertion'):
out = urllib.urlencode(dict(audience=web.ctx.host, assertion=c.browserid_assertion))
o = json.loads(urllib.urlopen('https://browserid.org/verify', out).read())
if o['status'] == 'failure':
return FalseStorage(o)
else:
return web.storage(o)
else:
return web.storage()
def authenticate():
sys.stdout.write("getting info from browserid...")
bid = browserid()
if not bid:
print "not found"
return
else:
bid = bid['email']
print "got it!"
print "logged in as", bid
web.ctx.session.email = bid
web.ctx.session.active = True
print "debugging getadmin()"
if web.ctx.session.email in admins:
print "current email found in admins"
web.ctx.session.name = admins[web.ctx.session.email]
print "post author set to", web.ctx.session.name
web.ctx.session.admin = True
print "admin set to", web.ctx.session.admin
print "all rise, his majesty just popped in!"
else:
print "email not found in admins"
return
def hasloggedout():
c = web.cookies()
c = c.get('browserid_assertion')
if not c:
return True
else:
return False
def check_auth():
print "authenticating..."
print "ip:", web.ctx.ip
print "email:", web.ctx.session.email
if web.ctx.session.active == True:
if hasloggedout() == True:
reset_session()
print "user has logged out"
return
else:
print "user:", web.ctx.session.email
if web.ctx.session.active == False:
authenticate()
return
class index:
def GET(self):
print "entering frontpage"
check_auth()
posts = getposts('published')
recent = getposts('recent')
return render.index(web.ctx.session, posts, recent)
class drafts:
def GET(self):
print "getting drafts"
check_auth()
posts = getposts('drafts')
return render.drafts(web.ctx.session, posts)
class editor:
def GET(self):
print "entering post editor"
check_auth()
if web.ctx.session.admin:
params = web.input(id=None, save=None, publish=None)
if params.type == "new":
return render.editor(web.ctx.session, "", "", "", "", "")
if params.type == "edit":
postid = web.input().id
post = getpost(postid)
post.content = unformat_post(post.content)
return render.editor(web.ctx.session, post.title, post.content, post.url, post.date, "")
if params.type == "draft":
postid = web.input().id
post = getpost(postid)
post.content = unformat_post(post.content)
return render.editor(web.ctx.session, post.title, post.content, post.url, post.date, "")
else:
return render.notification(web.ctx.session, "wtf are you doing, man?")
def POST(self):
if web.ctx.session.admin:
form = web.input(id=None, save=None, publish=None)
print "FORM CONTENT:", form
if (form.title == "") or (form.content== ""):
return render.editor(web.ctx.session, form.title, form.content, "", "", "You need to fill all fields")
else:
if form.save == "Save":
print "user pressed SAVE"
if form.type == "new":
addpost(form, False)
if form.type == "edit":
updatepost(form, False)
if form.type == "draft":
updatepost(form, False)
post = getpostbyurl(form.url)
redirstring = 'Post saved! <a href="/admin/editor?type=edit&id=' + str(post.id) + '">Continue editing</a>'
return render.success(web.ctx.session, redirstring)
if form.publish == "Publish":
print "user pressed PUBLISH"
if form.type == "new":
addpost(form, True)
if form.type == "edit":
updatepost(form, True)
if form.type == "draft":
updatepost(form, True)
redirstring = 'Post published! <a href="/' + form.url + '">View post</a>'
return render.success(web.ctx.session, redirstring)
return
else:
return render.notification(web.ctx.session, "wtf are you trying to do, man?")
class post:
def GET(self):
check_auth()
params = web.input(type=None, id=None, name=None, comment=None, btn=None)
print "we got a request for post id:", params
print "trying to get just the id:", params.id
postid = params.id
post = getpost(postid)
comments = getcomments(postid)
#print "debug, comments:"
#for i in comments:
# print i
print "we got from getpost():", post
if post:
return render.post(web.ctx.session, post, comments, "", "")
else:
return render.notification(web.ctx.session, "Post not found!", "")
def POST(self):
check_auth()
if web.ctx.session.admin:
form = web.input(type=None, id=None, name=None, comment=None, btn=None)
post = getpost(form.id)
comments = getcomments(form.id)
if (form.name == "") or (form.comment == ""):
print "form not accepted"
return render.post(web.ctx.session, post, comments, form.name, form.comment)
else:
print "form accepted"
if addcomment(form.id, form.name, form.comment):
return render.notification(web.ctx.session, "Comment added!")
else:
return render.notification(web.ctx.session, "Something failed")
class view:
def GET(self, url):
check_auth()
print "debug, self, url:", url
print "getting post by url:", web.ctx.fullpath
post = getpostbyurl(url)
comments = getcomments(post.id)
print "debug: post id:", post.id
if post:
return render.view(web.ctx.session, post, comments, "", "")
else:
return render.notification(web.ctx.session, "Post not found!", "")
def POST(self, url):
check_auth()
form = web.input(type=None, id=None, name=None, comment=None, btn=None)
post = getpostbyurl(url)
comments = getcomments(post.id)
if (form.name == "") or (form.comment == ""):
print "form not accepted"
return render.post(web.ctx.session, post, comments, form.name, form.comment)
else:
print "form accepted"
if addcomment(post.id, form.name, form.comment):
return render.notification(web.ctx.session, "Comment added!")
else:
return render.notification(web.ctx.session, "Something failed")
class delete:
def GET(self):
print "got a delete request"
postid = web.input(id=None)
if web.ctx.session.admin == True:
return render.confirm(web.ctx.session, postid, "Are you sure you want to delete the post?")
else:
return render.notification(web.ctx.session, "Wtf are you trying to do man?")
def POST(self):
if web.ctx.session.admin:
feedback = web.input(id=None, btn=None)
if feedback.btn == "Yes":
print "deleting post"
deletepost(feedback.id)
return render.notification(web.ctx.session, "Post deleted.")
if feedback.btn == "Cancel":
print "canceled"
return render.notification(web.ctx.session, "You had me scared there for a while.")
class about:
def GET(self):
check_auth()
return render.about(web.ctx.session)
if __name__ == '__main__':
app.run()
application = app.wsgifunc()
Jump to Line
Something went wrong with that request. Please try again.