#! /usr/bin/env python
+# coding: koi8-r
"""Search tags CGI"""
__author__ = "Oleg Broytman <phd@phdru.name>"
__copyright__ = "Copyright (C) 2014 PhiloSoft Design"
__license__ = "GNU GPL"
-import cgi
-from parse_query import parser
-from html.response import response
+import cgi, sys
+from ply.lex import LexError
+
+from html.response import redirect, response
+from parser.parser import parser
form = cgi.FieldStorage()
if not form.has_key('q'):
title = "Error!"
body = "Required parameter is missing!"
+else:
+ q = form['q'].value
+ try:
+ tree = parser.parse(q)
+ except LexError:
+ tree = None
+ if tree is None:
+ status = "400 Bad request"
+ title = "Error!"
+ body = "Bad query syntax!"
+ elif tree[0] == 'NAME': # Single tag - just do redirect
+ tag = tree[1]
+ assert isinstance(tag, str)
+ from tags import tag_exists
+ if tag_exists(tag):
+ redirect("/Russian/blog/tags/%s.html" % tag, status="301 Moved")
+ sys.exit()
+ status = "404 Tag not found"
+ title = "Ошибка!"
+ body = "Тег %s не существует!" % tag
+ else: # Process tree
+ from tags import calc_tree
+ posts = calc_tree(tree)
+ status = None
+ title = "Записи, найденные для выражения " + q
+ if posts:
+ _posts = []
+ for suburl, title in posts:
+ _posts.append('<a href="/Russian/blog/%s">%s</a>' % (suburl, title))
+ body = "<br>\n".join(_posts)
+ else:
+ body = "Не найдено ни одной записи."
+
response(title, body, status)