ubuntu-bots/commoncgi.py

85 lines
2.3 KiB
Python

# -*- Encoding: utf-8 -*-
###
# Copyright (c) 2006-2007 Dennis Kaarsemaker
# Copyright (c) 2008-2010 Terence Simpson
# Copyright (c) 2018- Krytarik Raido
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of version 2 of the GNU General Public License as
# published by the Free Software Foundation.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
###
import cgi, cgitb, sys, os, re, math, codecs
import supybot.utils as utils
if sys.version_info < (3,0):
import Cookie as cookies
else:
import http.cookies as cookies
cgitb.enable()
form = cgi.FieldStorage()
cookie = cookies.SimpleCookie()
if 'HTTP_COOKIE' in os.environ:
cookie.load(os.environ['HTTP_COOKIE'])
if 'sess' in cookie:
cookie['sess']['max-age'] = 2592000 * 3
cookie['sess']['version'] = 1
if 'tz' in cookie:
cookie['tz']['max-age'] = 2592000 * 3
cookie['tz']['version'] = 1
class IOWrapper:
'''Class to wrap default IO, used with templates'''
def __init__(self):
self.buf = ''
def write(self, val):
self.buf += val
def getvalue(self):
return self.buf
sys.stdout = IOWrapper()
sys.stderr = IOWrapper()
def send_page(template):
'''Sends a template page and exit'''
data = sys.stdout.getvalue()
errdata = sys.stderr.getvalue()
# Ensure Unicode output
if sys.version_info < (3,1):
sys.stdout = codecs.getwriter('utf-8')(sys.__stdout__)
else:
sys.stdout = codecs.getwriter('utf-8')(sys.__stdout__.detach())
print("Content-Type: text/html")
print(cookie)
print("")
fd = open(template)
tmpl = fd.read()
fd.close()
estart = tmpl.find('%e')
sstart = tmpl.find('%s')
if sys.version_info < (3,0):
page = u'{}{}{}{}{}'.format(tmpl[:estart], errdata,
tmpl[estart+2:sstart], data, tmpl[sstart+2:])
else:
page = '{}{}{}{}{}'.format(tmpl[:estart], errdata,
tmpl[estart+2:sstart], data, tmpl[sstart+2:])
print(page)
sys.exit(0)
def q(txt):
'''Simple HTML entity quoting'''
return txt.replace('&','&amp;').replace('<','&lt;').replace('>','&gt;').replace('"','&quot;')