Source

alecwh / index.py

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
"""
blog web interface
acts as the gateway to the web log (uses WSGI, web.py, among others)
$author: alecwh
$date: 08/08/2009
"""

__author__ = "Alec Henriksen <alecwh@gmail.com>"
__website__ = "http://alecwh.com/"

import sys
import os
# get current dir for session storage
__directory__ = os.path.dirname(__file__)
# add this directory to module search
sys.path.append(__directory__)

# get the configuration file
from config import config

import web
web.config.debug = False

import time
import objects as db
import markdown
import hashlib
import re
import data_handler

from templater import templater

import log

# for the cgi.escape() function
import cgi

urls = (
	'/',												'articleList',
	'/page/(\d+)/?',									'articleList',
	'/(\d{4})/(\d{2})/(\d{2})',							'articleList',
	'/\d{4}/\d{1,2}/\d{1,2}/([-a-zA-Z0-9_]*)(\..*)*/?', 'articleDisplay',
	'/\+tags/(.*)/?',									'Tags',
	'/(\w+)(\.\w*/?)*/?',								'Wiki',
	'/static/(.+)',										'StaticFile',
	'/\+ajax/(\w+)/(\d*)/?',							'Ajax',
	'/\+login/?',										'Login',
	'/\+logout/?',										'Logout',
	'/\+admin/(.+)/(.+)/?',								'Admin',
	'/\+feed/(\w+)/?',									'Feed',
	)
	

class redirect:
	def GET(self):
		web.seeother('/' + path)

class articleList:
	def GET(self, page=0, year=None, month=None, day=None):
		page_type="article_list"
		# web.py and mod_wsgi make a persistent python session
		# therefore, reload db after every use
		# to avoid ConnectionClosed errors
		reload(db)
		web.webapi.header("Content-Type","text/html; charset=utf-8") 
		page_html = ''
		
		# This is a *new* article
		form_vars = {
			"form_type":"new",
			"title":"Title",
			"url_id":"",
			"action":config.general.base_url,
			"tags":"Tags, like, this",
			"content":"",
			"year":"",
			"month":"",
			"day":"",
			"session":session,
			}
			
		article_form_html = templater(config.general.base_path+"templates/article_form.html", form_vars)
		page_html += article_form_html
		
		# moving on to article list
		# html holder
		article_html = ''
		
		# grab article list
		articles = db.store.find(db.Article, db.Article.active == 1)
		
		for article in articles.order_by(db.Desc(db.Article.id_)):
			# format/get date
			date = data_handler.parse_date(article.timestamp)
			# do all necessary replacements, execs, formatting, etc
			article = data_handler.handle_article_content(article)
			
			article_meta = {
				"title":article.title,
				"url_id":article.url_id,
				"id_":article.id_,
				"date":article.timestamp,
				"content":article.content,
				"base_url":config.general.base_url,
				#"comment_count":db.get_num_comments(article.id_),
				"comment_count":db.get_num_comments(article.id_),
				#"comment_count":0,
				"tag_list": article.tags,
				"year":date[0],
				"month":date[1],
				"day":date[2],
				"session":session,
				}
				
			article_html += str(templater(config.general.base_path+"templates/article.html", article_meta))
			
			# make sure storm doesn't save our mods
			# from data_handler (because these mods are only for output)
			db.store.rollback()
			
		page_html += article_html
		
		site_vars = {
			"page_html":page_html,
			"base_url":config.general.base_url,
			"page_type":page_type,
			"session":session,
			"page_name":'Latest articles'
			}
			
		return templater(config.general.base_path+"templates/site.html", site_vars)
		
	def POST(self):
		# web.py and mod_wsgi make a persistance python session
		# therefore, reload db after every use
		# to avoid ConnectionClosed errors
		reload(db)
		i = web.input()
		if i.action == "article":
			# set to draft if form field exists
			# and prepare data dict
			i.draft = 1 if "1" else 0
			
			data = {
				"url_id":i.url_id,
				"title":i.title,
				"tags":i.tags,
				"author":config.general.admin,
				"timestamp":unicode(time.time()),
				"content":i.content,
				"ip":u"localhost",
				"active": i.draft
				}
				
			the_article = db.Article(data)

			# add to store, and flush (save)
			db.store.add(the_article)
			db.store.flush()
			
			# New tag management
			# new tags will be added to the `tags` table
			# old tags are not involved here
			tag_list = i.tags.split(",")
			new_tags = []
			new_tags_sql = ""
			tag_assoc_sql = ""
			
			
			for tag in tag_list:
				tag = tag.strip()
				# form sql for adding to the assoc table
				tag_assoc_sql = "('%s', '%s')," % (tag, the_article.id_)
				
				if not db.tag_exists(tag):
					new_tags.append(tag)
					
			# now add the new tags that pointblank hasn't seen yet	
			for tag in new_tags:
				# add to entire sql statement
				new_tags_sql += "('%s', '%s')," % (tag, unicode(time.time()))
				
			if new_tags:
				db.store.execute("INSERT INTO `tags` (tag, timestamp) VALUES %s" % new_tags_sql[:-1])
			
			# finally associate the tags and the article
			db.store.execute("INSERT INTO `article_tag_assoc` (tag, article) VALUES %s" % tag_assoc_sql[:-1])	
			
			# redirect to index
			raise web.seeother(config.general.base_url)
			
