view av_conn.py @ 508:64f8666690d8

README update (Logical change 1.149)
author optonline.net!jeffpc
date Fri, 16 Jan 2004 02:53:48 +0000
parents 3f11f8e93035
children 56166b03a6b3
line wrap: on
line source

#/*
# * AV Admin - Helps to manage an AV department
# *
# * Copyright (C) 2003, 2004 Josef "Jeff" Sipek
# *
# * This program is free software; you can redistribute it and/or modify
# * it under the terms of the GNU General Public License as published by
# * the Free Software Foundation; either version 2 of the License, or
# * (at your option) any later version.
# *
# * 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.
# *
# * You should have received a copy of the GNU General Public License
# * along with this program; if not, write to the Free Software
# * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
# *
# * $Id$
# */

import os
import sys
import re
import cgi
import time
from htmltmpl import TemplateManager, TemplateProcessor

import av_debug
import av_db
import av_user
import av_html
import av_utils
import av_settings
import av_log

class Conn:
	""" Class to hold all connection data and more """
	def __init__(self,reqlogin=1):
		""" Set all variables to their default values

		does not return anything """
		self.__compile_regexp()
		self.__reqlogin = reqlogin
		self.templ = TemplateManager().prepare("templates/window.tmpl")
		self.tproc = TemplateProcessor(html_escape=0)

		self.db = av_db.DB()
		self.html = av_html.HTML()
		self.user = av_user.User()
		self.utils = av_utils.Utils()
		
		self.db.attach(self)
		self.html.attach(self)
		self.user.attach(self)
		self.utils.attach(self)

		self.__set_template_vars()
		self.__check_login()

	def __check_login(self):
		if ((self.__reqlogin) and (not self.user.isloggedin()) and (not self.user.timedout())):
			self.html.header("Error")
			self.html.heading("Error")
			text = "ERROR" # default text, will be changed at run time
			if (self.user.TEXTBUF["logincheckerror"]):
				text  = self.user.TEXTBUF["logincheckerror"]
			if (text=="ERROR"): # This should not happen
				text = "<br />Sorry, but you must log in to access this page. To log in, select the appropreate option from the menu."
				av_log.seclog(self,"User attempted to access " + self.currentpage() + " without specifying SESSION ID")
			self.html.body.init()
			self.html.body.set(text)
			self.html.footer()
			print self.flush()
			self.conn.exit()

	
	def __compile_regexp(self):
		""" Compiles all regural expressions used throughout the program
		
		does not return anything """
		self.regexp_Aa0s = re.compile("^[A-Za-z0-9\s\!@#\$%\^&*\(\)\-=_\+\[\]\{\};:,\./<>\?'\|~`\\\"]+$")
		self.regexp_Aa0 = re.compile('^[A-Za-z0-9]+$')
		self.regexp_a0 = re.compile('^[a-z0-9]+$')
		self.regexp_0 = re.compile('^[0-9]+$')

	def __set_template_vars(self):
		self.tproc.set("sys_progname", av_settings.getSetting(self,"name"))
		self.tproc.set("sys_sid",self.user.getSID())

	def securitycheck(self,condition,loglevel,printtext="Sorry, but you don't have the necesarry priveledges to view this page.",logmessage=None):
		""" Return printtext and add logmessage to loglevel log if condition is false
		
		does not return anything """
		if (condition):
			return None

		if (logmessage is None):
			logmessage = "User \"" + self.user.UID2User() + "\" tried to access " + self.currentscript() + " but lacks the necessary priv."
		
		av_log.genericlog(self,logmessage,loglevel)
		self.html.body.set(printtext)
		self.html.footer()
		print self.flush()
		self.exit()
	
	def getIP(self):
		""" Return client's IP address

		returns string """
		return os.environ["REMOTE_ADDR"]

	def getUserAgent(self):
		""" Return client's User Agent ID string

		returns string """
		return os.environ["HTTP_USER_AGENT"]
		
	def currentpage(self):
		""" Return the name of the script being run
		
		returns string """
		return os.environ["SCRIPT_NAME"]
	
	def currentscript(self):
		""" Returns the name of the script being run
		
		returns string """
		return self.currentpage().replace(av_settings.getSetting(self,"baseurl"),"")

	def getparam(self,key,printable=0):
		""" Return parameter from query string..

		returns string """
		co = cgi.FormContentDict()
		value = ""
		try:
			if (printable):
				value = self.stripchars(co[key][0])
			value = co[key][0]
		except KeyError:
			value = ""
		return value

	def now(self):
		""" Return the number of seconds since the epoch

		returns number """
		return int(time.mktime(time.localtime()))
		
	def today(self):
		""" Returns the number of second between the epoch and the passed midmight
		
		returns number """
		date = list(time.localtime())
		date[3:6] = [0, 0, 0]
		return int(time.mktime(tuple(date)))
		
	def text_now(self,format="%Y-%m-%d %H:%M:%S"):
		""" Return string that corresponds to current time
		
		returns string """
		return time.strftime(format)

	def stripchars(self,text):
		""" Return string that is stripped

		returns string """
		text2 = text
		for i in range(self.__class__.DisAllowedChars.__len__()):
			text2 = text2.replace(self.__class__.DisAllowedChars[i],"")
		return text2

	def validatestring(self,text,num=1,caps=1,lower=1,special=0):
		""" Check that string does not contain disallowed chars

		returns bool """
		if (num and caps and lower and (not special)):
			if (self.regexp_Aa0.match(text)):
				return 1
		if (num and caps and lower and special):
			if (self.regexp_Aa0s.match(text)):
				return 1
		if (num and (not caps) and (not lower) and (not special)):
			if (self.regexp_0.match(text)):
				return 1
		return 0
	
	def makeURL(self,page,static=0,usesid=1,params={}):
		""" Return formated url
		
		returns string """
		url = ""
		if (static):
			url += av_settings.getSetting(self,"staticurl")
		else:
			url += av_settings.getSetting(self,"baseurl")
		url += page
		
		if (static):
			url = url.replace("$THEME$",self.html.theme)
			return url
		
		url += "?"
		
		if (usesid):
			url += "sid=" + self.user.getSID() + "&amp;"
		
		for key in params.keys():
			url += key + "=" + params[key] + "&amp;"
		
		return url
	
	def parse(self,text):
		""" Changes certain keywords with other values
		
		returns string """
		text = text.replace("$INSTITUTION$",av_settings.getSetting(self,"institution"))
		text = text.replace("$LOCATION$",av_settings.getSetting(self,"location"))
		text = text.replace("$NAME$",av_settings.getSetting(self,"name"))
		text = text.replace("$VERSION$",av_settings.getSetting(self,"version"))
		text = text.replace("$BASEURL$",av_settings.getSetting(self,"baseurl"))
		text = text.replace("$STATICURL$",av_settings.getSetting(self,"staticurl"))
		
		return text
	
	def yesno(self,value):
		""" Return yes if value, else return no
		
		returns string """
		if (value):
			return "Yes"
		return "No"
	
	def flush(self):
		""" Sends all buffered output to the client

		does not return anything """
		self.html.menu(reqlogin=self.__reqlogin)
		self.tproc.set("sys_body",self.html.body.get())
		return self.tproc.process(self.templ)
	
	def exit(self):
		""" Terminate the program
		
		does not return anything """
		sys.exit(0)
		
if __name__ == "__main__":
	print "ERROR"