# -*- coding: utf-8 -*-
##
##
## This file is part of CDS Indico.
## Copyright (C) 2002, 2003, 2004, 2005, 2006, 2007 CERN.
##
## CDS Indico 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.
##
## CDS Indico 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 CDS Indico; if not, write to the Free Software Foundation, Inc.,
## 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA.
from MaKaC.plugins.base import PluginsHolder
import os,types,string
from xml.sax.saxutils import escape, quoteattr
from copy import copy
from datetime import timedelta,datetime, date
import exceptions
from MaKaC.common.db import DBMgr
import MaKaC.conference as conference
import MaKaC.user as user
import MaKaC.schedule as schedule
import MaKaC.common.info as info
import MaKaC.domain as domain
import MaKaC.webinterface.urlHandlers as urlHandlers
import MaKaC.common.Configuration as Configuration
from MaKaC import webcast
from MaKaC.accessControl import AdminList
from MaKaC.errors import UserError
from MaKaC.common.url import URL
from MaKaC.common import Config
from MaKaC.webinterface.common.person_titles import TitlesRegistry
from MaKaC.conference import Conference, Category
from MaKaC.webinterface.common.timezones import TimezoneRegistry, DisplayTimezoneRegistry
import MaKaC.webinterface.common.timezones as convertTime
from pytz import timezone
from MaKaC.common.timezoneUtils import DisplayTZ, nowutc
from MaKaC.webinterface.common import contribFilters as contribFilters
from MaKaC.common import filters, utils
from MaKaC.errors import MaKaCError
import MaKaC.webinterface.displayMgr as displayMgr
from MaKaC.common.TemplateExec import TemplateExec
from MaKaC.common.ContextHelp import ContextHelp
from MaKaC.rb_tools import FormMode, overlap
from libxml2 import parserError
from MaKaC.i18n import _
from MaKaC.i18n import langList
from MaKaC.common.TemplateExec import truncateTitle
from MaKaC.fossils.user import IAvatarFossil
from MaKaC.common.fossilize import fossilize
from MaKaC.common.contextManager import ContextManager
import re
class WTemplated:
"""This class provides a basic implementation of a web component (an
object which generates HTML related to a certain feature or
functionality) which relies in a template file for generating the
HTML it's in charge of.
By templating file we mean that there will be a file in the file
system (uniquely identified) which will contain HTML code plus some
"variables" (dynamic values). The class will take care of opening
this file, parsing the HTML and replacing the variables by the
corresponding values.
"""
tplId = None
def __init__( self, tpl_name = None):
if tpl_name != None:
self.tplId = tpl_name
#if ( '_rh' in ','.join( dir( self ) ) ):
from MaKaC.webinterface.rh.base import RH
self._rh = RH._currentRH
def _getSpecificTPL(self, dir, tplId, extension="tpl"):
"""
Checks if there is a defined set of specific templates (i.e. CERN),
and if there is a specific file for this page, for this template set.
Returns the file that should be used.
"""
if DBMgr.getInstance().isConnected():
template = info.HelperMaKaCInfo.getMaKaCInfoInstance().getDefaultTemplateSet()
if template != None :
specTpl = "%s.%s.%s" % (tplId, template, extension)
if os.path.exists(os.path.join(dir,specTpl)):
return specTpl
return "%s.%s" % (tplId, extension)
def _setTPLFile(self):
"""Sets the TPL (template) file for the object. It will try to get
from the configuration if there's a special TPL file for it and
if not it will look for a file called as the class name+".tpl"
in the configured TPL directory.
"""
cfg = Configuration.Config.getInstance()
dir = cfg.getTPLDir()
file = cfg.getTPLFile( self.tplId )
if file == "":
file = self._getSpecificTPL(dir,self.tplId)
self.tplFile = os.path.join(dir, file)
hfile = self._getSpecificTPL(os.path.join(dir,'chelp'),
self.tplId,
extension='wohl')
self.helpFile = os.path.join(dir,'chelp',hfile)
def getVars( self ):
"""Returns a dictionary containing the TPL variables that will
be passed at the TPL formating time. For this class, it will
return the configuration user defined variables.
Classes inheriting from this one will have to take care of adding
their variables to the ones returned by this method.
"""
from MaKaC.webinterface.rh.base import RH
self._rh = RH._currentRH
cfg = Configuration.Config.getInstance()
vars = cfg.getTPLVars()
for paramName in self.__params:
vars[ paramName ] = self.__params[ paramName ]
if len(vars.get("errorMsg", [])) > 0 :
vars["errorMsg"] = WErrorMessage().getHTML(vars)
else:
vars["errorMsg"] = ""
if len(vars.get("infoMsg", [])) > 0 :
vars["infoMsg"] = WInfoMessage().getHTML(vars)
else :
vars["infoMsg"] = ""
return vars
def getHTML( self, params=None ):
"""Returns the HTML resulting of formating the text contained in
the corresponding TPL file with the variables returned by the
getVars method.
Params:
params -- additional paramters received from the caller
"""
from MaKaC.webinterface.rh.base import RH
self._rh = RH._currentRH
if self.tplId == None:
self.tplId = self.__class__.__name__[1:]
self._setTPLFile()
self.__params = {}
if params != None:
self.__params = params
try:
fh = open( self.tplFile, "r")
text = fh.read()
fh.close()
except Exception, e:
raise MaKaCError( _("Could not open template: %s")%self.tplFile, _("Template"))
# include context help info, if it exists
helpText = None
if os.path.exists(self.helpFile):
try:
fh = open( self.helpFile, "r")
helpText = fh.read()
fh.close()
except exceptions.IOError:
pass
vars = self.getVars()
vars['__rh__'] = self._rh
vars['self'] = self
tempHTML = TemplateExec.executeTemplate( text, vars, self.tplId )
if helpText == None:
return tempHTML
else:
try:
return ContextHelp().merge(self.tplId, tempHTML, helpText)
except parserError, e:
if tempHTML.strip() == '':
raise MaKaCError(_("Template " + str(self.tplId) + " produced empty output, and it has a .wohl file. Error: " + str(e)))
else:
raise e
def htmlText(param):
if param:
return escape(param)
#return " "
return ""
htmlText = staticmethod( htmlText )
def textToHTML(param):
if param != "":
if param.lower().find(" ") == -1 and param.lower().find("
") == -1 and param.lower().find("
") == -1 and param.lower().find("
")
param=param.replace("\n"," ")
return param
return " "
textToHTML = staticmethod( textToHTML )
def _escapeChars(self, text):
return text.replace('%','%%')
class WHTMLHeader(WTemplated):
def __init__(self, tpl_name = None):
WTemplated.__init__(self)
def getVars( self ):
vars = WTemplated.getVars( self )
if DBMgr.getInstance().isConnected():
vars['stylesheet'] = Config.getInstance().getCssStylesheetName()
else:
vars['stylesheet'] = 'Default.css'
return vars
class WHeader(WTemplated):
"""Templating web component for generating a common HTML header for
the web interface.
"""
def __init__(self, aw, locTZ="", isFrontPage=False, currentCategory=None, tpl_name=None):
WTemplated.__init__(self, tpl_name=tpl_name)
self._currentuser = aw.getUser()
self._locTZ = locTZ
self._aw = aw
self.__isFrontPage = isFrontPage
self.__currentCategory = currentCategory
"""
Returns the current active timezone.
"""
def _getActiveTimezone(self):
if self._aw.getSession():
tz = self._aw.getSession().getVar("ActiveTimezone")
else:
tz = info.HelperMaKaCInfo.getMaKaCInfoInstance().getTimezone()
return tz
"""
Returns timezone string that is show to the user.
"""
def _getTimezoneDisplay( self, timezone ):
if timezone == 'LOCAL':
if self._locTZ:
return self._locTZ
else:
return info.HelperMaKaCInfo.getMaKaCInfoInstance().getTimezone()
else:
return timezone
def getVars( self ):
vars = WTemplated.getVars( self )
#urlHandlers.UHUserDetails.getURL(self._currentuser)
vars["logMeAs"] = ""
# TODO: Remove this after CRBS headers are fixed!
if self._currentuser:
vars["userInfo"] = """%s - logout"""%(urlHandlers.UHUserDetails.getURL(self._currentuser), self._currentuser.getFullName(), vars["logoutURL"])
vars["userDetails"] = """class="topbar" href="%s" target="_blank\""""%urlHandlers.UHUserDetails.getURL(self._currentuser)
if self._currentuser.isAdmin():
vars["logMeAs"] = vars["loginAsURL"]
else:
vars["userInfo"] = """login"""%(vars["loginURL"])
vars["userDetails"] = ""
# *****************
vars["currentUser"] = self._currentuser
imgLogo=Configuration.Config.getInstance().getSystemIconURL( "logoIndico" )
imgLogin=Configuration.Config.getInstance().getSystemIconURL( "login" )
##
## TOCHECK: We do not need this anymore since we use the flaog _ishttps in the clase RHSignIn
##
# if Configuration.Config.getInstance().getLoginURL().startswith("https"):
#
# # Set proper PROTOCOL for images requested via SSL
# imgLogo=imgLogo.replace("http://", "https://")
# imgLogin=imgLogin.replace("http://", "https://")
#
# # Set proper PORT for images requested via SSL
# imgLogo = urlHandlers.setSSLPort( imgLogo )
# imgLogin = urlHandlers.setSSLPort( imgLogin )
#
vars["imgLogo"] = imgLogo
vars["imgLogin"] = imgLogin
vars["isFrontPage"] = self.__isFrontPage
vars["currentCategory"] = self.__currentCategory
if self._aw.getSession():
selLang = self._aw.getSession().getLang()
else:
minfo = info.HelperMaKaCInfo.getMaKaCInfoInstance()
selLang = minfo.getLang()
#language list related
languages = {}
vars["SelectedLanguageName"] = "Unknown Language";
for lang in langList():
if selLang.lower() == lang[0].lower():
vars["SelectedLanguageName"] = lang[1];
languages[lang[0]] = lang[1]
vars["Languages"] = languages
vars["SelectedLanguage"] = selLang;
vars["ActiveTimezone"] = self._getActiveTimezone();
"""
Get the timezone for displaying on top of the page.
1. If the user has "LOCAL" timezone then show the timezone
of the event/category. If that's not possible just show the
standard timezone.
2. If the user has a custom timezone display that one.
"""
vars["ActiveTimezoneDisplay"] = self._getTimezoneDisplay(vars["ActiveTimezone"])
if DBMgr.getInstance().isConnected():
vars["title"] = info.HelperMaKaCInfo.getMaKaCInfoInstance().getTitle()
vars["organization"] = info.HelperMaKaCInfo.getMaKaCInfoInstance().getOrganisation()
else:
vars["title"] = "Indico"
vars["organization"] = ""
# Search box, in case search is active
if Config.getInstance().getIndicoSearchServer() != '' :
categId = 0
if self.__currentCategory:
categId = self.__currentCategory.getId()
vars['searchBox'] = WCategorySearchBox(categId=categId).getHTML()
else:
vars['searchBox'] = ""
# Check if room booking module is active
minfo = info.HelperMaKaCInfo.getMaKaCInfoInstance()
vars['roomBooking'] = minfo.getRoomBookingModuleActive()
#Build a list of items for the administration menu
adminList = AdminList.getInstance()
adminItemList = []
if self._currentuser:
if self._currentuser.isAdmin() or not adminList.getList():
adminItemList.append({'url': urlHandlers.UHAdminArea.getURL(), 'text': _("Server admin")})
if PluginsHolder().hasPluginType("Collaboration"):
from MaKaC.webinterface.rh.collaboration import RCCollaborationAdmin, RCCollaborationPluginAdmin
from MaKaC.plugins.Collaboration.collaborationTools import CollaborationTools
if (self._currentuser.isAdmin() or RCCollaborationAdmin.hasRights(user = self._currentuser) or RCCollaborationPluginAdmin.hasRights(user = self._currentuser, plugins = "any")) and CollaborationTools.anyPluginsAreActive():
adminItemList.append({'url': urlHandlers.UHAdminCollaboration.getURL(), 'text': _("Video Services Overview")})
if webcast.HelperWebcastManager.getWebcastManagerInstance().isManager(self._currentuser):
adminItemList.append({'url': urlHandlers.UHWebcast.getURL(), 'text': _("Webcast Admin")})
vars["adminItemList"] = adminItemList
return vars
class WStaticWebHeader( WTemplated ):
"""Templating web component for generating the HTML header for
the static web interface when generating a DVD.
"""
def getVars( self ):
vars = WTemplated.getVars( self )
return vars
class WManagementHeader( WHeader ):
"""Templating web component for generating the HTML header for
the management web interface.
"""
pass
class WHelpHeader( WHeader ):
"""Templating web component for generating the HTML header for
the help web interface.
"""
pass
class WRoomBookingHeader( WHeader ):
"""Templating web component for generating the HTML header for
the (standalone) room booking web interface.
"""
pass
class WConferenceHeader( WHeader ):
"""Templating web component for generating the HTML header for
the conferences' web interface.
"""
def __init__(self, aw, conf):
self._conf = conf
self._aw = aw
WHeader.__init__(self, self._aw, tpl_name='EventHeader')
tzUtil = DisplayTZ(self._aw,self._conf)
self._locTZ = tzUtil.getDisplayTZ()
def getVars( self ):
vars = WHeader.getVars( self )
vars["categurl"] = urlHandlers.UHCategoryDisplay.getURL(self._conf.getOwnerList()[0])
vars["conf"] = self._conf;
vars["imgLogo"] = Configuration.Config.getInstance().getSystemIconURL( "miniLogo" )
vars["MaKaCHomeURL"] = urlHandlers.UHCategoryDisplay.getURL(self._conf.getOwnerList()[0])
#moved here from WHeader in order to be able to use DisplayTZ with self._conf (in some pages WHeader has no self._conf).
#TODO: Is this needed?
#vars["Timezones"] = Config.getInstance().getTimezoneList()
# if self._conf.getModifKey() != '':
# url = urlHandlers.UHConfEnterModifKey.getURL(self._conf)
# url.addParam("redirectURL",urlHandlers.UHConferenceDisplay.getURL(self._conf))
# vars["confModif"] = """"""%(quoteattr(str(url)), quoteattr(str(Configuration.Config.getInstance().getSystemIconURL( "modify" ))))
# else:
# vars["confModif"] = ""
# Default values to avoid NameError while executing the template
vars["viewoptions"] = []
vars["SelectedStyle"] = ""
vars["pdfURL"] = ""
vars["displayURL"] = ""
# Setting the buttons that will be displayed in the header menu
vars["showFilterButton"] = False
vars["showMoreButton"] = True
vars["showExportToICal"] = True
vars["showExportToPDF"] = False
vars["showDLMaterial"] = False
vars["showLayout"] = False
vars["usingModifKey"]=False
if self._conf.canKeyModify(self._aw):
vars["usingModifKey"]=True
vars["displayNavigationBar"] = displayMgr.ConfDisplayMgrRegistery().getDisplayMgr(self._conf).getDisplayNavigationBar()
return vars
class WMenuConferenceHeader( WConferenceHeader ):
"""Templating web component for generating the HTML header for
the conferences' web interface with a menu
"""
def __init__(self, aw, conf, modifKey=False):
self._conf = conf
self._modifKey=modifKey
self._aw=aw
WConferenceHeader.__init__(self, self._aw, conf)
def getVars( self ):
vars = WConferenceHeader.getVars( self )
vars["categurl"] = urlHandlers.UHConferenceDisplay.getURL(self._conf)
url = urlHandlers.UHConfEnterModifKey.getURL(self._conf)
url.addParam("redirectURL",urlHandlers.UHConferenceOtherViews.getURL(self._conf))
vars["confModif"] = _(""" _("manage")""")%quoteattr(str(url))
if self._conf.canKeyModify(self._aw):
url = urlHandlers.UHConfCloseModifKey.getURL(self._conf)
url.addParam("redirectURL",urlHandlers.UHConferenceOtherViews.getURL(self._conf))
vars["confModif"] = _("""_("exit manage")""")%quoteattr(str(url))
styleMgr = info.HelperMaKaCInfo.getMaKaCInfoInstance().getStyleManager()
stylesheets = styleMgr.getStylesheetListForEventType(vars["type"])
# View Menu
viewoptions = []
if len(stylesheets) != 0:
stylesheets.sort()
for stylesheet in stylesheets:
viewoptions.append({"id": styleMgr.getStylesheetName(stylesheet), "name": stylesheet})
# Dates Menu
tz = DisplayTZ(self._aw,self._conf,useServerTZ=1).getDisplayTZ()
sdate = self._conf.getStartDate().astimezone(timezone(tz))
edate = self._conf.getEndDate().astimezone(timezone(tz))
dates = []
if sdate.strftime("%Y-%m-%d") != edate.strftime("%Y-%m-%d"):
selected = ""
if vars.has_key("selectedDate"):
selectedDate = vars["selectedDate"]
if selectedDate == "all" or selectedDate == "":
selected = "selected"
else:
selectedDate = "all"
dates = [ _(""" ")
else:
dates.append("""""")
# Sessions Menu
sessions = []
if len(self._conf.getSessionList()) != 0:
selected = ""
if vars.has_key("selectedSession"):
selectedSession = vars["selectedSession"]
if selectedSession == "all" or selectedSession == "":
selected = "selected"
else:
selectedSession = "all"
sessions = [ _(""" ")
else:
sessions.append("""""")
# Handle hide/show contributions option
hideContributions = None;
if len(self._conf.getSessionList()) != 0:
if vars.has_key("detailLevel"):
if vars["detailLevel"] == "session":
hideContributions = "checked"
else:
hideContributions = ""
# Save to session
vars["hideContributions"] = hideContributions;
if self._conf.getType() == "meeting" and self._conf.getParticipation().isAllowedForApplying() and self._conf.getStartDate() > nowutc():
vars["applyForParticipation"] = _("""_("Apply for participation")""")%urlHandlers.UHConfParticipantsNewPending.getURL(self._conf)
else :
vars["applyForParticipation"] = ""
evaluation = self._conf.getEvaluation()
if self._conf.hasEnabledSection("evaluation") and evaluation.isVisible() and evaluation.inEvaluationPeriod() and evaluation.getNbOfQuestions()>0 :
vars["evaluation"] = _(""" _("Evaluation")""")%urlHandlers.UHConfEvaluationDisplay.getURL(self._conf)
else :
vars["evaluation"] = ""
urlCustPrint = urlHandlers.UHConferenceOtherViews.getURL(self._conf)
urlCustPrint.addParam("showDate", vars.get("selectedDate", "all"))
urlCustPrint.addParam("showSession", vars.get("selectedSession", "all"))
urlCustPrint.addParam("fr", "no")
urlCustPrint.addParam("view", vars["currentView"])
vars["printURL"]=str(urlCustPrint)
vars["printIMG"]=quoteattr(str(Configuration.Config.getInstance().getSystemIconURL( "printer" )))
urlCustPDF=urlHandlers.UHConfTimeTableCustomizePDF.getURL(self._conf)
urlCustPDF.addParam("showDays", vars.get("selectedDate", "all"))
urlCustPDF.addParam("showSessions", vars.get("selectedSession", "all"))
vars["pdfURL"]=quoteattr(str(urlCustPDF))
vars["pdfIMG"]=quoteattr(str(Configuration.Config.getInstance().getSystemIconURL( "pdf" )))
urlMatPack=urlHandlers.UHConferenceDisplayMaterialPackage.getURL(self._conf)
vars["matPackURL"]=quoteattr(str(urlMatPack))
vars["zipIMG"]=quoteattr(str(Configuration.Config.getInstance().getSystemIconURL( "smallzip" )))
if Config.getInstance().getIndicoSearchServer() != '' :
vars["searchBox"] = WMicroSearchBox(self._conf.getId()).getHTML()
vars["searchURL"] = quoteattr(str(Configuration.Config.getInstance().getSystemIconURL( "search" )))
else:
vars["searchBox"] = ""
return vars
class WMenuMeetingHeader( WConferenceHeader ):
"""Templating web component for generating the HTML header for
the meetings web interface with a menu
"""
def __init__(self, aw, conf, modifKey=False):
self._conf = conf
self._modifKey=modifKey
self._aw=aw
WHeader.__init__(self, self._aw, tpl_name='EventHeader')
tzUtil = DisplayTZ(self._aw,self._conf)
self._locTZ = tzUtil.getDisplayTZ()
def getVars( self ):
vars = WConferenceHeader.getVars( self )
vars["categurl"] = urlHandlers.UHCategoryDisplay.getURL(self._conf.getOwnerList()[0])
#vars["confModif"] = _(""" _("manage")""")%quoteattr(str(urlHandlers.UHConfEnterModifKey.getURL(self._conf)))
#if self._conf.canKeyModify(self._aw):
# vars["confModif"] = _(""" _("exit manage")""")%quoteattr(str(urlHandlers.UHConfCloseModifKey.getURL(self._conf)))
#vars["confModif"] += " | "
#if not self._conf.canAccess(self._aw) and self._conf.getAccessKey() != "":
# vars["confModif"] += _("""_("full agenda") | """)%(quoteattr(str(urlHandlers.UHConfForceEnterAccessKey.getURL(self._conf))))
styleMgr = info.HelperMaKaCInfo.getMaKaCInfoInstance().getStyleManager()
stylesheets = styleMgr.getStylesheetListForEventType(vars["type"])
viewoptions = []
if len(stylesheets) != 0:
stylesheets.sort(key=styleMgr.getStylesheetName)
for stylesheet in stylesheets:
viewoptions.append({"id": stylesheet, "name": styleMgr.getStylesheetName(stylesheet) })
vars["viewoptions"] = viewoptions
vars["SelectedStyle"] = styleMgr.getStylesheetName(vars["currentView"])
vars["displayURL"] = urlHandlers.UHConferenceDisplay.getURL(self._rh._conf)
# Setting the buttons that will be displayed in the header menu
vars["showFilterButton"] = True
vars["showExportToPDF"] = True
vars["showDLMaterial"] = True
vars["showLayout"] = True
# Dates Menu
tz = DisplayTZ(self._aw,self._conf,useServerTZ=1).getDisplayTZ()
sdate = self._conf.getStartDate().astimezone(timezone(tz))
edate = self._conf.getEndDate().astimezone(timezone(tz))
dates = []
selected = ""
if vars.has_key("selectedDate"):
selectedDate = vars["selectedDate"]
if selectedDate == "all" or selectedDate == "":
selected = "selected"
else:
selectedDate = "all"
dates = [ _(""" """)%selected]
while sdate.strftime("%Y-%m-%d") <= edate.strftime("%Y-%m-%d"):
selected = ""
if selectedDate == sdate.strftime("%d-%B-%Y"):
selected = "selected"
d = sdate.strftime("%d-%B-%Y")
dates.append(""" """%(d, selected, d))
sdate = sdate + timedelta(days=1)
vars["datesMenu"] = "".join(dates);
# Sessions Menu
sessions = []
selected = ""
if vars.has_key("selectedSession"):
selectedSession = vars["selectedSession"]
if selectedSession == "all" or selectedSession == "":
selected = "selected"
else:
selectedSession = "all"
sessions = [ _(""" """)%selected]
for session in self._conf.getSessionList():
selected = ""
id = session.getId()
if id == selectedSession:
selected = "selected"
title = session.getTitle()
if len(title) > 60:
title = title[0:40] + "..."
sessions.append(""" """%(id, selected, title))
vars["sessionsMenu"] = "".join(sessions);
# Handle hide/show contributions option
hideContributions = None;
if len(self._conf.getSessionList()) != 0:
if vars.has_key("detailLevel"):
if vars["detailLevel"] == "session":
hideContributions = "checked"
else:
hideContributions = ""
vars["hideContributions"] = hideContributions;
if Config.getInstance().getIndicoSearchServer() != '' :
vars["searchBox"] = WCategorySearchBox(optionsClass='meetingHeaderSearchBox').getHTML()
else:
vars["searchBox"] = ""
urlCustPrint = urlHandlers.UHConferenceOtherViews.getURL(self._conf)
urlCustPrint.addParam("showDate", vars.get("selectedDate", "all"))
urlCustPrint.addParam("showSession", vars.get("selectedSession", "all"))
urlCustPrint.addParam("detailLevel", vars.get("detailLevel", "all"))
urlCustPrint.addParam("fr", "no")
urlCustPrint.addParam("view", vars["currentView"])
vars["printURL"]=str(urlCustPrint)
urlCustPDF=urlHandlers.UHConfTimeTableCustomizePDF.getURL(self._conf)
urlCustPDF.addParam("showDays", vars.get("selectedDate", "all"))
urlCustPDF.addParam("showSessions", vars.get("selectedSession", "all"))
# Add the view as a parameter to keep track of the current layout
# when exporting a pdf
urlCustPDF.addParam("view", vars["currentView"])
vars["pdfURL"]=str(urlCustPDF)
return vars
class WMenuSimpleEventHeader( WMenuMeetingHeader ):
"""Templating web component for generating the HTML header for
the simple event' web interface with a menu
"""
def getVars( self ):
vars = WMenuMeetingHeader.getVars( self )
vars["confModif"] = """manage"""%quoteattr(str(urlHandlers.UHConfEnterModifKey.getURL(self._conf)))
if self._conf.canKeyModify(self._aw):
vars["confModif"] = """exit manage"""%quoteattr(str(urlHandlers.UHConfCloseModifKey.getURL(self._conf)))
# Setting the buttons that will be displayed in the header menu
vars["showFilterButton"] = False
vars["showExportToPDF"] = False
vars["accessWrapper"] = self._aw
return vars
class WFooter(WTemplated):
"""Templating web component for generating a common HTML footer for the
web interface.
"""
def __init__(self, tpl_name = None, isFrontPage = False):
WTemplated.__init__(self, tpl_name)
self.__isFrontPage = isFrontPage
def getVars( self ):
vars = WTemplated.getVars( self )
vars["isFrontPage"] = self.__isFrontPage;
if not vars.has_key("modificationDate"):
vars["modificationDate"] = ""
if not vars.has_key("shortURL"):
vars["shortURL"] = ""
return vars
class WNavigationDrawer(WTemplated):
def __init__( self, pars, bgColor = None, appendPath = [] , type = None):
self._target = pars["target"]
self._isModif = pars.get("isModif", False)
self._track = pars.get("track", None) #for abstracts viewed inside a track
self._bgColor = bgColor
self._actionType = type #type of action
"""
The appendPath is an array with dictionaries: {"url": x, "title": x}.
Each of these links are added in the end of the breadcrumb
"""
self._appendPath = appendPath
def getVars( self ):
vars = WTemplated.getVars( self )
vars["target"] = self._target
vars["isModif"]= self._isModif
vars["track"]= self._track
vars["bgColor"] = self._bgColor
vars["appendPath"] = self._appendPath
vars["actionType"] = self._actionType
return vars
def getHTML(self, params=None):
return WTemplated.getHTML(self, params)
class WSimpleNavigationDrawer(WTemplated):
def __init__( self, title, handler = None, bgColor = None, **pars ):
self._urlHandler = handler
self._pars = pars
self._title = title
self._bgColor = bgColor
def getVars( self ):
vars = WTemplated.getVars( self )
vars["urlHandler"] = self._urlHandler
vars["title"] = self._title
vars["pars"] = self._pars
vars["bgColor"] = self._bgColor
return vars
def getHTML(self, params=None):
return WTemplated.getHTML(self, params)
class WBannerModif(WTemplated):
def __init__( self, path = [], itemType = "", title = "" ):
WTemplated.__init__( self, "BannerModif" )
self._path = path
self._title = title
self._type = itemType
def getHTML(self):
""" Retrieves the HTML of the banner of the modification interface
of the given target event / category / contribution / abstract / etc.
'track' argument should be provided for abstracts viewed inside a track.
If originUrl and originPageTitle is set then this link his added to the end
of the breadcrumb showed in the banner.
"""
return WTemplated.getHTML(self, {"type" : self._type, "path": self._path, "title": self._title})
class WTimetableBannerModif(WBannerModif):
def __init__(self, aw, target):
## PATH
# Iterate till conference is reached
conf = target.getConference()
path = self._getOwnerBasePath(target)
# if user has access to top-level timetable
if conf.canModify(aw):
scheduleModifURL = urlHandlers.UHConfModifSchedule.getURL( conf )
else:
# otherwise, let them access only the session timetable
scheduleModifURL = urlHandlers.UHSessionModifSchedule.getURL( target.getSession() )
path.append({"url": scheduleModifURL, "title": _("Timetable")})
# TITLE AND TYPE
itemType = type(target).__name__
title = target.getTitle()
WBannerModif.__init__(self, path, itemType, title)
def _getOwnerBasePath(self, target):
path = []
obj = target
while obj:
obj = obj.getOwner()
if type(obj) != Conference and type(obj) != conference.Category:
path.append({"url": urlHandlers.UHHelper.getModifUH(type(obj)).getURL(obj),
"title": truncateTitle(obj.getTitle(), 30),
"type": type(obj).__name__})
else:
break
return path
class WContribListBannerModif(WTimetableBannerModif):
def __init__(self, target ):
## PATH
# Iterate till conference is reached
conf = target.getConference()
path = self._getOwnerBasePath(target)
path.append({"url": urlHandlers.UHConfModifContribList.getURL( conf ), "title": _("Contributions list")})
# TITLE AND TYPE
itemType = type(target).__name__
title = target.getTitle()
WBannerModif.__init__(self, path, itemType, title)
class WNotifTplBannerModif(WBannerModif):
def __init__( self, target ):
path = [{"url": urlHandlers.UHConfModifCFA.getURL(target), "title":_("Call for abstracts setup")}]
itemType="Notification Template"
title=target.getName()
WBannerModif.__init__(self, path, itemType, title)
class WAbstractBannerModif(WBannerModif):
def __init__( self, target ):
path = [{"url": urlHandlers.UHConfAbstractManagment.getURL(target), "title":_("Abstracts list")}]
itemType="Abstract"
title=target.getTitle()
WBannerModif.__init__(self, path, itemType, title)
class WTrackBannerModif(WBannerModif):
def __init__( self, track, abstract=None, isManager = False ):
path = []
target = track
if abstract:
path.append({"url": urlHandlers.UHTrackModifAbstracts.getURL(track), "title":_("Abstract list")})
if isManager:
path.append({"url": urlHandlers.UHConfModifProgram.getURL(track.getConference()), "title":_("Track list")})
itemType=type(target).__name__
title=target.getTitle()
WBannerModif.__init__(self, path, itemType, title)
class WCategoryBannerModif(WBannerModif):
def __init__( self, target ):
itemType="Category"
title=target.getTitle()
WBannerModif.__init__(self, [], itemType, title)
class WRegFormBannerModif(WBannerModif):
def __init__( self, registrant ):
path=[{"url": urlHandlers.UHConfModifRegistrantList.getURL(registrant.getConference()), "title":_("Registrants list")}]
itemType="Registrant"
title=registrant.getFullName()
WBannerModif.__init__(self, path, itemType, title)
class WRegFormSectionBannerModif(WBannerModif):
def __init__( self, target, conf ):
path=[{"url": urlHandlers.UHConfModifRegForm.getURL(conf), "title":_("Registration form setup")}]
itemType="Registration form Section"
title=target.getTitle()
WBannerModif.__init__(self, path, itemType, title)
class WEpaymentBannerModif(WBannerModif):
def __init__( self, target, conf ):
path=[{"url": urlHandlers.UHConfModifEPayment.getURL(conf), "title":_("Epayment setup")}]
itemType="Epayment plugin"
title=target.getTitle()
WBannerModif.__init__(self, path, itemType, title)
class WListingsBannerModif(WBannerModif):
def __init__( self, conf, type ):
path=[{"url": urlHandlers.UHConfModifListings.getURL(conf), "title":_("All listings")}]
itemType= type
title=""
WBannerModif.__init__(self, path, itemType, title)
class WParticipantsBannerModif(WBannerModif):
def __init__( self, conf ):
path=[{"url": urlHandlers.UHConfModifParticipants.getURL(conf), "title":_("Participants list")}]
itemType="Pending participants"
title=""
WBannerModif.__init__(self, path, itemType, title)
class WConfLogsBannerModif(WBannerModif):
def __init__( self, conf ):
path=[{"url": urlHandlers.UHConfModifLog.getURL(conf), "title":_("Logs")}]
itemType="Log item"
title=""
WBannerModif.__init__(self, path, itemType, title)
class WCategModifHeader(WTemplated):
def __init__(self, targetConf ):
self._conf = targetConf
def _getSingleCategHTML( self, categ, URLGen ):
return """%s"""%(URLGen( categ ), categ.getName())
def _getMultipleCategHTML( self, categList, URLGen ):
l = []
for categ in self._conf.getOwnerList():
l.append(""""""%(categ.getId(),\
categ.getName()))
return _("""""")%(URLGen(), "".join(l))
def getVars( self ):
vars = WTemplated.getVars( self )
#raise "%s"%(type(self._conf))
try:
ol = self._conf.getOwnerList()
except:
ol=self._conf
#raise "%s"%ol
URLGen = vars.get("categDisplayURLGen", urlHandlers.UHCategoryDisplay.getURL )
try:
if len(ol)>1:
vars["categ"] = self._getMultipleCategHTML(ol, URLGen)
else:
vars["categ"] = self._getSingleCategHTML( ol[0], URLGen)
vars["viewImageURL"] = Configuration.Config.getInstance().getSystemIconURL( "view" )
except:
vars["categ"] = self._getSingleCategHTML( ol, URLGen)
vars["viewImageURL"] = Configuration.Config.getInstance().getSystemIconURL( "view" )
return vars
class WCategoryModificationHeader(WTemplated):
def __init__( self, category ):
self._categ = category
def getVars( self ):
vars = WTemplated.getVars( self )
vars["confTitle"] = self._categ.getName()
vars["title"] = self._categ.getName()
vars["catDisplayURL"] = urlHandlers.UHCategoryDisplay.getURL(self._categ)
vars["catModifURL"]= urlHandlers.UHCategoryModification.getURL(self._categ)
vars["titleTabPixels"] = self.getTitleTabPixels()
#vars["intermediateVTabPixels"] = self.getIntermediateVTabPixels()
vars["eventCaption"]= "Category"
return vars
def getIntermediateVTabPixels( self ):
return 0
def getTitleTabPixels( self ):
return 260
class WConfModifHeader(WTemplated):
def __init__( self, conf, aw ):
self._conf = conf
self._aw = aw
def getVars( self ):
vars = WTemplated.getVars( self )
#raise "%s"%vars
try:
vars["creator"] = self._conf.getCreator().getFullName()
except:
vars["creator"] = ""
vars["imgGestionGrey"] = Configuration.Config.getInstance().getSystemIconURL( "gestionGrey" )
vars["confTitle"] = escape(self._conf.getTitle())
if self._conf.canModify( self._aw ):
URLGen = vars.get("confModifURLGen", \
urlHandlers.UHConferenceModification.getURL )
vars["confTitle"] = """%s"""%(quoteattr( str( URLGen( self._conf ) ) ), escape(self._conf.getTitle()) )
URLGen = vars.get( "confDisplayURLGen", urlHandlers.UHConferenceDisplay.getURL )
vars["confDisplayURL"] = URLGen( self._conf )
vars["titleTabPixels"] = WConferenceModifFrame(self._conf, self._aw).getTitleTabPixels()
try:
type = self._conf.getType()
except:
type = ""
if type == "simple_event":
type = "lecture"
vars["eventCaption"]=type.capitalize()#"Event"
return vars
class WSessionModifHeader(WTemplated):
def __init__( self, session, aw ):
self._session = session
self._aw = aw
def getHTML( self, params ):
conf = self._session.getConference()
confHTML = WConfModifHeader( conf, self._aw ).getHTML( params )
return "%s%s"%(confHTML, WTemplated.getHTML( self, params ) )
def getVars( self ):
vars = WTemplated.getVars( self )
vars["imgGestionGrey"] = Configuration.Config.getInstance().getSystemIconURL( "gestionGrey" )
vars["sessionTitle"] = escape(self._session.getTitle())
vars["sessionDisplayURL"] = vars["sessionDisplayURLGen"](self._session)
vars["sessionModificationURL"] = vars["sessionModifURLGen"](self._session)
return vars
class WBreakModifHeader(WTemplated):
def __init__( self, breakSlot, aw ):
self._break = breakSlot
self._aw = aw
def getHTML( self, params ):
return WTemplated.getHTML( self, params )
def getVars( self ):
vars = WTemplated.getVars( self )
vars["imgGestionGrey"] = Configuration.Config.getInstance().getSystemIconURL( "gestionGrey" )
vars["breakTitle"] = escape(self._break.getTitle())
return vars
class WContribModifHeader(WTemplated):
def __init__( self, contrib, aw):
self._contrib = contrib
self._aw = aw
def getHTML( self, params ):
conf = self._contrib.getConference()
session = self._contrib.getSession()
if session is not None:
HTML = WSessionModifHeader( session, self._aw ).getHTML( params )
else:
HTML = WConfModifHeader( conf, self._aw ).getHTML( params )
return "%s%s"%(HTML, WTemplated.getHTML( self, params ) )
def getVars( self ):
vars = WTemplated.getVars( self )
vars["imgGestionGrey"] = Configuration.Config.getInstance().getSystemIconURL( "gestionGrey" )
vars["title"] = escape(self._contrib.getTitle())
urlGen = vars.get( "contribDisplayURLGen", urlHandlers.UHContributionDisplay.getURL )
vars["contribDisplayURL"] = urlGen(self._contrib)
urlGen = vars.get( "contribModifURLGen", urlHandlers.UHContributionModification.getURL )
vars["contribModificationURL"] = urlGen(self._contrib)
return vars
class WContribModifTool(WTemplated):
def __init__( self, contrib ):
self._contrib = contrib
def getVars( self ):
vars = WTemplated.getVars( self )
vars["deleteIconURL"] = Configuration.Config.getInstance().getSystemIconURL("delete")
vars["moveIconURL"] = Configuration.Config.getInstance().getSystemIconURL("move")
vars["writeIconURL"] = Configuration.Config.getInstance().getSystemIconURL("write_minutes")
return vars
class WContributionDeletion(object):
def __init__( self, contribList ):
self._contribList = contribList
def getHTML( self, actionURL ):
l = []
for contrib in self._contribList:
l.append("""
%s
"""%contrib.getTitle())
msg = _("""
_("Are you sure that you want to DELETE the following contributions"):
%s
?
_("Note that the following changes will result from this deletion"):
_("If the contribution is linked to an abstract"):
_("The link between the abstract and the contribution will be deleted")
_("The status of the abstract will change to 'submitted'")
_("You'll lose the information about when and who accepted the abstract")
_("ALL the existing sub-contributions within the above contribution(s) will also be deleted")
""")%("".join(l))
wc = WConfirmation()
contribIdList = []
for contrib in self._contribList:
contribIdList.append( contrib.getId() )
return wc.getHTML( msg, actionURL, {"selectedCateg": contribIdList}, \
confirmButtonCaption="Yes", \
cancelButtonCaption="No" )
def delete( self ):
for contrib in self._contribList:
contrib.delete()
return "done"
class WContribModifSC(WTemplated):
def __init__( self, contrib ):
self._contrib = contrib
self._conf = self._contrib.getConference()
def getSubContItems(self,SCModifURL):
temp = []
scList = self._contrib.getSubContributionList()
for sc in scList:
id = sc.getId()
selbox = """"""
temp.append("""
"""%(mat.getId(), Config.getInstance().getSystemIconURL("material"), self._modifyURLGen( mat ), mat.getTitle() ) )
return "".join(l)
def _getSpecialMaterialItems( self ):
if not self._fr:
return ""
l = []
for factory in self._fr.getList():
if factory.canDelete( self._owner ):
icon = ""
if factory.getIconURL():
icon = """"""%factory.getIconURL()
mat = factory.get( self._owner )
l.append("""
"""%(style, item.getIcon())
def _getSectionItemsHTML( self, group ):
lg = []
for gItem in section.getItemList():
if not gItem.isEnabled():
continue
style = self._getStyleForItem(gItem, section)
lg.append("""
"""%(self._getCurrentIconForItem(tbItem,style),\
style, itemHTML))
vars["items"] = "".join(l)
return vars
class WStdSectionDrawer(WStdTBDrawer):
def __init__( self, item ):
self.section = item
def getVars( self ):
vars = WTemplated.getVars( self )
l = []
l.append(self._getTBItemCaption(self.section))
if self.section != None:
for tbItem in self.section.getItemList():
if not tbItem.isEnabled():
continue
itemHTML = ""
if tbItem.__class__ == WTBSeparator:
itemHTML = ""
else:
itemHTML = self._getTBItemHTML( tbItem )
style = self._getStyleForItem(tbItem, self.section)
l.append( """
%s
%s
"""%(self._getCurrentIconForItem(tbItem,style),\
style, itemHTML))
for subitem in tbItem.getItemList():
if not subitem.isEnabled():
continue
styleSubitem = self._getStyleForItem(subitem, self.section)
if subitem.isCurrent():
subitemHTML = self._getTBItemHTML( subitem )
l.append("""
%s
\
%s
"""%(styleSubitem,\
self._getCurrentIconForItem(subitem,styleSubitem),styleSubitem, subitemHTML))
else:
styleSubitem = "menuConfMiddleCell"
if self.section.isLastItem(tbItem) and tbItem.isLastItem(subitem):
styleSubitem = "menuConfBottomCell"
l.append( """
""" % gradientDiv)
self._tabsBars.append("".join(html))
return True
return False
def _getTabs( self):
self._tabsBars=[]
self._getTabsHTML(tabCtrl=self._tabCtrl, maxtabs=len(self._tabCtrl.getTabList())+1)
self._tabsBars.reverse()
return "".join(self._tabsBars)
def getHTML( self, body ):
self._body = body
return WTemplated.getHTML( self )
def getVars( self ):
vars = WTemplated.getVars( self )
vars["cs"] = len(self._tabCtrl.getTabList())+1
vars["body"] = self._body
vars["tabItems"] = self._getTabs()
return vars
#class WAbstractFilterCtrl( WTemplated ):
#
# def __init__(self, conf, filter, sorter):
# self._filter = filter
# self._conf = conf
# self._sorter = sorter
#
# def getVars( self ):
# vars = WTemplated.getVars(self)
# abMgr = self._conf.getAbstractMgr()
#
# trackFilter = "\n"
# for track in self._conf.getTrackList():
# selected = ""
# if track.getId() == self._filter["track"]:
# selected = "selected"
# trackFilter += "\n"%(track.getId(), selected, track.getTitle())
# vars["trackFilter"] = trackFilter
#
# typeFilter = "\n"
# for type in self._conf.getContribTypeList():
# selected = ""
# if type.getId() == self._filter["type"]:
# selected = "selected"
# typeFilter += "\n"%(type.getId(), selected, type)
# vars["typeFilter"] = typeFilter
#
# statusFilter = "\n"
# for name in StatusName().getNameList():
# selected = ""
# if name == self._filter["status"]:
# selected = "selected"
# statusFilter += "\n"%(name, selected, name)
# vars["statusFilter"] = statusFilter
#
# fDay = "\n"
# for i in range(1,32):
# selected = ""
# if self._filter["fromDate"] != None:
# if i == self._filter["fromDate"].day:
# selected = "selected"
# fDay += "\n"%(i, selected, i)
# vars["fDay"] = fDay
#
# fMonth = "\n"
# month = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"]
# for i in range(1,13):
# selected = ""
# if self._filter["fromDate"] != None:
# if i == self._filter["fromDate"].month:
# selected = "selected"
# fMonth += "\n"%(i, selected, month[i-1])
# vars["fMonth"] = fMonth
#
# fYear = "\n"
# for i in range(2000,2011):
# selected = ""
# if self._filter["fromDate"] != None:
# if i == self._filter["fromDate"].year:
# selected = "selected"
# fYear += "\n"%(i, selected, i)
# vars["fYear"] = fYear
#
#
#
# tDay = "\n"
# for i in range(1,32):
# selected = ""
# if self._filter["toDate"] != None:
# if i == self._filter["toDate"].day:
# selected = "selected"
# tDay += "\n"%(i, selected, i)
# vars["tDay"] = tDay
#
# tMonth = "\n"
# for i in range(1,13):
# selected = ""
# if self._filter["toDate"] != None:
# if i == self._filter["toDate"].month:
# selected = "selected"
# tMonth += "\n"%(i, selected, month[i-1])
# vars["tMonth"] = tMonth
#
# tYear = "\n"
# for i in range(2000,2011):
# selected = ""
# if self._filter["toDate"] != None:
# if i == self._filter["toDate"].year:
# selected = "selected"
# tYear += "\n"%(i, selected, i)
# vars["tYear"] = tYear
#
#
#
# #sortList = ["title", "type", "modification date"]
# selected = ""
# if self._sorter["field"] == "title":
# selected = "selected"
# sortBy = "\n"%selected
# selected = ""
# if self._sorter["field"] == "type":
# selected = "selected"
# sortBy += "\n"%selected
# selected = ""
# if self._sorter["field"] == "modification date":
# selected = "selected"
# sortBy += "\n"%selected
# selected = ""
# if self._sorter["field"] == "status":
# selected = "selected"
# sortBy += "\n"%selected
# selected = ""
#
# if self._sorter["direction"] == "desc":
# vars["ascChecked"] = ""
# vars["descChecked"] = "checked"
# else:
# vars["ascChecked"] = "checked"
# vars["descChecked"] = ""
#
# vars["sortBy"] = sortBy
#
#
# return vars
#
#class WSubTrackCreation( WTemplated ):
#
# def __init__( self, track ):
# self.__track = track
#
# def getVars( self ):
# vars = WTemplated.getVars(self)
# vars["title"], vars["description"] = "", ""
# vars["locator"] = self.__track.getLocator().getWebForm()
# return vars
#class WSetLogo( WTemplated ):
#
# def __init__( self, conference ):
# self.__conf = conference
#
# def getVars( self ):
# vars = WTemplated.getVars( self )
# vars["confTitle"] = self.__conf.getTitle()
#
# return vars
class WSelectionBox(WTemplated):
def getVars(self):
vars=WTemplated.getVars(self)
if not vars.has_key("description"):
vars["description"]=""
if not vars.has_key("options"):
vars["options"]=""
if not vars.has_key("table_width"):
vars["table_width"]=""
return vars
class WSelectionBoxAuthors:
def getHTML(self):
wc=WSelectionBox()
p={
"description": _("Please make your selection if you want to add the submitter/s directly to any of the following roles:"),\
"options": _(""" _("Primary author")
_("Co-author")
_("Speaker")
""")
}
return wc.getHTML(p)
class WMSelectionBoxAuthors:
def getHTML(self):
wc=WSelectionBox()
p={
"description": _("Please make your selection if you want to add the submitter/s directly to:"),\
"options": _(""" _("Speaker")
"""), \
"table_width": "180px" \
}
return wc.getHTML(p)
class WSelectionBoxSubmitter:
def getHTML(self):
wc=WSelectionBox()
p={
"description": _(""" _("Please check the box if you want to add them as submitters"):
_("Note"): _("If this person is not already a user they will be sent an email asking them to create an account. After their registration the user will automatically be given submission rights"). """),\
"options": _(""" _("Add as submitter")
""")
}
return wc.getHTML(p)
class WSelectionBoxConveners:
def getHTML(self):
wc=WSelectionBox()
p={
"description": _("Please make your selection if you want to add the result/s directly to the role of session Convener:"),\
"options": _(""" _("Add as convener")
""")
}
return wc.getHTML(p)
class WSelectionBoxConvToManagerCoordinator:
def getHTML(self):
wc=WSelectionBox()
p={
"description": _(""" _("Please check the box if you want to add them as managers/coordinators"):"""),\
"options": _(""" _("Add as session manager")
_("Add as session coordinator")
""")
}
return wc.getHTML(p)
class WSelectionBoxCloneLecture :
def getHTML(self):
wc=WSelectionBox()
p={
"description": _("Please check the boxes indicating which elements of the lecture you want to clone"),\
"options": _(""" _("Event details")
_("Attached materials")
_("Access and management privileges")
""")
}
return wc.getHTML(p)
class WUserSelection(WTemplated):
def __init__( self, searchURL, multi=True, addTo=0, forceWithoutExtAuth=False):
self._title = _("Search for users")
self._searchURL = searchURL
self._forceWithoutExtAuth = forceWithoutExtAuth
self._multi = multi # for multiple selection
#addTo=0: do not show any selection box.
#addTo=1: show selection box to add submitter as primary author, coauthor or speaker.
#addTo=2: show selection box to add primary author, coauthor or speaker as submitter.
#addTo=3: show selection box to add session managers as session conveners
#addTo=4: show selection box to add submitter as speaker. This is just for meetings
#addTo=5: show selection box to add submitter and/or manager rights for convener.
self._addTo=addTo
def _performSearch( self, criteria, exact=0 ):
ah = user.AvatarHolder()
res = ah.match(criteria, exact=exact, forceWithoutExtAuth=self._forceWithoutExtAuth)
return res
def setTitle( self, newTitle ):
self._title = newTitle.strip()
def _getPassingParams( self, params ):
l = []
for p in params.keys():
if p in ["firstname", "surname", "organisation", "email", "groupname","exact","searchExt", 'selectedPrincipals']:
continue
l.append( """\n"""%(p, \
params[p] ) )
return "\n".join( l )
def _filterParams( self, params ):
pars = copy( params )
self._action = "show"
if pars.has_key("action"):
self._action = pars["action"].strip()
del pars["action"]
return pars
def _create( self, params ):
pass
#a = user.Avatar()
#a.setName( params["firstname"] )
#a.setSurName( params["surname"] )
#a.setEmail( params["email"] )
#a.setOrganisation( params["organisation"] )
#user.AvatarHolder().add( a )
def _normaliseListParam( self, param ):
if not isinstance(param, list):
return [ param ]
return param
def getHTML( self, params ):
self._cancelURL = params.get("addURL","")
pars = self._filterParams( params )
self._passingParams = self._getPassingParams( pars )
self._msg = ""
if self._action == _("create"):
try:
self._create( pars )
except UserError,e:
self._msg = str(e)#"User not created. The email address is already used."
self._action = _("search")
return WTemplated.getHTML( self, pars )
def getVars( self ):
vars = WTemplated.getVars( self )
vars["usericon"]=quoteattr(str(Config.getInstance().getSystemIconURL("user" )))
vars["firstName"] = vars.get("firstname", "")
vars["surName"] = vars.get("surname", "")
vars["email"] = vars.get("email", "")
vars["organisation"] = vars.get("organisation", "")
if "WPtitle" not in vars or vars["WPtitle"].strip() == "":
vars["WPtitle"] = self._title
vars["params"] = self._passingParams
vars["addURL"] = urlHandlers.UHUserSearchCreateExternalUser.getURL()
#vars["createURL"] = urlHandlers.UHUserSearchCreateExternalUser.getURL()
vars["postURL"] = self._searchURL
vars["cancelURL"] = self._cancelURL
vars["searchResultsTable"] = ""
res=[]
if self._action == _("search").strip():
criteria = { "name": vars["firstName"], \
"surName": vars["surName"], \
"email" : vars["email"], \
"organisation": vars["organisation"] \
}
if vars.has_key("groupname"):
criteria["groupname"] = vars["groupname"]
exact = 0
if vars.get("exact",0) != 0:
exact = 1
res = self._performSearch( criteria, exact=exact )
vars["searchResultsTable"] = WUserSearchResultsTable(self._multi).getHTML( res )
vars["msg"] = ""
if self._msg:
vars["msg"] = """
%s
"""%self._msg
sb=""
if res!=[]:
if self._addTo==1:
sb=WSelectionBoxAuthors().getHTML()
elif self._addTo==2:
sb=WSelectionBoxSubmitter().getHTML()
elif self._addTo==3:
sb=WSelectionBoxConveners().getHTML()
elif self._addTo==4:
sb=WMSelectionBoxAuthors().getHTML()
elif self._addTo==5:
sb=WSelectionBoxConvToManagerCoordinator().getHTML()
vars["selectionBox"]=sb
vars["searchOptions"]=""
authenticators = Config.getInstance().getAuthenticatorList()
searchList = self._normaliseListParam(vars.get("searchExt",""))
for auth in authenticators:
if auth.lower() != "local":
selected = ""
if auth in searchList:
selected = "checked"
vars["searchOptions"]+= _(""" _("search %s database") """) % (auth, selected, auth.upper())
selected = ""
if vars.get("exact","") != "":
selected = "checked"
vars["searchOptions"]+= _(""" _("exact match") """) % selected
return vars
class WAuthorSearch(WUserSelection):
def __init__(self, conf, searchURL, multi=True, addTo=0, forceWithoutExtAuth=False):
_title = _("Search Users and Authors")
WUserSelection.__init__(self, searchURL, multi, addTo, forceWithoutExtAuth=forceWithoutExtAuth)
self._conf = conf
def _performSearch( self, criteria, exact=0 ):
#this should go in the PrincipalHolder match method
ah = user.AvatarHolder()
resUsers = ah.match(criteria, exact=exact, forceWithoutExtAuth=self._forceWithoutExtAuth)
auths = self._conf.getAuthorIndex()
resAuths = auths.match(criteria, exact=exact)
#crear una lista y devolver el resultado
l = []
emails = []
for usr in resUsers:
l.append(usr)
emails.append(usr.getEmail())
for author in resAuths :
if author.getEmail() not in emails:
l.append(author)
return l
class WPrincipalSelection(WUserSelection):
def _performSearch( self, criteria, exact=0 ):
#this should go in the PrincipalHolder match method
_title = _("Search for users and groups")
ah = user.AvatarHolder()
resUsers = ah.match(criteria,exact=exact,forceWithoutExtAuth=self._forceWithoutExtAuth)
resGroups = [ group for group in user.GroupHolder().match(criteria, forceWithoutExtAuth=self._forceWithoutExtAuth) if not group.isObsolete()]
l = []
for item in resUsers:
l.append(item)
for item in resGroups:
l.append(item)
return l
def getVars( self ):
vars=WUserSelection.getVars(self)
vars["usericon"]=quoteattr(str(Config.getInstance().getSystemIconURL("user" )))
vars["groupicon"]=quoteattr(str(Config.getInstance().getSystemIconURL("group" )))
vars["groupNICEicon"]=quoteattr(str(Config.getInstance().getSystemIconURL("groupNICE" )))
vars["groupname"] = vars.get("groupname", "")
return vars
class WComplexSelection(WUserSelection):
def __init__(self, target, searchAction, addTo = 0, forceWithoutExtAuth=False):
_title = _("Search for users")
WUserSelection.__init__(self, searchAction, addTo = addTo, forceWithoutExtAuth=forceWithoutExtAuth)
try:
self._conf = target.getConference()
except:
self._conf = None
self._target = target
def _performSearch( self, criteria, exact=0 ):
#this should go in the PrincipalHolder match method
ah = user.AvatarHolder()
resUsers = ah.match(criteria, exact=exact, forceWithoutExtAuth=self._forceWithoutExtAuth)
try:
auths = self._conf.getAuthorIndex()
resAuths = auths.match(criteria, exact=exact)
except:
resAuths = []
l = []
emails = []
for usr in resUsers:
l.append(usr)
emails.append(usr.getEmail())
for author in resAuths :
if author.getEmail() not in emails:
l.append(author)
return l
def getVars(self):
vars = WUserSelection.getVars( self )
vars["usericon"]=quoteattr(str(Config.getInstance().getSystemIconURL("user" )))
return vars
class WCategoryComplexSelection(WComplexSelection):
def __init__(self, category, searchAction, forceWithoutExtAuth=False):
WComplexSelection.__init__(self, None, searchAction,forceWithoutExtAuth=forceWithoutExtAuth)
self._category = category
def _performSearch( self, criteria, exact=0 ):
#this should go in the PrincipalHolder match method
ah = user.AvatarHolder()
resUsers = ah.match(criteria, exact=exact, forceWithoutExtAuth=self._forceWithoutExtAuth)
return resUsers
class WNewPerson(WTemplated):
def getVars( self ):
vars = WTemplated.getVars( self )
options = [" ", _("Mr."), _("Ms."), _("Dr."), _("Prof.")]
titles = []
titleValue = vars.get("titleValue", " ")
for o in options :
selected = ""
if titleValue == o :
selected = "selected"
text = """"""%(o, selected, o)
titles.append(text)
vars["titles"] = """
""".join(titles)
if vars.get("disabledTitle", False) :
vars["titles"] = """%s"""%(titleValue,titleValue)
else :
vars["titles"] = """
"""%vars["titles"]
if vars.get("disabledSurName", False) :
vars["surName"] = """%s"""%(vars["surNameValue"],vars["surNameValue"])
else :
vars["surName"] = """"""%vars["surNameValue"]
if vars.get("disabledName", False) :
vars["name"] = """%s"""%(vars["nameValue"],vars["nameValue"])
else :
vars["name"] = """"""%vars["nameValue"]
if vars.get("disabledAffiliation", False) :
vars["affiliation"] = """%s"""%(vars["affiliationValue"],vars["affiliationValue"])
else :
vars["affiliation"] = """"""%vars["affiliationValue"]
if vars.get("disabledEmail", False) :
vars["email"] = """%s"""%(vars["emailValue"],vars["emailValue"])
else :
js=""
if not vars.get("disabledRole", True) and vars["roleDescription"] == "Submitter":
js="""onkeyup="if (!this.form.submissionControl.checked || this.value.length != 0) {this.form.warning_email.type='hidden';}else{this.form.warning_email.type='text';}">
"""%(vars["emailValue"],js)
if vars.get("disabledAddress", False) :
vars["address"] = """%s"""%(vars["addressValue"],vars["addressValue"])
else :
vars["address"] = """"""%vars["emailValue"]
if vars.get("disabledPhone", False) :
vars["phone"] = """%s"""%(vars["phoneValue"],vars["phoneValue"])
else :
vars["phone"] = """"""%vars["phoneValue"]
if vars.get("disabledPhone", False) :
vars["phone"] = """%s"""%(vars["phoneValue"],vars["phoneValue"])
else :
vars["phone"] = """"""%vars["phoneValue"]
if vars.get("disabledFax", False) :
vars["fax"] = """%s"""%(vars["faxValue"],vars["faxValue"])
else :
vars["fax"] = """"""%vars["faxValue"]
if vars.get("disabledRole", True) :
vars["role"] = ""
else :
vars["role"] = """
"""%vars["noticeValue"]
if vars.get("msg","")!="":
vars["msg"]= _("""
_("You must enter a valid email address.")
""")
#raise vars["msg"]
else: vars["msg"]=""
return vars
class WAddPersonModule(WTemplated):
def __addBasketPeople(self, peopleList):
user = self._rh._getUser()
# add extra options if the user is logged in
if user:
basket = user.getPersonalInfo().getBasket().getUsers()
peopleList += """"""
for userId in basket:
peopleList += """"""%(userId,basket[userId].getStraightFullName())
return peopleList
# just add nothing if the user is not logged in
else:
return ""
def __init__(self,personType, displayName=""):
self._personType = personType
self._displayName = displayName
def getVars( self ):
vars = WTemplated.getVars( self )
if self._personType is None or self._personType == "" :
raise MaKaCError( _("'personType' must be set to use the Add Person Module"))
return
if self._displayName != "":
vars["personName"] = self._displayName
else:
vars["personName"] = string.capwords("%s"%self._personType)
# Add people from the users basket
vars["personOptions"] = self.__addBasketPeople("")
vars["personOptions"] += vars["%sOptions"%self._personType]
vars["personChosen"] = "%sChosen"%self._personType
vars["personDefined"] = vars["%sDefined"%self._personType]
if vars["personOptions"] == """""":
vars["disabledAdd"] = "disabled"
else:
vars["disabledAdd"] = ""
vars["personType"] = self._personType
if vars.get("submission",None) is not None :
vars["submissionButtons"] = _("""
""")
else :
vars["submissionButtons"] = ""
return vars
class WAccountAlreadyActivated(WTemplated):
def __init__(self, av):
self._av = av
def getVars( self ):
vars = WTemplated.getVars( self )
return vars
class WAccountActivated(WTemplated):
def __init__(self, av):
self._av = av
def getVars( self ):
vars = WTemplated.getVars( self )
return vars
class WAccountDisabled(WTemplated):
def __init__(self, av):
self._av = av
def getVars( self ):
vars = WTemplated.getVars( self )
return vars
class WUnactivatedAccount(WTemplated):
def __init__(self, av):
self._av = av
def getVars( self ):
vars = WTemplated.getVars( self )
minfo = info.HelperMaKaCInfo.getMaKaCInfoInstance()
vars["moderated"]=minfo.getModerateAccountCreation()
return vars
class WAbstractModIntCommentEdit(WTemplated):
def __init__(self,comment):
self._comment=comment
def getVars(self):
vars=WTemplated.getVars(self)
vars["content"]=self.htmlText(self._comment.getContent())
return vars
class WAbstractModNewIntComment(WTemplated):
def __init__(self,aw,abstract):
self._aw=aw
self._abstract=abstract
def getVars(self):
vars=WTemplated.getVars(self)
return vars
class WSessionModifComm(WTemplated):
def __init__(self, aw,session):
self._aw = aw
self._session = session
self._conf = session.getConference()
def _getHTML(self,editCommentsURLGen):
try:
comment =self._session.getComments()
if comment=="":
comment= _("No Session Comment Entered")
except:
comment = _("No Session Comment Entered")
self._session.setComments("")
modifButton=""
if self._conf.canModify(self._aw):
modifButton = _("""
""")%quoteattr(str(editCommentsURLGen(self._session)))
return ( _("""
_("Session comment")
%s
%s
""")%(comment,modifButton))
def getVars(self):
vars=WTemplated.getVars(self)
vars["comment"]=self._getHTML(vars["editCommentsURLGen"])
return vars
class WSessionModifCommEdit(WTemplated):
def __init__(self,comment):
self._comment=comment
def getVars(self):
vars=WTemplated.getVars(self)
vars["comment"]=self.htmlText(self._comment)
return vars
class WAbstractModIntComments(WTemplated):
def __init__(self,aw,abstract):
self._aw=aw
self._abstract=abstract
def _getCommentsHTML(self,commentEditURLGen,commentRemURLGen):
res=[]
commentList = self._abstract.getIntCommentList()
for c in commentList:
mailtoSubject="[Indico] Abstract %s: %s"%(self._abstract.getId(), self._abstract.getTitle())
mailtoURL=URL("mailto:%s"%c.getResponsible().getEmail())
mailtoURL.addParam("subject", mailtoSubject)
responsible="""%s"""%(quoteattr(str(mailtoURL)),self.htmlText(c.getResponsible().getFullName()))
date=self.htmlText(c.getCreationDate().strftime("%Y-%m-%d %H:%M"))
buttonMod,buttonRem="",""
if self._aw.getUser()==c.getResponsible():
buttonMod= _("""
""")%quoteattr(str(commentEditURLGen(c)))
buttonRem= _("""
""")%quoteattr(str(commentRemURLGen(c)))
res.append("""
%s on %s
%s
%s
%s
"""%(responsible,date,c.getContent(),buttonMod,buttonRem))
if res == []:
res.append( _("""
--_("no internal comments")--
"""))
return "".join(res)
def getVars(self):
vars=WTemplated.getVars(self)
vars["comments"]=self._getCommentsHTML(vars["commentEditURLGen"],vars["commentRemURLGen"])
vars["newCommentURL"]=quoteattr(str(vars["newCommentURL"]))
return vars
class WAbstractModMarkAsDup(WTemplated):
def __init__(self,abstract):
self._abstract=abstract
def _getErrorHTML(self,msg):
if msg.strip()=="":
return ""
return """
%s
"""%self.htmlText(msg)
def getVars(self):
vars=WTemplated.getVars(self)
vars["duplicateURL"]=quoteattr(str(vars["duplicateURL"]))
vars["cancelURL"]=quoteattr(str(vars["cancelURL"]))
vars["error"]=self._getErrorHTML(vars.get("errorMsg",""))
return vars
class WAbstractModUnMarkAsDup(WTemplated):
def __init__(self,abstract):
self._abstract=abstract
def getVars(self):
vars=WTemplated.getVars(self)
vars["unduplicateURL"]=quoteattr(str(vars["unduplicateURL"]))
vars["cancelURL"]=quoteattr(str(vars["cancelURL"]))
return vars
class WConfModAbstractEditData(WTemplated):
def __init__(self,conference,abstractData):
self._ad=abstractData
self._conf=conference
#def _getTitleItemsHTML(self,selected=""):
# titles=["", "Mr.", "Mrs.", "Miss.", "Prof.", "Dr."]
# res=[]
# for t in titles:
# sel=""
# if t==selected:
# sel=" selected"
# res.append(""""""%(quoteattr(t),sel,self.htmlText(t)))
# return "".join(res)
def _getContribTypeItemsHTML(self):
res=[ _("""""")]
for cType in self._conf.getContribTypeList():
selected=""
if cType.getId()==self._ad.getContribTypeId():
selected=" selected"
res.append(""""""%(quoteattr(cType.getId()),selected,self.htmlText(cType.getName())))
return "".join(res)
def _getPrimaryAuthorsHTML(self):
res=[]
for author in self._ad.getPrimaryAuthorList():
spk_checked=""
if author.isSpeaker():
spk_checked=" checked"
tmp= _("""
""") % ( mandatoryText, caption, maxLengthJS, id, nbRows, maxLengthText, value )
return html
def getVars(self):
vars=WTemplated.getVars(self)
vars["postURL"]=quoteattr(str(vars["postURL"]))
vars["title"]=quoteattr(str(self._ad.getTitle()))
vars["additionalFields"]=self._getAdditionalFieldsHTML(self._ad)
vars["contribTypeItems"]=self._getContribTypeItemsHTML()
vars["primaryAuthors"]=self._getPrimaryAuthorsHTML()
vars["coAuthors"]=self._getCoAuthorsHTML()
return vars
class WScheduleAddContributions(WTemplated):
def __init__(self,selectList,targetDay=None):
self._contribList=selectList
self._targetDay=targetDay
def _getContribListHTML(self):
res=[]
contribList=filters.SimpleFilter(None,contribFilters.SortingCriteria(["number"])).apply(self._contribList)
for contrib in self._contribList:
typeCaption=""
if contrib.getType() is not None:
typeCaption=contrib.getType().getName()
l=[]
for spk in contrib.getSpeakerList():
l.append("""%s"""%(self.htmlText(spk.getFullName())))
spksCaption=" ".join(l)
res.append("""
%s
[%s]
%s
%s
"""%(quoteattr(str(contrib.getId())),
self.htmlText(contrib.getId()),
self.htmlText(typeCaption),
self.htmlText(contrib.getTitle()),
spksCaption))
return "".join(res)
def getVars(self):
vars=WTemplated.getVars(self)
vars["contribs"]="".join(self._getContribListHTML())
vars["targetDay"]=""
if self._targetDay is not None:
vars["targetDay"]=""""""%(quoteattr(str(self._targetDay.strftime("%Y-%m-%d"))))
return vars
class WSchEditContrib(WTemplated):
def __init__(self,contrib):
self._contrib=contrib
def getVars(self):
vars=WTemplated.getVars(self)
vars["postURL"]=quoteattr(str(vars["postURL"]))
vars["title"]=self.htmlText(self._contrib.getTitle())
confTZ = self._contrib.getConference().getTimezone()
sDate=self._contrib.getStartDate().astimezone(timezone(confTZ))
vars["sYear"]=quoteattr(str(sDate.year))
vars["sMonth"]=quoteattr(str(sDate.month))
vars["sDay"]=quoteattr(str(sDate.day))
vars["sHour"]=quoteattr(str(sDate.hour))
vars["sMinute"]=quoteattr(str(sDate.minute))
vars["durHours"]=quoteattr(str(int(self._contrib.getDuration().seconds/3600)))
vars["durMins"]=quoteattr(str(int((self._contrib.getDuration().seconds%3600)/60)))
defaultDefinePlace=defaultDefineRoom=""
defaultInheritPlace=defaultInheritRoom="checked"
locationName,locationAddress,roomName="","",""
if self._contrib.getOwnLocation():
defaultDefinePlace,defaultInheritPlace="checked",""
locationName=self._contrib.getLocation().getName()
locationAddress=self._contrib.getLocation().getAddress()
if self._contrib.getOwnRoom():
defaultDefineRoom,defaultInheritRoom="checked",""
roomName=self._contrib.getRoom().getName()
vars["defaultInheritPlace"]=defaultInheritPlace
vars["defaultDefinePlace"]=defaultDefinePlace
vars["confPlace"]=""
confLocation=self._contrib.getOwner().getLocation()
if self._contrib.isScheduled():
confLocation=self._contrib.getSchEntry().getSchedule().getOwner().getLocation()
if confLocation:
vars["confPlace"]=confLocation.getName()
vars["locationName"]=locationName
vars["locationAddress"]=locationAddress
vars["defaultInheritRoom"]=defaultInheritRoom
vars["defaultDefineRoom"]=defaultDefineRoom
vars["confRoom"]=""
confRoom=self._contrib.getOwner().getRoom()
if self._contrib.isScheduled():
confRoom=self._contrib.getSchEntry().getSchedule().getOwner().getRoom()
if confRoom:
vars["confRoom"]=confRoom.getName()
vars["roomName"]=quoteattr(roomName)
vars["parentType"]="conference"
if self._contrib.getSession() is not None:
vars["parentType"]="session"
if self._contrib.isScheduled():
vars["parentType"]="session slot"
vars["boardNumber"]=quoteattr(str(self._contrib.getBoardNumber()))
vars["autoUpdate"] = ""
return vars
class WConfModParticipEdit(WTemplated):
def __init__(self,title="",part=None):
self._part=part
self._ctitle=title
def getVars(self):
vars=WTemplated.getVars(self)
vars["postURL"]=quoteattr(str(vars["postURL"]))
vars["caption"]=self.htmlText(self._ctitle)
title,firstName,familyName="","",""
affiliation,email,address,phone,fax="","","","",""
if self._part is not None:
title=self._part.getTitle()
firstName=self._part.getFirstName()
familyName=self._part.getFamilyName()
affiliation=self._part.getAffiliation()
email=self._part.getEmail()
address=self._part.getAddress()
phone=self._part.getPhone()
fax=self._part.getFax()
vars["titles"]=TitlesRegistry().getSelectItemsHTML(title)
vars["surName"]=quoteattr(familyName)
vars["name"]=quoteattr(firstName)
vars["affiliation"]=quoteattr(affiliation)
vars["email"]=quoteattr(email)
vars["address"]=address
vars["phone"]=quoteattr(phone)
vars["fax"]=quoteattr(fax)
if not vars.has_key("addToManagersList"):
vars["addToManagersList"]=""
return vars
class WSessionModEditDataCode(WTemplated):
def __init__(self):
pass
def getVars( self ):
vars=WTemplated.getVars(self)
vars["code"]=quoteattr(str(vars.get("code","")))
return vars
class WSessionModEditDataType(WTemplated):
def __init__(self):
pass
def getVars( self ):
vars=WTemplated.getVars(self)
l=[]
currentTTType=vars.get("tt_type",conference.SlotSchTypeFactory.getDefaultId())
for i in conference.SlotSchTypeFactory.getIdList():
sel=""
if i==currentTTType:
sel=" selected"
l.append(""""""%(quoteattr(str(i)),
sel,self.htmlText(i)))
vars["tt_types"]="".join(l)
return vars
class WSessionModEditDataColors(WTemplated):
def __init__(self):
pass
def getVars( self ):
vars=WTemplated.getVars(self)
return vars
class WSessionModEditData(WTemplated):
def __init__(self,targetConf,aw,pageTitle="",targetDay=None):
self._conf=targetConf
self._title=pageTitle
self._targetDay=targetDay
self._aw = aw
def _getErrorHTML(self,l):
if len(l)>0:
return """
"""%("convener",convener.getId(),convener.getFullName())
html.append(text)
vars["definedConveners"] = """
""".join(html)
if vars.get("locationAction","")=="define":
vars["defaultInheritPlace"]=""
vars["defaultDefinePlace"]="checked"
vars["confPlace"]=""
confLocation=self._conf.getConference().getLocation()
if confLocation:
vars["confPlace"]=self.htmlText(confLocation.getName())
vars["locationName"]=quoteattr(str(vars.get("locationName","")))
vars["locationAddress"]=self.htmlText(vars.get("locationAddress",""))
vars["defaultInheritRoom"]=""
vars["defaultDefineRoom"]=""
vars["defaultExistRoom"]=""
if vars.get("roomAction","")=="inherit":
vars["defaultInheritRoom"]="checked"
roomName = ""
elif vars.get("roomAction","")=="define":
vars["defaultDefineRoom"]="checked"
roomName = vars.get( "bookedRoomName" ) or vars.get("roomName","")
elif vars.get("roomAction","")=="exist":
vars["defaultExistRoom"]="checked"
roomName = vars.get("exists", "") or vars.get("roomName","")
else:
vars["defaultInheritRoom"]="checked"
roomName = ""
vars["confRoom"]=""
rx=[]
roomsexist = self._conf.getRoomList()
roomsexist.sort()
for room in roomsexist:
sel=""
if room==roomName:
sel="selected=\"selected\""
rx.append(""""""%(quoteattr(str(room)),
sel,self.htmlText(room)))
vars ["roomsexist"] = "".join(rx)
confRoom=self._conf.getConference().getRoom()
if confRoom:
vars["confRoom"]=self.htmlText(confRoom.getName())
vars["roomName"]=quoteattr(str(roomName))
vars["autoUpdate"]=""
if not self._conf.getEnableSessionSlots():
vars["disabled"] = "disabled"
else:
vars["disabled"] = ""
if self._title.find("Ed") != -1 and self._conf.getEnableSessionSlots():
vars["adjustSlots"]= _(""" _("Also move timetable entries")""")
else:
vars["adjustSlots"]=""""""
import MaKaC.webinterface.webFactoryRegistry as webFactoryRegistry
wr = webFactoryRegistry.WebFactoryRegistry()
wf = wr.getFactory(self._conf)
if wf != None:
type = wf.getId()
else:
type = "conference"
if type == "conference":
vars["Type"]=WSessionModEditDataType().getHTML(vars)
vars["Colors"]=WSessionModEditDataColors().getHTML(vars)
vars["code"]=WSessionModEditDataCode().getHTML(vars)
else:
vars["Type"]=""
vars["Colors"]=""
vars["code"]=""
return vars
#--------------------------------------------------------------------------------------
class WConfModMoveContribsToSessionConfirmation(WTemplated):
def __init__(self,conf,contribIdList=[],targetSession=None):
self._conf=conf
self._contribIdList=contribIdList
self._targetSession=targetSession
def _getWarningsHTML(self):
wl=[]
for id in self._contribIdList:
contrib=self._conf.getContributionById(id)
if contrib is None:
continue
spkList=[]
for spk in contrib.getSpeakerList():
spkList.append(self.htmlText(spk.getFullName()))
spkCaption=""
if len(spkList)>0:
spkCaption=" by %s"%"; ".join(spkList)
if (contrib.getSession() is not None and \
contrib.getSession()!=self._targetSession):
scheduled=""
if contrib.isScheduled():
scheduled= _(""" _("and scheduled") (%s)""")%self.htmlText(contrib.getStartDate().strftime("%Y-%b-%d %H:%M"))
wl.append( _("""
%s-%s%s: is _("already in session") %s%s
""")%(self.htmlText(contrib.getId()),
self.htmlText(contrib.getTitle()),
spkCaption,
self.htmlText(contrib.getSession().getTitle()),
scheduled))
if (contrib.getSession() is None and \
self._targetSession is not None and \
contrib.isScheduled()):
wl.append( _("""
"%"".join(wl)
def getVars(self):
vars=WTemplated.getVars(self)
vars["postURL"]=quoteattr(str(vars["postURL"]))
vars["systemIconWarning"]=Config.getInstance().getSystemIconURL("warning")
vars["contribIdList"]=", ".join(self._contribIdList)
vars["targetSession"]="--none--"
if self._targetSession is not None:
vars["targetSession"]=self.htmlText("%s"%self._targetSession.getTitle())
vars["warnings"]=self._getWarningsHTML()
vars["targetSessionId"]=quoteattr("--none--")
if self._targetSession is not None:
vars["targetSessionId"]=quoteattr(str(self._targetSession.getId()))
l=[]
for id in self._contribIdList:
l.append(""""""%quoteattr(str(id)))
vars["contributions"]="\n".join(l)
return vars
class WConfTBDrawer:
def __init__(self,tb):
self._tb=tb
def getHTML(self):
if self._tb is None:
return ""
res=[]
for item in self._tb.getItemList():
if not item.isEnabled():
continue
res.append("""
"""%(quoteattr(str(item.getActionURL())),
quoteattr(str(item.getIcon())),
quoteattr(item.getCaption())))
if res != []:
return """
%s
"""%("".join(res))
return ""
class WErrorMessage :
def getHTML( self, vars ):
if vars.get("errorMsg", None) is None :
return ""
if type(vars["errorMsg"]) != list:
vars["errorMsg"]=[vars["errorMsg"]]
for i in range(0,len(vars["errorMsg"])) :
vars["errorMsg"][i] = """"""+vars["errorMsg"][i]+""""""
errorMsg = """
""".join(vars["errorMsg"])
html = """
%s
"""%errorMsg
return html
class WInfoMessage :
def getHTML( self, vars ):
if vars.get("infoMsg", None) is None :
return ""
if type(vars["infoMsg"]) != list:
vars["infoMsg"]=[vars["infoMsg"]]
for i in range(0,len(vars["infoMsg"])) :
vars["infoMsg"][i] = """"""+vars["infoMsg"][i]+""""""
infoMsg = """
""".join(vars["infoMsg"])
html = """
%s
"""%infoMsg
return html
class WConfTickerTapeDrawer(WTemplated):
def __init__(self,conf, tz=None):
self._conf=conf
self._tz = tz
dm = displayMgr.ConfDisplayMgrRegistery().getDisplayMgr(self._conf, False)
self._tickerTape = dm.getTickerTape()
def getNowHappeningHTML( self, params=None ):
if not self._tickerTape.isActive():
return None
html = WTemplated.getHTML( self, params )
if html == "":
return None
return html
def getSimpleText( self ):
if not self._tickerTape.isSimpleTextEnabled() or \
self._tickerTape.getText().strip() == "":
return None
return self._tickerTape.getText()
def getVars(self):
vars = WTemplated.getVars( self )
vars["nowHappeningArray"] = None
if self._tickerTape.isNowHappeningEnabled():
vars["nowHappeningArray"] = self._getNowHappening()
return vars
def _getNowHappening( self ):
# This will contain a string formated for use in the template
# javascripts
nowHappeningArray = None
# currently happening:
n = nowutc()
entries = self._conf.getSchedule().getEntriesOnDate(n)
entryCaptions = []
for entry in entries:
if isinstance(entry, schedule.LinkedTimeSchEntry) and \
isinstance(entry.getOwner(), conference.SessionSlot):
ss=entry.getOwner()
ssEntries=ss.getSchedule().getEntriesOnDate(n)
if isinstance(ss.getSchedule(), conference.PosterSlotSchedule):
ssEntries=ss.getSchedule().getEntries()
for ssEntry in ssEntries:
title=ssEntry.getTitle()
if isinstance(ssEntry.getOwner(), conference.Contribution):
title="""%s"""%( \
quoteattr(str(urlHandlers.UHContributionDisplay.getURL(ssEntry.getOwner()))), title)
else:
title="""%s"""%( \
quoteattr(str(urlHandlers.UHSessionDisplay.getURL(ssEntry.getOwner()))), title)
if ssEntry.getOwnRoom() is not None:
if self._conf.getRoom() is None or \
ssEntry.getOwnRoom().getName().strip().lower() != self._conf.getRoom().getName().strip().lower():
title="%s (%s)"%(title, ssEntry.getOwnRoom().getName().strip())
entryCaptions.append("%s %s-%s" %(title,
entry.getAdjustedStartDate(self._tz).strftime("%H:%M"), \
entry.getAdjustedEndDate(self._tz).strftime("%H:%M")))
else:
title=entry.getTitle()
if isinstance(entry.getOwner(), conference.Contribution):
title="""%s"""%(quoteattr(str(urlHandlers.UHContributionDisplay.getURL(entry.getOwner()))), title)
else:
url=urlHandlers.UHConferenceTimeTable.getURL(self._conf)
url.addParam("showDate",entry.getStartDate().strftime("%d-%B-%Y"))
title="""%s"""%(quoteattr(str(url)), title)
if entry.getOwnRoom() is not None:
if self._conf.getRoom() is None or \
entry.getOwnRoom().getName().strip().lower() != self._conf.getRoom().getName().strip().lower():
title="%s (%s)"%(title, entry.getOwnRoom().getName().strip())
entryCaptions.append("%s %s-%s" %(title,
entry.getAdjustedStartDate(self._tz).strftime("%H:%M"), \
entry.getAdjustedEndDate(self._tz).strftime("%H:%M")))
if entryCaptions!=[]:
nowHappeningArray = """['%s']""" %("', '".join(entryCaptions))
return nowHappeningArray
class WSubmitMaterialLink(WTemplated):
def __init__(self, filenb, availMF):
self._filenb=filenb
self._availMF=availMF
def getVars(self):
vars=WTemplated.getVars(self)
vars["itemNumber"]=self._filenb
vars["materialTypeSelectFieldName"]="LinkType%s"%self._filenb
vars["materialTypeInputFieldName"]="LinkTypeFT%s"%self._filenb
vars["urlFieldName"]="link%s"%self._filenb
l=[ _("""""")]
selMatType=vars.get("LinkType%s" % self._filenb,"")
for mf in self._availMF:
try:
id = mf.getId()
title = mf.getTitle()
except:
id = mf
title = mf.capitalize()
selected=""
if id==selMatType:
selected=" selected"
l.append(""""""%(\
quoteattr(str(id)),selected,
self.htmlText(title)))
vars["matTypeItems"]="".join(l)
if vars.get("LinkTypeFT%s" % self._filenb, "") != "":
vars["materialTypeInputFieldValue"] = vars.get("LinkTypeFT%s" % self._filenb, "")
else:
vars["materialTypeInputFieldValue"] = ""
if vars.get("link%s" % self._filenb, "") != "":
vars["linkValue"] = vars.get("link%s" % self._filenb, "")
else:
vars["linkValue"] = ""
return vars
class WSubmitMaterialFile(WTemplated):
def __init__(self, filenb, availMF):
self._filenb=filenb
self._availMF=availMF
def getVars(self):
vars=WTemplated.getVars(self)
vars["itemNumber"]=self._filenb
vars["materialTypeSelectFieldName"]="FileType%s"%self._filenb
vars["materialTypeInputFieldName"]="FileTypeFT%s"%self._filenb
vars["fileFieldName"]="file%s"%self._filenb
l=[ _("""""")]
selMatType=vars.get("FileType%s" % self._filenb,"")
for mf in self._availMF:
try:
id = mf.getId()
title = mf.getTitle()
except:
id = mf
title = mf.capitalize()
selected=""
if id==selMatType:
selected=" selected"
l.append(""""""%(\
quoteattr(str(id)),selected,
self.htmlText(title)))
vars["matTypeItems"]="".join(l)
if vars.get("FileTypeFT%s" % self._filenb, "") != "":
vars["materialTypeInputFieldValue"] = vars.get("FileTypeFT%s" % self._filenb, "")
else:
vars["materialTypeInputFieldValue"] = ""
if vars.get("FileNewName%s" % self._filenb, "") != "":
vars["fileName"] = vars.get("FileNewName%s" % self._filenb)
else:
vars["fileName"] = ""
vars["fileNewName"] = "FileNewName%s" % self._filenb
return vars
class WMaterialListFile(WTemplated):
def __init__(self, target):
self._target=target
def getVars(self):
vars=WTemplated.getVars(self)
try:
name=self._target.getFileName()
except:
name=self._target.getURL()
vars["fileName"]=name
if self._target.getName()!="" and name!=self._target.getName():
vars["fileName"]+=" (%s)" % self._target.getName()
vars["fileActions"] = ""
if isinstance(self._target, conference.Link):
if vars["resourcesLinkModifHandler"]:
vars["fileActions"] += """"""%(vars["resourcesLinkModifHandler"].getURL(self._target), Config.getInstance().getSystemIconURL("file_edit"))
if vars["resourcesLinkProtectHandler"]:
vars["fileActions"] += """"""%(vars["resourcesLinkProtectHandler"].getURL(self._target), Config.getInstance().getSystemIconURL("file_protect"))
elif isinstance(self._target, conference.LocalFile):
if vars["resourcesFileModifHandler"]:
vars["fileActions"] += """"""%(vars["resourcesFileModifHandler"].getURL(self._target), Config.getInstance().getSystemIconURL("file_edit"))
if vars["resourcesFileProtectHandler"]:
vars["fileActions"] += """"""%(vars["resourcesFileProtectHandler"].getURL(self._target), Config.getInstance().getSystemIconURL("file_protect"))
vars["deleteIconURL"]=Configuration.Config.getInstance().getSystemIconURL("smallDelete")
vars["delName"]="delete-%s-%s"% (self._target.getOwner().getId(),self._target.getId())
try:
vars["fileInfo"]="[%s bytes - %s]" % (self._target.getSize(),self._target.getCreationDate().strftime("%d.%m.%Y %H:%M:%S"))
except:
vars["fileInfo"]="[link]"
if self._target.isProtected():
vars["fileActions"] += """""" % Config.getInstance().getSystemIconURL("protected")
if isinstance(self._target, conference.Link):
vars["fileAccessURL"]=quoteattr(str(self._target.getURL()))
else:
vars["fileAccessURL"]=quoteattr(str(urlHandlers.UHFileAccess.getURL(self._target)))
return vars
class WMaterialListItem(WTemplated):
def __init__(self, target, returnURL=""):
self._target=target
self._returnURL = returnURL.strip('"')
def getVars(self):
vars=WTemplated.getVars(self)
deleteURL = None
mf = None
from MaKaC.webinterface.materialFactories import ConfMFRegistry,SessionMFRegistry,ContribMFRegistry
if isinstance(self._target.getOwner(),conference.Conference):
mf=ConfMFRegistry().get(self._target)
deleteURL = urlHandlers.UHConferenceRemoveMaterials.getURL(self._target)
elif isinstance(self._target.getOwner(),conference.Session):
mf=SessionMFRegistry().get(self._target)
deleteURL = urlHandlers.UHSessionRemoveMaterials.getURL(self._target)
elif isinstance(self._target.getOwner(),conference.Contribution):
mf=ContribMFRegistry().get(self._target)
contrib=self._target.getOwner()
deleteURL = urlHandlers.UHContributionRemoveMaterials.getURL(self._target)
elif isinstance(self._target.getOwner(),conference.SubContribution):
mf=ContribMFRegistry().get(self._target)
deleteURL = urlHandlers.UHSubContributionRemoveMaterials.getURL(self._target)
elif isinstance(self._target.getOwner(),conference.Category):
deleteURL = urlHandlers.UHCategoryRemoveMaterial.getURL(self._target)
if deleteURL:
deleteURL.addParam("returnURL",self._returnURL)
vars["materialName"] = self._target.getTitle()
vars["materialActions"] = ""
vars["materialActions"] += """""" % (str(deleteURL),Config.getInstance().getSystemIconURL("smallDelete"))
if vars["materialModifHandler"]:
vars["materialActions"] += """""" % (urlHandlers.UHMaterialModification.getURL(self._target),Config.getInstance().getSystemIconURL("file_edit"))
if vars["materialProtectHandler"]:
vars["materialActions"] += """""" % (vars["materialProtectHandler"].getURL(self._target),Config.getInstance().getSystemIconURL("file_protect"))
if self._target.isProtected():
vars["materialActions"] += """""" % Config.getInstance().getSystemIconURL("protected")
vars["fileList"]=""
for resource in self._target.getResourceList():
vars["fileList"] += WMaterialListFile(resource).getHTML(vars)
if mf is None:
vars["materialIcon"]=quoteattr(str(Config.getInstance().getSystemIconURL("material")))
else:
vars["materialIcon"]=quoteattr(str(mf.getIconURL()))
return vars
class WShowExistingMaterial(WTemplated):
def __init__(self,target, mode='display'):
"""
mode should be 'display' or 'management'
"""
self._target=target
self._mode = mode
def getVars(self):
vars=WTemplated.getVars(self)
# yes, this may look a bit redundant, but materialRegistry isn't
# bound to a particular target
materialRegistry = self._target.getMaterialRegistry()
vars["materialList"] = materialRegistry.getMaterialList(self._target)
vars["materialModifHandler"] = vars.get("materialModifHandler", None)
vars["materialProtectHandler"] = vars.get("materialProtectHandler", None)
vars["resourcesFileModifHandler"] = vars.get("resourcesFileModifHandler", None)
vars["resourcesFileProtectHandler"] = vars.get("resourcesFileProtectHandler", None)
vars["resourcesLinkModifHandler"] = vars.get("resourcesLinkModifHandler", None)
vars["resourcesLinkProtectHandler"] = vars.get("resourcesLinkProtectHandler", None)
vars['mode'] = self._mode
return vars
class WAddNewMaterial(WTemplated):
def __init__(self,target,availMF):
self._target=target
self._availMF=availMF
def _getErrorHTML(self,errorList):
if len(errorList)==0:
return ""
return """
%s
"""%(" ".join(errorList))
def _getTargetName(self):
if isinstance(self._target, conference.Contribution):
return "Contribution"
elif isinstance(self._target, conference.SubContribution):
return "Subcontribution"
elif isinstance(self._target, conference.Conference):
return "Event"
return ""
def getVars(self):
vars=WTemplated.getVars(self)
nbFiles=int(vars.get("nbFiles",1))
nbLinks=int(vars.get("nbLinks",1))
vars["targetName"]=self._getTargetName()
vars["targetId"]=self.htmlText(self._target.getId())
vars["targetTitle"]=self.htmlText(self._target.getTitle())
vars["selectNumberOfFiles"] = ""
for i in range(1,10):
if i == nbFiles:
vars["selectNumberOfFiles"] += "
"""%(system, rnsystems[system]["name"] ) )
return "".join(html)
def getVars(self):
vars = WTemplated.getVars(self)
if self._type == "event":
vars["deleteURL"]=quoteattr(str(urlHandlers.UHConfModifReportNumberRemove.getURL(self._target)))
vars["addURL"]=quoteattr(str(urlHandlers.UHConfModifReportNumberEdit.getURL(self._target)))
elif self._type == "contribution":
vars["deleteURL"]=quoteattr(str(urlHandlers.UHContributionReportNumberRemove.getURL(self._target)))
vars["addURL"]=quoteattr(str(urlHandlers.UHContributionReportNumberEdit.getURL(self._target)))
else:
vars["deleteURL"]=quoteattr(str(urlHandlers.UHSubContributionReportNumberRemove.getURL(self._target)))
vars["addURL"]=quoteattr(str(urlHandlers.UHSubContributionReportNumberEdit.getURL(self._target)))
vars["items"]=self._getCurrentItems()
vars["repTypesSelectItems"]=self._getSystems()
return vars
class WModifReportNumberEdit(WTemplated):
def __init__(self, target, rns, type="event"):
self._target=target
self._rnSystem=rns
self._type=type
def getVars(self):
vars=WTemplated.getVars(self)
vars["reportNumber"]=""
vars["reportNumberSystem"]=self._rnSystem
name=self._rnSystem
if self._rnSystem in Config.getInstance().getReportNumberSystems().keys():
name=Config.getInstance().getReportNumberSystems()[self._rnSystem]["name"]
vars["system"]=name
if self._type == "event":
vars["postURL"]=quoteattr(str(urlHandlers.UHConfModifReportNumberPerformEdit.getURL(self._target)))
elif self._type == "contribution":
vars["postURL"]=quoteattr(str(urlHandlers.UHContributionReportNumberPerformEdit.getURL(self._target)))
else:
vars["postURL"]=quoteattr(str(urlHandlers.UHSubContributionReportNumberPerformEdit.getURL(self._target)))
return vars
# ============================================================================
# === ROOM BOOKING RELATED ===================================================
# ============================================================================
# 1. Freestanding
# 2. In the context of an event
from MaKaC.rb_reservation import ReservationBase, Collision, RepeatabilityEnum
from MaKaC.rb_factory import Factory
from MaKaC.rb_tools import iterdays
from calendar import day_name
from MaKaC.rb_location import Location, CrossLocationFactory
class Bar:
"""
Keeps data necessary for graphical bar on calendar.
"""
PREBOOKED, PRECONCURRENT, UNAVAILABLE, CANDIDATE, PRECONFLICT, CONFLICT = xrange( 0, 6 )
# I know this names are not wisely choosed; it's due to unexpected additions
# without refactoring
# UNAVAILABLE : represents confirmed reservation (bright-red)
# CANDIDATE: represents new reservation (green)
# CONFLICT: overlap between candidate and confirmed resv. (dark red)
# PREBOOKED: represents pre-reservation (yellow)
# PRECONFLICT: represents conflict with pre-reservation (orange)
# PRECONCURRENT: conflicting pre-reservations
def __init__( self, c, barType ):
self.startDT = c.startDT
self.endDT = c.endDT
self.forReservation = c.withReservation
self.type = barType
def __cmp__( self, obj ):
return cmp( self.type, obj.type )
class RoomBars:
room = None
bars = []
def __init__( self, room, bars ):
self.room = room
self.bars = bars
def __cmp__( self, obj ):
return cmp( self.room, obj.room )
# ============================================================================
# == FREESTANDING ==== (Room Booking Related) ================================
# ============================================================================
class WRoomBookingWelcome( WTemplated ):
def __init__(self):
self.__adminList = AdminList.getInstance()
def getVars( self ):
vars = WTemplated.getVars( self )
return vars
class WRoomBookingRoomSelectList( WTemplated ):
def __init__( self, rh ):
self._rh = rh
def getVars( self ):
vars = WTemplated.getVars( self )
vars['roomList'] = self._rh._roomList
vars['locationRoom'] = self._rh._locationRoom
return vars
class WRoomBookingRoomSelectList4SubEvents( WTemplated ):
def __init__( self, rh ):
self._rh = rh
def getVars( self ):
vars = WTemplated.getVars( self )
vars['roomList'] = self._rh._roomList
vars['locationRoom'] = self._rh._locationRoom
return vars
# ============================================================================
# == EVENT CONTEXT ==== (Room Booking Related) ===============================
# ============================================================================
# 0. Choosing an "event" (conference / session / contribution)...
class WRoomBookingChooseEvent( WTemplated ):
def __init__( self, rh ):
self._rh = rh
def getVars( self ):
vars = WTemplated.getVars( self )
vars["conference"] = self._rh._conf
vars["contributions"] = list( [ c for c in self._rh._conf.getContributionList() if c.getStartDate() ] )
return vars
# 1. Searching
class WRoomBookingSearch4Rooms( WTemplated ):
def __init__( self, rh, standalone = False ):
self._standalone = standalone
self._rh = rh
def getVars( self ):
vars = WTemplated.getVars( self )
websession = self._rh._websession
vars["standalone"] = self._standalone
vars["Location"] = Location
vars["rooms"] = self._rh._rooms
vars["possibleEquipment"] = self._rh._equipment
vars["forNewBooking"] = self._rh._forNewBooking
vars["eventRoomName"] = self._rh._eventRoomName
vars["preview"] = False
vars["startDT"] = websession.getVar( "defaultStartDT" )
vars["endDT"] = websession.getVar( "defaultEndDT" )
vars["startT"] = websession.getVar( "defaultStartDT" ).time().strftime( "%H:%M" )
vars["endT"] = websession.getVar( "defaultEndDT" ).time().strftime( "%H:%M" )
vars["repeatability"] = websession.getVar( "defaultRepeatability" )
if self._standalone:
# URLs for standalone room booking
vars["roomBookingRoomListURL"] = urlHandlers.UHRoomBookingRoomList.getURL( None )
vars["detailsUH"] = urlHandlers.UHRoomBookingRoomDetails
vars["bookingFormUH"] = urlHandlers.UHRoomBookingBookingForm
else:
# URLs for room booking in the event context
vars["roomBookingRoomListURL"] = urlHandlers.UHConfModifRoomBookingRoomList.getURL( self._rh._conf )
vars["detailsUH"] = urlHandlers.UHConfModifRoomBookingRoomDetails
vars["bookingFormUH"] = urlHandlers.UHConfModifRoomBookingBookingForm
return vars
class WRoomBookingSearch4Bookings( WTemplated ):
def __init__( self, rh ):
self._rh = rh
def getVars( self ):
vars = WTemplated.getVars( self )
vars["today"] = datetime.now()
vars["weekLater"] = datetime.now() + timedelta( 7 )
vars["Location"] = Location
vars["rooms"] = self._rh._rooms
vars["repeatability"] = None
vars["roomBookingBookingListURL"] = urlHandlers.UHRoomBookingBookingList.getURL( None )
return vars
class WRoomBookingRoomList( WTemplated ):
def __init__( self, rh, standalone = False ):
self._rh = rh
self._standalone = standalone
self._title = None
try: self._title = self._rh._title;
except: pass
def getVars( self ):
vars=WTemplated.getVars( self )
vars["rooms"] = self._rh._rooms
#vars["roomPhotoUH"] = urlHandlers.UHSendRoomPhoto
vars["standalone"] = self._standalone
vars["title"] = self._title
if self._standalone:
vars["detailsUH"] = urlHandlers.UHRoomBookingRoomDetails
vars["bookingFormUH"] = urlHandlers.UHRoomBookingBookingForm
else:
vars["conference"] = self._rh._conf
vars["detailsUH"] = urlHandlers.UHConfModifRoomBookingRoomDetails
vars["bookingFormUH"] = urlHandlers.UHConfModifRoomBookingBookingForm
return vars
class WRoomBookingList( WTemplated ):
def __init__( self, rh, standalone = False ):
self._standalone = standalone
self._rh = rh
if not standalone:
self._conf = rh._conf
def getVars( self ):
vars=WTemplated.getVars( self )
vars["reservations"] = self._rh._resvs
vars["standalone"] = self._standalone
dm = datetime.now() - timedelta( 1 )
vars["yesterday"] = dm #datetime( dm.year, dm.month, dm.day, 0, 0, 1 )
if self._standalone:
vars["bookingDetailsUH"] = urlHandlers.UHRoomBookingBookingDetails
else:
vars["conference"] = self._conf
vars["bookingDetailsUH"] = urlHandlers.UHConfModifRoomBookingDetails
return vars
class WRoomBookingBookingList( WTemplated ): # Standalone version
def __init__( self, rh ):
self._rh = rh
self._title = None
try: self._title = self._rh._title;
except: pass
def _isOn(self, boolVal):
if boolVal:
return "on"
else:
return ""
def getVars( self ):
vars = WTemplated.getVars( self )
rh = self._rh
vars["reservations"] = rh._resvs
#vars["smallPhotoUH"] = urlHandlers.UHSendRoomPhoto
vars["bookingDetailsUH"] = urlHandlers.UHRoomBookingBookingDetails
vars["withPhoto"] = False
vars["title"] = self._title
vars["showRejectAllButton"] = rh._showRejectAllButton
vars["prebookingsRejected"] = rh._prebookingsRejected
vars["subtitle"] = rh._subtitle
vars["description"] = rh._description
yesterday = datetime.now() - timedelta( 1 )
vars["yesterday"] = yesterday #datetime( dm.year, dm.month, dm.day, 0, 0, 1 )
overload = ( len( rh._resvs ) > 300 ) or self._rh._overload
ed = None
sd = rh._resvEx.startDT.date()
if rh._resvEx.endDT:
ed = rh._resvEx.endDT.date()
# autoCriteria - dates are calculated based on the next reservation
if rh._autoCriteria:
tmp = ReservationBase.findSoonest( rh._resvs, afterDT = yesterday )
if tmp:
tmp = tmp.getNextRepeating( afterDT = yesterday )
if tmp and tmp.startDT.date() > sd:
sd = tmp.startDT
if not ed:
# one month of time span
ed = sd + timedelta( 30 )
# set the calendar dates as calculated
calendarStartDT = datetime( sd.year, sd.month, sd.day, 0, 0, 1 )
calendarEndDT = datetime( ed.year, ed.month, ed.day, 23, 59 )
from MaKaC.rb_tools import formatDate
if calendarStartDT.date() == calendarEndDT.date():
vars["periodName"] = "day"
vars["verbosePeriod"] = formatDate(calendarStartDT)
else:
vars["periodName"] = "period"
vars["verbosePeriod"] = "%s -> %s" % ( formatDate(calendarStartDT), formatDate(calendarEndDT) )
vars["startD"] = formatDate(calendarStartDT)
vars["endD"] = formatDate(calendarEndDT)
# Data for previous/next URLs (it's about periods, not paging)
newParams4Previous = rh._reqParams.copy()
newParams4Next = rh._reqParams.copy()
if rh._reqParams.has_key( 'autoCriteria' ):
del newParams4Previous['autoCriteria']
del newParams4Next['autoCriteria']
if rh._reqParams.has_key( 'day' ):
del newParams4Previous['day']
del newParams4Next['day']
startD = calendarStartDT.date()
endD = calendarEndDT.date()
if endD != startD:
period = endD - startD
prevStartD = startD - period
prevEndD = startD - timedelta(1)
nextStartD = endD + timedelta(1)
nextEndD = endD + period
else:
prevStartD = prevEndD = startD - timedelta(1)
nextStartD = nextEndD = endD + timedelta(1)
newParams4Previous['sDay'] = prevStartD.day
newParams4Previous['sMonth'] = prevStartD.month
newParams4Previous['sYear'] = prevStartD.year
newParams4Previous['eDay'] = prevEndD.day
newParams4Previous['eMonth'] = prevEndD.month
newParams4Previous['eYear'] = prevEndD.year
newParams4Next['sDay'] = nextStartD.day
newParams4Next['sMonth'] = nextStartD.month
newParams4Next['sYear'] = nextStartD.year
newParams4Next['eDay'] = nextEndD.day
newParams4Next['eMonth'] = nextEndD.month
newParams4Next['eYear'] = nextEndD.year
#Number of the RoomBookingBookingListPrevNext templates used in the code.
#Variable increments when new template is put.
vars["prevNextNo"] = 0
vars["withPrevNext"] = True
vars["prevURL"] = urlHandlers.UHRoomBookingBookingList.getURL( newParams = newParams4Previous )
vars["nextURL"] = urlHandlers.UHRoomBookingBookingList.getURL( newParams = newParams4Next )
# empty days are shown for "User bookings" and "User pre-bookings"
# and for the calendar as well
# but not for the booking search
showEmptyDays = ( self._rh._ofMyRooms or \
(not self._rh._ofMyRooms and not self._rh._onlyMy) ) and \
not self._rh._search
showEmptyRooms = showEmptyDays
# Calendar related stuff ==========
bars = []
collisionsOfResvs = []
# there's at least one reservation
if len( rh._resvs ) > 0 and not overload:
# Prepare the list of Collisions
# (collision is just a helper object, it's not the best notion here)
for r in rh._resvs:
for p in r.splitToPeriods(endDT=calendarEndDT, startDT=calendarStartDT):
if p.startDT >= calendarStartDT and p.endDT <= calendarEndDT:
collisionsOfResvs.append( Collision( ( p.startDT, p.endDT ), r ) )
if len( collisionsOfResvs ) > 500:
overload = True
else:
# Translate collisions to Bars
for c in collisionsOfResvs:
if c.withReservation.isConfirmed:
bars.append( Bar( c, Bar.UNAVAILABLE ) )
else:
bars.append( Bar( c, Bar.PREBOOKED ) )
bars = barsList2Dictionary( bars )
bars = addOverlappingPrebookings( bars )
bars = sortBarsByImportance( bars, calendarStartDT, calendarEndDT )
rooms = []
for r in rh._resvs:
rooms.append(r.room)
#rooms = {}
#for r in rh._resvs:
# rooms[r.room] = None
#rooms = rooms.keys()
#CrossLocationQueries.getRooms( location = self.location )
if not self._rh._onlyMy:
rooms = self._rh._rooms
bars = introduceRooms( rooms, bars, calendarStartDT, calendarEndDT, showEmptyDays = showEmptyDays, showEmptyRooms = showEmptyRooms )
vars["Bar"] = Bar
self.__sortUsingCriterion(rh._order, collisionsOfResvs)
# we want to display every room, with or without reservation
elif not overload:
# initialize collision bars
bars = {}
bars = sortBarsByImportance( bars, calendarStartDT, calendarEndDT )
# insert rooms
if not self._rh._onlyMy:
rooms = self._rh._rooms
else:
rooms = []
bars = introduceRooms( rooms, bars, calendarStartDT, calendarEndDT, showEmptyDays = showEmptyDays, showEmptyRooms = showEmptyRooms )
vars["unrolledReservations"] = collisionsOfResvs
vars["bars"] = bars
vars["calendarStartDT"] = calendarStartDT
vars["calendarEndDT"] = calendarEndDT
vars["iterdays"] = iterdays
vars['overload'] = overload
vars["manyRooms"] = not self._rh._rooms or len(self._rh._rooms) > 1
if not vars["manyRooms"]:
vars["room"] = self._rh._rooms[0]
vars["withConflicts"] = False
bars = []
for c in collisionsOfResvs:
if c.withReservation.isConfirmed:
bars.append( Bar( c, Bar.UNAVAILABLE ) )
else:
bars.append( Bar( c, Bar.PREBOOKED ) )
bars = barsList2Dictionary( bars )
bars = addOverlappingPrebookings( bars )
bars = sortBarsByImportance( bars, calendarStartDT, calendarEndDT )
vars["bars"] = bars
return vars
def __sortUsingCriterion(self, order, uresvs):
if order == "" or order =="room":
# standard sorting order (by room, and then date)
uresvs.sort(lambda r1,r2: cmp(r1.withReservation.room.name,r2.withReservation.room.name))
else:
if order == 'date':
uresvs.sort(lambda r1, r2: cmp(r1.startDT, r2.startDT))
elif order == 'reason':
uresvs.sort(lambda r1, r2: cmp(r1.withReservation.reason.lower(), r2.withReservation.reason.lower()))
elif order == 'for':
uresvs.sort(lambda r1, r2: cmp(r1.withReservation.bookedForName.lower(), r2.withReservation.bookedForName.lower()))
elif order == 'hours':
uresvs.sort(lambda r1, r2: cmp(r1.startDT.time(), r2.startDT.time()))
# 3. Details of...
def barsList2Dictionary( bars ):
"""
Converts:
list of bars => dictionary of bars, key = datetime, value = list of bars
"""
h = {}
for bar in bars:
d = bar.startDT.date()
if h.has_key( d ):
h[d].append( bar )
else:
h[d] = [bar]
return h
def addOverlappingPrebookings( bars ):
"""
Adds bars representing overlapping pre-bookings.
Returns new bars dictionary.
"""
# For each day
for dt in bars.keys():
dayBars = bars[dt]
# For each (prebooked) bar i
for i in xrange( 0, len( dayBars ) ):
bar = dayBars[i]
if bar.type == Bar.PREBOOKED:
# For each (prebooked) bar j
for j in xrange( i+1, len( dayBars ) ):
collCand = dayBars[j]
if collCand.type == Bar.PREBOOKED:
# If there is an overlap, add PRECONCURRENT bar
over = overlap( bar.startDT, bar.endDT, collCand.startDT, collCand.endDT )
if over and bar.forReservation.room == collCand.forReservation.room:
collision = Collision( over, collCand.forReservation )
dayBars.append( Bar( collision, Bar.PRECONCURRENT ) )
bars[dt] = dayBars # With added concurrent prebooking bars
return bars
def sortBarsByImportance( bars, calendarStartDT, calendarEndDT ):
"""
Moves conflict bars to the end of the list,
so they will be drawn last and therefore be visible.
Returns sorted bars.
"""
for dt in bars.keys():
dayBars = bars[dt]
dayBars.sort()
bars[dt] = dayBars
for day in iterdays( calendarStartDT, calendarEndDT ):
if not bars.has_key( day.date() ):
bars[day.date()] = []
return bars
def getRoomBarsList( rooms ):
roomBarsList = []
if rooms is None:
rooms=[]
for room in rooms:
roomBarsList.append( RoomBars( room, [] ) )
roomBarsList.sort()
return roomBarsList
def introduceRooms( rooms, dayBarsDic, calendarStartDT, calendarEndDT, showEmptyDays=True, showEmptyRooms=True ):
# Input:
# dayBarsDic is a dictionary date => [bar1, bar2, bar3, ...]
#
# Output:
# newDayBarsDic is a dictionary date => [roomBars1, roomBars2, roomBars3, ...],
# where roomBars is object JSON:{ room: RoomBase, bars: [bar1, bar2, bar3, ...] }
import copy
cleanRoomBarsList = getRoomBarsList( rooms )
newDayBarsDic = {}
s = ""
for day in iterdays( calendarStartDT, calendarEndDT ):
dayBars = dayBarsDic[day.date()]
roomBarsDic = {}
for bar in dayBars:
room = bar.forReservation.room
if not roomBarsDic.has_key( room ):
roomBarsDic[room] = []
# Bars order should be preserved
roomBarsDic[room].append( bar )
if showEmptyRooms:
dayRoomBarsList = getRoomBarsList( rooms ) #copy.copy( cleanRoomBarsList )
for roomBar in dayRoomBarsList:
roomBar.bars = roomBarsDic.get( roomBar.room, [] )
else:
dayRoomBarsList = []
for room in roomBarsDic.keys():
dayRoomBarsList.append(RoomBars(room,roomBarsDic[room]))
if showEmptyDays or len(dayBars) > 0:
newDayBarsDic[day.date()] = dayRoomBarsList
return newDayBarsDic
class WRoomBookingRoomStats( WTemplated ):
def __init__( self, rh, standalone = False ):
self._rh = rh
self._standalone = standalone
def getVars( self ):
vars = WTemplated.getVars( self )
vars["room"] = self._rh._room
vars["standalone"] = self._standalone
vars["period"] = self._rh._period
vars["kpiAverageOccupation"] = str( int( round( self._rh._kpiAverageOccupation * 100 ) ) ) + "%"
# Bookings
vars["kbiTotalBookings"] = self._rh._totalBookings
# Next 9 KPIs
vars["stats"] = self._rh._booking_stats
vars["statsURL"] = urlHandlers.UHRoomBookingRoomStats.getURL()
return vars
class WRoomBookingRoomDetails( WTemplated ):
def __init__( self, rh, standalone = False ):
self._rh = rh
self._standalone = standalone
def getVars( self ):
vars = WTemplated.getVars( self )
vars["room"] = self._rh._room
goodFactory = Location.parse( self._rh._room.locationName ).factory
attributes = goodFactory.getCustomAttributesManager().getAttributes( location = self._rh._room.locationName )
vars["attrs"] = {}
for attribute in attributes:
if not attribute.get("hidden",False) or self._rh._getUser().isAdmin():
vars["attrs"][attribute['name']] = self._rh._room.customAtts.get(attribute['name'],"")
if attribute['name'] == 'notification email' :
vars["attrs"][attribute['name']] = vars["attrs"][attribute['name']].replace(',', ', ')
vars["config"] = Config.getInstance()
#vars["roomPhoto"] = urlHandlers.UHSendRoomPhoto.getURL( self._rh._room.photoId, small = False )
vars["standalone"] = self._standalone
vars["actionSucceeded"] = self._rh._afterActionSucceeded
vars["deletionFailed"] = self._rh._afterDeletionFailed
vars["roomStatsUH"] = urlHandlers.UHRoomBookingRoomStats
if self._standalone:
vars["bookingFormUH"] = urlHandlers.UHRoomBookingBookingForm
vars["modifyRoomUH"] = urlHandlers.UHRoomBookingRoomForm
vars["deleteRoomUH"] = urlHandlers.UHRoomBookingDeleteRoom
vars["bookingDetailsUH"] = urlHandlers.UHRoomBookingBookingDetails
else:
vars["bookingDetailsUH"] = urlHandlers.UHConfModifRoomBookingDetails
vars["conference"] = self._rh._conf
vars["bookingFormUH"] = urlHandlers.UHConfModifRoomBookingBookingForm
vars["modifyRoomUH"] = urlHandlers.UHRoomBookingRoomForm
vars["deleteRoomUH"] = urlHandlers.UHRoomBookingDeleteRoom
# Calendar range: 3 months
if self._rh._searchingStartDT and self._rh._searchingEndDT:
sd = self._rh._searchingStartDT
calendarStartDT = datetime( sd.year, sd.month, sd.day, 0, 0, 1 )
ed = self._rh._searchingEndDT
calendarEndDT = datetime( ed.year, ed.month, ed.day, 23, 59 )
else:
now = datetime.now()
calendarStartDT = datetime( now.year, now.month, now.day, 0, 0, 1 )
calendarEndDT = calendarStartDT + timedelta( 3 * 31, 50, 0, 0, 59, 23 )
# Example resv. to ask for other reservations
resvEx = CrossLocationFactory.newReservation( location = self._rh._room.locationName )
resvEx.startDT = calendarStartDT
resvEx.endDT = calendarEndDT
resvEx.repeatability = RepeatabilityEnum.daily
resvEx.room = self._rh._room
resvEx.isConfirmed = None # to include not also confirmed
# Bars: Existing reservations
collisionsOfResvs = resvEx.getCollisions()
bars = []
for c in collisionsOfResvs:
if c.withReservation.isConfirmed:
bars.append( Bar( c, Bar.UNAVAILABLE ) )
else:
bars.append( Bar( c, Bar.PREBOOKED ) )
bars = barsList2Dictionary( bars )
bars = addOverlappingPrebookings( bars )
bars = sortBarsByImportance( bars, calendarStartDT, calendarEndDT )
# Set owner for all
if not self._standalone:
for dt in bars.iterkeys():
for bar in bars[dt]:
bar.forReservation.setOwner( self._rh._conf )
vars["calendarStartDT"] = calendarStartDT
vars["calendarEndDT"] = calendarEndDT
vars["bars"] = bars
vars["iterdays"] = iterdays
vars["day_name"] = day_name
vars["Bar"] = Bar
vars["withConflicts"] = False
return vars
class WRoomBookingDetails( WTemplated ):
def __init__( self, rh, standalone = False ):
self._rh = rh
self._resv = rh._resv
self._standalone = standalone
def getVars( self ):
vars=WTemplated.getVars( self )
vars["standalone"] = self._standalone
vars["reservation"] = self._resv
vars["config"] = Config.getInstance()
#vars["smallPhotoUH"] = urlHandlers.UHSendRoomPhoto
#vars["roomPhotoUH"] = urlHandlers.UHSendRoomPhoto
vars["actionSucceeded"] = self._rh._afterActionSucceeded
if self._rh._afterActionSucceeded:
vars["title"] = self._rh._title
vars["description"] = self._rh._description
if self._standalone:
vars["roomDetailsUH"] = urlHandlers.UHRoomBookingRoomDetails
else:
vars["roomDetailsUH"] = urlHandlers.UHConfModifRoomBookingRoomDetails
vars["bookMessage"] = "Book"
if not self._resv.isConfirmed:
vars["bookMessage"] = "PRE-Book"
return vars
# 4. Booking Form
class WRoomBookingBookingForm( WTemplated ):
def __init__( self, rh, standalone = False ):
self._rh = rh
self._candResv = rh._candResv
self._standalone = standalone
def getVars( self ):
vars = WTemplated.getVars( self )
vars["standalone"] = self._standalone
vars["config"] = Config.getInstance()
if self._standalone:
vars["conf"] = None
vars["saveBookingUH"] = urlHandlers.UHRoomBookingSaveBooking
vars["roomDetailsUH"] = urlHandlers.UHRoomBookingRoomDetails
vars["calendarPreviewUH"] = urlHandlers.UHRoomBookingBookingForm
else:
vars["conf"] = self._rh._conf
vars["saveBookingUH"] = urlHandlers.UHConfModifRoomBookingSaveBooking
vars["roomDetailsUH"] = urlHandlers.UHConfModifRoomBookingRoomDetails
vars["calendarPreviewUH"] = urlHandlers.UHConfModifRoomBookingBookingForm
vars["candResv"] = self._candResv
vars["startDT"] = self._candResv.startDT
vars["endDT"] = self._candResv.endDT
vars["startT"] = '%02d:%02d' % (self._candResv.startDT.hour, self._candResv.startDT.minute )
vars["endT"] = '%02d:%02d' % (self._candResv.endDT.hour, self._candResv.endDT.minute )
vars["showErrors"] = self._rh._showErrors
vars["errors"] = self._rh._errors
vars["thereAreConflicts"] = self._rh._thereAreConflicts
vars["skipConflicting"] = self._rh._skipConflicting
if self._rh._formMode == FormMode.MODIF:
vars["allowPast"] = "true"
else:
vars["allowPast"] = "false"
vars["formMode"] = self._rh._formMode
vars["FormMode"] = FormMode
# [Book] or [PRE-Book] ?
bookingMessage = "Book"
room = self._candResv.room
user = self._rh._getUser()
if room.canPrebook( user ) and not room.canBook( user ):
bookingMessage = "PRE-Book"
vars["bookingMessage"] = bookingMessage
if self._rh._formMode != FormMode.MODIF:
bText = bookingMessage
else:
bText = "Save"
vars["roomBookingRoomCalendar"] = WRoomBookingRoomCalendar( self._rh, self._standalone, buttonText=bText).getHTML( {} )
return vars
class WRoomBookingConfirmBooking( WRoomBookingBookingForm ):
def getVars( self ):
vars = WTemplated.getVars( self )
vars["candResv"] = self._candResv
vars["standalone"] = self._standalone
vars["formMode"] = self._rh._formMode
vars["FormMode"] = FormMode
vars["collisions"] = self._rh._collisions
bookingMessage = "Book"
room = self._candResv.room
user = self._rh._getUser()
if room.canPrebook( user ) and not room.canBook( user ):
bookingMessage = "PRE-Book"
vars["bookingMessage"] = bookingMessage
if self._standalone:
vars["conf"] = None
vars["saveBookingUH"] = urlHandlers.UHRoomBookingSaveBooking
vars["roomDetailsUH"] = urlHandlers.UHRoomBookingRoomDetails
else:
vars["conf"] = self._rh._conf
vars["saveBookingUH"] = urlHandlers.UHConfModifRoomBookingSaveBooking
vars["roomDetailsUH"] = urlHandlers.UHConfModifRoomBookingRoomDetails
return vars
class WRoomBookingRoomForm( WTemplated ):
def __init__( self, rh ):
self._rh = rh
def getVars( self ):
vars = WTemplated.getVars( self )
candRoom = self._rh._candRoom
goodFactory = Location.parse( candRoom.locationName ).factory
vars["Location"] = Location
vars["room"] = candRoom
vars["largePhotoPath"] = None
vars["smallPhotoPath"] = None
vars["config"] = Config.getInstance()
vars["possibleEquipment"] = goodFactory.getEquipmentManager().getPossibleEquipment( location = candRoom.locationName )
vars["showErrors"] = self._rh._showErrors
vars["errors"] = self._rh._errors
vars["insert"] = ( candRoom.id == None )
vars["attrs"] = goodFactory.getCustomAttributesManager().getAttributes( location = candRoom.locationName )
resp = candRoom.getResponsible()
if resp:
vars["responsibleName"] = resp.getFullName()
else:
vars["responsibleName"] = ""
nbd = candRoom.getNonBookableDates()
if len(nbd) == 0:
from MaKaC.plugins.RoomBooking.default.room import NonBookableDate
nbd = [NonBookableDate(None, None)]
vars["nonBookableDates"] = nbd
return vars
class WRoomBookingRoomCalendar( WTemplated ):
def __init__( self, rh, standalone = False, buttonText ='' ):
self._rh = rh
self._candResv = rh._candResv
self._standalone = standalone
self._buttonText = buttonText
def getVars( self ):
vars = WTemplated.getVars( self )
candResv = self._candResv
room = candResv.room
if self._standalone:
vars["bookingDetailsUH"] = urlHandlers.UHRoomBookingBookingDetails
else:
vars["bookingDetailsUH"] = urlHandlers.UHConfModifRoomBookingDetails
# Calendar range
now = datetime.now()
if candResv != None: #.startDT != None and candResv.endDT != None:
calendarStartDT = datetime( candResv.startDT.year, candResv.startDT.month, candResv.startDT.day, 0, 0, 1 ) # Potential performance problem
calendarEndDT = datetime( candResv.endDT.year, candResv.endDT.month, candResv.endDT.day, 23, 59 ) # with very long reservation periods
else:
calendarStartDT = datetime( now.year, now.month, now.day, 0, 0, 1 )
calendarEndDT = calendarStartDT + timedelta( 3 * 31, 50, 0, 0, 59, 23 )
# example resv. to ask for other reservations
resvEx = CrossLocationFactory.newReservation( location = room.locationName )
resvEx.startDT = calendarStartDT
resvEx.endDT = calendarEndDT
resvEx.repeatability = RepeatabilityEnum.daily
resvEx.room = room
resvEx.isConfirmed = None # To include both confirmed and not confirmed
# Bars: Existing reservations
collisionsOfResvs = resvEx.getCollisions()
bars = []
for c in collisionsOfResvs:
if c.withReservation.isConfirmed:
bars.append( Bar( c, Bar.UNAVAILABLE ) )
else:
bars.append( Bar( c, Bar.PREBOOKED ) )
# Bars: Candidate reservation
periodsOfCandResv = candResv.splitToPeriods()
for p in periodsOfCandResv:
bars.append( Bar( Collision( (p.startDT, p.endDT), candResv ), Bar.CANDIDATE ) )
# Bars: Conflicts all vs candidate
candResvIsConfirmed = candResv.isConfirmed;
candResv.isConfirmed = None
allCollisions = candResv.getCollisions()
candResv.isConfirmed = candResvIsConfirmed
if candResv.id:
# Exclude candidate vs self pseudo-conflicts (Booking modification)
allCollisions = filter( lambda c: c.withReservation.id != candResv.id, allCollisions )
collisions = [] # only with confirmed resvs
for c in allCollisions:
if c.withReservation.isConfirmed:
bars.append( Bar( c, Bar.CONFLICT ) )
collisions.append( c )
else:
bars.append( Bar( c, Bar.PRECONFLICT ) )
if not candResv.isRejected and not candResv.isCancelled:
vars["thereAreConflicts"] = len( collisions ) > 0
else:
vars["thereAreConflicts"] = False
vars["conflictsNumber"] = len( collisions )
bars = barsList2Dictionary( bars )
bars = addOverlappingPrebookings( bars )
bars = sortBarsByImportance( bars, calendarStartDT, calendarEndDT )
if not self._standalone:
for dt in bars.iterkeys():
for bar in bars[dt]:
bar.forReservation.setOwner( self._rh._conf )
vars["calendarStartDT"] = calendarStartDT
vars["calendarEndDT"] = calendarEndDT
vars["bars"] = bars
vars["iterdays"] = iterdays
vars["day_name"] = day_name
vars["Bar"] = Bar
vars["room"] = room
vars["buttonText"] = self._buttonText
vars["withConflicts"] = True
return vars
class WRoomBookingStatement( WTemplated ):
def __init__( self, rh ):
self._rh = rh
def getVars( self ):
vars = WTemplated.getVars( self )
vars['title'] = self._rh._title
vars['description'] = self._rh._description
return vars
class WRoomBookingAdmin( WTemplated ):
def __init__( self, rh ):
self._rh = rh
def getVars( self ):
vars = WTemplated.getVars( self )
vars["Location"] = Location
return vars
class WRoomBookingAdminLocation( WTemplated ):
def __init__( self, rh, location ):
self._rh = rh
self._location = location
def getVars( self ):
vars = WTemplated.getVars( self )
vars["location"] = self._location
vars["possibleEquipment"] = self._location.factory.getEquipmentManager().getPossibleEquipment(location = self._location.friendlyName)
vars["AttsManager"] = self._location.factory.getCustomAttributesManager()
# Rooms
rooms = self._location.factory.newRoom().getRooms(location = self._location.friendlyName)
rooms.sort(key = lambda r: r.getFullName())
vars["Rooms"] = rooms
rh = self._rh
vars["withKPI"] = rh._withKPI
if rh._withKPI:
vars["kpiAverageOccupation"] = str( int( round( rh._kpiAverageOccupation * 100 ) ) ) + "%"
vars["kpiTotalRooms"] = rh._kpiTotalRooms
vars["kpiActiveRooms"] = rh._kpiActiveRooms
vars["kpiReservableRooms"] = rh._kpiReservableRooms
vars["kpiReservableCapacity"] = rh._kpiReservableCapacity
vars["kpiReservableSurface"] = rh._kpiReservableSurface
# Bookings
vars["kbiTotalBookings"] = rh._totalBookings
# Next 9 KPIs
vars["stats"] = rh._booking_stats
return vars
class WBaseSearchBox(WTemplated):
def __init__(self, template='SearchBox', targetId=0):
# overload the template
WTemplated.__init__(self,template)
self._targetId = targetId
def getVars(self):
vars = WTemplated.getVars( self )
vars["searchAction"] = urlHandlers.UHSearch.getURL();
vars['targetId'] = self._targetId
vars['searchImg'] = imgLogo=Configuration.Config.getInstance().getSystemIconURL( "search" )
vars['categId'] = 0
return vars
class WMiniSearchBox(WBaseSearchBox):
def __init__(self, confId):
WBaseSearchBox.__init__(self, template='MiniSearchBox',targetId = confId)
def getVars(self):
vars = WBaseSearchBox.getVars( self )
return vars
class WMicroSearchBox(WBaseSearchBox):
def __init__(self, confId):
WBaseSearchBox.__init__(self, template='MicroSearchBox',targetId = confId)
self._confId = confId
def getVars(self):
vars = WBaseSearchBox.getVars( self )
vars["innerBox"] = WMiniSearchBox(self._confId).getHTML().replace('"', '\\"').replace("'", "\\'").replace("\n"," ")
vars["closeIcon"] = quoteattr(str(Configuration.Config.getInstance().getSystemIconURL("remove")));
return vars
class WCategorySearchBox(WBaseSearchBox):
def __init__(self, categId = 0, optionsClass='arrowExpandIcon'):
WBaseSearchBox.__init__(self, targetId = categId)
self._categId = categId
self._moreOptionsClass = optionsClass
def getVars(self):
vars = WBaseSearchBox.getVars( self )
vars["categId"] = self._categId
vars['moreOptionsClass'] = self._moreOptionsClass
return vars
class WRootSearchBox(WBaseSearchBox):
def __init__(self):
# overload the template
WBaseSearchBox.__init__(self,'RootSearchBox')
def getVars(self):
vars = WBaseSearchBox.getVars( self )
vars["innerBox"] = WBaseSearchBox().getHTML()
return vars
class WUtils:
"""A interface for creating easily some HTML elements..."""
def createImg(cls, imgId, imgInfo="", imgText="", **attributes):
""" returns an HTML image with optional text on the right.
Params:
imgId -- ID of the picture (see /code/MaKaC/common/MaCaKConfig.py ->SystemIcons).
ImgInfo -- optional information text about the link.
imgText -- optional text which will be displayed on the right of the pic.
attributes -- [dictionary] attributes for (e.g. border="" name="" ...).
"""
attr = utils.dictionaryToString(attributes)
return """ %s"""%(Config.getInstance().getSystemIconURL(imgId),imgInfo,attr,imgText)
createImg = classmethod(createImg)
def createImgButton(cls, url, imgId, imgInfo="", imgText="", **attributes):
""" returns an HTML image link with optional text on the right.
Params:
url -- link of target.
imgId -- ID of the picture (see /code/MaKaC/common/MaCaKConfig.py ->SystemIcons).
ImgInfo -- optional information text about the link.
imgText -- optional text which will be displayed on the right of the pic.
attributes -- [dictionary] attributes for (e.g. onclick="" onchange="" ...).
"""
attr = utils.dictionaryToString(attributes)
return """ %s
"""%(url, attr, Config.getInstance().getSystemIconURL(imgId), imgInfo, imgText)
createImgButton = classmethod(createImgButton)
def createChangingImgButton(cls, url, imgID, imgOverId, imgInfo="", imgText="", **attributes):
""" returns a changing HTML image link
(i.e. the image changes depending on mouseOver/mouseOut)
with optional text on the right.
Params:
url -- link of target.
imgID -- ID of the basic picture (see /code/MaKaC/common/MaCaKConfig.py ->SystemIcons).
imgOverId -- ID of the picture appearing with onMouseOver.
ImgInfo -- optional information text about the link.
imgText -- optional text which will be displayed on the right of the pic.
attributes -- [dictionary] attributes for (e.g. onclick="" onchange="" ...).
"""
attr = utils.dictionaryToString(attributes)
iconUrl = Config.getInstance().getSystemIconURL(imgID)
iconOverUrl = Config.getInstance().getSystemIconURL(imgOverId)
return """ %s
"""%(url, attr, iconUrl, imgInfo, iconOverUrl, iconUrl, imgText)
createChangingImgButton = classmethod(createChangingImgButton)
def createTextarea(cls, content="", **attributes):
""" returns an HTML textarea with optional text.
Params:
content -- optional text which will be displayed in the textarea.
attributes -- [dictionary] attributes for (e.g. name="" type="" ...).
"""
#check
if content==None: content=""
#attributes to string...
attr = utils.dictionaryToString(attributes)
#return HTML string
return """"""%(attr,content)
createTextarea = classmethod(createTextarea)
def createInput(cls, text="", **attributes):
""" returns an HTML input with optional text.
Params:
text -- optional text which will be displayed on the right of the input.
attributes -- [dictionary] attributes for (e.g. name="" type="" ...).
"""
#check
if text==None: text=""
#attributes to string...
attr = utils.dictionaryToString(attributes)
#return HTML string
return """%s"""%(attr,text)
createInput = classmethod(createInput)
def createSelect(cls, emptyOption, options, selected="", **attributes):
""" returns an HTML select field.
Params:
emptyOption -- [bool] if True, add a selectionable empty option in the select.
options -- list of the options.
selected -- (optional) the selected option.
attributes -- [dictionary] attributes for