class articleDisplay:
	def GET(self, url_id, format):
		page_type="article_display"
		# web.py and mod_wsgi make a persistent python session
		# therefore, reload db after every use
		# to avoid ConnectionClosed errors
		reload(db)
		
		
		# grab article with url_id
		articles = db.store.find(db.Article, db.Article.url_id == url_id, db.Article.active == 1)[:1]
		
		# hold article html
		page_html = ''
		
		for article in articles:
			date = data_handler.parse_date(article.timestamp)
			# do all necessary replacements, execs, formatting, etc
			if type(format) != type(None) and format == ".markdown":
				# prepare content
				web.webapi.header("Content-Type","text/plain; charset=utf-8")
				return templater(config.general.base_path+"templates/article.markdown", article)
			
			article = data_handler.handle_article_content(article)

			article_meta = {
				"title":article.title,
				"url_id":article.url_id,
				"id_":article.id_,
				"date":article.timestamp,
				"content":article.content,
				"base_url":config.general.base_url,
				"comment_count":db.get_num_comments(article.id_),
				"tag_list": article.tags,
				"year":date[0],
				"month":date[1],
				"day":date[2],
				"session":session,
				}
				
			page_html += templater(config.general.base_path+"templates/article.html", article_meta)
			
			# make sure storm doesn't save our mods (data_handler only works on output of db)
			db.store.rollback()
			
			# only if we're dealing in html
			if 'html' in format:
			
				# now grab all comments for this article (by id_)
				comments = db.store.find(db.Comment, db.Comment.article_id == article.id_).order_by(db.Comment.id_)
				comments_html = ""
			
				for comment in comments:
					emailhash = hashlib.md5(comment.email.strip()).hexdigest()
					comment = data_handler.handle_comment_content(comment)
					comment_meta = {
						"text":comment.text,
						"author":comment.author,
						"id_":comment.id_,
						"thread_id":comment.thread_id,
						"website":comment.website,
						"email":comment.email,
						"emailhash":emailhash,
						"timestamp":comment.timestamp,
						"session":session
						}
					comments_html += templater(config.general.base_path+"templates/comment.html", comment_meta)
				
					# make sure storm doesn't save our mods (data_handler only works on output of db)
					db.store.rollback()
			
				comment_form_meta = {
					"article_id":article.id_,
					"url_id":article.url_id,
					"base_url":config.general.base_url,
					"year":"2000",
					"month":"00",
					"day":"00",
					"session":session
					}
				comment_form = templater(config.general.base_path+"templates/comment_form.html", comment_form_meta)
				
				page_html = page_html + comments_html + comment_form
				
		
		# prepare content
		web.webapi.header("Content-Type","text/html; charset=utf-8")
		
		# 404, if no article
		if page_html.strip() == "":
			page_html = data_handler.Markdown2HTML(open(config.general.base_path+"static/pages/404").read())
			return templater(config.general.base_path+"templates/site.html", {"page_html":page_html, "base_url":config.general.base_url, "page_type":page_type, "session":session, "page_name":"404 not found"})
		
		return templater(config.general.base_path+"templates/site.html", {"page_html":page_html, "base_url":config.general.base_url, "page_type":page_type, "session":session, "page_name":article.title})
		
	def POST(self, url_id, format):
		# init input
		i = web.input()
		# check to see if we're editing an article or posting comment
		if i.action == "article":
			i.draft = 1 if "1" else 0
			
			# grab the article's contents
			article = db.store.find(db.Article, db.Article.url_id == url_id)[0]
			
			# change values
			article.url_id = i.url_id
			article.title = i.title
			article.tags = i.tags
			article.content = i.content
			article.ip = u"localhost"
			article.active = i.draft
			
			# Tag management
			# Creates new tags and associates articles and tags
			# Delete old associates of this article (we just do the whole process over again)
			db.store.execute("DELETE FROM `article_tag_assoc` WHERE article=%s" % (article.id_))
			
			new_tags = []
			new_tags_sql = ""
			
			for tag in i.tags.split(","):
				tag = tag.strip()
				if db.tag_exists(tag):
					db.store.execute("INSERT INTO `article_tag_assoc` (tag, article) VALUES ('%s','%s')" % (tag, article.id_))
					
				else:
					new_tags.append(tag)
					
			# now add the new tags that pointblank hasn't seen yet	
			for tag in new_tags:
				# add to entire sql statement
				new_tags_sql += "('%s', '%s')," % (tag, unicode(time.time()))
				
			if new_tags:
				db.store.execute("INSERT INTO `tags` (tag, timestamp) VALUES %s" % new_tags_sql[:-1])
			
			# save changes
			db.store.commit()
			
			# show article again
			raise web.seeother(config.general.domain+web.http.url())
				
		elif i.action == "comment":
			# grab all comments for this article (by id_)
			# increment from the last one's thread_id
			try:
				last_comment = db.store.find(db.Comment, db.Comment.article_id == int(i.article_id)).order_by(db.Desc(db.Comment.thread_id))[0]
				last_thread_id = last_comment.thread_id
			except IndexError:
				# this is the first comment
				last_thread_id = 0
			
			# TODO: check for @replyto
			# if i.text
			
			data = {
				"author":i.author,
				"email":i.email,
				"author":i.author,
				"website":i.website,
				"thread_id":last_thread_id+1,
				"article_id":int(i.article_id),
				"text":i.text,
				"timestamp":unicode(time.time())
				}
				
			comment = db.Comment(data)

			# add to store, and flush (save)
			db.store.add(comment)
			db.store.flush()
			
			if session.username == "":
				# sessionize data (auto-input to other forms)
				session.username = data['author']
				session.website = data['website']
				session.email = data['email']
			
			# redirect to index
			raise web.seeother(config.general.domain+web.http.url())
				
			
