def postmaker(query): #get main info results = [ dict(id=row[0], title=row[1], ctitle=row[2], author=row[3], date=dateit(row[4]).read, category=row[5], tags=row[6].split(','), pic=row[7], picinfo=row[8], desc=row[9]) for row in query ] #get num of comments for article and misc for row in results: row['comments'] = query_db( 'SELECT COUNT(*) FROM comments WHERE ArticleID = ?', [row['id']])[0][0] row['author'] = [ dict(name=ro[0], pic=ro[1]) for ro in query_db('SELECT Name, Picture FROM users WHERE ID = ?', [row['author']]) ][0] #clumsy way of selecting first row > array > name row['scategory'] = ''.join(e for e in row['category'] if e.isalnum()) row['color'] = query_db('SELECT Color FROM category WHERE Name = ?', [row['category']]) return results
def index(): if not session.get('user'): return redirect(url_for('pkd.login')) #get main info results = [ dict(id=row[0], title=row[1], ctitle=row[2], author=row[3], date=dateit(row[4]).read, category=row[5], tags=row[6].split(','), pic=row[7], picinfo=row[8], desc=row[9]) for row in query_db( 'SELECT ID, Title, SafeTitle, AuthorID, Date, Category, Tags, CoverURL, CoverInfo, Description FROM articles ORDER BY ID DESC' ) ] #get num of comments for article for row in results: row['comments'] = query_db( 'SELECT COUNT(*) FROM comments WHERE ArticleID = ?', [row['id']])[0][0] row['author'] = query_db( 'SELECT Name FROM users WHERE ID = ?', [row['author'] ])[0][0] #clumsy way of selecting first row > array > name #output everything return render_template('admin/index.html', user=get_user(), results=results)
def category(category=None): results = [ dict(name=row[0], desc=row[1], color=row[2], pic=row[3]) for row in query_db( 'SELECT Name, Description, Color, Picture FROM category where Name = ?', [category]) ] articles = postmaker( query_db( 'SELECT ID, Title, SafeTitle, AuthorID, Date, Category, Tags, CoverURL, CoverInfo, Description, Content FROM articles WHERE Category = ? ORDER BY ID DESC LIMIT ?', [category, numarticles[0]])) tags = taggin( query_db('SELECT Tags FROM articles WHERE Category = ?', [category])) amount = True if len(articles) == 0 else False if len(results) == 0 or len(results) > 1: return abort(404) return render_template('category.html', categories=get_category(), category=results[0], article=articles, amount=amount, na=numarticles, tags=tags, args=','.join(['Category', results[0]['name']]))
def edit(article=None): if not session.get('user'): return redirect(url_for('pkd.login')) if article == None: return redirect(url_for('pkd.index')) #get main article info results = [ dict(id=row[0], title=row[1], author=row[2], date=dateit(row[3]).read, category=row[4], tags=row[5].split(','), pic=row[6], picinfo=row[7], desc=row[8], text=row[9]) for row in query_db( 'SELECT ID, Title, AuthorID, Date, Category, Tags, CoverURL, CoverInfo, Description, Text FROM articles WHERE Title = ?', [article.replace('_', ' ')]) ] #check if article exists if len(results) == 0 or len(results) > 1: return abort(404) #get comments & author for article for row in results: row['comment'] = query_db( 'SELECT COUNT(*) FROM comments WHERE ArticleID = ? ORDER BY ID DESC', [row['id']])[0][0] author = [ dict(name=ro[0], pic=ro[1], desc=ro[2]) for ro in query_db( 'SELECT Name, Picture, Description FROM users WHERE ID = ?', [row['author']]) ] category = [ dict(name=ro[0]) for ro in query_db('SELECT (Name) FROM category ORDER BY ID DESC') ] #output everything return render_template('admin/editor.html', hidden=True, article=results[0], title=results[0]['title'], author=author[0], user=get_user(), category=category)
def index(): g = postmaker( query_db( 'SELECT ID, Title, SafeTitle, AuthorID, Date, Category, Tags, CoverURL, CoverInfo, Description, Content FROM articles ORDER BY ID DESC LIMIT ?', [numarticles[0]])) tags = taggin(query_db('SELECT Tags FROM articles')) amount = True if len(g) == 0 else False #output everything return render_template('index.html', results=g, amount=amount, categories=get_category(), na=numarticles, args=None, tags=tags)
def valid_login(u, p): query = (dict(user=row[0], name=row[1], passw=row[2]) for row in query_db('SELECT Username, Name, Password FROM users')) for d in query: if d['user'].upper() == u.upper() and d['passw'] == p: return [d['user'], d['name']] return False
def get_user(): return [ dict(id=row[0], user=row[1], name=row[2], pic=row[3], desc=row[4]) for row in query_db( 'SELECT ID, Username, Name, Picture, Description FROM users WHERE Username=?', [session.get('user')]) ][0]
def about(): #get authors authors = ( dict(name=row[0], pic=row[1], desc=row[2]) for row in query_db('SELECT Name, Picture, Description FROM users')) return render_template('about.html', categories=get_category(), authors=authors)
def new(): if not session.get('user'): return redirect(url_for('pkd.login')) date = datetime.datetime.now() category = [ dict(name=ro[0]) for ro in query_db('SELECT (Name) FROM category ORDER BY ID DESC') ] return render_template('admin/editor.html', user=get_user(), date=date.strftime('%b %d, %Y'), category=category, new=True)
def tags(tag=None): results = postmaker( query_db( 'SELECT ID, Title, SafeTitle,AuthorID, Date, Category, Tags, CoverURL, CoverInfo, Description, Content FROM articles WHERE Tags LIKE ? ORDER BY ID DESC LIMIT ?', ['%' + tag + '%', numarticles[0]])) if len(results) == 0: return abort(404) articles = [result for result in results if str(tag) in result['tags']] amount = True if len(articles) == 0 else False return render_template('tag.html', categories=get_category(), tag=tag, article=articles, amount=amount, na=numarticles, args=','.join(['Tags', tag]))
def archives(): g = [ dict(id=row[0], name=row[1], cname=row[2], authorid=row[3], date=dateit(row[4]).read, year=dateit(row[4]).year, month=dateit(row[4]).month, monthnum=dateit(row[4]).monthnum, category=row[5], scategory=''.join(e for e in row[4] if e.isalnum())) for row in query_db( 'SELECT ID, Title, SafeTitle, AuthorID, Date, Category FROM articles' ) ] #----sort by date----# a = defaultdict(list) #sort by year > monthnum > id, and newest on top for d in sorted(g, key=itemgetter('year', 'monthnum', 'id'), reverse=True): #add to defaultdict with the key(year) => dictionary of results a[d['year']].append(d) #final default dict to be outputted q = defaultdict(list) #for each year in a (list of tuples) version of the default dict above for v in a.items(): #new defaultdict for each month s = defaultdict(list) #for each dict in the year for e in v[1]: #create new default dict key(month) => dictionary of results (this is inside each year's dict!) s[e['month']].append(e) #add the results to the new defaultdict q[v[0]].append(s) #FIN~ return render_template('archives.html', categories=get_category(), archives=q)
def get_atom(query, text=''): feed = AtomFeed(''.join(['NightStuffs ', text]), feed_url=request.url, url=request.url_root) articles = [ dict(id=row[0], title=row[1], ctitle=row[2], author=row[3], date=row[4], category=row[5], tags=row[6].split(','), content=row[7], cover=row[8], info=row[9]) for row in query ] for article in articles: article['author'] = query_db('SELECT Name FROM users WHERE ID = ?', [article['author']])[0][0] image = "<img src=\"%s\" title=\"%s\" alt=\"%s\">" % (urljoin( request.url_root, url_for('pics', set='covers', pic=article['cover'])), article['info'], article['info']) feed.add(article['title'], unicode(image + article['content']), content_type='html', author=article['author'], url=make_external( url_for('article', article=article['ctitle'], category=article['category'])), updated=datetime.strptime(article['date'], '%Y-%m-%d %H:%M:%S'), published=datetime.strptime(article['date'], '%Y-%m-%d %H:%M:%S')) return feed.get_response()
def requests(req=None): if req == 'comment' and request.method == 'POST': #COMMENT REQUESTS error = False r = request.json n = r['name'] e = r['email'] s = r['text'] l = r['level'] + 1 if 'level' in r else '0' p = r['parent'] if 'parent' in r else '0' d = r['id'] if n.replace(" ", "") == "": error = True if s.replace(" ", "") == "": error = True if e.split('@')[1] == 'undefined' or e.split('@')[1].split( '.')[1] == 'undefined': error = True if error == True: return 'failed: requests not valid' #processing and limiting text s = ("<p>%s</p>" % cut(Markup.escape(s), 1500)).replace( "\n", "</p><p>") n = cut(n, 60) e = cut(e, 100) query_db( "INSERT INTO comments (Name, Date, Email, Parent, Level, Comment, ArticleID) VALUES (?,DATETIME('NOW'),?,?,?,?,?)", [n, e, p, l, s, d]) get_db().commit() return "Nice! Request recieved! And look at you looking into the console. Well here's your reward: raw request data { Name: %s, Email: %s, Comment: %s, Level: %s, Parent: %s, ArticleID: %s }" % ( n, e, s, l, p, d) if req == 'profile' and request.method == 'POST': if not session.get('user'): return "Fail.." r = request.form['name'] d = request.form['desc'] h = request.form['hasimage'] n = session.get('name') query_db("UPDATE users SET Description=? WHERE Username = ?", [d, session.get('user')]) get_db().commit() g = 'image uploaded!' if h == 'true': s = FileStorage(stream=request.files['image']).save( os.path.join(app.config['AUTHOR_FOLDER'], secure_filename(''.join([n, '.jpg'])))) else: g = "no image uploaded." return "Nice! Author Updated! Description changed to '%s', and %s" % ( d, g) if req == 'article' and request.method == 'POST': if not session.get('user'): return "Fail.." a = request.form['article'] h = request.form['html'] id = request.form['id'] t = request.form['title'].lstrip().rstrip() st = secure_filename(t) c = request.form['category'] ta = request.form['tags'] hc = request.form['hascover'] cd = request.form['coverdesc'] d = request.form['desc'] i = request.form[ 'image'] #DO NOT I REPEAT DO NOT Markup.escape THIS U F*****G DUMB PIECE OF SHIT. titles = query_db('SELECT ID FROM articles WHERE Title=?', [t]) hoc = request.form['hoc'] p = None ta = ','.join([e.strip() for e in ta.split(',')]) if id == 'false': #new article if (len(titles) > 0): return "ERROR: The title ur trying to use has been used %s time before!" % ( len(titles)) id = query_db('SELECT ID FROM users WHERE Username=?', [session.get('user') ])[0][0] #set ID from article id to author id query_db( "INSERT INTO articles (Title, SafeTitle, AuthorID, Date, Category, Tags, Description, CoverInfo, Pictures, Content, Text) VALUES (?,?,?,DATETIME('NOW'),?,?,?,?,?,?,?)", [t, st, id, c, ta, d, cd, i, h, a]) else: #update article if (len(titles) > 0 and id != str(titles[0][0])): return "ERROR: The renaming of this article will cause a conflict with (%s) other articles!" % ( len(titles)) query_db( "UPDATE articles SET Title=?, SafeTitle=?, Category=?, Tags=?, Description=?, CoverInfo=?, Pictures=?, Content=?, Text=? WHERE id = ?", [t, st, c, ta, d, cd, i, h, a, id]) #UPLOAD COVER if hc == 'true': pid = str( query_db("SELECT ID FROM articles WHERE Title=?", [t])[0][0]) p = secure_filename(''.join([pid, '.jpeg'])) pic = os.path.join(app.config['COVER_FOLDER'], p) s = FileStorage(stream=request.files['cover']).save(pic) optimize(pic) query_db("UPDATE articles SET CoverURL=?, CoverInfo=? WHERE id=?", [p, cd, pid]) #DELETE cover?!?!? D: if hoc == 'false': pic = query_db("SELECT CoverURL FROM articles WHERE ID=?", [str(id)]) try: os.remove( os.path.join(app.config['COVER_FOLDER'], secure_filename(str(pic[0][0])))) except: pass query_db( "UPDATE articles SET CoverURL='', CoverInfo='' WHERE id=?", [id]) get_db().commit() return "Nice! everything went smoothly!" if req == 'upload' and request.method == 'POST': if not session.get('user'): return "Fail.." t = request.form['type'] n = secure_filename(request.form['name']) folder = app.config['PICTURE_FOLDER'] allfiles = [f for f in listdir(folder) if isfile(join(folder, f))] for file in allfiles: if file.split('.')[0] == n: return "FAIL:, Already a picture named that!" if t == 'file': ext = request.form['ext'] if allowed_file(ext): d = request.files['stuff'] filename = secure_filename(''.join([n, ext])) pic = os.path.join(folder, filename) s = FileStorage(stream=d).save(pic) optimize(pic) n = filename else: return "FAIL:, not right file type!" elif t == 'url': d = request.form['stuff'] name = urlparse(d) notusing, ext = splitext(basename(name.path)) filename = secure_filename(''.join([n, ext])) if allowed_file(filename): finalp = os.path.join(folder, filename) urllib.urlretrieve(d, finalp) optimize(finalp) n = filename else: return "FAIL:, not right file type!" else: return "FAIL:, no images!!" return "%s" % url_for('pics', set='pictures', pic=n) if req == 'category' and request.method == 'POST': if not session.get('user'): return "Fail.." n = request.form['name'].lstrip().rstrip() d = request.form['desc'] c = request.form['color'] h = request.form['hasimage'] fname = secure_filename(''.join([n.lower(), '.jpg'])) all = query_db('SELECT Name FROM category') done = False for a in all: if n.lower() == str(a[0]).lower(): done = True query_db( "UPDATE category SET Name = ?, Description = ?, Color = ?, Picture = ? WHERE Name = ?", [n.lower(), d, c, fname, n.lower()]) if done == False: query_db( "INSERT INTO category(Name, Description, Color, Picture) VALUES (?,?,?,?)", [n.lower(), d, c, fname]) get_db().commit() g = 'image uploaded!' if h == 'true': file = os.path.join(app.config['TOPIC_FOLDER'], fname) s = FileStorage(stream=request.files['image']).save(file) optimize(file, resize=False) else: g = 'no image uploaded.' return "DONE my good sir! NEW CATEGORY! Name: %s, Color: %s, Description: %s and %s" % ( n, c, d, g) if req == 'delete_article' and request.method == 'POST': if not session.get('user'): return "Fail.." id = request.form['id'] pic = str( query_db("SELECT CoverURL FROM articles WHERE ID=?", [str(id)])[0][0]) try: os.remove( os.path.join(app.config['COVER_FOLDER'], secure_filename(pic))) except: pass query_db("DELETE FROM articles WHERE ID = ?", [id]) query_db("DELETE FROM comments WHERE ArticleID = ?", [id]) get_db().commit() return "article with id #%s deleted :(" % (id) if req == 'posts' and request.method == 'POST': na = request.form['numthere'] #number of articles already there n = request.form['numnew'] #number of articles to request args = request.form['args'].split(',') #get main info if args[0] == 'None': results = postmaker( query_db( "SELECT ID, Title, AuthorID, Date, Category, Tags, CoverURL, CoverInfo, Description, Content FROM articles ORDER BY ID DESC LIMIT ?,?", [na, n])) elif args[0] == 'Category': results = postmaker( query_db( "SELECT ID, Title, AuthorID, Date, Category, Tags, CoverURL, CoverInfo, Description, Content FROM articles WHERE Category = ? ORDER BY ID DESC LIMIT ?,?", [args[1], na, n])) elif args[0] == 'Tags': results = postmaker( query_db( "SELECT ID, Title, AuthorID, Date, Category, Tags, CoverURL, CoverInfo, Description, Content FROM articles WHERE Tags = ? ORDER BY ID DESC LIMIT ?,?", [args[1], na, n])) if len(results) == 0: return "FAIL: NO RESULTS" #output everything return render_template('post.html', results=results) return abort(404)
def categoryfeed(category=None): return get_atom( query_db( 'SELECT ID, Title, SafeTitle, AuthorID, Date, Category, Tags, Content, CoverURL, CoverInfo FROM articles WHERE Category = ? ORDER BY ID DESC LIMIT 15', [category]), category)
def feed(): return get_atom( query_db( 'SELECT ID, Title, SafeTitle, AuthorID, Date, Category, Tags, Content, CoverURL, CoverInfo FROM articles ORDER BY ID DESC LIMIT 15' ))
def article(category=None, article=None): if article == None: return redirect(url_for('category', category=category)) #get main article info results = [ dict(id=row[0], title=row[1], ctitle=row[2], author=row[3], date=dateit(row[4]).read, category=row[5], tags=row[6].split(','), pic=row[7], picinfo=row[8], desc=row[9], content=row[10]) for row in query_db( 'SELECT ID, Title, SafeTitle, AuthorID, Date, Category, Tags, CoverURL, CoverInfo, Description, Content FROM articles WHERE SafeTitle = ?', [article]) ] #check if article exists if len(results) == 0 or len(results) > 1: return abort(404) #get comments for article THIS BETTER BE 1 ROW! for row in results: comments = [ dict(id=ro[0], name=ro[1], date=dateit(ro[2]).read, email=hashlib.md5(ro[3]).hexdigest(), parent=ro[4], level=ro[5], comment=ro[6]) for ro in query_db( 'SELECT ID, Name, Date, Email, Parent, Level, Comment FROM comments WHERE ArticleID = ? ORDER BY ID DESC', [row['id']]) ] row['comment'] = query_db( 'SELECT COUNT(*) FROM comments WHERE ArticleID = ? ORDER BY ID DESC', [row['id']])[0][0] author = [ dict(name=ro[0], pic=ro[1], desc=ro[2]) for ro in query_db( 'SELECT Name, Picture, Description FROM users WHERE ID = ?', [row['author']]) ] row['scategory'] = ''.join(e for e in row['category'] if e.isalnum()) row['color'] = query_db('SELECT Color FROM category WHERE Name = ?', [row['category']])[0][0] #related articles re = [ dict(name=ro[0], pic=ro[1], tags=ro[2], cname=ro[0].replace(' ', '_'), category=ro[3]) for ro in query_db( 'SELECT Title, CoverURL, Tags, Category FROM articles WHERE Category = ?', [row['category']]) ] related = [] others = None g = [i.upper() for i in row['tags']] for r in re: cnt = 0 for x in r['tags'].split(','): if x.upper() in g and r['name'] != row['title']: cnt += 1 if cnt >= 1: #if at least 1 tag matched (set up like this so it can be adjusted later) related.append(r) if len(related) == 0: related = None others = [ dict(name=ro[0], pic=ro[1], tags=ro[2], cname=ro[0].replace(' ', '_'), category=ro[3]) for ro in query_db( 'SELECT Title, CoverURL, Tags, Category FROM articles WHERE Title != ? AND Category = ?', [row['title'], row['category']]) ] if len(others) == 0: others = None #sorting comments comments = commentsorter.popcomments(comments) #output everything return render_template('article.html', categories=get_category(), article=results[0], title=results[0]['title'], author=author[0], related=related, others=others, comments=comments)