class Tags:
	def GET(self, tags):
		page_type="tag_list"
		
		if tags == None:
			# TODO: Add tag list without any tags supplied
			page_html = "What tag?"
			web.webapi.header("Content-Type","text/html; charset=utf-8") 
			return templater(config.general.base_path+"templates/site.html", {"page_html":page_html, "page_name":"Tag filtering", "page_type":page_type, "session":session})
			
		else:
			page_html = '<h1>Articles tagged %s</h1><hr />' % data_handler.hyperlink_tags(tags)
		
		# matching articles
		match_id_list = []
		# holds all article results in html to be added to page_html
		article_html = ''

		for x in tags.split(','):
			# TODO: Improve how this works; each tag should filter results down to articles with
			# all tags specified.
			res = db.store.find(db.ArticleTagAssoc, db.ArticleTagAssoc.tag == unicode(x))
			
			for y in res:
				match_id_list.append(y.article)
				
		match_list = db.store.find(db.Article, db.Article.id_.is_in(match_id_list) and db.Article.active == 1)
			
		for article in match_list:
			# format/get date
			date = data_handler.parse_date(article.timestamp)
			
			# do all necessary replacements, execs, formatting, etc
			article = data_handler.handle_article_content(article)
			
			article_meta = {
				"title":article.title,
				"url_id":article.url_id,
				"id_":article.id_,
				"date":article.timestamp,
				"content":article.content,
				"base_url":config.general.base_url,
				"comment_count":db.get_num_comments(article.id_),
				"tag_list": article.tags,
				"year":date[0],
				"month":date[1],
				"day":date[2],
				"session":session,
				}
				
			article_html += str(templater(config.general.base_path+"templates/article.html", article_meta))
			
			# make sure storm doesn't save our mods (data_handler only works on output of db)
			db.store.rollback()
		
		page_html += article_html
		
		web.webapi.header("Content-Type","text/html; charset=utf-8")
		return templater(config.general.base_path+"templates/site.html", {
			"page_html":page_html,
			"page_name":"tags",
			"base_url":config.general.base_url,
			"page_type":page_type,
			"session":session})
				
class Wiki:
	def GET(self, name, format):
		page_type="wiki"
		
		try:
			page = open(config.general.base_path+"static/pages/%s" % (name,))
		except IOError:
			page = open(config.general.base_path+"static/pages/404")
			
		if format == '.html':
			# when was this modified?
			# os.stat() returns an iterable of file metadata items, -2 is last-motified
			try:
				last_modified_date = data_handler.human_timestamp(os.stat(config.general.base_path+"static/pages/%s" % (name,))[-2])
			except OSError:
				# 404, no page
				last_modified_date = data_handler.human_timestamp(os.stat(config.general.base_path+"static/pages/404")[-2])
			# get contents, parse markdown
			Markdown = markdown.Markdown()
			page_html = Markdown.convert(page.read())
			web.webapi.header("Content-Type","text/html; charset=utf-8") 
			return templater(config.general.base_path+"templates/site.html", {"page_html":page_html, "page_name":"Wiki", "page_type":page_type, "session":session, "date_modified":last_modified_date})
			
		elif format == ".markdown" :
			web.webapi.header("Content-Type","text/plain; charset=utf-8") 
			return page
		
		elif type(format) == type(None):
			url = config.general.domain+web.http.url()
			if url[-1] == u"/":
				url = url[0:-1]
			
			raise web.seeother(url+u'.html')
		
		page.close()
		
class Login:
	def GET(self):
		page_type="login"
		# login page
		page_html = templater(config.general.base_path+"templates/login.html", {'action':config.general.base_url+"+login"})
		web.webapi.header("Content-Type","text/html; charset=utf-8") 
		
		return templater(config.general.base_path+"templates/site.html", {"page_html":page_html, "page_name":"Login", "page_type":page_type, "session":session})
		
	def POST(self):
		page_type="login"
		i = web.input()
		
		# hash the password sent by the form
		# to check against config.rc usernames
		pass_hash = hashlib.md5()
		pass_hash.update(i.password)
		
		# login successful?
		success = 0
		
		# see if login matches whatever is in config.rc
		for x, y in config.users:
			if i.username == unicode(x) and pass_hash.hexdigest() == y:
				session.auth = 1
				session.username = x
				session.email = config.general.admin_email
				session.website = config.general.domain
				success = 1
				
				# output
				web.webapi.header("Content-Type","text/html; charset=utf-8") 
				page_html = "<h1>Login success</h1>\n\n<p>You have successfully logged in as <code>%s</code>. Admin actions on the website are marked in <span class=\"admin_link\">red</span>." % (session.username,)
				return templater(config.general.base_path+"templates/site.html", {"page_html":page_html, "page_name":"Login", "page_type":page_type, "session":session})
				
		if success == 0:
			# TODO accurate changeable
			raise web.seeother(config.general.base_url+'+login/')
			
class Logout:
	def GET(self):
		session.kill()
		raise web.seeother(config.general.base_url)
			
class Admin:
	def GET(self, component, id_="null"):
		if session.auth != 1:
			raise web.seeother(config.general.base_url)
			
		if component == "delete_article":
			id_ = str(id_).replace("delete_", "").replace("/", "")
			
			# execute query
			# using SQL because Storm manual is incomplete...
			db.store.execute("UPDATE `articles` SET active ='0' WHERE id_='%s'" % id_,
			noresult=True)
			
			db.store.execute("UPDATE `articles` SET active ='0' WHERE id_='%s'" % id_,
			noresult=True)
			
			web.webapi.header("Content-Type","text/html; charset=utf-8") 
			page_html = "<h2>Deleted!</h2> <p>There is still a record in the database, in case you deleted this article accidentally."
			
			return page_html
			
		elif component == "delete_comment":
			# need right type
			id_ = str(id_).replace("/", "")
			
			# execute query
			# using SQL because Storm manual is incomplete...
			db.store.execute("DELETE FROM `comments` WHERE id_ IN (%s)" % id_, noresult=True)
			
			web.webapi.header("Content-Type","text/html; charset=utf-8") 
			page_html = '<em class="confirmation">deleted</em>'
			
			return page_html
		
class Ajax:
	def GET(self, action, object_id=16):
		if session.auth != 1:
			raise web.seeother(config.general.base_url)
			
		if action == "edit_form":
			# serve a preloaded edit form
			matches = db.store.find(db.Article, db.Article.id_ == int(object_id))
			
			# hold article html
			form_html = ''
		
			for article in matches:
				# we need to construct a url (using dates)
				# for edit submissions
				date = data_handler.parse_date(article.timestamp)
				
				article_meta = {
					"title":article.title,
					"url_id":article.url_id,
					"id_":article.id_,
					"form_type":"edit",
					"date":article.timestamp,
					"content":article.content,
					"action":"%s%s/%s/%s/%s.html" % (config.general.base_url, date[0], date[1], date[2], article.url_id),
					"tags": article.tags,
					"session":session,
					}
				form_html += templater(config.general.base_path+"templates/article_form.html", article_meta)
				
			return form_html
			
class Feed:
	def GET(self, format):
		page_type = "feed"
		
		if format == "rss":
			# xml item holder
			article_xml = ''
		
			# grab article list
			articles = db.store.find(db.Article, db.Article.active == 1)
		
			for article in articles.order_by(db.Desc(db.Article.id_)):
				# format/get date
				date = data_handler.parse_date(article.timestamp)
				# do all necessary replacements, execs, formatting, etc
				article = data_handler.handle_article_content(article)
				
				article_meta = {
					"title":cgi.escape(article.title),
					"url_id":article.url_id,
					"id_":article.id_,
					"date":article.timestamp,
					"content":cgi.escape(article.content),
					"base_url":config.general.base_url,
					"comment_count":db.get_num_comments(article.id_),
					"tag_list": cgi.escape(article.tags),
					"year":date[0],
					"month":date[1],
					"day":date[2],
					"session":session,
					}
				
				article_xml += str(templater(config.general.base_path+"templates/rss_item.xml", article_meta))
			
				# make sure storm doesn't save our mods
				# from data_handler (because these mods are only for output)
				db.store.rollback()
		
			feed_vars = {
				"base_url":config.general.base_url,
				"page_type":page_type,
				"config":config,
				"items":article_xml
				}
				
			web.webapi.header("Content-Type","application/rss+xml")
			return templater(config.general.base_path+"templates/rss.xml", feed_vars)
				
			
class StaticFile:
	# Even though they're not!
	def GET(self, location):
		type_dict = {
			".css":"text/css",
			".js":"text/javascript",
			".html":"text/html",
			".png":"image/png",
			".jpg":"image/jpg"
			}
			
		for x in type_dict:
			if x in location:
				web.header("Content-Type", type_dict[x])
				
		# allow web.py templating in css/js files
		if "css/_" in location or "js/_" in location:
			text = open(config.general.base_path+"static/"+location, "rb").read()
			fixed = web.template.Template("$def with (vars)\n"+text)
			return fixed(config.general)
			
		else:
			return open(config.general.base_path+"static/"+location,"rb").read() 
		
	
# Create web.py app
app = web.application(urls, globals())
session = web.session.Session(app, web.session.DiskStore(config.general.base_path + 'sessions'), initializer={'auth': 0, 'username':'', 'email':'', 'website':''})
	
# Deploy application based on settings
if config.deployment.type == "built-in":
	app.run()
elif config.deployment.type == "wsgi":
	application = app.wsgifunc()