[REF] Remove unused vars
[cds-indico.git] / indico / MaKaC / webinterface / wcomponents.py
blobeb7d46aa6f0b09d178d58d1d5bde55d3a23c305f
1 # -*- coding: utf-8 -*-
2 ##
3 ##
4 ## This file is part of CDS Indico.
5 ## Copyright (C) 2002, 2003, 2004, 2005, 2006, 2007 CERN.
6 ##
7 ## CDS Indico is free software; you can redistribute it and/or
8 ## modify it under the terms of the GNU General Public License as
9 ## published by the Free Software Foundation; either version 2 of the
10 ## License, or (at your option) any later version.
12 ## CDS Indico is distributed in the hope that it will be useful, but
13 ## WITHOUT ANY WARRANTY; without even the implied warranty of
14 ## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15 ## General Public License for more details.
17 ## You should have received a copy of the GNU General Public License
18 ## along with CDS Indico; if not, write to the Free Software Foundation, Inc.,
19 ## 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA.
21 from MaKaC.plugins import PluginsHolder, OldObservable
23 import os,types,string
24 import itertools
25 from xml.sax.saxutils import escape, quoteattr
26 from copy import copy
27 from datetime import timedelta,datetime,date,time
28 import exceptions
29 import urllib
30 from operator import attrgetter
31 from MaKaC.common.db import DBMgr
32 import MaKaC.conference as conference
33 import MaKaC.user as user
34 import MaKaC.schedule as schedule
35 import MaKaC.common.info as info
36 import MaKaC.domain as domain
37 import MaKaC.webinterface.urlHandlers as urlHandlers
38 import MaKaC.common.Configuration as Configuration
39 from MaKaC import webcast
41 from MaKaC.accessControl import AdminList
42 from MaKaC.errors import UserError
43 from MaKaC.common.url import URL
44 from MaKaC.common import Config
45 from MaKaC.webinterface.common.person_titles import TitlesRegistry
46 from MaKaC.conference import Conference, Category
48 from MaKaC.webinterface.common.timezones import TimezoneRegistry, DisplayTimezoneRegistry
49 import MaKaC.webinterface.common.timezones as convertTime
50 from pytz import timezone
51 from MaKaC.common.timezoneUtils import DisplayTZ, nowutc
52 from MaKaC.webinterface.common import contribFilters as contribFilters
53 from MaKaC.common import filters, utils
54 from MaKaC.common.TemplateExec import escapeHTMLForJS
55 from MaKaC.errors import MaKaCError
56 import MaKaC.webinterface.displayMgr as displayMgr
57 import MaKaC.common.TemplateExec as templateEngine
58 from MaKaC.common.ContextHelp import ContextHelp
59 from MaKaC.rb_tools import FormMode, overlap
61 from lxml import etree
63 from indico.util.i18n import i18nformat, parseLocale, getLocaleDisplayNames
65 from MaKaC.common.TemplateExec import truncateTitle
66 from MaKaC.fossils.user import IAvatarFossil
67 from MaKaC.common.fossilize import fossilize
68 from MaKaC.common.contextManager import ContextManager
70 from indico.util.date_time import utc_timestamp
71 from indico.core.index import Catalog
73 import re
75 MIN_PRESENT_EVENTS = 6
76 OPTIMAL_PRESENT_EVENTS = 10
79 class WTemplated(OldObservable):
80 """This class provides a basic implementation of a web component (an
81 object which generates HTML related to a certain feature or
82 functionality) which relies in a template file for generating the
83 HTML it's in charge of.
84 By templating file we mean that there will be a file in the file
85 system (uniquely identified) which will contain HTML code plus some
86 "variables" (dynamic values). The class will take care of opening
87 this file, parsing the HTML and replacing the variables by the
88 corresponding values.
89 """
90 tplId = None
92 @classmethod
93 def forModule(cls, module, *args):
94 tplobj = cls(*args)
95 # HACK :/
96 tplobj._dir = os.path.join(module.__path__[0], 'tpls')
97 return tplobj
99 def __init__( self, tpl_name = None):
100 if tpl_name != None:
101 self.tplId = tpl_name
103 self._rh = ContextManager.get('currentRH', None)
105 cfg = Configuration.Config.getInstance()
106 self._dir = cfg.getTPLDir()
108 def _getSpecificTPL(self, dir, tplId, extension="tpl"):
110 Checks if there is a defined set of specific templates (i.e. CERN),
111 and if there is a specific file for this page, for this template set.
112 Returns the file that should be used.
116 if DBMgr.getInstance().isConnected():
117 template = info.HelperMaKaCInfo.getMaKaCInfoInstance().getDefaultTemplateSet()
119 if template != None :
120 specTpl = "%s.%s.%s" % (tplId, template, extension)
122 if os.path.exists(os.path.join(dir,specTpl)):
123 return specTpl
126 return "%s.%s" % (tplId, extension)
128 def _setTPLFile(self):
129 """Sets the TPL (template) file for the object. It will try to get
130 from the configuration if there's a special TPL file for it and
131 if not it will look for a file called as the class name+".tpl"
132 in the configured TPL directory.
134 cfg = Configuration.Config.getInstance()
136 file = cfg.getTPLFile( self.tplId )
138 # because MANY classes skip the constructor...
139 if hasattr(self, '_dir'):
140 tplDir = self._dir
141 else:
142 tplDir = cfg.getTPLDir()
144 if file == "":
145 file = self._getSpecificTPL(tplDir,self.tplId)
146 self.tplFile = os.path.join(tplDir, file)
148 hfile = self._getSpecificTPL(os.path.join(tplDir,'chelp'),
149 self.tplId,
150 extension='wohl')
152 self.helpFile = os.path.join(tplDir,'chelp',hfile)
155 def getVars( self ):
156 """Returns a dictionary containing the TPL variables that will
157 be passed at the TPL formating time. For this class, it will
158 return the configuration user defined variables.
159 Classes inheriting from this one will have to take care of adding
160 their variables to the ones returned by this method.
162 self._rh = ContextManager.get('currentRH', None)
164 cfg = Configuration.Config.getInstance()
165 vars = cfg.getTPLVars()
167 for paramName in self.__params:
168 vars[ paramName ] = self.__params[ paramName ]
169 if len(vars.get("errorMsg", [])) > 0 :
170 vars["errorMsg"] = WErrorMessage().getHTML(vars)
171 else:
172 vars["errorMsg"] = ""
174 if len(vars.get("infoMsg", [])) > 0 :
175 vars["infoMsg"] = WInfoMessage().getHTML(vars)
176 else :
177 vars["infoMsg"] = ""
179 return vars
181 def getHTML( self, params=None ):
182 """Returns the HTML resulting of formating the text contained in
183 the corresponding TPL file with the variables returned by the
184 getVars method.
185 Params:
186 params -- additional paramters received from the caller
189 self._rh = ContextManager.get('currentRH', None)
190 if self.tplId == None:
191 self.tplId = self.__class__.__name__[1:]
192 self._setTPLFile()
193 self.__params = {}
194 if params != None:
195 self.__params = params
197 # include context help info, if it exists
198 helpText = None
199 if os.path.exists(self.helpFile):
200 try:
201 fh = open( self.helpFile, "r")
202 helpText = fh.read()
203 fh.close()
204 except exceptions.IOError:
205 pass
207 vars = self.getVars()
209 vars['__rh__'] = self._rh
210 vars['self_'] = self
212 tempHTML = templateEngine.render(self.tplFile, vars)
214 if self._rh and self._rh._req.is_https():
215 imagesBaseURL = Config.getInstance().getImagesBaseURL()
216 imagesBaseSecureURL = urlHandlers.setSSLPort(Config.getInstance().getImagesBaseSecureURL())
217 tempHTML = tempHTML.replace(imagesBaseURL, imagesBaseSecureURL)
218 tempHTML = tempHTML.replace(escapeHTMLForJS(imagesBaseURL), escapeHTMLForJS(imagesBaseSecureURL))
220 if helpText == None:
221 return tempHTML
222 else:
223 try:
224 return ContextHelp().merge(self.tplId, tempHTML, helpText)
225 except etree.LxmlError, e:
226 if tempHTML.strip() == '':
227 raise MaKaCError(_("Template " + str(self.tplId) + " produced empty output, and it has a .wohl file. Error: " + str(e)))
228 else:
229 raise
232 def htmlText(param):
233 if param:
234 return escape(param)
235 #return " "
236 return ""
237 htmlText = staticmethod( htmlText )
239 def textToHTML(param):
240 if param != "":
241 if param.lower().find("<br>") == -1 and param.lower().find("<p>") == -1 and param.lower().find("<li>") == -1 and param.lower().find("<table") == -1:
242 param=param.replace("\r\n", "<br>")
243 param=param.replace("\n","<br>")
244 return param
245 return "&nbsp;"
246 textToHTML = staticmethod( textToHTML )
248 def _escapeChars(self, text):
249 # Does nothing right now - it used to replace % with %% for the old-style templates
250 return text
252 class WHTMLHeader(WTemplated):
256 def __init__(self, tpl_name = None):
257 WTemplated.__init__(self)
259 def getVars( self ):
260 vars = WTemplated.getVars( self )
262 if DBMgr.getInstance().isConnected():
263 vars['stylesheet'] = Config.getInstance().getCssStylesheetName()
264 else:
265 vars['stylesheet'] = 'Default.css'
266 return vars
269 class WHeader(WTemplated):
270 """Templating web component for generating a common HTML header for
271 the web interface.
273 def __init__(self, aw, locTZ="", isFrontPage=False, currentCategory=None, tpl_name=None):
274 WTemplated.__init__(self, tpl_name=tpl_name)
275 self._currentuser = aw.getUser()
276 self._locTZ = locTZ
277 self._aw = aw
278 self._isFrontPage = isFrontPage
279 self.__currentCategory = currentCategory
282 Returns the current active timezone.
284 def _getActiveTimezone(self):
285 if self._aw.getSession():
286 tz = self._aw.getSession().getVar("ActiveTimezone")
287 else:
288 tz = info.HelperMaKaCInfo.getMaKaCInfoInstance().getTimezone()
290 return tz
293 Returns timezone string that is show to the user.
295 def _getTimezoneDisplay( self, timezone ):
296 if timezone == 'LOCAL':
297 if self._locTZ:
298 return self._locTZ
299 else:
300 return info.HelperMaKaCInfo.getMaKaCInfoInstance().getTimezone()
301 else:
302 return timezone
304 def getVars( self ):
305 vars = WTemplated.getVars( self )
306 #urlHandlers.UHUserDetails.getURL(self._currentuser)
307 vars["logMeAs"] = ""
308 # TODO: Remove this after CRBS headers are fixed!
309 if self._currentuser:
310 vars["userInfo"] = """<font size="-1"><a class="topbar" href="%s" target="_blank">%s</a> - <a href="%s">logout</a></font>"""%(urlHandlers.UHUserDetails.getURL(self._currentuser), self._currentuser.getFullName(), vars["logoutURL"])
311 vars["userDetails"] = 'class="topbar" href="%s" target="_blank"'%urlHandlers.UHUserDetails.getURL(self._currentuser)
313 if self._currentuser.isAdmin():
314 vars["logMeAs"] = vars["loginAsURL"]
315 else:
316 vars["userInfo"] = """<a href="%s">login</a>"""%(vars["loginURL"])
317 vars["userDetails"] = ""
318 # *****************
320 vars["currentUser"] = self._currentuser
322 imgLogo=Configuration.Config.getInstance().getSystemIconURL( "logoIndico" )
323 imgLogin=Configuration.Config.getInstance().getSystemIconURL( "login" )
325 vars["imgLogo"] = imgLogo
326 vars["imgLogin"] = imgLogin
327 vars["isFrontPage"] = self._isFrontPage
328 vars["currentCategory"] = self.__currentCategory
330 if self._aw.getSession():
331 selLang = self._aw.getSession().getLang()
332 else:
333 minfo = info.HelperMaKaCInfo.getMaKaCInfoInstance()
334 selLang = minfo.getLang()
336 vars["ActiveTimezone"] = self._getActiveTimezone();
338 Get the timezone for displaying on top of the page.
339 1. If the user has "LOCAL" timezone then show the timezone
340 of the event/category. If that's not possible just show the
341 standard timezone.
342 2. If the user has a custom timezone display that one.
344 vars["ActiveTimezoneDisplay"] = self._getTimezoneDisplay(vars["ActiveTimezone"])
346 vars["SelectedLanguage"] = selLang
347 locale = parseLocale(selLang)
348 vars["SelectedLanguageName"] = locale.languages[locale.language].encode('utf-8')
349 vars["Languages"] = getLocaleDisplayNames()
351 if DBMgr.getInstance().isConnected():
352 vars["title"] = info.HelperMaKaCInfo.getMaKaCInfoInstance().getTitle()
353 vars["organization"] = info.HelperMaKaCInfo.getMaKaCInfoInstance().getOrganisation()
354 else:
355 vars["title"] = "Indico"
356 vars["organization"] = ""
359 # Search box, in case search is active
360 if Config.getInstance().getIndicoSearchServer() != '' :
361 categId = 0
362 if self.__currentCategory:
363 categId = self.__currentCategory.getId()
364 vars['searchBox'] = WCategorySearchBox(categId=categId).getHTML()
365 else:
366 vars['searchBox'] = ""
368 # Check if room booking module is active
369 minfo = info.HelperMaKaCInfo.getMaKaCInfoInstance()
370 vars['roomBooking'] = minfo.getRoomBookingModuleActive()
372 #Build a list of items for the administration menu
373 adminList = AdminList.getInstance()
374 adminItemList = []
375 if self._currentuser:
376 if self._currentuser.isAdmin() or not adminList.getList():
377 adminItemList.append({'url': urlHandlers.UHAdminArea.getURL(), 'text': _("Server admin")})
378 if PluginsHolder().hasPluginType("Collaboration"):
379 from MaKaC.webinterface.rh.collaboration import RCCollaborationAdmin, RCCollaborationPluginAdmin
380 from MaKaC.plugins.Collaboration.collaborationTools import CollaborationTools
381 if (self._currentuser.isAdmin() or RCCollaborationAdmin.hasRights(user = self._currentuser) or RCCollaborationPluginAdmin.hasRights(user = self._currentuser, plugins = "any")) and CollaborationTools.anyPluginsAreActive():
382 adminItemList.append({'url': urlHandlers.UHAdminCollaboration.getURL(), 'text': _("Video Services Overview")})
383 if webcast.HelperWebcastManager.getWebcastManagerInstance().isManager(self._currentuser):
384 adminItemList.append({'url': urlHandlers.UHWebcast.getURL(), 'text': _("Webcast Admin")})
387 vars["adminItemList"] = adminItemList
389 return vars
392 class WStaticWebHeader( WTemplated ):
393 """Templating web component for generating the HTML header for
394 the static web interface when generating a DVD.
396 def getVars( self ):
397 vars = WTemplated.getVars( self )
398 return vars
400 class WManagementHeader( WHeader ):
401 """Templating web component for generating the HTML header for
402 the management web interface.
404 pass
406 class WHelpHeader( WHeader ):
407 """Templating web component for generating the HTML header for
408 the help web interface.
410 pass
412 class WRoomBookingHeader( WHeader ):
413 """Templating web component for generating the HTML header for
414 the (standalone) room booking web interface.
416 pass
418 class WConferenceHeader( WHeader ):
419 """Templating web component for generating the HTML header for
420 the conferences' web interface.
423 def __init__(self, aw, conf):
424 self._conf = conf
425 self._aw = aw
426 WHeader.__init__(self, self._aw, tpl_name='EventHeader')
427 tzUtil = DisplayTZ(self._aw,self._conf)
428 self._locTZ = tzUtil.getDisplayTZ()
430 def getVars( self ):
431 vars = WHeader.getVars( self )
432 vars["categurl"] = urlHandlers.UHCategoryDisplay.getURL(self._conf.getOwnerList()[0])
434 vars["conf"] = self._conf;
436 vars["imgLogo"] = Configuration.Config.getInstance().getSystemIconURL( "miniLogo" )
437 vars["MaKaCHomeURL"] = urlHandlers.UHCategoryDisplay.getURL(self._conf.getOwnerList()[0])
439 #moved here from WHeader in order to be able to use DisplayTZ with self._conf (in some pages WHeader has no self._conf).
440 #TODO: Is this needed?
441 #vars["Timezones"] = Config.getInstance().getTimezoneList()
444 # if self._conf.getModifKey() != '':
445 # url = urlHandlers.UHConfEnterModifKey.getURL(self._conf)
446 # url.addParam("redirectURL",urlHandlers.UHConferenceDisplay.getURL(self._conf))
447 # vars["confModif"] = """<a href=%s><img src=%s valign="middle"></a>"""%(quoteattr(str(url)), quoteattr(str(Configuration.Config.getInstance().getSystemIconURL( "modify" ))))
448 # else:
449 # vars["confModif"] = ""
451 # Default values to avoid NameError while executing the template
452 vars["viewoptions"] = []
453 vars["SelectedStyle"] = ""
454 vars["pdfURL"] = ""
455 vars["displayURL"] = ""
457 # Setting the buttons that will be displayed in the header menu
458 vars["showFilterButton"] = False
459 vars["showMoreButton"] = True
460 vars["showExportToICal"] = True
461 vars["showExportToPDF"] = False
462 vars["showDLMaterial"] = True
463 vars["showLayout"] = False
465 vars["usingModifKey"]=False
466 if self._conf.canKeyModify(self._aw):
467 vars["usingModifKey"]=True
468 vars["displayNavigationBar"] = displayMgr.ConfDisplayMgrRegistery().getDisplayMgr(self._conf, False).getDisplayNavigationBar()
469 return vars
471 class WMenuConferenceHeader( WConferenceHeader ):
472 """Templating web component for generating the HTML header for
473 the conferences' web interface with a menu
475 def __init__(self, aw, conf, modifKey=False):
476 self._conf = conf
477 self._modifKey=modifKey
478 self._aw=aw
479 WConferenceHeader.__init__(self, self._aw, conf)
481 def getVars( self ):
482 vars = WConferenceHeader.getVars( self )
483 vars["categurl"] = urlHandlers.UHConferenceDisplay.getURL(self._conf)
484 url = urlHandlers.UHConfEnterModifKey.getURL(self._conf)
485 url.addParam("redirectURL",urlHandlers.UHConferenceOtherViews.getURL(self._conf))
486 vars["confModif"] = i18nformat("""<a href=%s> _("manage")</a>""")%quoteattr(str(url))
487 if self._conf.canKeyModify(self._aw):
488 url = urlHandlers.UHConfCloseModifKey.getURL(self._conf)
489 url.addParam("redirectURL",urlHandlers.UHConferenceOtherViews.getURL(self._conf))
490 vars["confModif"] = i18nformat("""<a href=%s>_("exit manage")</a>""")%quoteattr(str(url))
492 # Dates Menu
493 tz = DisplayTZ(self._aw,self._conf,useServerTZ=1).getDisplayTZ()
494 sdate = self._conf.getStartDate().astimezone(timezone(tz))
495 edate = self._conf.getEndDate().astimezone(timezone(tz))
496 dates = []
497 if sdate.strftime("%Y-%m-%d") != edate.strftime("%Y-%m-%d"):
498 selected = ""
499 if vars.has_key("selectedDate"):
500 selectedDate = vars["selectedDate"]
501 if selectedDate == "all" or selectedDate == "":
502 selected = "selected"
503 else:
504 selectedDate = "all"
505 dates = [ i18nformat(""" <select name="showDate" onChange="document.forms[0].submit();" style="font-size:8pt;"><option value="all" %s>- - _("all days") - -</option> """)%selected]
506 while sdate.strftime("%Y-%m-%d") <= edate.strftime("%Y-%m-%d"):
507 selected = ""
508 if selectedDate == sdate.strftime("%d-%B-%Y"):
509 selected = "selected"
510 d = sdate.strftime("%d-%B-%Y")
511 dates.append(""" <option value="%s" %s>%s</option> """%(d, selected, d))
512 sdate = sdate + timedelta(days=1)
513 dates.append("</select>")
514 else:
515 dates.append("""<input type="hidden" name="showDate" value="all">""")
516 # Sessions Menu
517 sessions = []
518 if len(self._conf.getSessionList()) != 0:
519 selected = ""
520 if vars.has_key("selectedSession"):
521 selectedSession = vars["selectedSession"]
522 if selectedSession == "all" or selectedSession == "":
523 selected = "selected"
524 else:
525 selectedSession = "all"
526 sessions = [ i18nformat(""" <select name="showSession" onChange="document.forms[0].submit();" style="font-size:8pt;"><option value="all" %s>- - _("all sessions") - -</option> """)%selected]
527 for session in self._conf.getSessionList():
528 selected = ""
529 id = session.getId()
530 if id == selectedSession:
531 selected = "selected"
532 sessions.append(""" <option value="%s" %s>%s</option> """%(id, selected, session.getTitle()))
533 sessions.append("</select>")
534 else:
535 sessions.append("""<input type="hidden" name="showSession" value="all">""")
536 # Handle hide/show contributions option
537 hideContributions = None;
538 if len(self._conf.getSessionList()) != 0:
539 if vars.has_key("detailLevel"):
540 if vars["detailLevel"] == "session":
541 hideContributions = "checked"
542 else:
543 hideContributions = ""
544 # Save to session
545 vars["hideContributions"] = hideContributions;
547 if self._conf.getType() == "meeting" and self._conf.getParticipation().isAllowedForApplying() and self._conf.getStartDate() > nowutc():
548 vars["applyForParticipation"] = i18nformat("""<a href="%s">_("Apply for participation")</a>""")%urlHandlers.UHConfParticipantsNewPending.getURL(self._conf)
549 else :
550 vars["applyForParticipation"] = ""
551 evaluation = self._conf.getEvaluation()
552 if self._conf.hasEnabledSection("evaluation") and evaluation.isVisible() and evaluation.inEvaluationPeriod() and evaluation.getNbOfQuestions()>0 :
553 vars["evaluation"] = i18nformat("""<a href="%s"> _("Evaluation")</a>""")%urlHandlers.UHConfEvaluationDisplay.getURL(self._conf)
554 else :
555 vars["evaluation"] = ""
557 urlCustPrint = urlHandlers.UHConferenceOtherViews.getURL(self._conf)
558 urlCustPrint.addParam("showDate", vars.get("selectedDate", "all"))
559 urlCustPrint.addParam("showSession", vars.get("selectedSession", "all"))
560 urlCustPrint.addParam("fr", "no")
561 urlCustPrint.addParam("view", vars["currentView"])
562 vars["printURL"]=str(urlCustPrint)
564 vars["printIMG"]=quoteattr(str(Configuration.Config.getInstance().getSystemIconURL( "printer" )))
565 urlCustPDF=urlHandlers.UHConfTimeTableCustomizePDF.getURL(self._conf)
566 urlCustPDF.addParam("showDays", vars.get("selectedDate", "all"))
567 urlCustPDF.addParam("showSessions", vars.get("selectedSession", "all"))
568 vars["pdfURL"]=quoteattr(str(urlCustPDF))
569 vars["pdfIMG"]=quoteattr(str(Configuration.Config.getInstance().getSystemIconURL( "pdf" )))
570 urlMatPack=urlHandlers.UHConferenceDisplayMaterialPackage.getURL(self._conf)
571 vars["matPackURL"]=quoteattr(str(urlMatPack))
572 vars["zipIMG"]=quoteattr(str(Configuration.Config.getInstance().getSystemIconURL( "smallzip" )))
574 return vars
576 class WMenuMeetingHeader( WConferenceHeader ):
577 """Templating web component for generating the HTML header for
578 the meetings web interface with a menu
580 def __init__(self, aw, conf, modifKey=False):
581 self._conf = conf
582 self._modifKey=modifKey
583 self._aw=aw
584 WHeader.__init__(self, self._aw, tpl_name='EventHeader')
585 tzUtil = DisplayTZ(self._aw,self._conf)
586 self._locTZ = tzUtil.getDisplayTZ()
589 def getVars( self ):
590 vars = WConferenceHeader.getVars( self )
592 vars["categurl"] = urlHandlers.UHCategoryDisplay.getURL(self._conf.getOwnerList()[0])
593 #vars["confModif"] = i18nformat("""<a href=%s> _("manage")</a>""")%quoteattr(str(urlHandlers.UHConfEnterModifKey.getURL(self._conf)))
594 #if self._conf.canKeyModify(self._aw):
595 # vars["confModif"] = i18nformat("""<a href=%s> _("exit manage")</a>""")%quoteattr(str(urlHandlers.UHConfCloseModifKey.getURL(self._conf)))
596 #vars["confModif"] += "&nbsp;|&nbsp;"
597 #if not self._conf.canAccess(self._aw) and self._conf.getAccessKey() != "":
598 # vars["confModif"] += i18nformat("""<a href=%s>_("full agenda")</a>&nbsp;|&nbsp;""")%(quoteattr(str(urlHandlers.UHConfForceEnterAccessKey.getURL(self._conf))))
599 styleMgr = info.HelperMaKaCInfo.getMaKaCInfoInstance().getStyleManager()
600 styles = styleMgr.getExistingStylesForEventType(vars["type"])
602 viewoptions = []
603 if len(styles) != 0:
604 styles.sort(key=styleMgr.getStyleName)
605 for styleId in styles:
606 viewoptions.append({"id": styleId, "name": styleMgr.getStyleName(styleId) })
607 vars["viewoptions"] = viewoptions
608 vars["SelectedStyle"] = styleMgr.getStyleName(vars["currentView"])
609 vars["displayURL"] = urlHandlers.UHConferenceDisplay.getURL(self._rh._conf)
611 # Setting the buttons that will be displayed in the header menu
612 vars["showFilterButton"] = True
613 vars["showExportToPDF"] = True
614 vars["showDLMaterial"] = True
615 vars["showLayout"] = True
618 # Dates Menu
619 tz = DisplayTZ(self._aw,self._conf,useServerTZ=1).getDisplayTZ()
620 sdate = self._conf.getStartDate().astimezone(timezone(tz))
621 edate = self._conf.getEndDate().astimezone(timezone(tz))
622 dates = []
623 selected = ""
624 if vars.has_key("selectedDate"):
625 selectedDate = vars["selectedDate"]
626 if selectedDate == "all" or selectedDate == "":
627 selected = "selected"
628 else:
629 selectedDate = "all"
630 dates = [ i18nformat(""" <option value="all" %s>- - _("all days") - -</option> """)%selected]
631 while sdate.strftime("%Y-%m-%d") <= edate.strftime("%Y-%m-%d"):
632 selected = ""
633 if selectedDate == sdate.strftime("%d-%B-%Y"):
634 selected = "selected"
635 d = sdate.strftime("%d-%B-%Y")
636 dates.append(""" <option value="%s" %s>%s</option> """%(d, selected, d))
637 sdate = sdate + timedelta(days=1)
638 vars["datesMenu"] = "".join(dates);
640 # Sessions Menu
641 sessions = []
642 selected = ""
643 if vars.has_key("selectedSession"):
644 selectedSession = vars["selectedSession"]
645 if selectedSession == "all" or selectedSession == "":
646 selected = "selected"
647 else:
648 selectedSession = "all"
649 sessions = [ i18nformat(""" <option value="all" %s>- - _("all sessions") - -</option> """)%selected]
650 for session in self._conf.getSessionList():
651 selected = ""
652 id = session.getId()
653 if id == selectedSession:
654 selected = "selected"
655 title = session.getTitle()
656 if len(title) > 60:
657 title = title[0:40] + "..."
658 sessions.append(""" <option value="%s" %s>%s</option> """%(id, selected, title))
659 vars["sessionsMenu"] = "".join(sessions);
661 # Handle hide/show contributions option
662 hideContributions = None;
663 if len(self._conf.getSessionList()) != 0:
664 if vars.has_key("detailLevel"):
665 if vars["detailLevel"] == "session":
666 hideContributions = "checked"
667 else:
668 hideContributions = ""
669 vars["hideContributions"] = hideContributions;
671 if Config.getInstance().getIndicoSearchServer() != '' :
672 vars["searchBox"] = WCategorySearchBox(optionsClass='meetingHeaderSearchBox').getHTML()
673 else:
674 vars["searchBox"] = ""
676 urlCustPrint = urlHandlers.UHConferenceOtherViews.getURL(self._conf)
677 urlCustPrint.addParam("showDate", vars.get("selectedDate", "all"))
678 urlCustPrint.addParam("showSession", vars.get("selectedSession", "all"))
679 urlCustPrint.addParam("detailLevel", vars.get("detailLevel", "all"))
680 urlCustPrint.addParam("fr", "no")
681 urlCustPrint.addParam("view", vars["currentView"])
682 vars["printURL"]=str(urlCustPrint)
685 urlCustPDF=urlHandlers.UHConfTimeTableCustomizePDF.getURL(self._conf)
686 urlCustPDF.addParam("showDays", vars.get("selectedDate", "all"))
687 urlCustPDF.addParam("showSessions", vars.get("selectedSession", "all"))
688 # Add the view as a parameter to keep track of the current layout
689 # when exporting a pdf
690 urlCustPDF.addParam("view", vars["currentView"])
691 vars["pdfURL"]=str(urlCustPDF)
694 return vars
696 class WMenuSimpleEventHeader( WMenuMeetingHeader ):
697 """Templating web component for generating the HTML header for
698 the simple event' web interface with a menu
701 def getVars( self ):
702 vars = WMenuMeetingHeader.getVars( self )
703 vars["confModif"] = """<a href=%s>manage</a>"""%quoteattr(str(urlHandlers.UHConfEnterModifKey.getURL(self._conf)))
704 if self._conf.canKeyModify(self._aw):
705 vars["confModif"] = """<a href=%s>exit manage</a>"""%quoteattr(str(urlHandlers.UHConfCloseModifKey.getURL(self._conf)))
707 # Setting the buttons that will be displayed in the header menu
708 vars["showFilterButton"] = False
709 vars["showExportToPDF"] = False
711 vars["accessWrapper"] = self._aw
712 return vars
716 class WFooter(WTemplated):
717 """Templating web component for generating a common HTML footer for the
718 web interface.
721 def __init__(self, tpl_name = None, isFrontPage = False):
722 WTemplated.__init__(self, tpl_name)
723 self._isFrontPage = isFrontPage
725 def getVars( self ):
726 vars = WTemplated.getVars( self )
728 vars["isFrontPage"] = self._isFrontPage;
730 if not vars.has_key("modificationDate"):
731 vars["modificationDate"] = ""
733 if not vars.has_key("shortURL"):
734 vars["shortURL"] = ""
736 return vars
739 class WEventFooter(WFooter):
741 Specialization of WFooter that provides extra info for events
743 def __init__(self, conf, tpl_name = None, isFrontPage = False):
744 WFooter.__init__(self, tpl_name, isFrontPage)
745 self._conf = conf
747 def _gCalDateFormat(self, dtime):
748 return dtime.strftime("%Y%m%dT%H%M%SZ")
750 def getVars(self):
751 v = WFooter.getVars(self)
752 v['gc_params'] = urllib.urlencode({
753 'action': 'TEMPLATE',
754 'text': self._conf.getTitle(),
755 'dates': "%s/%s" % (self._gCalDateFormat(self._conf.getStartDate()),
756 self._gCalDateFormat(self._conf.getEndDate())),
757 'details': self._conf.getDescription(),
758 'location': self._conf.getLocation().getName() if self._conf.getLocation() else '',
759 'trp': False,
760 'sprop': [str(urlHandlers.UHConferenceDisplay.getURL(self._conf)),
761 'name:indico']
764 cid = self._conf.getUrlTag().strip() or self._conf.getId()
765 minfo = info.HelperMaKaCInfo.getMaKaCInfoInstance()
766 app_data = minfo.getSocialAppConfig()
768 v['icalURL'] = urlHandlers.UHConferenceToiCal.getURL(self._conf)
769 v["shortURL"] = Config.getInstance().getShortEventURL() + cid
770 v["app_data"] = app_data
771 v["showSocial"] = app_data.get('active', False) and self._conf.getDisplayMgr().getShowSocialApps()
772 return v
775 class WNavigationDrawer(WTemplated):
777 def __init__( self, pars, bgColor = None, appendPath = [] , type = None):
778 self._target = pars["target"]
779 self._isModif = pars.get("isModif", False)
780 self._track = pars.get("track", None) #for abstracts viewed inside a track
781 self._bgColor = bgColor
782 self._actionType = type #type of action
785 The appendPath is an array with dictionaries: {"url": x, "title": x}.
786 Each of these links are added in the end of the breadcrumb
788 self._appendPath = appendPath
790 def getVars( self ):
791 vars = WTemplated.getVars( self )
792 vars["target"] = self._target
793 vars["isModif"]= self._isModif
794 vars["track"]= self._track
795 vars["bgColor"] = self._bgColor
796 vars["appendPath"] = self._appendPath
797 vars["actionType"] = self._actionType
798 return vars
800 def getHTML(self, params=None):
801 return WTemplated.getHTML(self, params)
803 class WSimpleNavigationDrawer(WTemplated):
805 def __init__( self, title, handler = None, bgColor = None, **pars ):
806 self._urlHandler = handler
807 self._pars = pars
808 self._title = title
809 self._bgColor = bgColor
811 def getVars( self ):
812 vars = WTemplated.getVars( self )
813 vars["urlHandler"] = self._urlHandler
814 vars["title"] = self._title
815 vars["pars"] = self._pars
816 vars["bgColor"] = self._bgColor
817 return vars
819 def getHTML(self, params=None):
820 return WTemplated.getHTML(self, params)
822 class WBannerModif(WTemplated):
824 def __init__( self, path = [], itemType = "", title = "" ):
825 WTemplated.__init__( self, "BannerModif" )
826 self._path = path
827 self._title = title
828 self._type = itemType
830 def getHTML(self):
831 """ Retrieves the HTML of the banner of the modification interface
832 of the given target event / category / contribution / abstract / etc.
833 'track' argument should be provided for abstracts viewed inside a track.
834 If originUrl and originPageTitle is set then this link his added to the end
835 of the breadcrumb showed in the banner.
838 return WTemplated.getHTML(self, {"type" : self._type, "path": self._path, "title": self._title})
840 class WTimetableBannerModif(WBannerModif):
842 def __init__(self, aw, target):
843 ## PATH
844 # Iterate till conference is reached
845 conf = target.getConference()
846 path = self._getOwnerBasePath(target)
847 scheduleModifURL = None
849 # if user has access to top-level timetable
850 if conf.canModify(aw):
851 scheduleModifURL = urlHandlers.UHConfModifSchedule.getURL( conf )
852 elif target.getSession():
853 # otherwise, let them access only the session timetable
854 scheduleModifURL = urlHandlers.UHSessionModifSchedule.getURL( target.getSession() )
855 if scheduleModifURL:
856 path.append({"url": scheduleModifURL, "title": _("Timetable")})
857 # TITLE AND TYPE
858 itemType = type(target).__name__
859 title = target.getTitle()
860 WBannerModif.__init__(self, path, itemType, title)
862 def _getOwnerBasePath(self, target):
863 path = []
864 obj = target
865 while obj:
866 obj = obj.getOwner()
867 if type(obj) != Conference and type(obj) != conference.Category:
868 path.append({"url": urlHandlers.UHHelper.getModifUH(type(obj)).getURL(obj),
869 "title": truncateTitle(obj.getTitle(), 30),
870 "type": type(obj).__name__})
871 else:
872 break
873 return path
875 class WListOfPapersToReview(WBannerModif):
877 def __init__(self, target, user ):
878 ## PATH
879 # Iterate till conference is reached
880 conf = target.getConference()
881 if user == "referee":
882 path = [{"url": urlHandlers.UHConfModifListContribToJudge.getURL(conf), "title":_("Contributions list")}]
883 if user == "reviewer":
884 path = [{"url": urlHandlers.UHConfModifListContribToJudgeAsReviewer.getURL(conf), "title":_("Contributions list")}]
885 if user == "editor":
886 path = [{"url": urlHandlers.UHConfModifListContribToJudgeAsEditor.getURL(conf), "title":_("Contributions list")}]
887 # TITLE AND TYPE
888 itemType = type(target).__name__
889 title = target.getTitle()
890 WBannerModif.__init__(self, path, itemType, title)
892 class WContribListBannerModif(WTimetableBannerModif):
894 def __init__(self, target ):
895 ## PATH
896 # Iterate till conference is reached
897 conf = target.getConference()
898 path = self._getOwnerBasePath(target)
900 path.append({"url": urlHandlers.UHConfModifContribList.getURL( conf ), "title": _("Contributions list")})
902 # TITLE AND TYPE
903 itemType = type(target).__name__
904 title = target.getTitle()
905 WBannerModif.__init__(self, path, itemType, title)
908 class WNotifTplBannerModif(WBannerModif):
910 def __init__( self, target ):
911 path = [{"url": urlHandlers.UHAbstractReviewingNotifTpl.getURL(target), "title":_("Notification template list")}]
912 itemType="Notification Template"
913 title=target.getName()
914 WBannerModif.__init__(self, path, itemType, title)
916 class WAbstractBannerModif(WBannerModif):
918 def __init__( self, target ):
919 path = [{"url": urlHandlers.UHConfAbstractManagment.getURL(target), "title":_("Abstracts list")}]
920 itemType="Abstract"
921 title=target.getTitle()
922 WBannerModif.__init__(self, path, itemType, title)
924 class WTrackBannerModif(WBannerModif):
926 def __init__( self, track, abstract=None, isManager = False ):
927 path = []
928 target = track
929 if abstract:
930 path.append({"url": urlHandlers.UHTrackModifAbstracts.getURL(track), "title":_("Abstract list")})
931 if isManager:
932 path.append({"url": urlHandlers.UHConfModifProgram.getURL(track.getConference()), "title":_("Track list")})
933 itemType=type(target).__name__
934 title=target.getTitle()
935 WBannerModif.__init__(self, path, itemType, title)
937 class WCategoryBannerModif(WBannerModif):
939 def __init__( self, target ):
940 itemType="Category"
941 title=target.getTitle()
942 WBannerModif.__init__(self, [], itemType, title)
944 class WRegFormBannerModif(WBannerModif):
946 def __init__( self, registrant ):
947 path=[{"url": urlHandlers.UHConfModifRegistrantList.getURL(registrant.getConference()), "title":_("Registrants list")}]
949 itemType="Registrant"
950 title=registrant.getFullName()
951 WBannerModif.__init__(self, path, itemType, title)
953 class WRegFormSectionBannerModif(WBannerModif):
955 def __init__( self, target, conf ):
956 path=[{"url": urlHandlers.UHConfModifRegForm.getURL(conf), "title":_("Registration form setup")}]
958 itemType="Registration form Section"
959 title=target.getTitle()
960 WBannerModif.__init__(self, path, itemType, title)
962 class WEpaymentBannerModif(WBannerModif):
964 def __init__( self, target, conf ):
965 path=[{"url": urlHandlers.UHConfModifEPayment.getURL(conf), "title":_("Epayment setup")}]
967 itemType="Epayment plugin"
968 title=target.getTitle()
969 WBannerModif.__init__(self, path, itemType, title)
971 class WListingsBannerModif(WBannerModif):
973 def __init__( self, conf, type ):
974 path=[{"url": urlHandlers.UHConfModifListings.getURL(conf), "title":_("All listings")}]
976 itemType= type
977 title=""
978 WBannerModif.__init__(self, path, itemType, title)
980 class WParticipantsBannerModif(WBannerModif):
982 def __init__( self, conf ):
983 path=[{"url": urlHandlers.UHConfModifParticipants.getURL(conf), "title":_("Participants list")}]
985 itemType="Pending participants"
986 title=""
987 WBannerModif.__init__(self, path, itemType, title)
990 class WConfLogsBannerModif(WBannerModif):
992 def __init__( self, conf ):
993 path=[{"url": urlHandlers.UHConfModifLog.getURL(conf), "title":_("Logs")}]
995 itemType="Log item"
996 title=""
997 WBannerModif.__init__(self, path, itemType, title)
999 class WCategModifHeader(WTemplated):
1001 def __init__(self, targetConf ):
1002 self._conf = targetConf
1004 def _getSingleCategHTML( self, categ, URLGen ):
1006 return """<a href="%s">%s</a>"""%(URLGen( categ ), categ.getName())
1008 def _getMultipleCategHTML( self, categList, URLGen ):
1009 l = []
1010 for categ in self._conf.getOwnerList():
1011 l.append("""<option value="%s">%s</option>"""%(categ.getId(),\
1012 categ.getName()))
1013 return i18nformat("""<form action="%s" method="GET">
1014 <select name="categId">%s</select>
1015 <input type="submit" class="btn" value="_("go")">
1016 </form>""")%(URLGen(), "".join(l))
1018 def getVars( self ):
1020 vars = WTemplated.getVars( self )
1021 #raise "%s"%(type(self._conf))
1022 try:
1023 ol = self._conf.getOwnerList()
1024 except:
1025 ol=self._conf
1026 #raise "%s"%ol
1027 URLGen = vars.get("categDisplayURLGen", urlHandlers.UHCategoryDisplay.getURL )
1029 try:
1030 if len(ol)>1:
1031 vars["categ"] = self._getMultipleCategHTML(ol, URLGen)
1032 else:
1033 vars["categ"] = self._getSingleCategHTML( ol[0], URLGen)
1034 vars["viewImageURL"] = Configuration.Config.getInstance().getSystemIconURL( "view" )
1035 except:
1036 vars["categ"] = self._getSingleCategHTML( ol, URLGen)
1037 vars["viewImageURL"] = Configuration.Config.getInstance().getSystemIconURL( "view" )
1039 return vars
1042 class WCategoryModificationHeader(WTemplated):
1045 def __init__( self, category ):
1046 self._categ = category
1048 def getVars( self ):
1049 vars = WTemplated.getVars( self )
1051 vars["confTitle"] = self._categ.getName()
1052 vars["title"] = self._categ.getName()
1053 vars["catDisplayURL"] = urlHandlers.UHCategoryDisplay.getURL(self._categ)
1054 vars["catModifURL"]= urlHandlers.UHCategoryModification.getURL(self._categ)
1055 vars["titleTabPixels"] = self.getTitleTabPixels()
1056 #vars["intermediateVTabPixels"] = self.getIntermediateVTabPixels()
1057 vars["eventCaption"]= "Category"
1058 return vars
1060 def getIntermediateVTabPixels( self ):
1061 return 0
1063 def getTitleTabPixels( self ):
1064 return 260
1066 class WConfModifHeader(WTemplated):
1068 def __init__( self, conf, aw ):
1069 self._conf = conf
1070 self._aw = aw
1072 def getVars( self ):
1073 vars = WTemplated.getVars( self )
1074 #raise "%s"%vars
1075 try:
1076 vars["creator"] = self._conf.getCreator().getFullName()
1077 except:
1078 vars["creator"] = ""
1079 vars["imgGestionGrey"] = Configuration.Config.getInstance().getSystemIconURL( "gestionGrey" )
1080 vars["confTitle"] = escape(self._conf.getTitle())
1081 if self._conf.canModify( self._aw ):
1082 URLGen = vars.get("confModifURLGen", \
1083 urlHandlers.UHConferenceModification.getURL )
1084 vars["confTitle"] = """<a href=%s>%s</a>"""%(quoteattr( str( URLGen( self._conf ) ) ), escape(self._conf.getTitle()) )
1085 URLGen = vars.get( "confDisplayURLGen", urlHandlers.UHConferenceDisplay.getURL )
1086 vars["confDisplayURL"] = URLGen( self._conf )
1087 vars["titleTabPixels"] = WConferenceModifFrame(self._conf, self._aw).getTitleTabPixels()
1088 try:
1089 type = self._conf.getType()
1090 except:
1091 type = ""
1092 if type == "simple_event":
1093 type = "lecture"
1094 vars["eventCaption"]=type.capitalize()#"Event"
1097 return vars
1100 class WSessionModifHeader(WTemplated):
1102 def __init__( self, session, aw ):
1103 self._session = session
1104 self._aw = aw
1106 def getHTML( self, params ):
1107 conf = self._session.getConference()
1108 confHTML = WConfModifHeader( conf, self._aw ).getHTML( params )
1109 return "%s%s"%(confHTML, WTemplated.getHTML( self, params ) )
1111 def getVars( self ):
1112 vars = WTemplated.getVars( self )
1113 vars["imgGestionGrey"] = Configuration.Config.getInstance().getSystemIconURL( "gestionGrey" )
1114 vars["sessionTitle"] = escape(self._session.getTitle())
1115 vars["sessionDisplayURL"] = vars["sessionDisplayURLGen"](self._session)
1116 vars["sessionModificationURL"] = vars["sessionModifURLGen"](self._session)
1117 return vars
1119 class WBreakModifHeader(WTemplated):
1121 def __init__( self, breakSlot, aw ):
1122 self._break = breakSlot
1123 self._aw = aw
1125 def getHTML( self, params ):
1126 return WTemplated.getHTML( self, params )
1128 def getVars( self ):
1129 vars = WTemplated.getVars( self )
1130 vars["imgGestionGrey"] = Configuration.Config.getInstance().getSystemIconURL( "gestionGrey" )
1131 vars["breakTitle"] = escape(self._break.getTitle())
1132 return vars
1135 class WContribModifHeader(WTemplated):
1137 def __init__( self, contrib, aw):
1138 self._contrib = contrib
1139 self._aw = aw
1141 def getHTML( self, params ):
1142 conf = self._contrib.getConference()
1143 session = self._contrib.getSession()
1144 if session is not None:
1145 HTML = WSessionModifHeader( session, self._aw ).getHTML( params )
1146 else:
1147 HTML = WConfModifHeader( conf, self._aw ).getHTML( params )
1148 return "%s%s"%(HTML, WTemplated.getHTML( self, params ) )
1150 def getVars( self ):
1151 vars = WTemplated.getVars( self )
1152 vars["imgGestionGrey"] = Configuration.Config.getInstance().getSystemIconURL( "gestionGrey" )
1153 vars["title"] = escape(self._contrib.getTitle())
1154 urlGen = vars.get( "contribDisplayURLGen", urlHandlers.UHContributionDisplay.getURL )
1155 vars["contribDisplayURL"] = urlGen(self._contrib)
1156 urlGen = vars.get( "contribModifURLGen", urlHandlers.UHContributionModification.getURL )
1157 vars["contribModificationURL"] = urlGen(self._contrib)
1158 return vars
1161 class WContribModifTool(WTemplated):
1163 def __init__( self, contrib ):
1164 self._contrib = contrib
1166 def getVars( self ):
1167 vars = WTemplated.getVars( self )
1168 vars["deleteIconURL"] = Configuration.Config.getInstance().getSystemIconURL("delete")
1169 vars["moveIconURL"] = Configuration.Config.getInstance().getSystemIconURL("move")
1170 return vars
1174 class WContributionDeletion(object):
1176 def __init__( self, contribList ):
1177 self._contribList = contribList
1179 def getHTML( self, actionURL ):
1180 l = []
1181 for contrib in self._contribList:
1182 l.append("""<li><i>%s</i></li>"""%contrib.getTitle())
1183 msg = i18nformat("""
1184 <font size="+2"> _("Are you sure that you want to DELETE the following contributions"):<ul>%s</ul>?</font><br>
1185 <table>
1186 <tr><td>
1187 <font color="red"> _("Note that the following changes will result from this deletion"):</font>
1188 <ul>
1189 <li> _("If the contribution is linked to an abstract"):</li>
1190 <ul>
1191 <li> _("The link between the abstract and the contribution will be deleted")</li>
1192 <li> _("The status of the abstract will change to 'submitted'")</li>
1193 <li> _("You'll lose the information about when and who accepted the abstract")</li>
1194 </ul>
1195 <li> _("ALL the existing sub-contributions within the above contribution(s) will also be deleted")</li>
1196 </ul>
1197 </td></tr>
1198 </table>
1199 """)%("".join(l))
1200 wc = WConfirmation()
1201 contribIdList = []
1202 for contrib in self._contribList:
1203 contribIdList.append( contrib.getId() )
1204 return wc.getHTML( msg, actionURL, {"selectedCateg": contribIdList}, \
1205 confirmButtonCaption="Yes", \
1206 cancelButtonCaption="No" )
1208 def delete( self ):
1209 for contrib in self._contribList:
1210 contrib.delete()
1211 return "done"
1214 class WContribModifSC(WTemplated):
1216 def __init__( self, contrib ):
1217 self._contrib = contrib
1218 self._conf = self._contrib.getConference()
1221 def getSubContItems(self,SCModifURL):
1222 temp = []
1223 scList = self._contrib.getSubContributionList()
1224 for sc in scList:
1225 id = sc.getId()
1226 selbox = """<select name="newpos%s" onChange="this.form.oldpos.value='%s';this.form.submit();">""" % (scList.index(sc),scList.index(sc))
1227 for i in range(1,len(scList)+1):
1228 if i== scList.index(sc)+1:
1229 selbox += "<option selected value='%s'>%s" % (i-1,i)
1230 else:
1231 selbox += "<option value='%s'>%s" % (i-1,i)
1232 selbox += """
1233 </select>"""
1234 temp.append("""
1235 <tr>
1236 <td>
1237 <input type="checkbox" name="selSubContribs" value="%s">
1239 &nbsp;<a href="%s">%s</a>
1240 </td>
1241 </tr>"""%(id, selbox,SCModifURL(sc), escape(sc.getTitle())))
1242 html = """
1243 <input type="hidden" name="oldpos">
1244 <table align="center">%s
1245 </table>"""%"".join( temp )
1246 return html
1248 def getVars( self ):
1249 vars = WTemplated.getVars( self )
1250 cfg = Configuration.Config.getInstance()
1251 vars["subContList"] = self.getSubContItems(vars["subContModifURL"])
1252 vars["confId"] = self._contrib.getConference().getId()
1253 vars["contribId"] = self._contrib.getId()
1254 vars["deleteItemsURL"] = vars["moveSubContribURL"]
1256 return vars
1257 ###ness##################################################################################
1258 # def __getSubCategoryItems( self, sl, modifURLGen ):
1259 # temp = []
1260 # for categ in sl:
1261 # id = categ.getId()
1262 # selbox = """<select name="newpos%s" onChange="this.form.oldpos.value='%s';this.form.submit();">""" % (sl.index(categ),sl.index(categ))
1263 # for i in range (1,len(sl)+1):
1264 # if i==sl.index(categ)+1:
1265 # selbox += "<option selected value='%s'>%s" % (i-1,i)
1266 # else:
1267 # selbox += "<option value='%s'>%s" % (i-1,i)
1268 # selbox += """
1269 # </select>"""
1270 # temp.append("""
1271 # <tr>
1272 # <td>
1273 # <input type="checkbox" name="selectedCateg" value="%s">
1274 # %s
1275 # &nbsp;<a href="%s">%s</a>
1276 # </td>
1277 # </tr>"""%(id, selbox,modifURLGen( categ ), categ.getName()))
1278 # html = """
1279 # <input type="hidden" name="oldpos">
1280 # <table align="center">%s
1281 # </table>"""%"".join( temp )
1282 # return html
1283 ##ness##############################################################################
1285 class WMaterialModifHeader(WTemplated):
1287 def __init__( self, material, aw ):
1288 self._mat = material
1289 self._aw = aw
1291 def getHTML( self, params ):
1292 owner = self._mat.getOwner()
1293 if isinstance( owner, conference.Contribution ):
1294 HTML = WContribModifHeader( owner, self._aw ).getHTML( params )
1295 elif isinstance( owner, conference.SubContribution ):
1296 HTML = WSubContribModifHeader( owner, self._aw ).getHTML( params )
1297 elif isinstance( owner, conference.Session ):
1298 HTML = WSessionModifHeader( owner, self._aw ).getHTML( params )
1299 elif isinstance( owner, conference.Conference ):
1300 HTML = WConfModifHeader( owner, self._aw ).getHTML( params )
1301 elif isinstance( owner, conference.Category):
1302 HTML = WCategoryModificationHeader( owner ).getHTML( params )
1303 return "%s%s"%(HTML, WTemplated.getHTML( self, params ))
1305 def getVars( self ):
1306 vars = WTemplated.getVars( self )
1307 vars["imgGestionGrey"] = Configuration.Config.getInstance().getSystemIconURL( "gestionGrey" )
1308 vars["title"] = escape(self._mat.getTitle())
1309 vars["materialDisplayURL"] = vars["materialDisplayURLGen"](self._mat)
1310 vars["materialModificationURL"] = vars["materialModifURLGen"](self._mat)
1311 vars["titleTabPixels"] = WMaterialModifFrame(self._mat, self._aw).getTitleTabPixels()
1312 return vars
1315 class WConferenceModifFrame(WTemplated):
1317 def __init__( self, conference, aw,):
1318 self.__conf = conference
1319 self._aw = aw
1321 def getHTML( self, body, **params ):
1322 params["body"] = body
1323 return WTemplated.getHTML( self, params )
1325 def getVars( self ):
1326 vars = WTemplated.getVars( self )
1328 vars["conf"] = self.__conf
1329 vars["startDate"] = utils.formatDateTime(self.__conf.getAdjustedStartDate(), format="d MMM")
1330 vars["endDate"] = utils.formatDateTime(self.__conf.getAdjustedEndDate(), format="d MMM")
1332 return vars
1334 class WCategoryModifFrame(WTemplated):
1336 def __init__( self, conference):
1337 self.__conf = conference
1340 def getHTML( self, body, **params ):
1341 params["body"] = body
1342 return WTemplated.getHTML( self, params )
1344 def getVars( self ):
1345 vars = WTemplated.getVars( self )
1346 #p = {"categDisplayURLGen": vars["categDisplayURLGen"] }
1347 #vars["context"] = WCategModifHeader(self.__conf).getHTML(p)
1348 vars["creator"] = ""#self.__conf.getCreator().getFullName()
1349 vars["context"] = ""
1350 vars["imgGestionGrey"] = Configuration.Config.getInstance().getSystemIconURL( "gestionGrey" )
1351 vars["categDisplayURL"] = vars["categDisplayURLGen"]( self.__conf )
1352 vars["title"] = escape(self.__conf.getTitle())
1353 vars["titleTabPixels"] = self.getTitleTabPixels()
1354 vars["intermediateVTabPixels"] = self.getIntermediateVTabPixels()
1355 return vars
1358 def getIntermediateVTabPixels( self ):
1359 return 0
1361 def getTitleTabPixels( self ):
1362 return 260
1364 def getCloseHeaderTags( self ):
1365 return ""
1367 class WNotifTPLModifFrame(WTemplated):
1369 def __init__(self, notifTpl, aw):
1370 self._notifTpl = notifTpl
1371 self._aw = aw
1373 def getHTML( self, body, **params ):
1374 params["body"] = body
1375 return WTemplated.getHTML( self, params )
1377 def getVars( self ):
1378 vars = WTemplated.getVars( self )
1379 conf = self._notifTpl.getConference()
1380 vars["context"] = WConfModifHeader( conf, self._aw ).getHTML(vars)
1381 vars["title"] = self._notifTpl.getName()
1382 vars["titleTabPixels"] = self.getTitleTabPixels()
1383 vars["intermediateVTabPixels"] = self.getIntermediateVTabPixels()
1384 vars["closeHeaderTags"] = self.getCloseHeaderTags()
1385 return vars
1387 def getOwnerComponent( self ):
1388 owner = self._notifTpl.getOwner()
1389 wc = WConferenceModifFrame(owner, self._aw)
1390 return wc
1392 def getIntermediateVTabPixels( self ):
1393 wc = self.getOwnerComponent()
1394 return 7 + wc.getIntermediateVTabPixels()
1396 def getTitleTabPixels( self ):
1397 wc = self.getOwnerComponent()
1398 return wc.getTitleTabPixels() - 7
1400 def getCloseHeaderTags( self ):
1401 wc = self.getOwnerComponent()
1402 return "</table></td></tr>" + wc.getCloseHeaderTags()
1405 class WScheduleContributionModifFrame(WTemplated):
1407 def __init__( self, contribution, aw, days, handler=urlHandlers.UHContributionModification):
1408 self._contrib = contribution
1409 self._conf = self._contrib.getConference()
1410 self._aw = aw
1411 self._days = days
1412 self._handler = handler
1414 def getHTML( self, body, **params ):
1416 params["body"] = body
1418 dateList = [d.getDate() for d in self._days]
1420 # Keep contributions that happen in the selected day(s)
1422 # DEBUG
1424 for c in self._conf.getContributionList():
1425 assert(type(c.getStartDate()) == datetime),"Not all dates are present for the contributions!"
1429 l = []
1430 for contrib in self._conf.getContributionList():
1431 if contrib.getStartDate().date() in dateList:
1432 l.append(contrib)
1433 params["contribList"] = l
1434 params["handler"] = self._handler
1436 return WTemplated.getHTML( self, params )
1438 class WContributionModifFrame(WTemplated):
1440 def __init__( self, contribution, aw):
1441 self._contrib = contribution
1442 self._aw = aw
1444 def getHTML( self, body, **params ):
1445 params["body"] = body
1446 return WTemplated.getHTML( self, params )
1448 def getVars( self ):
1449 vars = WTemplated.getVars( self )
1450 vars["target"] = self._contrib
1451 return vars
1454 class WMaterialModifFrame(WTemplated):
1456 def __init__( self, material, aw):
1457 self._material = material
1458 self._aw = aw
1460 def getHTML( self, body, **params ):
1461 params["body"] = body
1462 return WTemplated.getHTML( self, params )
1464 def getVars( self ):
1465 closeHeaderTags = "</table></td></tr>"
1466 vars = WTemplated.getVars( self )
1467 vars["imgGestionGrey"] = Config.getInstance().getSystemIconURL( "gestionGrey" )
1468 owner = self._material.getOwner()
1469 if isinstance(owner, conference.Contribution):
1470 wc = WContribModifHeader( owner, self._aw )
1471 elif isinstance(owner, conference.Session):
1472 wc = WSessionModifHeader( owner, self._aw )
1473 elif isinstance(owner, conference.SubContribution):
1474 wc = WSubContribModifHeader( owner, self._aw )
1475 elif isinstance(owner, conference.Category) :
1476 wc = WCategoryModificationHeader(owner)
1477 else:
1478 wc = WConfModifHeader( owner, self._aw )
1479 vars["context"] = wc.getHTML( vars )
1480 vars["closeHeaderTags"] = self.getCloseHeaderTags()
1481 vars["intermediateVTabPixels"] = self.getIntermediateVTabPixels()
1482 vars["titleTabPixels"] = self.getTitleTabPixels()
1483 vars["title"] = escape(self._material.getTitle())
1484 vars["materialDisplayURL"] = vars["materialDisplayURLGen"]( self._material )
1485 return vars
1487 def getOwnerComponent( self ):
1488 owner = self._material.getOwner()
1489 if isinstance(owner, conference.Contribution):
1490 wc = WContributionModifFrame(owner, self._aw)
1491 elif isinstance(owner, conference.Session):
1492 wc = WSessionModifFrame(owner, self._aw)
1493 elif isinstance(owner, conference.SubContribution):
1494 wc = WSubContributionModifFrame(owner, self._aw)
1496 else:
1497 wc = WConferenceModifFrame(owner, self._aw)
1498 return wc
1500 def getIntermediateVTabPixels( self ):
1501 wc = self.getOwnerComponent()
1502 return 7 + wc.getIntermediateVTabPixels()
1504 def getTitleTabPixels( self ):
1505 wc = self.getOwnerComponent()
1506 return wc.getTitleTabPixels() - 7
1508 def getCloseHeaderTags( self ):
1509 wc = self.getOwnerComponent()
1510 return "</table></td></tr>" + wc.getCloseHeaderTags()
1513 class WResourceModifFrame(WTemplated):
1515 def __init__( self, resource, aw):
1516 self._resource = resource
1517 self._aw = aw
1519 def getHTML( self, body, **params ):
1520 params["body"] = body
1521 return WTemplated.getHTML( self, params )
1523 def getVars( self ):
1524 vars = WTemplated.getVars( self )
1525 wc = WMaterialModifHeader( self._resource.getOwner(), self._aw )
1526 vars["context"] = wc.getHTML( vars )
1527 vars["name"] = self._resource.getName()
1528 vars["intermediateVTabPixels"] = self.getIntermediateVTabPixels()
1529 vars["titleTabPixels"] = self.getTitleTabPixels()
1530 vars["closeHeaderTags"] = self.getCloseHeaderTags()
1531 return vars
1533 def getOwnerComponent( self ):
1534 owner = self._resource.getOwner()
1535 wc = WMaterialModifFrame(owner, self._aw)
1536 return wc
1538 def getIntermediateVTabPixels( self ):
1539 wc = self.getOwnerComponent()
1540 return 7 + wc.getIntermediateVTabPixels()
1542 def getTitleTabPixels( self ):
1543 wc = self.getOwnerComponent()
1544 return wc.getTitleTabPixels() - 7
1546 def getCloseHeaderTags( self ):
1547 wc = self.getOwnerComponent()
1548 return "</table></td></tr>" + wc.getCloseHeaderTags()
1551 class WFileModifFrame( WResourceModifFrame ):
1552 pass
1555 class WLinkModifFrame( WResourceModifFrame ):
1556 pass
1560 class ModifFrameFactory:
1562 def getFrameClass( cls, target ):
1563 if isinstance(target, conference.Conference):
1564 return WConferenceModifFrame
1565 if isinstance( target, conference.Session ):
1566 return WSessionModifFrame
1567 if isinstance( target, conference.Contribution ):
1568 return WContributionModifFrame
1569 if isinstance( target, conference.SubContribution ):
1570 return WSubContributionModifFrame
1571 if isinstance(target, conference.Material):
1572 return WMaterialModifFrame
1573 if isinstance(target, conference.LocalFile):
1574 return WFileModifFrame
1575 if isinstance( target, conference.Link ):
1576 return WLinkModifFrame
1577 return None
1578 getFrameClass = classmethod( getFrameClass )
1580 def getModifFrame( target ):
1581 f = ModifFrameFactory.getFrameClass( target )
1582 if f:
1583 return f( target )
1584 return None
1585 getModifFrame = staticmethod( getModifFrame )
1588 class WSubContributionDisplay:
1590 def __init__(self, aw, subContrib):
1591 self._aw = aw
1592 self._subContrib = subContrib
1594 def getHTML( self, params ):
1595 if self._subContrib.canAccess( self._aw ):
1596 c = WSubContributionDisplayFull( self._aw, self._subContrib)
1597 return c.getHTML( params )
1598 if self._subContrib.canView( self._aw ):
1599 c = WSubContributionDisplayMin( self._aw, self._subContrib)
1600 return c.getHTML( params )
1601 return ""
1603 class WSubContributionDisplayBase(WTemplated):
1605 def __init__(self, aw, subContrib):
1606 self._aw = aw
1607 self._subContrib = subContrib
1609 def __getHTMLRow( self, title, body):
1610 if body.strip() == "":
1611 return ""
1612 str = """
1613 <tr>
1614 <td valign="top" align="right">
1615 <font size="-1" color="#000060">%s:</font>
1616 </td>
1617 <td width="100%%">%s</td>
1618 </tr>"""%(title, body)
1619 return str
1621 def getVars( self ):
1622 vars = WTemplated.getVars( self )
1623 vars["title"] = self._subContrib.getTitle()
1624 vars["description"] = self._subContrib.getDescription()
1625 vars["modifyItem"] = ""
1626 if self._subContrib.canModify( self._aw ):
1627 vars["modifyItem"] = """<a href="%s"><img src="%s" alt="Jump to the modification interface"></a> """%(vars["modifyURL"], Configuration.Config.getInstance().getSystemIconURL( "modify" ) )
1628 l=[]
1629 for speaker in self._subContrib.getSpeakerList():
1630 l.append( """<a href="mailto:%s">%s</a>"""%(speaker.getEmail(), \
1631 speaker.getFullName()))
1632 l.append(self._subContrib.getSpeakerText())
1633 vars["speakers"] = self.__getHTMLRow( _("Presenters"), "<br>".join( l ) )
1634 lm = []
1635 for material in self._subContrib.getAllMaterialList():
1636 lm.append( WMaterialDisplayItem().getHTML( self._aw, material, \
1637 vars["materialURLGen"]( material) ))
1638 vars["material"] = self.__getHTMLRow( "Material", "<br>".join( lm ) )
1639 vars["duration"] = (datetime(1900,1,1)+self._subContrib.getDuration()).strftime("%M'")
1640 if int(self._subContrib.getDuration().seconds/3600)>0:
1641 vars["duration"] = (datetime(1900,1,1)+self._subContrib.getDuration()).strftime("%Hh%M'")
1642 return vars
1645 class WSubContributionDisplayFull(WSubContributionDisplayBase):
1646 pass
1649 class WSubContributionDisplayMin(WSubContributionDisplayBase):
1650 pass
1653 class WMaterialDisplayItem(WTemplated):
1655 def getHTML( self, aw, material, URL="", icon=Configuration.Config.getInstance().getSystemIconURL( "material" ) ):
1656 if material.canView( aw ):
1658 return """<a href=%s>%s</a>"""%(quoteattr( str( URL ) ), WTemplated.htmlText( material.getTitle() ) )
1659 return ""
1662 class WBreakDataModification(WTemplated):
1664 def __init__(self,sch,breakEntry=None,targetDay=None,conf=None):
1665 self._break=breakEntry
1666 if self._break!=None:
1667 self._sch=self._break.getSchedule()
1668 else:
1669 self._sch=sch
1670 self._targetDay=targetDay
1671 self._conf=conf
1673 def getVars( self ):
1674 vars = WTemplated.getVars( self )
1675 defaultDefinePlace = defaultDefineRoom = ""
1676 defaultInheritPlace = defaultInheritRoom = "checked"
1677 locationName, locationAddress, roomName = "", "", ""
1678 if self._break is not None:
1679 wpTitle = _("Break entry data modification")
1680 title=self._break.getTitle()
1681 description=self._break.getDescription()
1682 tz = self._conf.getTimezone()
1683 sDate=convertTime.convertTime(self._break.getStartDate(),self._conf.getTimezone())
1684 day=sDate.day
1685 month=sDate.month
1686 year=sDate.year
1687 sHour=sDate.hour
1688 sMinute=sDate.minute
1689 durHours=int(self._break.getDuration().seconds/3600)
1690 durMinutes=int((self._break.getDuration().seconds%3600)/60)
1691 if self._break.getOwnLocation() is not None:
1692 defaultDefinePlace = "checked"
1693 defaultInheritPlace = ""
1694 locationName = self._break.getLocation().getName()
1695 locationAddress = self._break.getLocation().getAddress()
1696 if self._break.getOwnRoom() is not None:
1697 defaultDefineRoom= "checked"
1698 defaultInheritRoom = ""
1699 roomName = self._break.getRoom().getName()
1700 bgcolor=self._break.getColor()
1701 textcolor=self._break.getTextColor()
1702 textcolortolinks=""
1703 if self._break.isTextColorToLinks():
1704 textcolortolinks="checked=\"checked\""
1705 schOptions= i18nformat("""&nbsp;<input type="checkbox" name="moveEntries" value="1"> _("reschedule entries after this time")""")
1706 else:
1707 wpTitle = "Create new break"
1708 title, description = "break", ""
1709 refDate=self._sch.getFirstFreeSlotOnDay(self._targetDay)
1710 day = refDate.day
1711 month = refDate.month
1712 year = refDate.year
1713 sHour = refDate.hour
1714 sMinute = refDate.minute
1715 durHours, durMinutes = 0, 15
1716 bgcolor="#90C0F0"
1717 textcolor="#777777"
1718 schOptions=""
1719 textcolortolinks=False
1720 vars["defaultInheritPlace"] = defaultInheritPlace
1721 vars["defaultDefinePlace"] = defaultDefinePlace
1722 vars["ownerPlace"] = ""
1723 owner = self._sch.getOwner()
1724 vars["ownerType"]="conference"
1725 if isinstance(owner, conference.SessionSlot):
1726 vars["ownerType"]="session"
1727 ownerLocation = owner.getLocation()
1728 if ownerLocation:
1729 vars["ownerPlace"] = ownerLocation.getName()
1730 vars["locationName"] = quoteattr(str(locationName))
1731 vars["locationAddress"] = locationAddress
1732 vars["defaultInheritRoom"] = defaultInheritRoom
1733 vars["defaultDefineRoom"] = defaultDefineRoom
1734 vars["ownerRoom"] = ""
1735 ownerRoom =owner.getRoom()
1736 if ownerRoom:
1737 vars["ownerRoom"] = ownerRoom.getName()
1738 vars["roomName"] = quoteattr(str(roomName))
1740 vars["WPtitle"]=wpTitle
1741 vars["title"]=quoteattr(str(title))
1742 vars["description"]=self.htmlText(description)
1743 vars["sDay"]=str(day)
1744 vars["sMonth"]=str(month)
1745 vars["sYear"]=str(year)
1746 vars["sHour"]=str(sHour)
1747 vars["sMinute"]=str(sMinute)
1748 vars["durationHours"]=quoteattr(str(durHours))
1749 vars["durationMinutes"]=quoteattr(str(durMinutes))
1750 vars["postURL"]=quoteattr(str(vars["postURL"]))
1751 vars["colorChartIcon"]=Config.getInstance().getSystemIconURL("colorchart")
1752 urlbg=urlHandlers.UHSimpleColorChart.getURL()
1753 urlbg.addParam("colorCodeTarget", "backgroundColor")
1754 urlbg.addParam("colorPreviewTarget", "backgroundColorpreview")
1755 vars["bgcolorChartURL"]=urlbg
1756 vars["bgcolor"] = bgcolor
1757 urltext=urlHandlers.UHSimpleColorChart.getURL()
1758 urltext.addParam("colorCodeTarget", "textColor")
1759 urltext.addParam("colorPreviewTarget", "textColorpreview")
1760 vars["textcolorChartURL"]=urltext
1761 vars["textcolor"] = textcolor
1762 vars["textColorToLinks"] = textcolortolinks
1763 vars["calendarIconURL"]=Config.getInstance().getSystemIconURL( "calendar" )
1764 vars["calendarSelectURL"]=urlHandlers.UHSimpleCalendar.getURL()
1765 vars["schOptions"]=schOptions
1766 vars["autoUpdate"]=""
1767 import MaKaC.webinterface.webFactoryRegistry as webFactoryRegistry
1768 wr = webFactoryRegistry.WebFactoryRegistry()
1769 wf = wr.getFactory(self._conf)
1770 if wf != None:
1771 type = wf.getId()
1772 else:
1773 type = "conference"
1774 if type == "conference":
1775 vars["Colors"]=WSessionModEditDataColors().getHTML(vars)
1776 else:
1777 vars["Colors"]=""
1778 vars["conference"] = self._conf
1779 minfo = info.HelperMaKaCInfo.getMaKaCInfoInstance()
1780 vars["useRoomBookingModule"] = minfo.getRoomBookingModuleActive()
1782 vars['rbActive'] = info.HelperMaKaCInfo.getMaKaCInfoInstance().getRoomBookingModuleActive()
1783 return vars
1786 class WMaterialTable( WTemplated ):
1787 # Deprecated - used in old file management scheme
1789 def __init__(self, matOwner, registry = None ):
1790 self._owner = matOwner
1791 self._fr = registry
1793 def _getAdditionalMaterialItems( self ):
1794 l = []
1795 for mat in self._owner.getMaterialList():
1796 l.append("""
1797 <tr>
1798 <td>
1799 <table cellpadding="1" cellspacing="1">
1800 <tr>
1801 <td align="left">
1802 <input type="checkbox" name="deleteMaterial" value="%s">
1803 </td>
1804 <td align="left">
1805 <img src="%s" style="vertical-align:middle" alt="">
1806 </td>
1807 <td align="left">&nbsp;</td>
1808 <td align="left" width="100%%">
1809 <a href="%s">%s</a>
1810 </td>
1811 </tr>
1812 </table>
1813 </td>
1814 </tr>
1815 """%(mat.getId(), Config.getInstance().getSystemIconURL("material"), self._modifyURLGen( mat ), mat.getTitle() ) )
1816 return "".join(l)
1818 def _getSpecialMaterialItems( self ):
1819 if not self._fr:
1820 return ""
1821 l = []
1822 for factory in self._fr.getList():
1823 if factory.canDelete( self._owner ):
1824 icon = ""
1825 if factory.getIconURL():
1826 icon = """<img src="%s" style="vertical-align:middle" alt="">"""%factory.getIconURL()
1827 mat = factory.get( self._owner )
1828 l.append(""" <tr>
1829 <td valing="bottom">
1830 <table cellpadding="1" cellspacing="1">
1831 <tr>
1832 <td align="left">
1833 <input type="checkbox" name="deleteMaterial" value="%s">
1834 </td>
1835 <td align="left">
1837 </td>
1838 <td align="left">&nbsp;</td>
1839 <td align="left" width="100%%">
1840 <a href="%s">%s</a>
1841 </td>
1842 </tr>
1843 </table>
1844 </td>
1845 </tr>
1846 """%(factory.getId(), icon, factory.getModificationURL( mat ), mat.getTitle()))
1847 return "".join(l)
1849 def getHTML( self, addURL, removeURL, modifyURLGen ):
1850 self._modifyURLGen = modifyURLGen
1851 params={"addURL": addURL, "deleteURL": removeURL}
1853 hiddenParams = self._owner.getLocator().getWebForm()
1855 return WTemplated.getHTML( self, params )
1857 def getVars( self ):
1858 vars = WTemplated.getVars( self )
1859 vars["items"] = "%s%s"%(self._getSpecialMaterialItems(), \
1860 self._getAdditionalMaterialItems())
1861 vars["locator"] = self._owner.getLocator().getWebForm()
1862 l = []
1863 if self._fr:
1864 for factory in self._fr.getList():
1865 if factory.canAdd( self._owner ):
1866 l.append("""<option value="%s">%s</option>"""%(\
1867 factory.getId(), factory.getTitle()))
1868 vars["matTypesSelectItems"] = "".join(l)
1869 return vars
1872 class WAccessControlFrame(WTemplated):
1874 def getHTML( self, target, setVisibilityURL, type ):
1875 self.__target = target
1877 params = { "setPrivacyURL": setVisibilityURL,\
1878 "target": target,\
1879 "type": type }
1880 return WTemplated.getHTML( self, params )
1882 def getVars( self ):
1883 vars = WTemplated.getVars( self )
1885 if self.__target.getAccessProtectionLevel() == -1:
1886 vars["privacy"] = "PUBLIC"
1887 vars["statusColor"] = "#128F33"
1888 elif self.__target.isItselfProtected():
1889 vars["privacy"] = "PRIVATE"
1890 vars["statusColor"] = "#B02B2C"
1891 else :
1892 vars["privacy"] = "INHERITING"
1893 vars["statusColor"] = "#444444"
1895 vars["isFullyPublic"] = None
1897 if not isinstance(self.__target, Category) :
1898 vars["isFullyPublic"] = self.__target.isFullyPublic()
1900 if isinstance(self.__target, Category) and self.__target.isRoot():
1901 vars["parentName"] = vars["parentPrivacy"] = vars["parentStatusColor"] = ''
1902 else :
1903 vars["parentName"] = self.__target.getOwner().getTitle()
1905 if self.__target.hasProtectedOwner():
1906 vars["parentPrivacy"] = "PRIVATE"
1907 vars["parentStatusColor"] = "#B02B2C"
1908 else :
1909 vars["parentPrivacy"] = "PUBLIC"
1910 vars["parentStatusColor"] = "#128F33"
1912 vars["locator"] = self.__target.getLocator().getWebForm()
1913 vars["contactInfo"] = self.__target.getAccessController().getContactInfo()
1914 return vars
1917 class WConfAccessControlFrame(WTemplated):
1919 def getHTML( self, target, setVisibilityURL, setAccessKeyURL):
1920 self.__target = target
1921 params = { "target": target,\
1922 "setPrivacyURL": setVisibilityURL,\
1923 "setAccessKeyURL": setAccessKeyURL,\
1924 "type": "Event" }
1925 return WTemplated.getHTML( self, params )
1927 def getVars( self ):
1928 vars = WTemplated.getVars( self )
1930 if self.__target.getAccessProtectionLevel() == -1:
1931 vars["privacy"] = "PUBLIC"
1932 vars["statusColor"] = "#128F33"
1933 elif self.__target.isItselfProtected():
1934 vars["privacy"] = "PRIVATE"
1935 vars["statusColor"] = "#B02B2C"
1936 else :
1937 vars["privacy"] = "INHERITING"
1938 vars["statusColor"] = "#444444"
1940 vars["isFullyPublic"] = self.__target.isFullyPublic()
1941 vars["parentName"] = self.__target.getOwner().getName()
1943 if self.__target.hasProtectedOwner():
1944 vars["parentPrivacy"] = "PRIVATE"
1945 vars["parentStatusColor"] = "#B02B2C"
1946 else :
1947 vars["parentPrivacy"] = "PUBLIC"
1948 vars["parentStatusColor"] = "#128F33"
1950 vars["locator"] = self.__target.getLocator().getWebForm()
1951 vars["accessKey"] = self.__target.getAccessKey()
1952 vars["contactInfo"] = self.__target.getAccessController().getContactInfo()
1953 return vars
1956 class WUserTableItem(WTemplated):
1958 def __init__(self, multi=True):
1959 self._multi = multi
1961 def getHTML( self, user, selected=False, selectable=True, parentPrincipalTableId=None ):
1962 self.__user = user
1963 self._selected = selected
1964 self._selectable = selectable
1965 self._parentPrincipalTableId = parentPrincipalTableId
1966 return WTemplated.getHTML( self, {} )
1968 def getVars( self ):
1969 vars = WTemplated.getVars( self )
1971 vars["ParentPrincipalTableId"] = self._parentPrincipalTableId
1973 vars["avatar"] = fossilize(self.__user, IAvatarFossil)
1975 vars["id"] = self.__user.getId()
1976 vars["email"] = self.__user.getEmail()
1977 vars["fullName"] = self.__user.getFullName()
1979 vars["selectable"] = self._selectable
1980 vars["inputType"] = "checkbox"
1981 selectionText = "checked"
1982 if not self._multi:
1983 vars["inputType"] = "radio"
1984 selectionText = "selected"
1985 vars["selected"] = ""
1986 if self._selected:
1987 vars["selected"] = selectionText
1989 if self._rh._getUser():
1990 vars["currentUserBasket"] = self._rh._getUser().getPersonalInfo().getBasket()
1991 else:
1992 vars["currentUserBasket"] = None
1994 return vars
1996 class WPendingUserTableItem(WTemplated):
1998 def getHTML( self, email, selectable=True ):
1999 self.email = email
2000 self._selectable = selectable
2001 return WTemplated.getHTML( self, {} )
2003 def getVars( self ):
2004 vars = WTemplated.getVars( self )
2005 vars["email"] = self.email
2006 vars["selectable"] = self._selectable
2008 return vars
2010 class WGroupTableItem(WTemplated):
2012 def __init__(self, multi=True):
2013 self._multi = multi
2015 def getHTML( self, group, selected=False, selectable=True ):
2016 self.__group = group
2017 self._selected = selected
2018 self._selectable = selectable
2019 return WTemplated.getHTML( self, {} )
2021 def getVars( self ):
2022 vars = WTemplated.getVars( self )
2023 vars["groupImg"] = Configuration.Config.getInstance().getSystemIconURL("group")
2024 vars["id"] = self.__group.getId()
2025 vars["fullName"] = self.__group.getName()
2026 vars["type"] = "checkbox"
2027 selectionText = "checked"
2028 if not self._multi:
2029 vars["type"] = "radio"
2030 selectionText = "selected"
2031 vars["selected"] = ""
2032 if self._selected:
2033 vars["selected"] = selectionText
2034 vars["selectable"] = self._selectable
2035 return vars
2037 class WGroupNICETableItem(WTemplated):
2039 def __init__(self, multi=True):
2040 self._multi = multi
2042 def getHTML( self, group, selected=False, selectable=True ):
2043 self.__group = group
2044 self._selected = selected
2045 self._selectable = selectable
2046 return WTemplated.getHTML( self, {} )
2048 def getVars( self ):
2049 vars = WTemplated.getVars( self )
2050 vars["id"] = self.__group.getId()
2051 vars["fullName"] = self.__group.getName()
2052 vars["type"] = "checkbox"
2053 selectionText = "checked"
2054 if not self._multi:
2055 vars["type"] = "radio"
2056 selectionText = "selected"
2057 vars["selected"] = ""
2058 if self._selected:
2059 vars["selected"] = selectionText
2060 vars["selectable"] = self._selectable
2061 return vars
2063 class WAuthorTableItem(WTemplated):
2065 def __init__(self, multi=False):
2066 self._multi = multi
2068 def getHTML( self, author, selected=False ):
2069 self.__author = author
2070 self._selected = selected
2071 return WTemplated.getHTML( self, {} )
2073 def getVars( self ):
2074 vars = WTemplated.getVars( self )
2075 vars["id"] = "*author*:%s"%conference.AuthorIndex()._getKey(self.__author)
2076 vars["fullName"] = self.__author.getFullName()
2077 vars["type"] = "checkbox"
2078 selectionText = "checked"
2079 if not self._multi:
2080 vars["type"] = "radio"
2081 selectionText = "selected"
2082 vars["selected"] = ""
2083 if self._selected:
2084 vars["selected"] = selectionText
2085 return vars
2088 class WPrincipalTable(WTemplated):
2090 def __init__(self):
2091 WTemplated.__init__(self)
2092 if not "principalTableCounter" in ContextManager.get():
2093 ContextManager.set("principalTableCounter", 0)
2094 self._principalTableId = ContextManager.get("principalTableCounter")
2095 ContextManager.set("principalTableCounter", self._principalTableId + 1)
2097 def getHTML( self, principalList, target, addPrincipalsURL, removePrincipalsURL, pendings=[], selectable=True ):
2098 self.__principalList = principalList[:]
2099 self.__principalList.sort(utils.sortPrincipalsByName)
2100 self.__pendings = pendings
2101 self.__target = target
2102 self.__selectable = selectable;
2103 return WTemplated.getHTML( self, {"addPrincipalsURL": addPrincipalsURL,\
2104 "removePrincipalsURL": removePrincipalsURL } )
2106 def getVars( self ):
2107 vars = WTemplated.getVars( self )
2108 vars["locator"] = ""
2109 if self.__target:
2110 vars["locator"] = self.__target.getLocator().getWebForm()
2111 ul = []
2112 selected = False
2113 if len(self.__principalList) == 1:
2114 selected = True
2115 for principal in self.__principalList:
2116 if isinstance(principal, user.Avatar):
2117 ul.append( WUserTableItem().getHTML( principal, selected, self.__selectable, self._principalTableId ) )
2118 elif isinstance(principal, user.CERNGroup):
2119 ul.append( WGroupNICETableItem().getHTML( principal, selected, self.__selectable ) )
2120 elif isinstance(principal, user.Group):
2121 ul.append( WGroupTableItem().getHTML( principal, selected, self.__selectable ) )
2122 for email in self.__pendings:
2123 ul.append(WPendingUserTableItem().getHTML(email, self.__selectable))
2124 vars["userItems"] = "".join( ul )
2125 return vars
2128 class WModificationControlFrame(WTemplated):
2130 def getHTML( self, target, addManagersURL, removeManagersURL ):
2131 self.__target = target
2132 params = { "addManagersURL": addManagersURL, \
2133 "removeManagersURL": removeManagersURL }
2134 return WTemplated.getHTML( self, params )
2136 def getVars( self ):
2137 vars = WTemplated.getVars( self )
2138 vars["locator"] = self.__target.getLocator().getWebForm()
2139 vars["principalTable"] = WPrincipalTable().getHTML( self.__target.getManagerList(),
2140 self.__target,vars["addManagersURL"],
2141 vars["removeManagersURL"],
2142 pendings=self.__target.getAccessController().getModificationEmail(),
2143 selectable=False)
2145 return vars
2148 class WConfModificationControlFrame(WTemplated):
2150 def getHTML( self, target, addManagersURL, removeManagersURL, setModifKeyURL ):
2151 self.__target = target
2152 params = { "addManagersURL": addManagersURL, \
2153 "removeManagersURL": removeManagersURL, \
2154 "setModifKeyURL": setModifKeyURL,
2155 "target": target }
2156 return WTemplated.getHTML( self, params )
2158 def getVars( self ):
2159 vars = WTemplated.getVars( self )
2160 vars["locator"] = self.__target.getLocator().getWebForm()
2161 vars["principalTable"] = WPrincipalTable().getHTML( self.__target.getManagerList(),
2162 self.__target, vars["addManagersURL"],
2163 vars["removeManagersURL"],
2164 pendings=self.__target.getAccessController().getModificationEmail(),
2165 selectable=False)
2166 vars["modifKey"] = self.__target.getModifKey()
2167 return vars
2169 class WConfRegistrarsControlFrame(WTemplated):
2171 def getHTML(self, target, addRegistrarURL, removeRegistrarURL):
2172 self.__target = target
2173 params = {
2174 "addRegistrarURL": addRegistrarURL,
2175 "removeRegistrarURL": removeRegistrarURL
2177 return WTemplated.getHTML( self, params )
2179 def getVars( self ):
2180 vars = WTemplated.getVars( self )
2181 vars["principalTable"] = WPrincipalTable().getHTML( self.__target.getRegistrarList(), self.__target, vars["addRegistrarURL"], vars["removeRegistrarURL"], selectable=False)
2182 return vars
2185 class WConfProtectionToolsFrame(WTemplated):
2187 def __init__( self, target ):
2188 self._target = target
2190 def getVars( self ):
2191 vars = WTemplated.getVars( self )
2192 vars["grantSubmissionToAllSpeakersURL"] = str(urlHandlers.UHConfGrantSubmissionToAllSpeakers.getURL(self._target))
2193 vars["removeAllSubmissionRightsURL"] = str(urlHandlers.UHConfRemoveAllSubmissionRights.getURL(self._target))
2194 vars["grantModificationToAllConvenersURL"] = str(urlHandlers.UHConfGrantModificationToAllConveners.getURL(self._target))
2195 return vars
2197 class WDomainControlFrame(WTemplated):
2199 def __init__( self, target ):
2200 self._target = target
2202 def getHTML(self, addURL, removeURL):
2203 self._addURL = addURL
2204 self._removeURL = removeURL
2205 return WTemplated.getHTML( self )
2207 def getVars( self ):
2208 vars = WTemplated.getVars( self )
2209 l = []
2210 for dom in self._target.getDomainList():
2211 l.append("""<input type="checkbox" name="selectedDomain" value="%s"> %s"""%(dom.getId(), dom.getName()))
2212 vars["domains"] = "<br>".join(l)
2213 l = []
2214 for dom in domain.DomainHolder().getList():
2215 if dom not in self._target.getDomainList():
2216 l.append("""<option value="%s">%s</option>"""%(dom.getId(), dom.getName()))
2217 vars["domainsToAdd"] = "".join(l)
2218 vars["removeURL"] = self._removeURL
2219 vars["addURL"] = self._addURL
2220 vars["locator"] = self._target.getLocator().getWebForm()
2221 return vars
2224 class WMaterialDataModificationBase(WTemplated):
2226 def __init__( self, material ):
2227 self._material = material
2228 self._owner = material.getOwner()
2230 def _setMaterialValues( self, material, materialData ):
2231 material.setTitle( materialData["title"] )
2232 material.setDescription( materialData["description"] )
2233 if "type" in materialData:
2234 material.setType( materialData["type"] )
2236 def _getTypesSelectItems( self, default = "misc" ):
2237 definedTypes = ["misc"]
2238 l = []
2239 for type in definedTypes:
2240 default = ""
2241 if type == default:
2242 default = "default"
2243 l.append("""<option value="%s" %s>%s</option>"""%( type, default, type ))
2244 return "".join( l )
2248 class WMaterialCreation(WMaterialDataModificationBase):
2250 def __init__( self, owner):
2251 self._owner = owner
2254 def getVars( self ):
2255 vars = WMaterialDataModificationBase.getVars( self )
2256 vars["title"] = ""
2257 vars["description"] = ""
2258 vars["types"] = self._getTypesSelectItems()
2259 vars["locator"] = self._owner.getLocator().getWebForm()
2260 return vars
2262 def create( self, materialData ):
2263 m = conference.Material()
2264 self._setMaterialValues( m, materialData )
2265 self._owner.addMaterial( m )
2266 return m
2268 class WInlineContextHelp(WTemplated):
2270 def __init__(self, content):
2271 self._content = content
2273 def getVars( self ):
2274 vars = WTemplated.getVars( self )
2275 vars["helpContent"] = self._content
2276 vars["imgSrc"] = Config.getInstance().getSystemIconURL( "help" )
2277 return vars
2279 #class WPaperDataModification( WMaterialDataModification ):
2280 # pass
2282 #class WMaterialModification( WTemplated ):
2284 # def __init__( self, material ):
2285 # self._material = material
2286 # self.__conf = material.getConference()
2287 # self.__session = material.getSession()
2288 # self.__contrib = material.getContribution()
2290 # def getVars( self ):
2291 # vars = WTemplated.getVars( self )
2292 # vars["locator"] = self._material.getLocator().getWebForm()
2293 # vars["confTitle"] = self.__conf.getTitle()
2294 # vars["sessionTitle"] = ""
2295 # if self.__session != None:
2296 # vars["sessionTitle"] = self.__session.getTitle()
2297 # vars["contributionTitle"] = ""
2298 # if self.__contrib != None:
2299 # vars["contributionTitle"] = self.__contrib.getTitle()
2300 # vars["title"] = self._material.getTitle()
2301 # vars["description"] = self._material.getDescription()
2302 # vars["type"] = self._material.getType()
2303 # l = []
2304 # for res in self._material.getResourceList():
2305 # if res.__class__ is conference.LocalFile:
2306 # l.append( """<li><input type="checkbox" name="removeResources" value="%s"><small>[%s]</small> <b><a href="%s">%s</a></b> (%s) - <small>%s bytes</small></li>"""%(res.getId(), res.getFileType(), vars["modifyFileURLGen"](res), res.getName(), res.getFileName(), strfFileSize( res.getSize() )))
2307 # elif res.__class__ is conference.Link:
2308 # l.append( """<li><input type="checkbox" name="removeResources" value="%s"><b><a href="%s">%s</a></b> (%s)</li>"""%(res.getId(), vars["modifyLinkURLGen"](res), res.getName(), res.getURL()))
2309 # vars["resources"] = "<ol>%s</ol>"%"".join( l )
2310 # vars["accessControlFrame"] = WAccessControlFrame().getHTML(\
2311 # self._material,\
2312 # vars["setVisibilityURL"],\
2313 # vars["addAllowedURL"],\
2314 # vars["removeAllowedURL"] )
2315 # if not self._material.isProtected():
2316 # df = WDomainControlFrame( self._material )
2317 # vars["accessControlFrame"] += "<br>%s"%df.getHTML( \
2318 # vars["addDomainURL"], \
2319 # vars["removeDomainURL"] )
2320 # return vars
2323 #class WResourceSubmission(WTemplated):
2325 # def _setObjects( self, confId, sessionId, contribId, materialId ):
2326 # ch = conference.ConferenceHolder()
2327 # self._conf = ch.getById( confId )
2328 # self._session = self._contrib = self._material = None
2329 # self._matParent = self._conf
2330 # if sessionId != None and sessionId != "":
2331 # self._session = self._conf.getSessionById( sessionId )
2332 # self._matParent = self._session
2333 # if contribId != None and contribId != "":
2334 # self._contrib = self._session.getContributionById( contribId )
2335 # self._matParent = self._contrib
2336 # elif contribId != None and contribId != "":
2337 # self._contrib = self._conf.getContributionById( contribId )
2338 # self._matParent = self._contrib
2339 # if materialId != None and materialId != "":
2340 # self._material = self._matParent.getMaterialById( materialId )
2342 # def getHTML( self, confId, sessionId, contribId, materialId, params ):
2343 # self._setObjects( confId, sessionId, contribId, materialId )
2344 # str = """
2345 # <form action="%s" method="POST" enctype="multipart/form-data">
2346 # <input type="hidden" name="confId" value="%s">
2347 # <input type="hidden" name="sessionId" value="%s">
2348 # <input type="hidden" name="contribId" value="%s">
2349 # <input type="hidden" name="materialId" value="%s">
2350 # %s
2351 # </form>
2352 # """%(params["postURL"], confId, sessionId, contribId, \
2353 # materialId, WTemplated.getHTML( self, params ) )
2354 # return str
2357 #class WFileSubmission(WTemplated):
2359 # def __init__(self, material):
2360 # self.__material = material
2362 # def getHTML( self, params ):
2363 # str = """
2364 # <form action="%s" method="POST" enctype="multipart/form-data">
2365 # %s
2366 # %s
2367 # </form>
2368 # """%(params["postURL"], \
2369 # self.__material.getLocator().getWebForm(),\
2370 # WTemplated.getHTML( self, params ) )
2371 # return str
2373 # def submit( self, params ):
2374 # f = conference.LocalFile()
2375 # f.setName( params["title"] )
2376 # f.setDescription( params["description"] )
2377 # f.setFileName( params["fileName"] )
2378 # f.setFilePath( params["filePath"] )
2379 # self.__material.addResource( f )
2380 # return "[done]"
2383 #class WLinkSubmission(WResourceSubmission):
2385 # def __init__(self, material):
2386 # self.__material = material
2388 # def getHTML( self, params ):
2389 # str = """
2390 # <form action="%s" method="POST" enctype="multipart/form-data">
2391 # %s
2392 # %s
2393 # </form>
2394 # """%(params["postURL"], \
2395 # self.__material.getLocator().getWebForm(),\
2396 # WTemplated.getHTML( self, params ) )
2397 # return str
2399 # def submit( self, params ):
2400 # l = conference.Link()
2401 # l.setName( params["title"] )
2402 # l.setDescription( params["description"] )
2403 # l.setURL( params["url"] )
2404 # self.__material.addResource( l )
2405 # return "[done]"
2408 class WResourceModification(WTemplated):
2410 def __init__( self, resource ):
2411 self._resource = resource
2412 self._conf = resource.getConference()
2413 self._session = resource.getSession()
2414 self._contrib = resource.getContribution()
2415 self._material = resource.getOwner()
2417 def getVars( self ):
2418 vars = WTemplated.getVars( self )
2419 vars["confTitle"] = self._conf.getTitle()
2420 vars["sessionTitle"] = ""
2421 if self._session != None:
2422 vars["sessionTitle"] = self._session.getTitle()
2423 vars["contributionTitle"] = ""
2424 if self._contrib != None:
2425 vars["contributionTitle"] = self._contrib.getTitle()
2426 vars["materialTitle"] = self._material.getTitle()
2427 vars["title"] = self._resource.getName()
2428 vars["description"] = self._resource.getDescription()
2429 vars["accessControlFrame"] = WAccessControlFrame().getHTML(\
2430 self._resource,\
2431 vars["setVisibilityURL"],\
2432 vars["addAllowedURL"],\
2433 vars["removeAllowedURL"],\
2434 vars["setAccessKeyURL"], \
2435 vars["setModifKeyURL"] )
2436 return vars
2439 class WResourceDataModification(WResourceModification):
2441 def getHTML(self, params):
2442 str = """
2443 <form action="%s" method="POST" enctype="multipart/form-data">
2446 </form>
2447 """%(params["postURL"],\
2448 self._resource.getLocator().getWebForm(),\
2449 WTemplated.getHTML( self, params ) )
2450 return str
2452 def getVars( self ):
2453 vars = WTemplated.getVars( self )
2454 vars["title"] = self._resource.getName()
2455 vars["description"] = self._resource.getDescription()
2456 return vars
2459 class WUserRegistration(WTemplated):
2461 def __init__( self, av = None ):
2462 self._avatar = av
2464 def __defineNewUserVars( self, vars={} ):
2465 vars["Wtitle"] = _("Creating a new Indico user")
2466 vars["name"] = quoteattr( vars.get("name","") )
2467 vars["surName"] = quoteattr( vars.get("surName","") )
2468 vars["organisation"] = quoteattr( vars.get("organisation","") )
2469 vars["address"] = vars.get("address","")
2470 vars["email"] = quoteattr( vars.get("email","") )
2471 vars["telephone"] = quoteattr( vars.get("telephone","") )
2472 vars["fax"] = quoteattr( vars.get("fax","") )
2473 vars["login"] = quoteattr( vars.get("login","") )
2474 return vars
2476 def __defineExistingUserVars( self, vars={} ):
2477 u = self._avatar
2478 vars["Wtitle"] = _("Modifying an Indico user")
2479 vars["name"] = quoteattr( u.getName() )
2480 vars["surName"] = quoteattr( u.getSurName() )
2481 vars["title"] = quoteattr( u.getTitle() )
2482 vars["organisation"] = quoteattr( u.getOrganisations()[0] )
2483 vars["address"] = u.getAddresses()[0]
2484 vars["email"] = quoteattr( u.getEmails()[0] )
2485 vars["telephone"] = quoteattr( u.getTelephones()[0] )
2486 vars["fax"] = quoteattr( u.getFaxes()[0] )
2487 return vars
2489 def getVars( self ):
2490 vars = WTemplated.getVars( self )
2491 minfo = info.HelperMaKaCInfo.getMaKaCInfoInstance()
2492 vars["after"] = _("After the submission of your personal data, an email will be sent to you")+".<br>"+ _("You will able to use your account only after you activate it by clicking on the link inside the email.")
2493 if minfo.getModerateAccountCreation():
2494 vars["after"] = _("The site manager has to accept your account creation request. You will be informed of the decision by email.")+"<br>"
2495 vars["postURL"] = quoteattr( str( vars["postURL"] ) )
2496 if not self._avatar:
2497 vars = self.__defineNewUserVars( vars )
2498 vars["locator"] = ""
2499 else:
2500 vars = self.__defineExistingUserVars( vars )
2501 vars["locator"] = self._avatar.getLocator().getWebForm()
2503 #note: there's a reason this line is TitlesRegistry() and not just TitlesRegistry
2504 #methods in TitlesRegistry cannot be classmethods because _items cannot be a class
2505 #attribute because the i18n '_' function doesn't work for class attributes
2506 vars["titleOptions"]=TitlesRegistry().getSelectItemsHTML(vars.get("title",""))
2507 tz = minfo.getTimezone()
2508 if vars.get("defaultTZ","") != "":
2509 tz = vars.get("defaultTZ")
2510 tzmode = "Event Timezone"
2511 if vars.get("displayTZMode","") != "":
2512 tzmode = vars.get("displayTZMode")
2513 vars["timezoneOptions"]=TimezoneRegistry.getShortSelectItemsHTML(tz)
2514 vars["displayTZModeOptions"]=DisplayTimezoneRegistry.getSelectItemsHTML(tzmode)
2515 minfo = info.HelperMaKaCInfo.getMaKaCInfoInstance()
2516 if vars.get("defaultLang","") == "":
2517 vars["defaultLang"] = minfo.getLang()
2518 return vars
2521 class WUserCreated(WTemplated):
2523 def __init__( self, av = None ):
2524 self._avatar = av
2526 def getVars( self ):
2527 vars = WTemplated.getVars( self )
2528 minfo = info.HelperMaKaCInfo.getMaKaCInfoInstance()
2529 vars["however"] = _("However, you will not be able to log into the system until you have activated your new account. To do this please follow the instructions in the mail that we have already sent you")+".<br>"
2530 if minfo.getModerateAccountCreation():
2531 vars["however"] = _("However, you will not be able to log into the system until the site administrator has accepted your account creation request. You will be notified of the decision by email")+".<br>"
2532 vars["signInURL"] = quoteattr( str( vars["signInURL"] ) )
2533 vars["supportAddr"] = info.HelperMaKaCInfo.getMaKaCInfoInstance().getSupportEmail()
2534 return vars
2537 class WUserSendIdentity(WTemplated):
2539 def __init__( self, av = None ):
2540 self._avatar = av
2542 def getVars( self ):
2543 vars = WTemplated.getVars( self )
2544 vars["locator"] = self._avatar.getLocator().getWebForm()
2545 vars["name"] = self._avatar.getName()
2546 vars["surName"] = self._avatar.getSurName()
2547 vars["email"] = self._avatar.getEmail()
2548 vars["org"] = self._avatar.getOrganisation()
2549 vars["title"] = self._avatar.getTitle()
2550 vars["address"] = self._avatar.getAddresses()[0]
2551 vars["contactEmail"] = info.HelperMaKaCInfo.getMaKaCInfoInstance().getSupportEmail()
2552 return vars
2555 class WUserSearchResultsTable( WTemplated ):
2557 def __init__(self, multi=True):
2558 self._multi = multi
2560 def __getItemClass( self, principal ):
2561 if principal.__class__.__name__ == "Avatar":
2562 return WUserTableItem
2563 elif isinstance(principal, user.CERNGroup):
2564 return WGroupNICETableItem
2565 elif isinstance(principal, user.Group):
2566 return WGroupTableItem
2567 elif isinstance(principal,conference.ContributionParticipation):
2568 return WAuthorTableItem
2569 return None
2571 def getHTML( self, resultList ):
2572 self.__resultList = resultList
2573 self.__resultList.sort(utils.sortPrincipalsByName)
2574 return WTemplated.getHTML( self, {} )
2576 def getVars( self ):
2577 vars = WTemplated.getVars( self )
2578 l = []
2579 selected = False
2580 if len(self.__resultList) == 1:
2581 selected = True
2582 for principal in self.__resultList:
2583 l.append( self.__getItemClass(principal)(self._multi).getHTML( principal, selected ) )
2584 if l:
2585 vars["usersFound"] = "".join( l )
2586 else:
2587 vars["usersFound"] = i18nformat(""""<br><span class=\"blacktext\">&nbsp;&nbsp;&nbsp; _("No results for this search")</span>""")
2588 vars["nbResults"] = len(self.__resultList)
2589 return vars
2592 class WSignIn(WTemplated):
2594 def getVars( self ):
2595 vars = WTemplated.getVars( self )
2596 minfo = info.HelperMaKaCInfo.getMaKaCInfoInstance()
2597 vars["postURL"] = quoteattr( str( vars.get( "postURL", "" ) ) )
2598 vars["returnURL"] = quoteattr( str( vars.get( "returnURL", "" ) ) )
2599 vars["forgotPasswordURL"] = quoteattr( str( vars.get( "forgotPassordURL", "" ) ) )
2600 vars["login"] = quoteattr( vars.get( "login", "" ) )
2601 vars["msg"] = self.htmlText( vars.get( "msg" ) )
2602 imgIcon=Configuration.Config.getInstance().getSystemIconURL("currentMenuItem")
2603 if Configuration.Config.getInstance().getAuthenticatedEnforceSecure():
2604 imgIcon=imgIcon.replace("http://", "https://")
2605 imgIcon = urlHandlers.setSSLPort( imgIcon )
2606 vars["itemIcon"] = imgIcon
2607 vars["createAccount"] = ""
2608 if minfo.getAuthorisedAccountCreation():
2609 vars["createAccount"] = i18nformat("""_("If you don't have an account, you can create one")<a href="%s"> _("here")</a>
2610 """) % (vars["createAccountURL"])
2611 vars["NiceMsg"]=""
2612 if "Nice" in Configuration.Config.getInstance().getAuthenticatorList():
2613 vars["NiceMsg"]= _("Please note you can use your NICE (CERN) account")
2614 return vars
2616 class WConfirmation(WTemplated):
2618 def getHTML( self, message, postURL, passingArgs, **opts):
2619 params = {}
2620 params["message"] = message
2621 params["postURL"] = postURL
2622 pa = []
2623 for arg in passingArgs.keys():
2624 if not type( passingArgs[arg] ) == types.ListType:
2625 passingArgs[arg] = [passingArgs[arg]]
2626 for value in passingArgs[arg]:
2627 pa.append("""<input type="hidden" name="%s" value="%s">"""%( arg, value ))
2628 params["passingArgs"] = "".join(pa)
2629 params["confirmButtonCaption"]=opts.get("confirmButtonCaption", _("OK"))
2630 params["cancelButtonCaption"]=opts.get("cancelButtonCaption", _("Cancel"))
2631 params["systemIconWarning"] = Configuration.Config.getInstance().getSystemIconURL( "warning" )
2632 return WTemplated.getHTML( self, params )
2634 class WDisplayConfirmation(WTemplated):
2636 def getHTML( self, message, postURL, passingArgs, **opts):
2637 params = {}
2638 params["message"] = message
2639 params["postURL"] = postURL
2640 pa = []
2641 for arg in passingArgs.keys():
2642 if not type( passingArgs[arg] ) == types.ListType:
2643 passingArgs[arg] = [passingArgs[arg]]
2644 for value in passingArgs[arg]:
2645 pa.append("""<input type="hidden" name="%s" value="%s">"""%( arg, value ))
2646 params["passingArgs"] = "".join(pa)
2647 params["confirmButtonCaption"]=opts.get("confirmButtonCaption", _("OK"))
2648 params["cancelButtonCaption"]=opts.get("cancelButtonCaption", _("Cancel"))
2649 params["systemIconWarning"] = Configuration.Config.getInstance().getSystemIconURL( "warning" )
2650 return WTemplated.getHTML( self, params )
2652 class SideMenu(object):
2653 def __init__(self, userStatus=False):
2654 """ Constructor
2655 userStatus: a boolean that is True if the user is logged in, False otherwise
2657 self._sections = []
2658 self._userStatus = userStatus
2660 def addSection(self, section, top=False):
2661 if top:
2662 self._sections.insert(0, section)
2663 else:
2664 self._sections.append(section)
2666 def getSections(self):
2667 return self._sections
2669 class ManagementSideMenu(SideMenu):
2671 def getHTML(self):
2672 return WSideMenu(self, self._userStatus, type="management").getHTML()
2674 class BasicSideMenu(SideMenu):
2676 def getHTML(self):
2677 return WSideMenu(self, self._userStatus, type="basic").getHTML()
2679 class SideMenuSection:
2680 """ class coment
2683 def __init__(self, title=None, active=False, currentPage = None, visible=True):
2684 """ -title is the words that will be displayed int he side menu.
2685 -active is True if ...
2686 -currentPage stores information about in which page we are seeing the Side Menu. For example,
2687 its values can be "category" or "admin".
2689 self._title = title
2690 self._active = active
2691 self._currentPage = currentPage
2692 self._items = []
2693 self._visible = visible
2695 def getTitle(self):
2696 return self._title
2698 def getItems(self):
2699 return self._items
2701 def addItem(self, item):
2702 self._items.append(item)
2703 item.setSection(self)
2705 def isActive(self):
2706 return self._active
2708 def setActive(self, val):
2709 self._active = val
2711 def checkActive(self):
2713 self._active = False
2715 for item in self._items:
2716 if item.isActive():
2717 self._active = True
2718 break
2720 def getCurrentPage(self):
2721 return self._currentPage
2723 def setCurrentPage(self, currentPage):
2724 self._currentPage = currentPage
2726 def isVisible(self):
2727 return self._visible
2729 def setVisible(self, visible):
2730 self._visible = visible
2732 def hasVisibleItems(self):
2733 for item in self._items:
2734 if item.isVisible():
2735 return True
2736 return False
2738 class SideMenuItem:
2740 def __init__(self, title, url, active=False, enabled=True, errorMessage = "msgNoPermissions", visible=True):
2741 """ errorMessage: one of the error messages in SideMenu.wohl
2743 self._title = title
2744 self._url = url
2745 self._active = active
2746 self._enabled = enabled
2747 self._errorMessage = errorMessage
2748 self._visible = visible
2750 def getTitle(self):
2751 return self._title;
2753 def setSection(self, section):
2754 self._section = section
2756 def getURL(self):
2757 return self._url
2759 def setURL(self, url):
2760 self._url = url
2762 def isActive(self):
2763 return self._active
2765 def isEnabled(self):
2766 return self._enabled
2768 def getErrorMessage(self):
2769 return self._errorMessage
2771 def setActive(self, val=True):
2772 self._active = val
2773 self._section.checkActive()
2775 def setEnabled(self, val):
2776 self._enabled = val
2778 def setErrorMessage(self, val):
2779 self._errorMessage = val
2781 def isVisible(self):
2782 return self._visible
2784 def setVisible(self, visible):
2785 self._visible = visible
2787 class WSideMenu(WTemplated):
2789 def __init__(self, menu, loggedIn, type="basic"):
2791 type can be: basic (display interface) or management (management interface).
2793 self._menu = menu
2794 self._type = type
2796 # is the user logged in? used for changing some tooltips
2797 self._loggedIn = loggedIn
2799 def getVars(self):
2800 vars = WTemplated.getVars(self)
2802 vars['menu'] = self._menu
2803 vars['loggedIn'] = self._loggedIn
2804 vars['sideMenuType'] = self._type
2805 return vars
2807 class WebToolBar(object):
2809 def __init__( self, caption="" ):
2810 self.caption = caption
2811 self.items = []
2812 self.currentItem = None
2814 def getCaption( self ):
2815 return self.caption
2817 def addItem( self, newItem ):
2818 if newItem not in self.items:
2819 self.items.append( newItem )
2820 newItem.setOwner( self )
2822 def removeItem( self, item ):
2823 if item in self.items:
2824 if self.isCurrent( item ):
2825 self.setCurrentItem( None )
2826 self.items.remove( item )
2828 def getItemList( self ):
2829 return self.items
2831 def isCurrent( self, item ):
2832 return self.currentItem == item
2834 def setCurrentItem( self, item ):
2835 self.currentItem = item
2837 def isFirstItem( self, item):
2838 return self.items[0] == item
2840 def isLastItem( self, item ):
2841 return self.items[len(self.items)-1] == item
2843 def getHTML( self ):
2844 return WTBDrawer(self).getHTML()
2847 class WTBItem:
2849 def __init__( self, caption, **args):
2850 self.owner = None
2851 self.caption = caption
2852 self.icon = args.get("icon", "")
2853 self.actionURL = args.get("actionURL", "")
2854 self.enabled = args.get("enabled", 1)
2855 self.subItems = []
2857 def getCaption(self):
2858 return self.caption
2860 def getIcon( self ):
2861 return self.icon
2863 def getActionURL( self ):
2864 return self.actionURL
2866 def setActionURL( self, URL ):
2867 self.actionURL = URL
2868 #self.actionURL = URL.strip()
2870 def setCurrent( self ):
2871 self.owner.setCurrentItem( self )
2873 def isCurrent( self ):
2874 return self.owner.isCurrent( self )
2876 def enable( self ):
2877 self.enabled = 1
2879 def disable( self ):
2880 self.enabled = 0
2882 def isEnabled( self ):
2883 return self.enabled
2885 def hasIcon( self ):
2886 return self.icon != ""
2888 def addItem( self, newItem ):
2889 if newItem not in self.subItems:
2890 self.subItems.append( newItem )
2891 newItem.setOwner( self.owner )
2893 def removeItem( self, item ):
2894 if item in self.subItems:
2895 self.subItems.remove( item )
2897 def getItemList( self ):
2898 return self.subItems
2900 def isFirstItem( self, item):
2901 return self.subItems[0] == item
2903 def isLastItem( self, item ):
2904 i = len(self.subItems)-1
2905 while not self.subItems[i].isEnabled():
2906 i -= 1
2907 return self.subItems[i] == item
2909 def setOwner( self, owner ):
2910 self.owner = owner
2911 for item in self.getItemList():
2912 item.setOwner( self.owner )
2915 class WTBSeparator(WTBItem):
2917 def __init__( self ):
2918 WTBItem.__init__(self, "")
2920 def setCurrent( self ):
2921 return
2923 class WTBGroup( WTBItem ):
2925 def __init__( self, caption, **args ):
2926 WTBItem.__init__( self, caption, **args )
2927 self.items= []
2929 def addItem( self, newItem ):
2930 if newItem not in self.items:
2931 self.items.append( newItem )
2932 newItem.setOwner( self.owner )
2934 def removeItem( self, item ):
2935 if item in self.items:
2936 self.items.remove( item )
2938 def getItemList( self ):
2939 return self.items
2941 def isFirstItem( self, item):
2942 return self.items[0] == item
2944 def isLastItem( self, item ):
2945 i = len(self.items)-1
2946 while not self.items[i].isEnabled():
2947 i -= 1
2948 return self.items[i] == item
2950 def setOwner( self, owner ):
2951 self.owner = owner
2952 for item in self.getItemList():
2953 item.setOwner( self.owner )
2955 class WTBSection( WTBItem ):
2957 def __init__( self, caption, **args ):
2958 WTBItem.__init__( self, caption, **args )
2959 self.items= []
2960 self.drawer = None
2962 def addItem( self, newItem ):
2963 if newItem not in self.items:
2964 self.items.append( newItem )
2965 newItem.setOwner( self.owner )
2967 def removeItem( self, item ):
2968 if item in self.items:
2969 self.items.remove( item )
2971 def getItemList( self ):
2972 return self.items
2974 def isFirstItem( self, item):
2975 return self.items[0] == item
2977 def isLastItem( self, item ):
2978 i = len(self.items)-1
2979 while not self.items[i].isEnabled():
2980 i -= 1
2981 return self.items[i] == item
2983 def setOwner( self, owner ):
2984 self.owner = owner
2985 for item in self.getItemList():
2986 item.setOwner( self.owner )
2988 def setDrawer( self, d ):
2989 self.drawer = d(self)
2991 def getDrawer( self ):
2992 return self.drawer
2994 def hasDrawer( self ):
2995 return self.drawer != None
2997 class WTBDrawer:
2998 def __init__( self, toolbar ):
2999 self.toolbar = toolbar
3001 def getHTML( self ):
3002 l = []
3003 for item in self.toolbar.getItemList():
3004 if not item.isEnabled():
3005 continue
3006 if isinstance(item, WTBSection) and item.hasDrawer():
3007 drawer = item.getDrawer()
3008 elif isinstance(item, WTBSection) and not item.hasDrawer():
3009 drawer = WStdSectionDrawer(item)
3010 else:
3011 drawer = WStdTBDrawer(item)
3012 l.append(drawer.getHTML())
3013 return "".join(l)
3015 class WStdTBDrawer(WTemplated):
3017 def __init__( self, item ):
3018 self.item = item
3020 def _getTBItemCaption( self, item):
3021 return """<tr>
3022 <td colspan="2" class="menutitle">%s</td>
3023 </tr>"""%item.getCaption()
3025 def _getTBItemHTML( self, item ):
3026 str = """%s"""%(item.getCaption() )
3027 if item.getActionURL() != "":
3028 str = """<a href="%s">%s</a>"""%(item.getActionURL(), \
3029 item.getCaption())
3030 return str
3032 def _getCurrentIconHTML( self, style ):
3033 return """<td class="%s">&nbsp;<img src="%s"\
3034 style="vertical-align:middle" alt=""></td>"""%(style,\
3035 Configuration.Config.getInstance().getSystemIconURL("arrowLeft"))
3037 def _getIconHTML( self, item, style ):
3038 return """<td class="%s">&nbsp;<img src="%s" alt="" hspace="3" vspace="2">
3039 </td>"""%(style, item.getIcon())
3041 def _getSectionItemsHTML( self, group ):
3042 lg = []
3043 for gItem in section.getItemList():
3044 if not gItem.isEnabled():
3045 continue
3046 style = self._getStyleForItem(gItem, section)
3047 lg.append("""<tr>
3048 <td><table cellspacing="0" cellpadding="0" width="100%%">
3049 <tr>%s<td class="%s" width="100%%">%s</td>
3050 </tr></table></td>
3051 </tr>"""%(self._getCurrentIconForItem(gItem, style),\
3052 style,\
3053 self._getTBItemHTML(gItem)))
3054 return """<table cellspacing="0" cellpadding="0" width="100%%">
3056 </table>"""%("".join(lg))
3058 def _getCurrentIconForItem( self, item, style ):
3059 if item.isCurrent():
3060 return self._getCurrentIconHTML(style)
3061 elif item.hasIcon():
3062 return self._getIconHTML(item, style)
3063 return ""
3065 def _getStyleForItem( self, item, list ):
3066 if item.isCurrent():
3067 return "menuselectedcell"
3068 elif list.isFirstItem(item):
3069 return "menutopcell"
3070 elif item.getItemList():
3071 return "menumiddlecell"
3072 elif list.isLastItem(item):
3073 return "menubottomcell"
3074 else:
3075 return "menumiddlecell"
3076 return ""
3078 def getVars( self ):
3079 vars = WTemplated.getVars( self )
3080 l = []
3082 if self.item != None:
3083 for tbItem in self.item.getItemList():
3084 if not tbItem.isEnabled():
3085 continue
3086 groupItemsHTML = ""
3087 itemHTML = ""
3088 if tbItem.__class__ == WTBSeparator:
3089 itemHTML = ""
3090 elif tbItem.__class__ == WTBSection:
3091 sectionItemsHTML = self._getSectionItemsHTML( tbItem )
3092 l.append(self._getTBItemCaption())
3093 l.append("""<tr><td colspan="2">%s</td>
3094 </tr>"""%(sectionItemsHTML) )
3095 else:
3096 itemHTML = self._getTBItemHTML( tbItem )
3097 style = self._getStyleForItem(tbItem, self.item)
3098 l.append( """<tr><td colspan="2">
3099 <table cellspacing="0" cellpadding="0" width="100%%">
3100 <tr>%s<td class="%s" width="100%%">%s</td></tr></table>
3101 </td></tr>"""%(self._getCurrentIconForItem(tbItem,style),\
3102 style, itemHTML))
3103 vars["items"] = "".join(l)
3104 return vars
3107 class WStdSectionDrawer(WStdTBDrawer):
3109 def __init__( self, item ):
3110 self.section = item
3112 def getVars( self ):
3113 vars = WTemplated.getVars( self )
3114 l = []
3115 l.append(self._getTBItemCaption(self.section))
3116 if self.section != None:
3117 for tbItem in self.section.getItemList():
3118 if not tbItem.isEnabled():
3119 continue
3120 itemHTML = ""
3121 if tbItem.__class__ == WTBSeparator:
3122 itemHTML = ""
3123 else:
3124 itemHTML = self._getTBItemHTML( tbItem )
3125 style = self._getStyleForItem(tbItem, self.section)
3126 l.append( """<tr><td colspan="2">
3127 <table cellspacing="0" cellpadding="0" width="100%%">
3128 <tr>%s<td class="%s" width="100%%">%s</td></tr></table>
3129 </td></tr>"""%(self._getCurrentIconForItem(tbItem,style),\
3130 style, itemHTML))
3131 for subitem in tbItem.getItemList():
3132 if not subitem.isEnabled():
3133 continue
3134 styleSubitem = self._getStyleForItem(subitem, self.section)
3135 if subitem.isCurrent():
3136 subitemHTML = self._getTBItemHTML( subitem )
3137 l.append("""<tr><td colspan="2">
3138 <table cellspacing="0" cellpadding="0" width="100%%">
3139 <tr><td class="%s">&nbsp;&nbsp;&nbsp;&nbsp;</td>%s<td class="%s" width="100%%">\
3140 <span style="font-size:11px">%s</span></td></tr></table></td></tr>"""%(styleSubitem,\
3141 self._getCurrentIconForItem(subitem,styleSubitem),styleSubitem, subitemHTML))
3142 else:
3143 styleSubitem = "menuConfMiddleCell"
3144 if self.section.isLastItem(tbItem) and tbItem.isLastItem(subitem):
3145 styleSubitem = "menuConfBottomCell"
3146 l.append( """<tr><td class="%s" nowrap>&nbsp;&nbsp;&nbsp;<a class="confSubSection" href="%s">\
3147 <img src="%s" alt="">&nbsp;%s</a></td></tr>\
3148 """%(styleSubitem, subitem.getActionURL(), subitem.getIcon(), subitem.getCaption()))
3149 vars["items"] = "".join(l)
3150 return vars
3153 class WAddEventSectionDrawer(WStdSectionDrawer):
3155 def __init__( self, item ):
3156 self.section = item
3158 def _getTBItemHTML( self, item ):
3159 str = """<span class="menuadd">%s</span>"""%(item.getCaption() )
3160 if item.getActionURL() != "":
3161 str = """<a class="menuaddlink" href="%s">%s
3162 </a>"""%(item.getActionURL(), \
3163 item.getCaption())
3164 return str
3166 def _getCurrentIconForItem( self, item, style ):
3167 if item.hasIcon():
3168 return self._getIconHTML(item, style)
3169 return ""
3171 def _getStyleForItem( self):
3172 return "menuadd"
3174 def getVars( self ):
3175 vars = WTemplated.getVars( self )
3176 l = []
3177 l.append(self._getTBItemCaption(self.section))
3178 if self.section != None:
3179 for tbItem in self.section.getItemList():
3180 if not tbItem.isEnabled():
3181 continue
3182 itemHTML = ""
3183 if tbItem.__class__ == WTBSeparator:
3184 itemHTML = ""
3185 else:
3186 itemHTML = self._getTBItemHTML( tbItem )
3187 style = self._getStyleForItem()
3188 l.append( """<tr><td class="%s" colspan="2">
3189 <table cellspacing="0" cellpadding="0" width="100%%">
3190 <tr>%s<td class="%s" width="100%%">%s</td></tr></table>
3191 </td></tr>"""%(WStdSectionDrawer._getStyleForItem(self,tbItem, self.section),self._getCurrentIconForItem(tbItem,style), style, itemHTML))
3192 vars["items"] = "".join(l)
3193 return vars
3196 class WConferenceListEvents(WTemplated):
3198 def __init__( self, items, aw):
3199 self._items = items
3200 self._aw = aw
3202 def getVars( self ):
3203 vars = WTemplated.getVars( self )
3204 vars["items"] = self._items
3205 vars["conferenceDisplayURLGen"] = urlHandlers.UHConferenceDisplay.getURL
3206 vars["aw"] = self._aw
3207 return vars
3209 class WEmptyCategory(WTemplated):
3211 def __init__(self, materialList):
3212 self._materialList = materialList
3214 def getVars(self):
3215 vars = {}
3216 vars["material"] = self._materialList
3217 return vars
3220 class WConferenceList(WTemplated):
3222 def __init__( self, category, wfRegm, showPastEvents ):
3223 self._categ = category
3224 self._showPastEvents = showPastEvents
3226 def getHTML( self, aw, params ):
3227 self._aw = aw
3228 return WTemplated.getHTML( self, params )
3230 def getEventTimeline(self, tz):
3231 index = Catalog.getIdx('categ_conf_sd').getCategory(self._categ.getId())
3232 today = nowutc().astimezone(timezone(tz)).replace(hour=0, minute=0, second=0)
3233 thisMonth = nowutc().astimezone(timezone(tz)).replace(hour=0, minute=0, second=0, day=1)
3234 thisMonthTS = utc_timestamp(thisMonth)
3235 nextMonthTS = utc_timestamp(thisMonth.replace(month = (thisMonth.month % 12) + 1))
3236 todayTS = utc_timestamp(thisMonth)
3237 oneMonthTS = utc_timestamp((today - timedelta(days=30)).replace(day=1))
3238 future = []
3239 present = []
3241 for ts, conf in index.iteritems(thisMonthTS):
3242 if ts < nextMonthTS or len(present) < OPTIMAL_PRESENT_EVENTS:
3243 present.append(conf)
3244 else:
3245 future.append(conf)
3247 if len(present) < MIN_PRESENT_EVENTS:
3248 present = list(index.values(oneMonthTS, thisMonthTS)) + present
3250 if not present:
3251 maxDT = timezone('UTC').localize(datetime.utcfromtimestamp(index.maxKey())).astimezone(timezone(tz))
3252 prevMonthTS = utc_timestamp(maxDT.replace(day=1))
3253 present = index.values(prevMonthTS)
3254 numPast = self._categ.getNumConferences() - len(present) - len(future)
3255 return present, future, len(future), numPast
3257 def getVars( self ):
3258 vars = WTemplated.getVars( self )
3259 displayTZ = DisplayTZ(self._aw, self._categ, useServerTZ=1).getDisplayTZ()
3260 vars["ActiveTimezone"] = displayTZ
3261 vars["presentItems"], vars["futureItems"], vars["numOfEventsInTheFuture"], vars["numOfEventsInThePast"] = self.getEventTimeline(displayTZ)
3262 vars["categ"] = self._categ
3264 vars["showPastEvents"] = self._showPastEvents
3266 return vars
3269 class WCategoryList(WTemplated):
3271 def __init__( self, categ ):
3272 self._categ = categ
3273 self._list = categ.getSubCategoryList()
3275 def getHTML( self, aw, params ):
3276 self._aw = aw
3277 return WTemplated.getHTML( self, params )
3279 def getVars( self ):
3281 vars = WTemplated.getVars( self )
3282 vars["items"] = self._list
3283 vars["categ"] = self._categ;
3285 return vars
3287 class WCategoryStatisticsListRow(WTemplated):
3289 def __init__( self, year, percent, number ):
3290 self._year = year
3291 self._percent = percent
3292 self._number = number
3294 def getHTML( self, aw ):
3295 self._aw = aw
3296 return WTemplated.getHTML( self )
3298 def getVars( self ):
3299 vars = WTemplated.getVars( self )
3300 vars["year"] = self._year
3301 vars["percent"] = self._percent
3302 vars["percentCompl"] = 100-self._percent
3303 vars["number"] = self._number
3304 return vars
3307 class WCategoryStatisticsList(WTemplated):
3309 def __init__( self, statsName, stats ):
3310 self._stats = stats
3311 self._statsName = statsName
3313 def getHTML( self, aw ):
3314 self._aw = aw
3315 return WTemplated.getHTML( self )
3317 def getVars( self ):
3318 vars = WTemplated.getVars( self )
3319 # Construction of the tables from the dictionary (stats).
3320 # Initialization:
3321 tmp = []
3322 maximum = 0
3323 stats = {}
3324 years = self._stats.keys()
3325 years.sort()
3326 for y in range(years[0], min(datetime.now().year + 4, years[-1] + 1)):
3327 stats[y] = self._stats.get(y,0)
3328 maximum = max(stats.values())
3329 years = stats.keys()
3330 years.sort()
3331 for y in years:
3332 nb = stats[y]
3333 percent = (nb*100)/maximum
3334 if nb > 0 and percent == 0:
3335 percent = 1
3336 wcslr = WCategoryStatisticsListRow( y, percent, stats[y] )
3337 tmp.append(wcslr.getHTML( self._aw ))
3338 vars["statsName"] = self._statsName
3339 vars["statsRows"] = "".join( tmp )
3340 vars["total"] = sum(stats.values())
3341 return vars
3343 class WConfCreationControlFrame(WTemplated):
3345 def __init__( self, categ ):
3346 self._categ = categ
3348 def getVars( self ):
3349 vars = WTemplated.getVars( self )
3350 vars["locator"] = self._categ.getLocator().getWebForm()
3351 vars["status"] = _("OPENED")
3352 vars["changeStatus"] = i18nformat("""( <input type="submit" class="btn" name="RESTRICT" value="_("RESTRICT it")"> )""")
3353 if self._categ.isConferenceCreationRestricted():
3354 vars["status"] = _("RESTRICTED")
3355 vars["changeStatus"] = i18nformat("""( <input type="submit" class="btn" name="OPEN" value="_("OPEN it")"> )""")
3356 vars["principalTable"] = WPrincipalTable().getHTML( self._categ.getConferenceCreatorList(), self._categ , vars["addCreatorsURL"], vars["removeCreatorsURL"], selectable=False )
3357 vars["notifyCreationList"] = quoteattr(self._categ.getNotifyCreationList())
3358 vars["setNotifyCreationURL"] = urlHandlers.UHCategorySetNotifyCreation.getURL(self._categ)
3359 return vars
3361 class WMinutesDisplay(WTemplated):
3363 def __init__( self, target ):
3364 self._target = target
3366 def getVars( self ):
3367 vars = WTemplated.getVars( self )
3368 vars["text"] = self.textToHTML(self._target.readBin())
3369 return vars
3371 class TabControl:
3373 def __init__( self, parent=None, child=None ):
3374 self._tabs = []
3375 self._active = None
3376 self._default = None
3377 # Parent element (another tabcontrol),
3378 # in case there is nesting
3379 self._parent = parent
3381 if parent != None:
3382 parent.setChild(self);
3383 self._child = child
3385 def _addTab( self, tab ):
3386 self._tabs.append( tab )
3387 if len( self._tabs ) == 1:
3388 self._default = tab
3389 self._active = tab
3391 def newTab( self, id, caption, url, hidden=False ):
3392 tab = Tab( self, id, caption, url, hidden=hidden )
3393 self._addTab( tab )
3394 return tab
3396 def setDefaultTab( self, tab ):
3397 if tab in self._tabs:
3398 self._default = tab
3400 def getDefaultTab( self ):
3401 return self._default
3403 def setActiveTab( self, tab ):
3404 if tab in self._tabs:
3405 self._active = tab
3407 def getActiveTab( self ):
3408 return self._active
3410 def getTabList( self ):
3411 return self._tabs
3413 def getTabById( self, id ):
3414 for tab in self.getTabList():
3415 if tab.getId() == id:
3416 return tab
3417 return None
3419 def getParent( self ):
3420 # retrieve parent TabControl
3421 return self._parent
3423 def setChild( self, child ):
3424 self._child = child
3426 def getChild( self ):
3427 # retrieve child TabControl
3428 return self._child
3430 def getLevel( self ):
3431 tmp = self.getParent()
3432 level = 0
3433 while tmp:
3434 level += 1
3435 tmp = tmp.getParent()
3436 return level
3438 class Tab:
3440 def __init__( self, owner, id, caption, URL, hidden = False ):
3441 self._owner = owner
3442 self._id = id.strip()
3443 self._caption = caption.strip()
3444 self._url = URL
3445 self._enabled = True
3446 self._subtabControl=None
3447 self._hidden = hidden
3449 def getId( self ):
3450 return self._id
3452 def getCaption( self ):
3453 return self._caption
3455 def setCaption( self, cp):
3456 self._caption = cp
3458 def getURL( self ):
3459 return self._url
3461 def setDefault( self ):
3462 self._owner.setDefaultTab( self )
3464 def isDefault( self ):
3465 return self._owner.getDefaultTab() == self
3467 def isActive( self ):
3468 return self._owner.getActiveTab() == self
3470 def setActive( self ):
3471 self._owner.setActiveTab( self )
3473 def enable( self ):
3474 self._enabled = True
3476 def disable( self ):
3477 self._enabled = False
3479 def setEnabled(self,value):
3480 self._enabled=value
3482 def isEnabled( self ):
3483 return self._enabled
3485 def setHidden(self, value):
3486 self._hidden = value
3488 def isHidden( self ):
3489 return self._hidden
3491 def getSubTabControl(self):
3492 return self._subtabControl
3494 def newSubTab( self, id, caption, url ):
3495 # guarantee that a subtabControl exists
3496 if not self._subtabControl:
3497 self._subtabControl = TabControl(parent=self._owner)
3499 tab=self._subtabControl.newTab( id, caption, url )
3500 return tab
3502 def hasChildren(self):
3503 return self._subtabControl is not None
3506 #class WTrackModifSubTrack( WTemplated ):
3508 # def __init__( self, track ):
3509 # self.__track = track
3510 # self.__conf = track.getConference()
3512 # def getVars( self ):
3513 # vars = WTemplated.getVars(self)
3514 # if len(self.__track.getSubTrackList()) == 0:
3515 # ht = "No sub track defined"
3516 # else:
3517 # ht = "<table width=\"100%%\">\n"
3518 # for subTrack in self.__track.getSubTrackList():
3519 # ht += "<tr bgcolor=\"#AAFFAA\"><td><input type=\"checkbox\" name=\"selSubTracks\" value=\"%s\"></td><td><a href=\"%s\">%s</a></td><td>%s</td></tr>\n"%(subTrack.getId(), vars["dataModificationURLGen"](subTrack) , subTrack.getTitle(), subTrack.getDescription())
3520 # ht += "</table>\n"
3521 # vars["listSubTrack"] = ht
3522 # return vars
3525 #class WSubTrackDataModification(WTemplated):
3527 # def __init__( self, subTrack ):
3528 # self.__subTrack = subTrack
3529 # self.__track = subTrack.getTrack()
3531 # def getVars( self ):
3532 # vars = WTemplated.getVars(self)
3534 # vars["title"] = self.__subTrack.getTitle()
3535 # vars["description"] = self.__subTrack.getDescription()
3537 # vars["locator"] = self.__subTrack.getLocator().getWebForm()
3539 # return vars
3541 #class WCFAModifFrame(WTemplated):
3543 # def __init__( self, conf, aw):
3544 # self.__conf = conf
3545 # self._aw = aw
3547 # def getHTML( self, body, **params):
3548 # params["body"] = body
3549 # return WTemplated.getHTML( self, params )
3551 # def getVars( self ):
3552 # vars = WTemplated.getVars( self )
3554 # vars["context"] = WConfModifHeader( self.__conf, self._aw ).getHTML(vars)
3557 # return vars
3559 #class WCFAModifMain(WTemplated):
3561 # def __init__( self, conf ):
3562 # self.__conf = conf
3564 # def getVars( self ):
3565 # vars = WTemplated.getVars( self )
3566 # abMgr = self.__conf.getAbstractMgr()
3568 # vars["startDate"] = abMgr.getStartSubmissionDate().strftime("%A %d %B %Y")
3569 # vars["endDate"] = abMgr.getEndSubmissionDate().strftime("%A %d %B %Y")
3571 # typeList = ""
3572 # for type in self._conf.getContribTypeList():
3573 # typeList += "<input type=\"checkbox\" name=\"types\" value=\"%s\">%s<br>\n"%(type.getId(), type.getName())
3574 # vars["typeList"] = typeList
3576 # return vars
3578 #class WCFARefereeList(WTemplated):
3580 # def __init__( self, conf ):
3581 # self.__conf = conf
3583 # def getVars( self ):
3584 # vars = WTemplated.getVars(self)
3585 # vars["refereeTable"] = "%s"%WPrincipalTable().getHTML( self.__conf.getAbstractMgr().getRefereeList(), self.__conf, vars["addRefereeURL"], vars["removeRefereeURL"] )
3586 # return vars
3588 class WTabControl(WTemplated):
3589 def __init__(self, ctrl, accessWrapper, **params):
3590 self._tabCtrl = ctrl
3591 self._aw = accessWrapper
3593 def _getTabs(self):
3594 tabs = []
3595 for tab in self._tabCtrl.getTabList():
3596 if not tab.isEnabled() or tab.isHidden():
3597 continue
3598 tabs.append((tab.getCaption(), tab.getURL(), tab.isActive()))
3599 return tabs
3601 def _getActiveTabId(self):
3602 for i, tab in enumerate(self._tabCtrl.getTabList()):
3603 if tab.isActive():
3604 return i
3605 return 0
3607 def _getActiveTab(self):
3608 for tab in self._tabCtrl.getTabList():
3609 if tab.isActive():
3610 return tab
3612 def _getBody(self):
3613 tab = self._getActiveTab()
3614 if not tab:
3615 return self._body
3616 sub = tab.getSubTabControl()
3617 if not sub:
3618 return self._body
3619 return WTabControl(sub, self._aw).getHTML(self._body)
3621 def getHTML(self, body):
3622 self._body = body
3623 return WTemplated.getHTML(self)
3625 def getVars( self ):
3626 vars = WTemplated.getVars(self)
3627 vars['body'] = self._getBody()
3628 vars['tabs'] = self._getTabs()
3629 vars['activeTab'] = self._getActiveTabId()
3630 vars['tabControlId'] = id(self)
3632 return vars
3634 #class WAbstractFilterCtrl( WTemplated ):
3636 # def __init__(self, conf, filter, sorter):
3637 # self._filter = filter
3638 # self._conf = conf
3639 # self._sorter = sorter
3641 # def getVars( self ):
3642 # vars = WTemplated.getVars(self)
3643 # abMgr = self._conf.getAbstractMgr()
3645 # trackFilter = "<option value=\"\">No filter</option>\n"
3646 # for track in self._conf.getTrackList():
3647 # selected = ""
3648 # if track.getId() == self._filter["track"]:
3649 # selected = "selected"
3650 # trackFilter += "<option value=\"%s\" %s>%s</option>\n"%(track.getId(), selected, track.getTitle())
3651 # vars["trackFilter"] = trackFilter
3653 # typeFilter = "<option value=\"\">No filter</option>\n"
3654 # for type in self._conf.getContribTypeList():
3655 # selected = ""
3656 # if type.getId() == self._filter["type"]:
3657 # selected = "selected"
3658 # typeFilter += "<option value=\"%s\" %s>%s</option>\n"%(type.getId(), selected, type)
3659 # vars["typeFilter"] = typeFilter
3661 # statusFilter = "<option value=\"\">No filter</option>\n"
3662 # for name in StatusName().getNameList():
3663 # selected = ""
3664 # if name == self._filter["status"]:
3665 # selected = "selected"
3666 # statusFilter += "<option value=\"%s\" %s>%s</option>\n"%(name, selected, name)
3667 # vars["statusFilter"] = statusFilter
3669 # fDay = "<option value=\"\"> </option>\n"
3670 # for i in range(1,32):
3671 # selected = ""
3672 # if self._filter["fromDate"] != None:
3673 # if i == self._filter["fromDate"].day:
3674 # selected = "selected"
3675 # fDay += "<option value=\"%s\" %s>%s</option>\n"%(i, selected, i)
3676 # vars["fDay"] = fDay
3678 # fMonth = "<option value=\"\"> </option>\n"
3679 # month = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"]
3680 # for i in range(1,13):
3681 # selected = ""
3682 # if self._filter["fromDate"] != None:
3683 # if i == self._filter["fromDate"].month:
3684 # selected = "selected"
3685 # fMonth += "<option value=\"%s\" %s>%s</option>\n"%(i, selected, month[i-1])
3686 # vars["fMonth"] = fMonth
3688 # fYear = "<option value=\"\"> </option>\n"
3689 # for i in range(2000,2011):
3690 # selected = ""
3691 # if self._filter["fromDate"] != None:
3692 # if i == self._filter["fromDate"].year:
3693 # selected = "selected"
3694 # fYear += "<option value=\"%s\" %s>%s</option>\n"%(i, selected, i)
3695 # vars["fYear"] = fYear
3699 # tDay = "<option value=\"\"> </option>\n"
3700 # for i in range(1,32):
3701 # selected = ""
3702 # if self._filter["toDate"] != None:
3703 # if i == self._filter["toDate"].day:
3704 # selected = "selected"
3705 # tDay += "<option value=\"%s\" %s>%s</option>\n"%(i, selected, i)
3706 # vars["tDay"] = tDay
3708 # tMonth = "<option value=\"\"> </option>\n"
3709 # for i in range(1,13):
3710 # selected = ""
3711 # if self._filter["toDate"] != None:
3712 # if i == self._filter["toDate"].month:
3713 # selected = "selected"
3714 # tMonth += "<option value=\"%s\" %s>%s</option>\n"%(i, selected, month[i-1])
3715 # vars["tMonth"] = tMonth
3717 # tYear = "<option value=\"\"> </option>\n"
3718 # for i in range(2000,2011):
3719 # selected = ""
3720 # if self._filter["toDate"] != None:
3721 # if i == self._filter["toDate"].year:
3722 # selected = "selected"
3723 # tYear += "<option value=\"%s\" %s>%s</option>\n"%(i, selected, i)
3724 # vars["tYear"] = tYear
3728 # #sortList = ["title", "type", "modification date"]
3729 # selected = ""
3730 # if self._sorter["field"] == "title":
3731 # selected = "selected"
3732 # sortBy = "<option value=\"title\" %s>Title</option>\n"%selected
3733 # selected = ""
3734 # if self._sorter["field"] == "type":
3735 # selected = "selected"
3736 # sortBy += "<option value=\"type\" %s>Type</option>\n"%selected
3737 # selected = ""
3738 # if self._sorter["field"] == "modification date":
3739 # selected = "selected"
3740 # sortBy += "<option value=\"modification date\" %s>Modification date</option>\n"%selected
3741 # selected = ""
3742 # if self._sorter["field"] == "status":
3743 # selected = "selected"
3744 # sortBy += "<option value=\"status\" %s>Status</option>\n"%selected
3745 # selected = ""
3747 # if self._sorter["direction"] == "desc":
3748 # vars["ascChecked"] = ""
3749 # vars["descChecked"] = "checked"
3750 # else:
3751 # vars["ascChecked"] = "checked"
3752 # vars["descChecked"] = ""
3754 # vars["sortBy"] = sortBy
3757 # return vars
3759 #class WSubTrackCreation( WTemplated ):
3761 # def __init__( self, track ):
3762 # self.__track = track
3764 # def getVars( self ):
3765 # vars = WTemplated.getVars(self)
3766 # vars["title"], vars["description"] = "", ""
3767 # vars["locator"] = self.__track.getLocator().getWebForm()
3768 # return vars
3770 #class WSetLogo( WTemplated ):
3772 # def __init__( self, conference ):
3773 # self.__conf = conference
3775 # def getVars( self ):
3776 # vars = WTemplated.getVars( self )
3777 # vars["confTitle"] = self.__conf.getTitle()
3779 # return vars
3781 class WSelectionBox(WTemplated):
3783 def getVars(self):
3784 vars=WTemplated.getVars(self)
3785 if not vars.has_key("description"):
3786 vars["description"]=""
3787 if not vars.has_key("options"):
3788 vars["options"]=""
3789 if not vars.has_key("table_width"):
3790 vars["table_width"]=""
3791 return vars
3793 class WSelectionBoxAuthors:
3795 def getHTML(self):
3796 wc=WSelectionBox()
3798 "description": _("Please make your selection if you want to add the submitter/s directly to any of the following roles:"),\
3799 "options": i18nformat("""<input type="radio" name="submitterRole" value="primaryAuthor"> _("Primary author")<br>
3800 <input type="radio" name="submitterRole" value="coAuthor"> _("Co-author")<br><hr>
3801 <input type="checkbox" name="submitterRole" value="speaker"> _("Speaker")
3802 """)
3804 return wc.getHTML(p)
3806 class WMSelectionBoxAuthors:
3808 def getHTML(self):
3809 wc=WSelectionBox()
3811 "description": _("Please make your selection if you want to add the submitter/s directly to:"),\
3812 "options": i18nformat("""<input type="checkbox" name="submitterRole" value="speaker"> _("Speaker")
3813 """), \
3814 "table_width": "180px" \
3816 return wc.getHTML(p)
3818 class WSelectionBoxSubmitter:
3820 def getHTML(self):
3821 wc=WSelectionBox()
3823 "description": i18nformat(""" _("Please check the box if you want to add them as submitters"):<br><br><i><font color=\"black\"><b> _("Note"): </b></font> _("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").</i><br>"""),\
3824 "options": i18nformat("""<input type="checkbox" name="submissionControl" value="speaker" checked> _("Add as submitter")
3825 """)
3827 return wc.getHTML(p)
3829 class WSelectionBoxConveners:
3831 def getHTML(self):
3832 wc=WSelectionBox()
3834 "description": _("Please make your selection if you want to add the result/s directly to the role of session Convener:"),\
3835 "options": i18nformat("""<input type="checkbox" name="userRole" value="convener"> _("Add as convener")
3836 """)
3838 return wc.getHTML(p)
3840 class WSelectionBoxConvToManagerCoordinator:
3842 def getHTML(self):
3843 wc=WSelectionBox()
3845 "description": i18nformat(""" _("Please check the box if you want to add them as managers/coordinators"):"""),\
3846 "options": i18nformat("""<input type="checkbox" name="managerControl"> _("Add as session manager")<br>
3847 <input type="checkbox" name="coordinatorControl"> _("Add as session coordinator")
3848 """)
3850 return wc.getHTML(p)
3853 class WSelectionBoxCloneLecture :
3855 def getHTML(self):
3856 wc=WSelectionBox()
3858 "description": _("Please check the boxes indicating which elements of the lecture you want to clone"),\
3859 "options": i18nformat("""<input type="checkbox" name="cloneDetails" id="cloneDetails" checked="1" disabled="1" value="1"> _("Event details")
3860 <input type="checkbox" name="cloneMaterials" id="cloneMaterials" value="1" > _("Attached materials")
3861 <input type="checkbox" name="cloneAccess" id="cloneAccess" value="1" > _("Access and management privileges")
3862 """)
3864 return wc.getHTML(p)
3867 class WUserSelection(WTemplated):
3870 def __init__( self, searchURL, multi=True, addTo=0, forceWithoutExtAuth=False):
3871 self._title = _("Search for users")
3872 self._searchURL = searchURL
3873 self._forceWithoutExtAuth = forceWithoutExtAuth
3874 self._multi = multi # for multiple selection
3875 #addTo=0: do not show any selection box.
3876 #addTo=1: show selection box to add submitter as primary author, coauthor or speaker.
3877 #addTo=2: show selection box to add primary author, coauthor or speaker as submitter.
3878 #addTo=3: show selection box to add session managers as session conveners
3879 #addTo=4: show selection box to add submitter as speaker. This is just for meetings
3880 #addTo=5: show selection box to add submitter and/or manager rights for convener.
3881 self._addTo=addTo
3883 def _performSearch( self, criteria, exact=0 ):
3884 ah = user.AvatarHolder()
3885 res = ah.match(criteria, exact=exact, forceWithoutExtAuth=self._forceWithoutExtAuth)
3886 return res
3888 def setTitle( self, newTitle ):
3889 self._title = newTitle.strip()
3891 def _getPassingParams( self, params ):
3892 l = []
3893 for p in params.keys():
3894 if p in ["firstname", "surname", "organisation", "email", "groupname","exact","searchExt", 'selectedPrincipals']:
3895 continue
3896 l.append( """<input type="hidden" name="%s" value="%s">\n"""%(p, \
3897 params[p] ) )
3898 return "\n".join( l )
3900 def _filterParams( self, params ):
3901 pars = copy( params )
3902 self._action = "show"
3903 if pars.has_key("action"):
3904 self._action = pars["action"].strip()
3905 del pars["action"]
3906 return pars
3908 def _create( self, params ):
3909 pass
3910 #a = user.Avatar()
3911 #a.setName( params["firstname"] )
3912 #a.setSurName( params["surname"] )
3913 #a.setEmail( params["email"] )
3914 #a.setOrganisation( params["organisation"] )
3915 #user.AvatarHolder().add( a )
3917 def _normaliseListParam( self, param ):
3918 if not isinstance(param, list):
3919 return [ param ]
3920 return param
3922 def getHTML( self, params ):
3923 self._cancelURL = params.get("addURL","")
3924 pars = self._filterParams( params )
3925 self._passingParams = self._getPassingParams( pars )
3926 self._msg = ""
3927 if self._action == _("create"):
3928 try:
3929 self._create( pars )
3930 except UserError,e:
3931 self._msg = str(e)#"User not created. The email address is already used."
3932 self._action = _("search")
3933 return WTemplated.getHTML( self, pars )
3935 def getVars( self ):
3936 vars = WTemplated.getVars( self )
3937 vars["usericon"]=quoteattr(str(Config.getInstance().getSystemIconURL("user" )))
3938 vars["firstName"] = vars.get("firstname", "")
3939 vars["surName"] = vars.get("surname", "")
3940 vars["email"] = vars.get("email", "")
3941 vars["organisation"] = vars.get("organisation", "")
3942 if "WPtitle" not in vars or vars["WPtitle"].strip() == "":
3943 vars["WPtitle"] = self._title
3944 vars["params"] = self._passingParams
3945 vars["addURL"] = urlHandlers.UHUserSearchCreateExternalUser.getURL()
3946 #vars["createURL"] = urlHandlers.UHUserSearchCreateExternalUser.getURL()
3947 vars["postURL"] = self._searchURL
3948 vars["cancelURL"] = self._cancelURL
3949 vars["searchResultsTable"] = ""
3950 res=[]
3952 if self._action == _("search").strip():
3953 criteria = { "name": vars["firstName"], \
3954 "surName": vars["surName"], \
3955 "email" : vars["email"], \
3956 "organisation": vars["organisation"] \
3958 if vars.has_key("groupname"):
3959 criteria["groupname"] = vars["groupname"]
3960 exact = 0
3961 if vars.get("exact",0) != 0:
3962 exact = 1
3963 res = self._performSearch( criteria, exact=exact )
3964 vars["searchResultsTable"] = WUserSearchResultsTable(self._multi).getHTML( res )
3965 vars["msg"] = ""
3966 if self._msg:
3967 vars["msg"] = """<tr>
3968 <td bgcolor="white" colspan="3" align="center">
3969 <font color="red">%s</font>
3970 </td>
3971 </tr>"""%self._msg
3972 sb=""
3973 if res!=[]:
3974 if self._addTo==1:
3975 sb=WSelectionBoxAuthors().getHTML()
3976 elif self._addTo==2:
3977 sb=WSelectionBoxSubmitter().getHTML()
3978 elif self._addTo==3:
3979 sb=WSelectionBoxConveners().getHTML()
3980 elif self._addTo==4:
3981 sb=WMSelectionBoxAuthors().getHTML()
3982 elif self._addTo==5:
3983 sb=WSelectionBoxConvToManagerCoordinator().getHTML()
3984 vars["selectionBox"]=sb
3985 vars["searchOptions"]=""
3986 authenticators = Config.getInstance().getAuthenticatorList()
3987 searchList = self._normaliseListParam(vars.get("searchExt",""))
3988 for auth in authenticators:
3989 if auth.lower() != "local":
3990 selected = ""
3991 if auth in searchList:
3992 selected = "checked"
3993 vars["searchOptions"]+= i18nformat("""<input type="checkbox" name="searchExt" value="%s" %s> _("search %s database")<br>""") % (auth, selected, auth.upper())
3994 selected = ""
3995 if vars.get("exact","") != "":
3996 selected = "checked"
3997 vars["searchOptions"]+= i18nformat("""<input type="checkbox" name="exact" value="1" %s> _("exact match")<br>""") % selected
3998 return vars
4000 class WAuthorSearch(WUserSelection):
4002 def __init__(self, conf, searchURL, multi=True, addTo=0, forceWithoutExtAuth=False):
4003 _title = _("Search Users and Authors")
4004 WUserSelection.__init__(self, searchURL, multi, addTo, forceWithoutExtAuth=forceWithoutExtAuth)
4005 self._conf = conf
4008 def _performSearch( self, criteria, exact=0 ):
4009 #this should go in the PrincipalHolder match method
4010 ah = user.AvatarHolder()
4011 resUsers = ah.match(criteria, exact=exact, forceWithoutExtAuth=self._forceWithoutExtAuth)
4012 auths = self._conf.getAuthorIndex()
4013 resAuths = auths.match(criteria, exact=exact)
4014 #crear una lista y devolver el resultado
4015 l = []
4016 emails = []
4017 for usr in resUsers:
4018 l.append(usr)
4019 emails.append(usr.getEmail())
4020 for author in resAuths :
4021 if author.getEmail() not in emails:
4022 l.append(author)
4023 return l
4025 class WPrincipalSelection(WUserSelection):
4028 def _performSearch( self, criteria, exact=0 ):
4029 #this should go in the PrincipalHolder match method
4030 _title = _("Search for users and groups")
4031 ah = user.AvatarHolder()
4032 resUsers = ah.match(criteria,exact=exact,forceWithoutExtAuth=self._forceWithoutExtAuth)
4033 resGroups = [ group for group in user.GroupHolder().match(criteria, forceWithoutExtAuth=self._forceWithoutExtAuth) if not group.isObsolete()]
4034 l = []
4035 for item in resUsers:
4036 l.append(item)
4037 for item in resGroups:
4038 l.append(item)
4039 return l
4041 def getVars( self ):
4042 vars=WUserSelection.getVars(self)
4043 vars["usericon"]=quoteattr(str(Config.getInstance().getSystemIconURL("user" )))
4044 vars["groupicon"]=quoteattr(str(Config.getInstance().getSystemIconURL("group" )))
4045 vars["groupNICEicon"]=quoteattr(str(Config.getInstance().getSystemIconURL("groupNICE" )))
4046 vars["groupname"] = vars.get("groupname", "")
4047 return vars
4050 class WComplexSelection(WUserSelection):
4053 def __init__(self, target, searchAction, addTo = 0, forceWithoutExtAuth=False):
4054 _title = _("Search for users")
4055 WUserSelection.__init__(self, searchAction, addTo = addTo, forceWithoutExtAuth=forceWithoutExtAuth)
4056 try:
4057 self._conf = target.getConference()
4058 except:
4059 self._conf = None
4060 self._target = target
4062 def _performSearch( self, criteria, exact=0 ):
4063 #this should go in the PrincipalHolder match method
4064 ah = user.AvatarHolder()
4065 resUsers = ah.match(criteria, exact=exact, forceWithoutExtAuth=self._forceWithoutExtAuth)
4066 try:
4067 auths = self._conf.getAuthorIndex()
4068 resAuths = auths.match(criteria, exact=exact)
4069 except:
4070 resAuths = []
4071 l = []
4072 emails = []
4073 for usr in resUsers:
4074 l.append(usr)
4075 emails.append(usr.getEmail())
4076 for author in resAuths :
4077 if author.getEmail() not in emails:
4078 l.append(author)
4079 return l
4081 def getVars(self):
4082 vars = WUserSelection.getVars( self )
4083 vars["usericon"]=quoteattr(str(Config.getInstance().getSystemIconURL("user" )))
4084 return vars
4086 class WCategoryComplexSelection(WComplexSelection):
4089 def __init__(self, category, searchAction, forceWithoutExtAuth=False):
4090 WComplexSelection.__init__(self, None, searchAction,forceWithoutExtAuth=forceWithoutExtAuth)
4091 self._category = category
4093 def _performSearch( self, criteria, exact=0 ):
4094 #this should go in the PrincipalHolder match method
4095 ah = user.AvatarHolder()
4096 resUsers = ah.match(criteria, exact=exact, forceWithoutExtAuth=self._forceWithoutExtAuth)
4097 return resUsers
4100 class WNewPerson(WTemplated):
4102 def getVars( self ):
4103 vars = WTemplated.getVars( self )
4104 options = [" ", _("Mr."), _("Ms."), _("Dr."), _("Prof.")]
4105 titles = []
4106 titleValue = vars.get("titleValue", " ")
4108 for o in options :
4109 selected = ""
4110 if titleValue == o :
4111 selected = "selected"
4112 text = """<option value="%s" %s>%s</option>"""%(o, selected, o)
4113 titles.append(text)
4114 vars["titles"] = """
4115 """.join(titles)
4117 if vars.get("disabledTitle", False) :
4118 vars["titles"] = """<input type="hidden" name="title" value="%s"></input>%s"""%(titleValue,titleValue)
4119 else :
4120 vars["titles"] = """
4121 <select name="title">
4123 </select>
4124 """%vars["titles"]
4126 if vars.get("disabledSurName", False) :
4127 vars["surName"] = """<input type="hidden" name="surName" value="%s"></input>%s"""%(vars["surNameValue"],vars["surNameValue"])
4128 else :
4129 vars["surName"] = """<input type="text" size="50" name="surName" value="%s" >"""%vars["surNameValue"]
4131 if vars.get("disabledName", False) :
4132 vars["name"] = """<input type="hidden" name="name" value="%s"></input>%s"""%(vars["nameValue"],vars["nameValue"])
4133 else :
4134 vars["name"] = """<input type="text" size="50" name="name" value="%s" >"""%vars["nameValue"]
4136 if vars.get("disabledAffiliation", False) :
4137 vars["affiliation"] = """<input type="hidden" name="affiliation" value="%s"></input>%s"""%(vars["affiliationValue"],vars["affiliationValue"])
4138 else :
4139 vars["affiliation"] = """<input type="text" size="50" name="affiliation" value="%s" >"""%vars["affiliationValue"]
4141 if vars.get("disabledEmail", False) :
4142 vars["email"] = """<input type="hidden" name="email" value="%s"></input>%s"""%(vars["emailValue"],vars["emailValue"])
4143 else :
4144 js=""
4145 if not vars.get("disabledRole", True) and vars["roleDescription"] == "Submitter":
4146 js="""onkeyup="if (!this.form.submissionControl.checked || this.value.length != 0) {this.form.warning_email.type='hidden';}else{this.form.warning_email.type='text';}">
4147 <input type="text" size="50" value="Warning: if email is empty, submission rights will not be given" style="border: 0px none ; color: red;" id="warning_email"/"""
4148 vars["email"] = """<input type="text" size="50" name="email" value="%s" %s>"""%(vars["emailValue"],js)
4149 if vars.get("disabledAddress", False) :
4150 vars["address"] = """<input type="hidden" name="address" value="%s"></input>%s"""%(vars["addressValue"],vars["addressValue"])
4151 else :
4152 vars["address"] = """<textarea name="address" rows="5" cols="38">%s</textarea>"""%vars["addressValue"]
4154 if vars.get("disabledPhone", False) :
4155 vars["phone"] = """<input type="hidden" name="phone" value="%s"></input>%s"""%(vars["phoneValue"],vars["phoneValue"])
4156 else :
4157 vars["phone"] = """<input type="text" size="50" name="phone" value="%s" >"""%vars["phoneValue"]
4159 if vars.get("disabledPhone", False) :
4160 vars["phone"] = """<input type="hidden" name="phone" value="%s"></input>%s"""%(vars["phoneValue"],vars["phoneValue"])
4161 else :
4162 vars["phone"] = """<input type="text" size="50" name="phone" value="%s" >"""%vars["phoneValue"]
4164 if vars.get("disabledFax", False) :
4165 vars["fax"] = """<input type="hidden" name="fax" value="%s"></input>%s"""%(vars["faxValue"],vars["faxValue"])
4166 else :
4167 vars["fax"] = """<input type="text" size="50" name="fax" value="%s" >"""%vars["faxValue"]
4168 if vars.get("disabledRole", True) :
4169 vars["role"] = ""
4170 else :
4171 vars["role"] = """
4172 <tr>
4173 <td nowrap class="titleCellTD"><span class="titleCellFormat">%s</span></td>
4174 <td bgcolor="white" width="100%%" valign="top" class="blacktext">%s</td>
4175 </tr>"""%(vars["roleDescription"], vars["roleValue"])
4177 if vars.get("disabledNotice", True) :
4178 vars["notice"] = ""
4179 else :
4180 vars["notice"] = """
4181 <tr>
4182 <td nowrap class="titleCellTD"></td>
4183 <td bgcolor="white" width="100%%" valign="top" class="blacktext">%s</td>
4184 </tr>"""%vars["noticeValue"]
4186 if vars.get("msg","")!="":
4187 vars["msg"]= i18nformat("""<table bgcolor="gray"><tr><td bgcolor="white">
4188 <font size="+1" color="red"><b> _("You must enter a valid email address.")</b></font>
4190 </td></tr></table>""")
4191 #raise vars["msg"]
4192 else: vars["msg"]=""
4193 return vars
4196 class WAddPersonModule(WTemplated):
4198 def __addBasketPeople(self, peopleList):
4200 user = self._rh._getUser()
4202 # add extra options if the user is logged in
4203 if user:
4204 basket = user.getPersonalInfo().getBasket().getUsers()
4206 peopleList += """<option value=""></option>"""
4208 for userId in basket:
4209 peopleList += """<option class="favoriteItem" value="%s">%s</option>"""%(userId,basket[userId].getStraightFullName())
4211 return peopleList
4212 # just add nothing if the user is not logged in
4213 else:
4214 return ""
4216 def __init__(self,personType, displayName=""):
4217 self._personType = personType
4218 self._displayName = displayName
4220 def getVars( self ):
4221 vars = WTemplated.getVars( self )
4222 if self._personType is None or self._personType == "" :
4223 raise MaKaCError( _("'personType' must be set to use the Add Person Module"))
4224 return
4226 if self._displayName != "":
4227 vars["personName"] = self._displayName
4228 else:
4229 vars["personName"] = string.capwords("%s"%self._personType)
4231 # Add people from the users basket
4232 vars["personOptions"] = self.__addBasketPeople("")
4234 vars["personOptions"] += vars["%sOptions"%self._personType]
4236 vars["personChosen"] = "%sChosen"%self._personType
4238 vars["personDefined"] = vars["%sDefined"%self._personType]
4240 if vars["personOptions"] == """<option value=""> </option>""":
4241 vars["disabledAdd"] = "disabled"
4242 else:
4243 vars["disabledAdd"] = ""
4245 vars["personType"] = self._personType
4247 if vars.get("submission",None) is not None :
4248 vars["submissionButtons"] = i18nformat("""
4249 <tr>
4250 <td colspan="4"><input type="submit" class="btn" value="_("Grant submission")" onClick="setAction(this.form,'Grant submission');"></td>
4251 </tr>
4252 <tr>
4253 <td colspan="4"><input type="submit" class="btn" value="_("Withdraw submission")" onClick="setAction(this.form,'Withdraw submission');"></td>
4254 </tr>""")
4255 else :
4256 vars["submissionButtons"] = ""
4257 return vars
4260 class WAccountAlreadyActivated(WTemplated):
4262 def __init__(self, av):
4263 self._av = av
4265 def getVars( self ):
4266 vars = WTemplated.getVars( self )
4267 return vars
4270 class WAccountActivated(WTemplated):
4272 def __init__(self, av):
4273 self._av = av
4275 def getVars( self ):
4276 vars = WTemplated.getVars( self )
4277 return vars
4280 class WAccountDisabled(WTemplated):
4282 def __init__(self, av):
4283 self._av = av
4285 def getVars( self ):
4286 vars = WTemplated.getVars( self )
4287 return vars
4290 class WUnactivatedAccount(WTemplated):
4292 def __init__(self, av):
4293 self._av = av
4295 def getVars( self ):
4296 vars = WTemplated.getVars( self )
4297 minfo = info.HelperMaKaCInfo.getMaKaCInfoInstance()
4298 vars["moderated"]=minfo.getModerateAccountCreation()
4299 return vars
4302 class WAbstractModIntCommentEdit(WTemplated):
4304 def __init__(self,comment):
4305 self._comment=comment
4307 def getVars(self):
4308 vars=WTemplated.getVars(self)
4309 vars["content"]=self.htmlText(self._comment.getContent())
4310 return vars
4313 class WAbstractModNewIntComment(WTemplated):
4315 def __init__(self,aw,abstract):
4316 self._aw=aw
4317 self._abstract=abstract
4319 def getVars(self):
4320 vars=WTemplated.getVars(self)
4321 return vars
4324 class WSessionModifComm(WTemplated):
4325 def __init__(self, aw,session):
4326 self._aw = aw
4327 self._session = session
4328 self._conf = session.getConference()
4330 def _getHTML(self,editCommentsURLGen):
4331 try:
4332 comment =self._session.getComments()
4333 if comment=="":
4334 comment= _("No Session Comment Entered")
4335 except:
4336 comment = _("No Session Comment Entered")
4337 self._session.setComments("")
4339 modifButton=""
4340 if self._conf.canModify(self._aw):
4342 modifButton = i18nformat("""<form action=%s method="POST">
4343 <td align="center">
4344 <input type="submit" class="btn" value="_("modify")">
4345 </td>
4346 </form>
4347 """)%quoteattr(str(editCommentsURLGen(self._session)))
4348 return ( i18nformat("""
4349 <table width="50%%" align="center" style="border-left: 1px solid #777777">
4350 <tr>
4351 <td class="groupTitle"> _("Session comment")</td>
4352 </tr>
4353 <tr>
4354 <td>
4356 </td>
4357 </tr>
4358 <tr>
4360 </tr>
4361 </table> """)%(comment,modifButton))
4363 def getVars(self):
4364 vars=WTemplated.getVars(self)
4365 vars["comment"]=self._getHTML(vars["editCommentsURLGen"])
4366 return vars
4370 class WSessionModifCommEdit(WTemplated):
4372 def __init__(self,comment):
4373 self._comment=comment
4375 def getVars(self):
4376 vars=WTemplated.getVars(self)
4377 vars["comment"]=self.htmlText(self._comment)
4378 return vars
4380 class WAbstractModIntComments(WTemplated):
4382 def __init__(self,aw,abstract):
4383 self._aw=aw
4384 self._abstract=abstract
4386 def _getCommentsHTML(self,commentEditURLGen,commentRemURLGen):
4387 res=[]
4388 commentList = self._abstract.getIntCommentList()
4389 for c in commentList:
4390 mailtoSubject="[Indico] Abstract %s: %s"%(self._abstract.getId(), self._abstract.getTitle())
4391 mailtoURL=URL("mailto:%s"%c.getResponsible().getEmail())
4392 mailtoURL.addParam("subject", mailtoSubject)
4393 responsible="""<a href=%s>%s</a>"""%(quoteattr(str(mailtoURL)),self.htmlText(c.getResponsible().getFullName()))
4394 date=self.htmlText(c.getCreationDate().strftime("%Y-%m-%d %H:%M"))
4395 buttonMod,buttonRem="",""
4396 if self._aw.getUser()==c.getResponsible():
4397 buttonMod= i18nformat("""
4398 <form action=%s method="POST">
4399 <td valign="bottom">
4400 <input type="submit" class="btn" value="_("modify")">
4401 </td>
4402 </form>
4403 """)%quoteattr(str(commentEditURLGen(c)))
4404 buttonRem= i18nformat("""
4405 <form action=%s method="POST">
4406 <td valign="bottom">
4407 <input type="submit" class="btn" value="_("remove")">
4408 </td>
4409 </form>
4410 """)%quoteattr(str(commentRemURLGen(c)))
4411 res.append("""
4412 <tr>
4413 <td bgcolor="white" style="border-top:1px solid #777777;border-bottom:1px solid #777777;">
4414 <table>
4415 <tr>
4416 <td width="100%%">%s on %s</td>
4417 </tr>
4418 <tr>
4419 <td>%s</td>
4422 </tr>
4423 </table>
4424 </td>
4425 </tr>"""%(responsible,date,c.getContent(),buttonMod,buttonRem))
4426 if res == []:
4427 res.append( i18nformat("""<tr><td align=\"center\" style=\"color:black\"><br>--_("no internal comments")--<br><br></td></tr>"""))
4428 return "".join(res)
4430 def getVars(self):
4431 vars=WTemplated.getVars(self)
4432 vars["comments"]=self._getCommentsHTML(vars["commentEditURLGen"],vars["commentRemURLGen"])
4433 vars["newCommentURL"]=quoteattr(str(vars["newCommentURL"]))
4434 return vars
4437 class WAbstractModMarkAsDup(WTemplated):
4439 def __init__(self,abstract):
4440 self._abstract=abstract
4442 def getVars(self):
4443 vars=WTemplated.getVars(self)
4444 vars["duplicateURL"]=quoteattr(str(vars["duplicateURL"]))
4445 vars["cancelURL"]=quoteattr(str(vars["cancelURL"]))
4446 vars["error"] = vars.get("errorMsg","")
4447 return vars
4450 class WAbstractModUnMarkAsDup(WTemplated):
4452 def __init__(self,abstract):
4453 self._abstract=abstract
4456 def getVars(self):
4457 vars=WTemplated.getVars(self)
4458 vars["unduplicateURL"]=quoteattr(str(vars["unduplicateURL"]))
4459 vars["cancelURL"]=quoteattr(str(vars["cancelURL"]))
4460 return vars
4463 class WScheduleAddContributions(WTemplated):
4465 def __init__(self,selectList,targetDay=None):
4466 self._contribList=selectList
4467 self._targetDay=targetDay
4469 def _getContribListHTML(self):
4470 res=[]
4471 contribList=filters.SimpleFilter(None,contribFilters.SortingCriteria(["number"])).apply(self._contribList)
4472 for contrib in self._contribList:
4473 typeCaption=""
4474 if contrib.getType() is not None:
4475 typeCaption=contrib.getType().getName()
4476 l=[]
4477 for spk in contrib.getSpeakerList():
4478 l.append("""%s"""%(self.htmlText(spk.getFullName())))
4479 spksCaption="<br>".join(l)
4480 res.append("""
4481 <tr>
4482 <td valign="top">
4483 <input type="checkbox" name="manSelContribs" value=%s>
4484 </td>
4485 <td valign="top">%s</td>
4486 <td valign="top">[%s]</td>
4487 <td valign="top"><i>%s</i></td>
4488 <td valign="top">%s</td>
4489 </tr>
4490 """%(quoteattr(str(contrib.getId())),
4491 self.htmlText(contrib.getId()),
4492 self.htmlText(typeCaption),
4493 self.htmlText(contrib.getTitle()),
4494 spksCaption))
4495 return "".join(res)
4498 def getVars(self):
4499 vars=WTemplated.getVars(self)
4500 vars["contribs"]="".join(self._getContribListHTML())
4501 vars["targetDay"]=""
4502 if self._targetDay is not None:
4503 vars["targetDay"]="""<input type="hidden" name="targetDay" value=%s>"""%(quoteattr(str(self._targetDay.strftime("%Y-%m-%d"))))
4504 return vars
4507 class WSchEditContrib(WTemplated):
4509 def __init__(self,contrib):
4510 self._contrib=contrib
4512 def getVars(self):
4513 vars=WTemplated.getVars(self)
4514 vars["postURL"]=quoteattr(str(vars["postURL"]))
4515 vars["title"]=self.htmlText(self._contrib.getTitle())
4516 confTZ = self._contrib.getConference().getTimezone()
4517 sDate=self._contrib.getStartDate().astimezone(timezone(confTZ))
4518 vars["sYear"]=quoteattr(str(sDate.year))
4519 vars["sMonth"]=quoteattr(str(sDate.month))
4520 vars["sDay"]=quoteattr(str(sDate.day))
4521 vars["sHour"]=quoteattr(str(sDate.hour))
4522 vars["sMinute"]=quoteattr(str(sDate.minute))
4523 vars["durHours"]=quoteattr(str(int(self._contrib.getDuration().seconds/3600)))
4524 vars["durMins"]=quoteattr(str(int((self._contrib.getDuration().seconds%3600)/60)))
4525 defaultDefinePlace=defaultDefineRoom=""
4526 defaultInheritPlace=defaultInheritRoom="checked"
4527 locationName,locationAddress,roomName="","",""
4528 if self._contrib.getOwnLocation():
4529 defaultDefinePlace,defaultInheritPlace="checked",""
4530 locationName=self._contrib.getLocation().getName()
4531 locationAddress=self._contrib.getLocation().getAddress()
4532 if self._contrib.getOwnRoom():
4533 defaultDefineRoom,defaultInheritRoom="checked",""
4534 roomName=self._contrib.getRoom().getName()
4535 vars["defaultInheritPlace"]=defaultInheritPlace
4536 vars["defaultDefinePlace"]=defaultDefinePlace
4537 vars["confPlace"]=""
4538 confLocation=self._contrib.getOwner().getLocation()
4539 if self._contrib.isScheduled():
4540 confLocation=self._contrib.getSchEntry().getSchedule().getOwner().getLocation()
4541 if confLocation:
4542 vars["confPlace"]=confLocation.getName()
4543 vars["locationName"]=locationName
4544 vars["locationAddress"]=locationAddress
4545 vars["defaultInheritRoom"]=defaultInheritRoom
4546 vars["defaultDefineRoom"]=defaultDefineRoom
4547 vars["confRoom"]=""
4548 confRoom=self._contrib.getOwner().getRoom()
4549 if self._contrib.isScheduled():
4550 confRoom=self._contrib.getSchEntry().getSchedule().getOwner().getRoom()
4551 if confRoom:
4552 vars["confRoom"]=confRoom.getName()
4553 vars["roomName"]=quoteattr(roomName)
4554 vars["parentType"]="conference"
4555 if self._contrib.getSession() is not None:
4556 vars["parentType"]="session"
4557 if self._contrib.isScheduled():
4558 vars["parentType"]="session slot"
4559 vars["boardNumber"]=quoteattr(str(self._contrib.getBoardNumber()))
4560 vars["autoUpdate"] = ""
4561 return vars
4564 class WConfModParticipEdit(WTemplated):
4566 def __init__(self,title="",part=None):
4567 self._part=part
4568 self._ctitle=title
4570 def getVars(self):
4571 vars=WTemplated.getVars(self)
4572 vars["postURL"]=quoteattr(str(vars["postURL"]))
4573 vars["caption"]=self.htmlText(self._ctitle)
4574 title,firstName,familyName="","",""
4575 affiliation,email,address,phone,fax="","","","",""
4576 if self._part is not None:
4577 title=self._part.getTitle()
4578 firstName=self._part.getFirstName()
4579 familyName=self._part.getFamilyName()
4580 affiliation=self._part.getAffiliation()
4581 email=self._part.getEmail()
4582 address=self._part.getAddress()
4583 phone=self._part.getPhone()
4584 fax=self._part.getFax()
4585 vars["titles"]=TitlesRegistry().getSelectItemsHTML(title)
4586 vars["surName"]=quoteattr(familyName)
4587 vars["name"]=quoteattr(firstName)
4588 vars["affiliation"]=quoteattr(affiliation)
4589 vars["email"]=quoteattr(email)
4590 vars["address"]=address
4591 vars["phone"]=quoteattr(phone)
4592 vars["fax"]=quoteattr(fax)
4593 if not vars.has_key("addToManagersList"):
4594 vars["addToManagersList"]=""
4595 return vars
4597 class WSessionModEditDataCode(WTemplated):
4599 def __init__(self):
4600 pass
4602 def getVars( self ):
4603 vars=WTemplated.getVars(self)
4604 vars["code"]=quoteattr(str(vars.get("code","")))
4605 return vars
4607 class WSessionModEditDataType(WTemplated):
4609 def __init__(self):
4610 pass
4612 def getVars( self ):
4613 vars=WTemplated.getVars(self)
4614 l=[]
4615 currentTTType=vars.get("tt_type",conference.SlotSchTypeFactory.getDefaultId())
4616 for i in conference.SlotSchTypeFactory.getIdList():
4617 sel=""
4618 if i==currentTTType:
4619 sel=" selected"
4620 l.append("""<option value=%s%s>%s</option>"""%(quoteattr(str(i)),
4621 sel,self.htmlText(i)))
4622 vars["tt_types"]="".join(l)
4623 return vars
4625 class WSessionModEditDataColors(WTemplated):
4627 def __init__(self):
4628 pass
4630 def getVars( self ):
4631 vars=WTemplated.getVars(self)
4632 return vars
4634 class WSessionModEditData(WTemplated):
4636 def __init__(self,targetConf,aw,pageTitle="",targetDay=None):
4637 self._conf=targetConf
4638 self._title=pageTitle
4639 self._targetDay=targetDay
4640 self._aw = aw
4642 def _getErrorHTML(self,l):
4643 if len(l)>0:
4644 return """
4645 <tr>
4646 <td colspan="2" align="center">
4647 <br>
4648 <table bgcolor="red" cellpadding="6">
4649 <tr>
4650 <td bgcolor="white" style="color: red">%s</td>
4651 </tr>
4652 </table>
4653 <br>
4654 </td>
4655 </tr>
4656 """%"<br>".join(l)
4657 else:
4658 return ""
4660 def getVars( self ):
4661 vars=WTemplated.getVars(self)
4662 vars["conference"] = self._conf
4663 vars["eventId"] = "s" + vars["sessionId"]
4664 minfo = info.HelperMaKaCInfo.getMaKaCInfoInstance()
4665 vars["useRoomBookingModule"] = minfo.getRoomBookingModuleActive()
4666 vars["calendarIconURL"]=Config.getInstance().getSystemIconURL( "calendar" )
4667 vars["calendarSelectURL"]=urlHandlers.UHSimpleCalendar.getURL()
4668 vars["pageTitle"]=self.htmlText(self._title)
4669 vars["errors"]=self._getErrorHTML(vars.get("errors",[]))
4670 vars["postURL"]=quoteattr(str(vars["postURL"]))
4671 vars["title"]=quoteattr(str(vars.get("title","")))
4672 vars["description"]=self.htmlText(vars.get("description",""))
4673 if self._targetDay == None:
4674 sessionId = vars["sessionId"]
4675 session = self._conf.getSessionById(sessionId)
4676 refDate = session.getAdjustedStartDate()
4677 else:
4678 refDate=self._conf.getSchedule().getFirstFreeSlotOnDay(self._targetDay)
4679 endDate = None
4680 if refDate.hour == 23:
4681 refDate = refDate - timedelta(minutes=refDate.minute)
4682 endDate = refDate + timedelta(minutes=59)
4683 vars["sDay"]=str(vars.get("sDay",refDate.day))
4684 vars["sMonth"]=str(vars.get("sMonth",refDate.month))
4685 vars["sYear"]=str(vars.get("sYear",refDate.year))
4686 vars["sHour"]=str(vars.get("sHour",refDate.hour))
4687 vars["sMinute"]=str(vars.get("sMinute",refDate.minute))
4688 if not endDate:
4689 endDate=refDate+timedelta(hours=1)
4690 vars["eDay"]=str(vars.get("eDay",endDate.day))
4691 vars["eMonth"]=str(vars.get("eMonth",endDate.month))
4692 vars["eYear"]=str(vars.get("eYear",endDate.year))
4693 vars["eHour"]=str(vars.get("eHour",endDate.hour))
4694 vars["eMinute"]=str(vars.get("eMinute",endDate.minute))
4695 vars["durHour"]=quoteattr(str(vars.get("durHour",0)))
4696 vars["durMin"]=quoteattr(str(vars.get("durMin",20)))
4697 vars["defaultInheritPlace"]="checked"
4698 vars["defaultDefinePlace"]=""
4700 if vars.get("convenerDefined",None) is None :
4701 sessionId = vars["sessionId"]
4702 session = self._conf.getSessionById(sessionId)
4703 html = []
4704 for convener in session.getConvenerList() :
4705 text = """
4706 <tr>
4707 <td width="5%%"><input type="checkbox" name="%ss" value="%s"></td>
4708 <td>&nbsp;%s</td>
4709 </tr>"""%("convener",convener.getId(),convener.getFullName())
4710 html.append(text)
4711 vars["definedConveners"] = """
4712 """.join(html)
4713 if vars.get("locationAction","")=="define":
4714 vars["defaultInheritPlace"]=""
4715 vars["defaultDefinePlace"]="checked"
4716 vars["confPlace"]=""
4717 confLocation=self._conf.getConference().getLocation()
4718 if confLocation:
4719 vars["confPlace"]=self.htmlText(confLocation.getName())
4720 vars["locationName"]=quoteattr(str(vars.get("locationName","")))
4721 vars["locationAddress"]=self.htmlText(vars.get("locationAddress",""))
4722 vars["defaultInheritRoom"]=""
4723 vars["defaultDefineRoom"]=""
4724 vars["defaultExistRoom"]=""
4725 if vars.get("roomAction","")=="inherit":
4726 vars["defaultInheritRoom"]="checked"
4727 roomName = ""
4728 elif vars.get("roomAction","")=="define":
4729 vars["defaultDefineRoom"]="checked"
4730 roomName = vars.get( "bookedRoomName" ) or vars.get("roomName","")
4731 elif vars.get("roomAction","")=="exist":
4732 vars["defaultExistRoom"]="checked"
4733 roomName = vars.get("exists", "") or vars.get("roomName","")
4734 else:
4735 vars["defaultInheritRoom"]="checked"
4736 roomName = ""
4739 vars["confRoom"]=""
4740 rx=[]
4741 roomsexist = self._conf.getRoomList()
4742 roomsexist.sort()
4743 for room in roomsexist:
4744 sel=""
4745 if room==roomName:
4746 sel="selected=\"selected\""
4747 rx.append("""<option value=%s %s>%s</option>"""%(quoteattr(str(room)),
4748 sel,self.htmlText(room)))
4749 vars ["roomsexist"] = "".join(rx)
4750 confRoom=self._conf.getConference().getRoom()
4751 if confRoom:
4752 vars["confRoom"]=self.htmlText(confRoom.getName())
4753 vars["roomName"]=quoteattr(str(roomName))
4755 vars["autoUpdate"]=""
4756 if not self._conf.getEnableSessionSlots():
4757 vars["disabled"] = "disabled"
4758 else:
4759 vars["disabled"] = ""
4760 if self._title.find("Ed") != -1 and self._conf.getEnableSessionSlots():
4761 vars["adjustSlots"]= i18nformat("""<input type="checkbox" name="slmove" value="1"> _("Also move timetable entries")""")
4762 else:
4763 vars["adjustSlots"]="""<input type="hidden" name="slmove" value="1">"""
4764 import MaKaC.webinterface.webFactoryRegistry as webFactoryRegistry
4765 wr = webFactoryRegistry.WebFactoryRegistry()
4766 wf = wr.getFactory(self._conf)
4767 if wf != None:
4768 type = wf.getId()
4769 else:
4770 type = "conference"
4771 if type == "conference":
4772 vars["Type"]=WSessionModEditDataType().getHTML(vars)
4773 vars["Colors"]=WSessionModEditDataColors().getHTML(vars)
4774 vars["code"]=WSessionModEditDataCode().getHTML(vars)
4775 else:
4776 vars["Type"]=""
4777 vars["Colors"]=""
4778 vars["code"]=""
4779 return vars
4781 #--------------------------------------------------------------------------------------
4783 class WConfModMoveContribsToSessionConfirmation(WTemplated):
4785 def __init__(self,conf,contribIdList=[],targetSession=None):
4786 self._conf=conf
4787 self._contribIdList=contribIdList
4788 self._targetSession=targetSession
4790 def _getWarningsHTML(self):
4791 wl=[]
4792 for id in self._contribIdList:
4793 contrib=self._conf.getContributionById(id)
4794 if contrib is None:
4795 continue
4796 spkList=[]
4797 for spk in contrib.getSpeakerList():
4798 spkList.append(self.htmlText(spk.getFullName()))
4799 spkCaption=""
4800 if len(spkList)>0:
4801 spkCaption=" by %s"%"; ".join(spkList)
4802 if (contrib.getSession() is not None and \
4803 contrib.getSession()!=self._targetSession):
4804 scheduled=""
4805 if contrib.isScheduled():
4806 scheduled= i18nformat(""" _("and scheduled") (%s)""")%self.htmlText(contrib.getStartDate().strftime("%Y-%b-%d %H:%M"))
4807 wl.append( i18nformat("""
4808 <li>%s-<i>%s</i>%s: is <font color="red"> _("already in session") <b>%s</b>%s</font></li>
4809 """)%(self.htmlText(contrib.getId()),
4810 self.htmlText(contrib.getTitle()),
4811 spkCaption,
4812 self.htmlText(contrib.getSession().getTitle()),
4813 scheduled))
4814 if (contrib.getSession() is None and \
4815 self._targetSession is not None and \
4816 contrib.isScheduled()):
4817 wl.append( i18nformat("""
4818 <li>%s-<i>%s</i>%s: is <font color="red"> _("scheduled") (%s)</font></li>
4819 """)%(self.htmlText(contrib.getId()),
4820 self.htmlText(contrib.getTitle()),
4821 spkCaption,
4822 self.htmlText(contrib.getStartDate().strftime("%Y-%b-%d %H:%M"))))
4823 return "<ul>%s</ul>"%"".join(wl)
4825 def getVars(self):
4826 vars=WTemplated.getVars(self)
4827 vars["postURL"]=quoteattr(str(vars["postURL"]))
4828 vars["systemIconWarning"]=Config.getInstance().getSystemIconURL("warning")
4829 vars["contribIdList"]=", ".join(self._contribIdList)
4830 vars["targetSession"]="--none--"
4831 if self._targetSession is not None:
4832 vars["targetSession"]=self.htmlText("%s"%self._targetSession.getTitle())
4833 vars["warnings"]=self._getWarningsHTML()
4834 vars["targetSessionId"]=quoteattr("--none--")
4835 if self._targetSession is not None:
4836 vars["targetSessionId"]=quoteattr(str(self._targetSession.getId()))
4837 l=[]
4838 for id in self._contribIdList:
4839 l.append("""<input type="hidden" name="contributions" value=%s">"""%quoteattr(str(id)))
4840 vars["contributions"]="\n".join(l)
4841 return vars
4844 class WConfTBDrawer:
4846 def __init__(self,tb):
4847 self._tb=tb
4849 def getHTML(self):
4850 if self._tb is None:
4851 return ""
4852 res=[]
4853 for item in self._tb.getItemList():
4854 if not item.isEnabled():
4855 continue
4856 res.append("""
4857 <td align="right" nowrap><a href=%s><img src=%s alt=%s></a></td>
4858 """%(quoteattr(str(item.getActionURL())),
4859 quoteattr(str(item.getIcon())),
4860 quoteattr(item.getCaption())))
4861 if res != []:
4862 return """
4863 <table cellpadding="0" cellspacing="1">
4864 <tr>
4866 </tr>
4867 </table>
4868 """%("".join(res))
4869 return ""
4871 class WErrorMessage :
4873 def getHTML( self, vars ):
4875 if vars.get("errorMsg", None) is None :
4876 return ""
4877 if type(vars["errorMsg"]) != list:
4878 vars["errorMsg"]=[vars["errorMsg"]]
4879 for i in range(0,len(vars["errorMsg"])) :
4880 vars["errorMsg"][i] = """<span style="color: red;">"""+vars["errorMsg"][i]+"""</span>"""
4882 errorMsg = """
4883 """.join(vars["errorMsg"])
4885 html = """
4886 <div class="errorMsgBox">
4888 </div>
4889 """%errorMsg
4891 return html
4893 class WInfoMessage :
4895 def getHTML( self, vars ):
4896 if vars.get("infoMsg", None) is None :
4897 return ""
4898 if type(vars["infoMsg"]) != list:
4899 vars["infoMsg"]=[vars["infoMsg"]]
4900 for i in range(0,len(vars["infoMsg"])) :
4901 vars["infoMsg"][i] = """<span style="color: green;">"""+vars["infoMsg"][i]+"""</span>"""
4903 infoMsg = """
4904 """.join(vars["infoMsg"])
4906 html = """
4907 <div class="errorMsgBox">
4909 </div>
4910 """%infoMsg
4912 return html
4914 class WConfTickerTapeDrawer(WTemplated):
4916 def __init__(self,conf, tz=None):
4917 self._conf=conf
4918 self._tz = tz
4919 dm = displayMgr.ConfDisplayMgrRegistery().getDisplayMgr(self._conf, False)
4920 self._tickerTape = dm.getTickerTape()
4922 def getNowHappeningHTML( self, params=None ):
4923 if not self._tickerTape.isActive():
4924 return None
4926 html = WTemplated.getHTML( self, params )
4928 if html == "":
4929 return None
4931 return html
4933 def getSimpleText( self ):
4934 if not self._tickerTape.isSimpleTextEnabled() or \
4935 self._tickerTape.getText().strip() == "":
4936 return None
4938 return self._tickerTape.getText()
4940 def getVars(self):
4941 vars = WTemplated.getVars( self )
4943 vars["nowHappeningArray"] = None
4944 if self._tickerTape.isNowHappeningEnabled():
4945 vars["nowHappeningArray"] = self._getNowHappening()
4947 return vars
4949 def _getNowHappening( self ):
4950 # This will contain a string formated for use in the template
4951 # javascripts
4952 nowHappeningArray = None
4954 # currently happening:
4955 n = nowutc()
4956 entries = self._conf.getSchedule().getEntriesOnDate(n)
4957 entryCaptions = []
4958 for entry in entries:
4959 if isinstance(entry, schedule.LinkedTimeSchEntry) and \
4960 isinstance(entry.getOwner(), conference.SessionSlot):
4961 ss=entry.getOwner()
4962 ssEntries=ss.getSchedule().getEntriesOnDate(n)
4963 if isinstance(ss.getSchedule(), conference.PosterSlotSchedule):
4964 ssEntries=ss.getSchedule().getEntries()
4965 for ssEntry in ssEntries:
4966 title=ssEntry.getTitle()
4967 if isinstance(ssEntry.getOwner(), conference.Contribution):
4968 title="""<a href=%s>%s</a>"""%( \
4969 quoteattr(str(urlHandlers.UHContributionDisplay.getURL(ssEntry.getOwner()))), title)
4970 else:
4971 title="""<a href=%s>%s</a>"""%( \
4972 quoteattr(str(urlHandlers.UHSessionDisplay.getURL(ssEntry.getOwner()))), title)
4973 if ssEntry.getOwnRoom() is not None:
4974 if self._conf.getRoom() is None or \
4975 ssEntry.getOwnRoom().getName().strip().lower() != self._conf.getRoom().getName().strip().lower():
4976 title="%s (%s)"%(title, ssEntry.getOwnRoom().getName().strip())
4977 entryCaptions.append("%s <em>%s-%s</em>" %(title,
4978 entry.getAdjustedStartDate(self._tz).strftime("%H:%M"), \
4979 entry.getAdjustedEndDate(self._tz).strftime("%H:%M")))
4980 else:
4981 title=entry.getTitle()
4982 if isinstance(entry.getOwner(), conference.Contribution):
4983 title="""<a href=%s>%s</a>"""%(quoteattr(str(urlHandlers.UHContributionDisplay.getURL(entry.getOwner()))), title)
4984 else:
4985 url=urlHandlers.UHConferenceTimeTable.getURL(self._conf)
4986 url.addParam("showDate",entry.getStartDate().strftime("%d-%B-%Y"))
4987 title="""<a href=%s>%s</a>"""%(quoteattr(str(url)), title)
4988 if entry.getOwnRoom() is not None:
4989 if self._conf.getRoom() is None or \
4990 entry.getOwnRoom().getName().strip().lower() != self._conf.getRoom().getName().strip().lower():
4991 title="%s (%s)"%(title, entry.getOwnRoom().getName().strip())
4992 entryCaptions.append("%s <em>%s-%s</em>" %(title,
4993 entry.getAdjustedStartDate(self._tz).strftime("%H:%M"), \
4994 entry.getAdjustedEndDate(self._tz).strftime("%H:%M")))
4995 if entryCaptions!=[]:
4996 nowHappeningArray = """['%s']""" %("', '".join(entryCaptions))
4998 return nowHappeningArray
5000 class WSubmitMaterialLink(WTemplated):
5002 def __init__(self, filenb, availMF):
5003 self._filenb=filenb
5004 self._availMF=availMF
5006 def getVars(self):
5007 vars=WTemplated.getVars(self)
5008 vars["itemNumber"]=self._filenb
5009 vars["materialTypeSelectFieldName"]="LinkType%s"%self._filenb
5010 vars["materialTypeInputFieldName"]="LinkTypeFT%s"%self._filenb
5011 vars["urlFieldName"]="link%s"%self._filenb
5012 l=[ i18nformat("""<option value="notype">--_("Select a type")--</option>""")]
5013 selMatType=vars.get("LinkType%s" % self._filenb,"")
5014 for mf in self._availMF:
5015 try:
5016 id = mf.getId()
5017 title = mf.getTitle()
5018 except:
5019 id = mf
5020 title = mf.capitalize()
5021 selected=""
5022 if id==selMatType:
5023 selected=" selected"
5024 l.append("""<option value=%s%s>%s</option>"""%(\
5025 quoteattr(str(id)),selected,
5026 self.htmlText(title)))
5027 vars["matTypeItems"]="".join(l)
5028 if vars.get("LinkTypeFT%s" % self._filenb, "") != "":
5029 vars["materialTypeInputFieldValue"] = vars.get("LinkTypeFT%s" % self._filenb, "")
5030 else:
5031 vars["materialTypeInputFieldValue"] = ""
5032 if vars.get("link%s" % self._filenb, "") != "":
5033 vars["linkValue"] = vars.get("link%s" % self._filenb, "")
5034 else:
5035 vars["linkValue"] = ""
5036 return vars
5038 class WSubmitMaterialFile(WTemplated):
5040 def __init__(self, filenb, availMF):
5041 self._filenb=filenb
5042 self._availMF=availMF
5044 def getVars(self):
5045 vars=WTemplated.getVars(self)
5046 vars["itemNumber"]=self._filenb
5047 vars["materialTypeSelectFieldName"]="FileType%s"%self._filenb
5048 vars["materialTypeInputFieldName"]="FileTypeFT%s"%self._filenb
5049 vars["fileFieldName"]="file%s"%self._filenb
5050 l=[ i18nformat("""<option value="notype">--_("Select a type")--</option>""")]
5051 selMatType=vars.get("FileType%s" % self._filenb,"")
5052 for mf in self._availMF:
5053 try:
5054 id = mf.getId()
5055 title = mf.getTitle()
5056 except:
5057 id = mf
5058 title = mf.capitalize()
5059 selected=""
5060 if id==selMatType:
5061 selected=" selected"
5062 l.append("""<option value=%s%s>%s</option>"""%(\
5063 quoteattr(str(id)),selected,
5064 self.htmlText(title)))
5065 vars["matTypeItems"]="".join(l)
5066 if vars.get("FileTypeFT%s" % self._filenb, "") != "":
5067 vars["materialTypeInputFieldValue"] = vars.get("FileTypeFT%s" % self._filenb, "")
5068 else:
5069 vars["materialTypeInputFieldValue"] = ""
5070 if vars.get("FileNewName%s" % self._filenb, "") != "":
5071 vars["fileName"] = vars.get("FileNewName%s" % self._filenb)
5072 else:
5073 vars["fileName"] = ""
5074 vars["fileNewName"] = "FileNewName%s" % self._filenb
5075 return vars
5077 class WMaterialListFile(WTemplated):
5079 def __init__(self, target):
5080 self._target=target
5082 def getVars(self):
5083 vars=WTemplated.getVars(self)
5084 try:
5085 name=self._target.getFileName()
5086 except:
5087 name=self._target.getURL()
5088 vars["fileName"]=name
5089 if self._target.getName()!="" and name!=self._target.getName():
5090 vars["fileName"]+=" (%s)" % self._target.getName()
5091 vars["fileActions"] = ""
5092 if isinstance(self._target, conference.Link):
5093 if vars["resourcesLinkModifHandler"]:
5094 vars["fileActions"] += """<a href="%s"><img src="%s" alt="Edit" style="margin-left: 5px; vertical-align:middle" /></a>"""%(vars["resourcesLinkModifHandler"].getURL(self._target), Config.getInstance().getSystemIconURL("file_edit"))
5095 if vars["resourcesLinkProtectHandler"]:
5096 vars["fileActions"] += """<a href="%s"><img src="%s" alt="Protect" style="margin-left: 5px; vertical-align:middle" /></a>"""%(vars["resourcesLinkProtectHandler"].getURL(self._target), Config.getInstance().getSystemIconURL("file_protect"))
5097 elif isinstance(self._target, conference.LocalFile):
5098 if vars["resourcesFileModifHandler"]:
5099 vars["fileActions"] += """<a href="%s"><img src="%s" alt="Edit" style="margin-left: 5px; vertical-align:middle" /></a>"""%(vars["resourcesFileModifHandler"].getURL(self._target), Config.getInstance().getSystemIconURL("file_edit"))
5100 if vars["resourcesFileProtectHandler"]:
5101 vars["fileActions"] += """<a href="%s"><img alt="Protected" src="%s" style="margin-left: 5px; vertical-align:middle"/></a>"""%(vars["resourcesFileProtectHandler"].getURL(self._target), Config.getInstance().getSystemIconURL("file_protect"))
5102 vars["deleteIconURL"]=Configuration.Config.getInstance().getSystemIconURL("smallDelete")
5103 vars["delName"]="delete-%s-%s"% (self._target.getOwner().getId(),self._target.getId())
5104 try:
5105 vars["fileInfo"]="[%s bytes - %s]" % (self._target.getSize(),self._target.getCreationDate().strftime("%d.%m.%Y %H:%M:%S"))
5106 except:
5107 vars["fileInfo"]="[link]"
5108 if self._target.isProtected():
5109 vars["fileActions"] += """<img src="%s" alt="Protected" style="vertical-align: middle; border: 0;">""" % Config.getInstance().getSystemIconURL("protected")
5110 if isinstance(self._target, conference.Link):
5111 vars["fileAccessURL"]=quoteattr(str(self._target.getURL()))
5112 else:
5113 vars["fileAccessURL"]=quoteattr(str(urlHandlers.UHFileAccess.getURL(self._target)))
5114 return vars
5116 class WMaterialListItem(WTemplated):
5118 def __init__(self, target, returnURL=""):
5119 self._target=target
5120 self._returnURL = returnURL.strip('"')
5122 def getVars(self):
5123 vars=WTemplated.getVars(self)
5124 deleteURL = None
5125 mf = None
5126 from MaKaC.webinterface.materialFactories import ConfMFRegistry,SessionMFRegistry,ContribMFRegistry
5127 if isinstance(self._target.getOwner(),conference.Conference):
5128 mf=ConfMFRegistry().get(self._target)
5129 deleteURL = urlHandlers.UHConferenceRemoveMaterials.getURL(self._target)
5130 elif isinstance(self._target.getOwner(),conference.Session):
5131 mf=SessionMFRegistry().get(self._target)
5132 deleteURL = urlHandlers.UHSessionRemoveMaterials.getURL(self._target)
5133 elif isinstance(self._target.getOwner(),conference.Contribution):
5134 mf=ContribMFRegistry().get(self._target)
5135 contrib=self._target.getOwner()
5136 deleteURL = urlHandlers.UHContributionRemoveMaterials.getURL(self._target)
5137 elif isinstance(self._target.getOwner(),conference.SubContribution):
5138 mf=ContribMFRegistry().get(self._target)
5139 deleteURL = urlHandlers.UHSubContributionRemoveMaterials.getURL(self._target)
5140 elif isinstance(self._target.getOwner(),conference.Category):
5141 deleteURL = urlHandlers.UHCategoryRemoveMaterial.getURL(self._target)
5142 if deleteURL:
5143 deleteURL.addParam("returnURL",self._returnURL)
5144 vars["materialName"] = self._target.getTitle()
5145 vars["materialActions"] = ""
5146 vars["materialActions"] += """<a href="%s" onClick="return confirm('Are you sure you want to delete all files of this type?');"><img src="%s" alt="Delete" style="margin-left: 5px; vertical-align:middle;"></a>""" % (str(deleteURL),Config.getInstance().getSystemIconURL("smallDelete"))
5147 if vars["materialModifHandler"]:
5148 vars["materialActions"] += """<a href="%s"><img src="%s" alt="Edit" style="margin-left: 5px; vertical-align:middle;"></a>""" % (urlHandlers.UHMaterialModification.getURL(self._target),Config.getInstance().getSystemIconURL("file_edit"))
5149 if vars["materialProtectHandler"]:
5150 vars["materialActions"] += """<a href="%s"><img src="%s" alt="Protect" style="margin-left: 5px; vertical-align:middle;" /></a>""" % (vars["materialProtectHandler"].getURL(self._target),Config.getInstance().getSystemIconURL("file_protect"))
5151 if self._target.isProtected():
5152 vars["materialActions"] += """<img src="%s" alt="Protected" style="margin-left: 5px; vertical-align: middle; border: 0;" />""" % Config.getInstance().getSystemIconURL("protected")
5153 vars["fileList"]=""
5154 for resource in self._target.getResourceList():
5155 vars["fileList"] += WMaterialListFile(resource).getHTML(vars)
5156 if mf is None:
5157 vars["materialIcon"]=quoteattr(str(Config.getInstance().getSystemIconURL("material")))
5158 else:
5159 vars["materialIcon"]=quoteattr(str(mf.getIconURL()))
5160 return vars
5163 class WShowExistingMaterial(WTemplated):
5165 def __init__(self,target, mode='display', showTitle=True):
5167 mode should be 'display' or 'management'
5169 self._target=target
5170 self._mode = mode
5171 self._showTitle = showTitle
5174 def getVars(self):
5175 vars=WTemplated.getVars(self)
5177 # yes, this may look a bit redundant, but materialRegistry isn't
5178 # bound to a particular target
5179 materialRegistry = self._target.getMaterialRegistry()
5180 vars["materialList"] = materialRegistry.getMaterialList(self._target)
5183 if self._showTitle:
5184 vars["existingMaterialsTitle"] = """ <div class="groupTitle" id="title">%s</div>""" % _("Existing material")
5185 else:
5186 vars["existingMaterialsTitle"] = " "
5187 vars["materialModifHandler"] = vars.get("materialModifHandler", None)
5188 vars["materialProtectHandler"] = vars.get("materialProtectHandler", None)
5189 vars["resourcesFileModifHandler"] = vars.get("resourcesFileModifHandler", None)
5190 vars["resourcesFileProtectHandler"] = vars.get("resourcesFileProtectHandler", None)
5191 vars["resourcesLinkModifHandler"] = vars.get("resourcesLinkModifHandler", None)
5192 vars["resourcesLinkProtectHandler"] = vars.get("resourcesLinkProtectHandler", None)
5193 vars['mode'] = self._mode
5195 return vars
5197 class WShowExistingReviewingMaterial(WTemplated):
5199 def __init__(self,target,showTitle=True, showSendButton=False):
5200 self._target=target
5201 self._showTitle=showTitle
5202 self._showSendButton = showSendButton
5205 def getVars(self):
5206 vars=WTemplated.getVars(self)
5208 if self._showTitle:
5209 vars["existingMaterialsTitle"] = """ <div class="groupTitle" id="title">%s</div>""" % _("Existing Reviewing material")
5210 else:
5211 vars["existingMaterialsTitle"] = " "
5212 vars["materialModifHandler"] = vars.get("materialModifHandler", None)
5213 vars["materialProtectHandler"] = vars.get("materialProtectHandler", None)
5214 vars["resourcesFileModifHandler"] = vars.get("resourcesFileModifHandler", None)
5215 vars["resourcesFileProtectHandler"] = vars.get("resourcesFileProtectHandler", None)
5216 vars["resourcesLinkModifHandler"] = vars.get("resourcesLinkModifHandler", None)
5217 vars["resourcesLinkProtectHandler"] = vars.get("resourcesLinkProtectHandler", None)
5218 # This var shows you if you are requesting the template from the contribution display (True)
5219 # or from the paper reviewing tab in the contribution (False), as consequence you will have (or not)
5220 # the "send" button
5221 vars["showSendButton"] = self._showSendButton
5223 return vars
5225 class WAddNewMaterial(WTemplated):
5227 def __init__(self,target,availMF):
5228 self._target=target
5229 self._availMF=availMF
5231 def _getErrorHTML(self,errorList):
5232 if len(errorList)==0:
5233 return ""
5234 return """
5235 <tr>
5236 <td>&nbsp;</td>
5237 </tr>
5238 <tr>
5239 <td colspan="2" align="center">
5240 <table bgcolor="red">
5241 <tr>
5242 <td bgcolor="white">
5243 <font color="red">%s</font>
5244 </td>
5245 </tr>
5246 </table>
5247 </td>
5248 </tr>
5249 <tr>
5250 <td>&nbsp;</td>
5251 </tr>
5252 """%("<br>".join(errorList))
5254 def _getTargetName(self):
5255 if isinstance(self._target, conference.Contribution):
5256 return "Contribution"
5257 elif isinstance(self._target, conference.SubContribution):
5258 return "Subcontribution"
5259 elif isinstance(self._target, conference.Conference):
5260 return "Event"
5261 return ""
5263 def getVars(self):
5264 vars=WTemplated.getVars(self)
5265 nbFiles=int(vars.get("nbFiles",1))
5266 nbLinks=int(vars.get("nbLinks",1))
5267 vars["targetName"]=self._getTargetName()
5268 vars["targetId"]=self.htmlText(self._target.getId())
5269 vars["targetTitle"]=self.htmlText(self._target.getTitle())
5271 vars["selectNumberOfFiles"] = ""
5272 for i in range(1,10):
5273 if i == nbFiles:
5274 vars["selectNumberOfFiles"] += "<option selected>%s" % i
5275 else:
5276 vars["selectNumberOfFiles"] += "<option>%s" % i
5277 vars["fileSubmitForms"] = ""
5278 for i in range(1,nbFiles+1):
5279 vars["fileSubmitForms"] += WSubmitMaterialFile(i,self._availMF).getHTML(vars)
5280 vars["selectNumberOfLinks"] = ""
5281 for i in range(1,10):
5282 if i == nbLinks:
5283 vars["selectNumberOfLinks"] += "<option selected>%s" % i
5284 else:
5285 vars["selectNumberOfLinks"] += "<option>%s" % i
5286 vars["linkSubmitForms"] = ""
5287 for i in range(1,nbLinks+1):
5288 vars["linkSubmitForms"] += WSubmitMaterialLink(i,self._availMF).getHTML(vars)
5289 vars["conversion"]=""
5290 if Configuration.Config.getInstance().hasFileConverter():
5291 vars["conversion"]="""
5292 <tr>
5293 <td class="titleCellTD"><span class="titleCellFormat">To PDF</span></td>
5294 <td><input type="checkbox" name="topdf" checked="checked">Automatic conversion to pdf (when applicable)? (PPT, DOC)</td>
5295 </tr>
5297 vars["errors"]=self._getErrorHTML(vars.get("errorList",[]))
5298 if vars["cancel"]:
5299 vars["CancelButton"] = """<input type="submit" name="CANCEL" value="cancel" class="btn">"""
5300 else:
5301 vars["CancelButton"] = ""
5302 return vars
5304 class WSubmitMaterial(WTemplated):
5306 def __init__(self,target,availMF):
5307 self._target=target
5308 self._availMF=availMF
5310 def _getErrorHTML(self,errorList):
5311 if len(errorList)==0:
5312 return ""
5313 return """
5314 <tr>
5315 <td>&nbsp;</td>
5316 </tr>
5317 <tr>
5318 <td colspan="2" align="center">
5319 <table bgcolor="red">
5320 <tr>
5321 <td bgcolor="white">
5322 <font color="red">%s</font>
5323 </td>
5324 </tr>
5325 </table>
5326 </td>
5327 </tr>
5328 <tr>
5329 <td>&nbsp;</td>
5330 </tr>
5331 """%("<br>".join(errorList))
5333 def _getTargetName(self):
5334 if isinstance(self._target, conference.Contribution):
5335 return "Contribution"
5336 elif isinstance(self._target, conference.SubContribution):
5337 return "Subcontribution"
5338 elif isinstance(self._target, conference.Conference):
5339 return "Event"
5340 return ""
5342 def getVars(self):
5343 vars=WTemplated.getVars(self)
5344 nbFiles=int(vars.get("nbFiles",1))
5345 nbLinks=int(vars.get("nbLinks",1))
5346 vars["targetName"]=self._getTargetName()
5347 vars["targetId"]=self.htmlText(self._target.getId())
5348 vars["targetTitle"]=self.htmlText(self._target.getTitle())
5349 vars["materialModifHandler"] = vars.get("materialModifHandler", None)
5350 vars["materialProtectHandler"] = vars.get("materialProtectHandler", None)
5351 vars["resourcesFileModifHandler"] = vars.get("resourcesFileModifHandler", None)
5352 vars["resourcesFileProtectHandler"] = vars.get("resourcesFileProtectHandler", None)
5353 vars["resourcesLinkModifHandler"] = vars.get("resourcesLinkModifHandler", None)
5354 vars["resourcesLinkProtectHandler"] = vars.get("resourcesLinkProtectHandler", None)
5355 vars["iconProtected"] = Config.getInstance().getSystemIconURL("protected")
5356 vars["iconDelete"] = Config.getInstance().getSystemIconURL("smallDelete")
5357 vars["iconKey"] = ""
5358 if vars["materialModifHandler"] or vars["resourcesFileModifHandler"] or vars["resourcesLinkModifHandler"]:
5359 vars["iconKey"] += i18nformat("""&nbsp;<img src=%s style="vertical-align:middle; margin: 1px;"> _("edit")""") % Config.getInstance().getSystemIconURL("file_edit")
5360 if vars["materialProtectHandler"] or vars["resourcesFileProtectHandler"] or vars["resourcesLinkProtectHandler"]:
5361 vars["iconKey"] += i18nformat("""&nbsp;<img src=%s style="vertical-align:middle; margin: 1px;"> _("protect")""") % Config.getInstance().getSystemIconURL("file_protect")
5362 vars["materialList"] = "<table>"
5363 materialList = self._target.getAllMaterialList()
5364 for material in materialList:
5365 vars["materialList"] += WMaterialListItem(material,vars["postURL"]).getHTML(vars)
5366 vars["materialList"] += "</table>"
5367 vars["selectNumberOfFiles"] = ""
5368 for i in range(1,10):
5369 if i == nbFiles:
5370 vars["selectNumberOfFiles"] += "<option selected>%s" % i
5371 else:
5372 vars["selectNumberOfFiles"] += "<option>%s" % i
5373 vars["fileSubmitForms"] = ""
5374 for i in range(1,nbFiles+1):
5375 vars["fileSubmitForms"] += WSubmitMaterialFile(i,self._availMF).getHTML(vars)
5376 vars["selectNumberOfLinks"] = ""
5377 for i in range(1,10):
5378 if i == nbLinks:
5379 vars["selectNumberOfLinks"] += "<option selected>%s" % i
5380 else:
5381 vars["selectNumberOfLinks"] += "<option>%s" % i
5382 vars["linkSubmitForms"] = ""
5383 for i in range(1,nbLinks+1):
5384 vars["linkSubmitForms"] += WSubmitMaterialLink(i,self._availMF).getHTML(vars)
5385 vars["conversion"]=""
5386 if Configuration.Config.getInstance().hasFileConverter():
5387 vars["conversion"]= i18nformat("""
5388 <tr>
5389 <td nowrap class="titleCellTD"><span class="titleCellFormat">To PDF</span></td>
5390 <td align="left"><input type="checkbox" name="topdf" checked="checked"> _("Automatic conversion to pdf (when applicable)? (PPT, DOC)")</td>
5391 </tr>
5392 """)
5393 vars["errors"]=self._getErrorHTML(vars.get("errorList",[]))
5394 if vars["cancel"]:
5395 vars["CancelButton"] = i18nformat("""<input type="submit" name="CANCEL" value="_("cancel")" class="btn">""")
5396 else:
5397 vars["CancelButton"] = ""
5398 return vars
5401 class WSchRelocateTime(WTemplated):
5403 def getVars(self):
5404 vars = WTemplated.getVars(self)
5405 return vars
5408 class WSchRelocate(WTemplated):
5410 def __init__(self, entry):
5411 self._entry=entry
5412 if isinstance(self._entry, conference.Contribution):
5413 self._conf = self._entry.getConference()
5414 else:
5415 # entry is a break
5416 self._conf = self._entry.getSchedule().getOwner().getConference()
5418 def _getTargetPlaceHTML(self):
5419 html=[]
5420 html.append( i18nformat("""
5421 <tr><td><input type="radio" name="targetId" value="conf"></td><td colspan="3" width="100%%"><b> _("Top timetable (within no session)")</b></td></tr>
5422 <tr><td colspan="4"><hr></td></tr>
5423 """))
5424 sessionList=self._conf.getSessionList()
5425 sessionList.sort(conference.Session._cmpTitle)
5426 for session in sessionList:
5427 if len(session.getSlotList())==1:
5428 html.append("""
5429 <tr><td><input type="radio" name="targetId" value="%s:%s"></td><td colspan="3" style="background-color:%s;color:%s" width="100%%">&nbsp;%s&nbsp;<b>%s</b></td></tr>
5430 """%(session.getId(), session.getSlotList()[0].getId(), session.getColor(), session.getTextColor(), session.getStartDate().strftime("%d-%m-%Y"),session.getTitle()) )
5431 else:
5432 html.append("""
5433 <tr><td></td><td colspan="3" style="background-color:%s;" width="100%%">
5434 <table>
5435 <tr><td colspan="2" width="100%%" style="color:%s"><b>%s:</b></td></tr>
5436 """%(session.getColor(), session.getTextColor(), session.getTitle()) )
5437 for slotEntry in session.getSchedule().getEntries():
5438 slot=slotEntry.getOwner()
5439 html.append("""
5440 <tr><td><input type="radio" name="targetId" value="%s:%s"></td><td width="100%%" style="color:%s">%s <small>(%s %s-%s)</small></td></tr>
5441 """%(session.getId(), slot.getId(), session.getTextColor(), slot.getTitle() or "[slot %s]"%slot.getId(), slot.getAdjustedStartDate().strftime("%d-%m-%Y"),\
5442 slot.getAdjustedStartDate().strftime("%H:%M"), slot.getAdjustedEndDate().strftime("%H:%M")) )
5443 html.append("</table></td></tr>")
5444 return "".join(html)
5447 def getVars(self):
5448 vars = WTemplated.getVars(self)
5449 if isinstance(self._entry, conference.Contribution):
5450 vars["entryType"]="Contribution"
5451 else:
5452 vars["entryType"]=""
5453 vars["entryTitle"]=self._entry.getTitle()
5454 vars["targetPlace"]=self._getTargetPlaceHTML()
5455 vars["autoUpdate"]=""
5456 return vars
5458 class WReportNumbersTable(WTemplated):
5460 def __init__(self, target, type="event"):
5461 self._target=target
5462 self._type=type
5464 def _getCurrentItems(self):
5465 html=[]
5466 rns = self._target.getReportNumberHolder().listReportNumbers()
5467 id = 0
5469 reportCodes = []
5471 for rn in rns:
5472 key = rn[0]
5473 number = rn[1]
5474 name=key
5475 if key in Configuration.Config.getInstance().getReportNumberSystems().keys():
5476 name=Configuration.Config.getInstance().getReportNumberSystems()[key]["name"]
5477 reportCodes.append((id, number, name))
5478 id+=1
5479 return reportCodes
5481 def _getSystems(self):
5482 html=[]
5483 rnsystems=Configuration.Config.getInstance().getReportNumberSystems()
5484 keys=rnsystems.keys()
5485 keys.sort()
5486 for system in keys:
5487 html.append("""
5488 <option value="%s">%s</option>
5489 """%(system, rnsystems[system]["name"] ) )
5490 return "".join(html)
5492 def getVars(self):
5493 vars = WTemplated.getVars(self)
5494 if self._type == "event":
5495 vars["deleteURL"]=quoteattr(str(urlHandlers.UHConfModifReportNumberRemove.getURL(self._target)))
5496 vars["addURL"]=quoteattr(str(urlHandlers.UHConfModifReportNumberEdit.getURL(self._target)))
5497 elif self._type == "contribution":
5498 vars["deleteURL"]=quoteattr(str(urlHandlers.UHContributionReportNumberRemove.getURL(self._target)))
5499 vars["addURL"]=quoteattr(str(urlHandlers.UHContributionReportNumberEdit.getURL(self._target)))
5500 else:
5501 vars["deleteURL"]=quoteattr(str(urlHandlers.UHSubContributionReportNumberRemove.getURL(self._target)))
5502 vars["addURL"]=quoteattr(str(urlHandlers.UHSubContributionReportNumberEdit.getURL(self._target)))
5503 vars["items"]=self._getCurrentItems()
5504 vars["repTypesSelectItems"]=self._getSystems()
5505 return vars
5507 class WModifReportNumberEdit(WTemplated):
5509 def __init__(self, target, rns, type="event"):
5510 self._target=target
5511 self._rnSystem=rns
5512 self._type=type
5514 def getVars(self):
5515 vars=WTemplated.getVars(self)
5516 vars["reportNumber"]=""
5517 vars["reportNumberSystem"]=self._rnSystem
5518 name=self._rnSystem
5519 if self._rnSystem in Config.getInstance().getReportNumberSystems().keys():
5520 name=Config.getInstance().getReportNumberSystems()[self._rnSystem]["name"]
5521 vars["system"]=name
5522 if self._type == "event":
5523 vars["postURL"]=quoteattr(str(urlHandlers.UHConfModifReportNumberPerformEdit.getURL(self._target)))
5524 elif self._type == "contribution":
5525 vars["postURL"]=quoteattr(str(urlHandlers.UHContributionReportNumberPerformEdit.getURL(self._target)))
5526 else:
5527 vars["postURL"]=quoteattr(str(urlHandlers.UHSubContributionReportNumberPerformEdit.getURL(self._target)))
5528 return vars
5531 # ============================================================================
5532 # === ROOM BOOKING RELATED ===================================================
5533 # ============================================================================
5534 # 1. Freestanding
5535 # 2. In the context of an event
5537 from MaKaC.rb_reservation import ReservationBase, Collision, RepeatabilityEnum
5538 from MaKaC.rb_factory import Factory
5539 from MaKaC.plugins.RoomBooking.default.room import Room
5540 from MaKaC.rb_tools import iterdays
5541 from calendar import day_name
5542 from MaKaC.rb_location import Location, CrossLocationFactory
5543 from indico.util.fossilize import Fossilizable, fossilizes
5544 from MaKaC.fossils.roomBooking import IRoomBarFossil, IBarFossil
5546 class Bar( Fossilizable ):
5548 Keeps data necessary for graphical bar on calendar.
5550 fossilizes(IBarFossil)
5551 PREBOOKED, PRECONCURRENT, UNAVAILABLE, CANDIDATE, PRECONFLICT, CONFLICT = xrange( 0, 6 )
5552 # I know this names are not wisely choosed; it's due to unexpected additions
5553 # without refactoring
5554 # UNAVAILABLE : represents confirmed reservation (bright-red)
5555 # CANDIDATE: represents new reservation (green)
5556 # CONFLICT: overlap between candidate and confirmed resv. (dark red)
5557 # PREBOOKED: represents pre-reservation (yellow)
5558 # PRECONFLICT: represents conflict with pre-reservation (orange)
5559 # PRECONCURRENT: conflicting pre-reservations
5561 def __init__( self, c, barType ):
5562 self.startDT = c.startDT
5563 self.endDT = c.endDT
5564 self.forReservation = c.withReservation
5565 self.type = barType
5567 def __cmp__( self, obj ):
5568 return cmp( self.type, obj.type )
5570 class RoomBars( Fossilizable ):
5572 fossilizes(IRoomBarFossil)
5574 room = None
5575 bars = []
5577 def __init__( self, room, bars ):
5578 self.room = room
5579 self.bars = bars
5580 def __cmp__( self, obj ):
5581 return cmp( self.room, obj.room )
5583 # ============================================================================
5584 # == FREESTANDING ==== (Room Booking Related) ================================
5585 # ============================================================================
5587 class WRoomBookingWelcome( WTemplated ):
5589 def __init__(self):
5590 self.__adminList = AdminList.getInstance()
5592 def getVars( self ):
5593 vars = WTemplated.getVars( self )
5594 return vars
5596 class WRoomBookingRoomSelectList( WTemplated ):
5598 def __init__( self, rh ):
5599 self._rh = rh
5601 def getVars( self ):
5602 vars = WTemplated.getVars( self )
5604 vars['roomList'] = self._rh._roomList
5605 vars['locationRoom'] = self._rh._locationRoom
5607 return vars
5609 class WRoomBookingRoomSelectList4SubEvents( WTemplated ):
5611 def __init__( self, rh ):
5612 self._rh = rh
5614 def getVars( self ):
5615 vars = WTemplated.getVars( self )
5617 vars['roomList'] = self._rh._roomList
5618 vars['locationRoom'] = self._rh._locationRoom
5620 return vars
5622 # ============================================================================
5623 # == EVENT CONTEXT ==== (Room Booking Related) ===============================
5624 # ============================================================================
5627 # 0. Choosing an "event" (conference / session / contribution)...
5629 class WRoomBookingChooseEvent( WTemplated ):
5631 def __init__( self, rh ):
5632 self._rh = rh
5634 def getVars( self ):
5635 vars = WTemplated.getVars( self )
5637 vars["conference"] = self._rh._conf
5638 vars["contributions"] = list( [ c for c in self._rh._conf.getContributionList() if c.getStartDate() ] )
5640 return vars
5642 # 1. Searching
5644 class WRoomBookingSearch4Rooms( WTemplated ):
5646 def __init__( self, rh, standalone = False ):
5647 self._standalone = standalone
5648 self._rh = rh
5650 def getVars( self ):
5651 vars = WTemplated.getVars( self )
5653 websession = self._rh._websession
5655 vars["standalone"] = self._standalone
5657 vars["Location"] = Location
5658 vars["rooms"] = self._rh._rooms
5659 vars["possibleEquipment"] = self._rh._equipment
5660 vars["forNewBooking"] = self._rh._forNewBooking
5661 vars["eventRoomName"] = self._rh._eventRoomName
5662 vars["isResponsibleForRooms"] = Room.isAvatarResponsibleForRooms(self._rh.getAW().getUser())
5664 vars["preview"] = False
5666 vars["startDT"] = websession.getVar( "defaultStartDT" )
5667 vars["endDT"] = websession.getVar( "defaultEndDT" )
5668 vars["startT"] = websession.getVar( "defaultStartDT" ).time().strftime( "%H:%M" )
5669 vars["endT"] = websession.getVar( "defaultEndDT" ).time().strftime( "%H:%M" )
5670 vars["repeatability"] = websession.getVar( "defaultRepeatability" )
5672 if self._standalone:
5673 # URLs for standalone room booking
5674 vars["roomBookingRoomListURL"] = urlHandlers.UHRoomBookingRoomList.getURL( None )
5675 vars["detailsUH"] = urlHandlers.UHRoomBookingRoomDetails
5676 vars["bookingFormUH"] = urlHandlers.UHRoomBookingBookingForm
5677 else:
5678 # URLs for room booking in the event context
5679 vars["roomBookingRoomListURL"] = urlHandlers.UHConfModifRoomBookingRoomList.getURL( self._rh._conf )
5680 vars["detailsUH"] = urlHandlers.UHConfModifRoomBookingRoomDetails
5681 vars["bookingFormUH"] = urlHandlers.UHConfModifRoomBookingBookingForm
5683 return vars
5685 class WRoomBookingSearch4Bookings( WTemplated ):
5687 def __init__( self, rh ):
5688 self._rh = rh
5690 def getVars( self ):
5691 vars = WTemplated.getVars( self )
5693 vars["today"] = datetime.now()
5694 vars["weekLater"] = datetime.now() + timedelta( 7 )
5695 vars["Location"] = Location
5696 vars["rooms"] = self._rh._rooms
5697 vars["repeatability"] = None
5698 vars["isResponsibleForRooms"] = Room.isAvatarResponsibleForRooms(self._rh.getAW().getUser())
5699 vars["roomBookingBookingListURL"] = urlHandlers.UHRoomBookingBookingList.getURL( None )
5701 return vars
5703 class WRoomBookingMapOfRooms(WTemplated):
5705 def __init__(self, **params):
5706 if params is not None:
5707 self._params = params
5708 else:
5709 self._params = {}
5710 WTemplated.__init__(self)
5712 def getVars(self):
5713 vars = WTemplated.getVars(self)
5714 vars["mapOfRoomsWidgetURL"] = urlHandlers.UHRoomBookingMapOfRoomsWidget.getURL(None, **self._params)
5716 return vars
5718 class WRoomBookingMapOfRoomsWidget(WTemplated):
5720 def __init__(self, aspects, buildings, defaultLocation, forVideoConference, roomID):
5721 self._aspects = aspects
5722 self._buildings = buildings
5723 self._defaultLocation = defaultLocation
5724 self._forVideoConference = forVideoConference
5725 self._roomID = roomID
5727 def getVars(self):
5728 vars = WTemplated.getVars(self)
5729 websession = self._rh._websession
5731 vars["aspects"] = self._aspects
5732 vars["buildings"] = self._buildings
5733 vars["defaultLocation"] = self._defaultLocation
5734 vars["forVideoConference"] = self._forVideoConference
5735 vars["roomID"] = self._roomID
5737 vars["roomBookingRoomListURL"] = urlHandlers.UHRoomBookingRoomList.getURL( None )
5738 vars["startDT"] = websession.getVar( "defaultStartDT" )
5739 vars["endDT"] = websession.getVar( "defaultEndDT" )
5740 vars["startT"] = websession.getVar( "defaultStartDT" ).time().strftime( "%H:%M" )
5741 vars["endT"] = websession.getVar( "defaultEndDT" ).time().strftime( "%H:%M" )
5742 vars["repeatability"] = websession.getVar( "defaultRepeatability" )
5744 return vars
5746 # 2. List of...
5748 class WRoomBookingRoomList( WTemplated ):
5750 def __init__( self, rh, standalone = False ):
5751 self._rh = rh
5752 self._standalone = standalone
5753 self._title = None
5754 try: self._title = self._rh._title;
5755 except: pass
5757 def getVars( self ):
5758 vars=WTemplated.getVars( self )
5760 vars["rooms"] = self._rh._rooms
5761 vars["mapAvailable"] = self._rh._mapAvailable
5762 #vars["roomPhotoUH"] = urlHandlers.UHSendRoomPhoto
5763 vars["standalone"] = self._standalone
5764 vars["title"] = self._title
5766 if self._standalone:
5767 vars["detailsUH"] = urlHandlers.UHRoomBookingRoomDetails
5768 vars["bookingFormUH"] = urlHandlers.UHRoomBookingBookingForm
5769 else:
5770 vars["conference"] = self._rh._conf
5771 vars["detailsUH"] = urlHandlers.UHConfModifRoomBookingRoomDetails
5772 vars["bookingFormUH"] = urlHandlers.UHConfModifRoomBookingBookingForm
5774 return vars
5776 class WRoomBookingList( WTemplated ):
5778 def __init__( self, rh, standalone = False ):
5779 self._standalone = standalone
5780 self._rh = rh
5781 if not standalone:
5782 self._conf = rh._conf
5784 def getVars( self ):
5785 vars=WTemplated.getVars( self )
5787 vars["reservations"] = self._rh._resvs
5788 vars["standalone"] = self._standalone
5789 dm = datetime.now() - timedelta( 1 )
5790 vars["yesterday"] = dm #datetime( dm.year, dm.month, dm.day, 0, 0, 1 )
5792 if self._standalone:
5793 vars["bookingDetailsUH"] = urlHandlers.UHRoomBookingBookingDetails
5794 else:
5795 vars["conference"] = self._conf
5796 vars["bookingDetailsUH"] = urlHandlers.UHConfModifRoomBookingDetails
5798 return vars
5800 class WRoomBookingBookingList( WTemplated ): # Standalone version
5802 def __init__( self, rh ):
5803 self._rh = rh
5804 self._title = None
5805 try: self._title = self._rh._title;
5806 except: pass
5808 def _isOn(self, boolVal):
5809 if boolVal:
5810 return "on"
5811 else:
5812 return ""
5814 def getVars( self ):
5815 vars = WTemplated.getVars( self )
5816 rh = self._rh
5817 vars["reservations"] = rh._resvs
5819 #vars["smallPhotoUH"] = urlHandlers.UHSendRoomPhoto
5820 vars["bookingDetailsUH"] = urlHandlers.UHRoomBookingBookingDetails
5821 vars["withPhoto"] = False
5822 vars["title"] = self._title
5823 vars["search"] = rh._search
5824 vars["showRejectAllButton"] = rh._showRejectAllButton
5826 vars["prebookingsRejected"] = rh._prebookingsRejected
5827 vars["subtitle"] = rh._subtitle
5828 vars["description"] = rh._description
5829 yesterday = datetime.now() - timedelta( 1 )
5830 vars["yesterday"] = yesterday #datetime( dm.year, dm.month, dm.day, 0, 0, 1 )
5832 ed = None
5833 sd = rh._resvEx.startDT.date()
5834 if rh._resvEx.endDT:
5835 ed = rh._resvEx.endDT.date()
5837 # autoCriteria - dates are calculated based on the next reservation
5838 if rh._autoCriteria:
5839 tmp = ReservationBase.findSoonest( rh._resvs, afterDT = yesterday )
5840 if tmp:
5841 tmp = tmp.getNextRepeating( afterDT = yesterday )
5842 if tmp and tmp.startDT.date() > sd:
5843 sd = tmp.startDT
5844 if not ed:
5845 # one month of time span
5846 ed = sd + timedelta( 30 )
5848 # set the calendar dates as calculated
5849 calendarStartDT = datetime( sd.year, sd.month, sd.day, 0, 0, 1 )
5850 calendarEndDT = datetime( ed.year, ed.month, ed.day, 23, 59 )
5852 from MaKaC.rb_tools import formatDate
5854 if calendarStartDT.date() == calendarEndDT.date():
5855 vars["periodName"] = "day"
5856 else:
5857 vars["periodName"] = "period"
5858 vars["startD"] = formatDate(calendarStartDT)
5859 vars["endD"] = formatDate(calendarEndDT)
5861 # Data for previous/next URLs (it's about periods, not paging)
5862 newParams4Previous = rh._reqParams.copy()
5863 newParams4Next = rh._reqParams.copy()
5864 if rh._reqParams.has_key( 'autoCriteria' ):
5865 del newParams4Previous['autoCriteria']
5866 del newParams4Next['autoCriteria']
5867 if rh._reqParams.has_key( 'day' ):
5868 del newParams4Previous['day']
5869 del newParams4Next['day']
5872 startD = calendarStartDT.date()
5873 endD = calendarEndDT.date()
5875 if endD != startD:
5876 period = endD - startD
5878 prevStartD = startD - period - timedelta(1)
5879 prevEndD = startD - timedelta(1)
5881 nextStartD = endD + timedelta(1)
5882 nextEndD = endD + period + timedelta(1)
5883 else:
5884 prevStartD = prevEndD = startD - timedelta(1)
5885 nextStartD = nextEndD = endD + timedelta(1)
5887 newParams4Previous['sDay'] = prevStartD.day
5888 newParams4Previous['sMonth'] = prevStartD.month
5889 newParams4Previous['sYear'] = prevStartD.year
5890 newParams4Previous['eDay'] = prevEndD.day
5891 newParams4Previous['eMonth'] = prevEndD.month
5892 newParams4Previous['eYear'] = prevEndD.year
5894 newParams4Next['sDay'] = nextStartD.day
5895 newParams4Next['sMonth'] = nextStartD.month
5896 newParams4Next['sYear'] = nextStartD.year
5897 newParams4Next['eDay'] = nextEndD.day
5898 newParams4Next['eMonth'] = nextEndD.month
5899 newParams4Next['eYear'] = nextEndD.year
5901 vars["attributes"] = { }
5902 vars["withPrevNext"] = True
5903 vars["prevURL"] = urlHandlers.UHRoomBookingBookingList.getURL( newParams = newParams4Previous )
5904 vars["nextURL"] = urlHandlers.UHRoomBookingBookingList.getURL( newParams = newParams4Next )
5906 vars['overload'] = self._rh._overload
5908 # empty days are shown for "User bookings" and "User pre-bookings"
5909 # and for the calendar as well
5910 # but not for the booking search
5911 #showEmptyDays = ( self._rh._ofMyRooms or \
5912 # (not self._rh._ofMyRooms and not self._rh._onlyMy) ) and \
5913 # not self._rh._search
5914 #showEmptyRooms = showEmptyDays
5915 # Always show empty rooms/days
5916 showEmptyDays = showEmptyRooms = not self._rh._search
5919 # Calendar related stuff ==========
5921 bars = []
5922 collisionsOfResvs = []
5924 # there's at least one reservation
5925 if len( rh._resvs ) > 0:
5928 # Prepare the list of Collisions
5929 # (collision is just a helper object, it's not the best notion here)
5931 for r in rh._resvs:
5932 for p in r.splitToPeriods(endDT=calendarEndDT, startDT=calendarStartDT):
5933 if p.startDT >= calendarStartDT and p.endDT <= calendarEndDT:
5934 collisionsOfResvs.append( Collision( ( p.startDT, p.endDT ), r ) )
5936 # Translate collisions to Bars
5937 for c in collisionsOfResvs:
5938 if c.withReservation.isConfirmed:
5939 bars.append( Bar( c, Bar.UNAVAILABLE ) )
5940 else:
5941 bars.append( Bar( c, Bar.PREBOOKED ) )
5943 bars = barsList2Dictionary( bars )
5944 bars = addOverlappingPrebookings( bars )
5945 bars = sortBarsByImportance( bars, calendarStartDT, calendarEndDT )
5947 rooms = set(r.room for r in rh._resvs)
5949 #CrossLocationQueries.getRooms( location = self.location )
5950 if not self._rh._onlyMy:
5951 rooms = self._rh._rooms
5953 bars = introduceRooms( rooms, bars, calendarStartDT, calendarEndDT, showEmptyDays = showEmptyDays, showEmptyRooms = showEmptyRooms, user = rh._aw.getUser() )
5955 vars["Bar"] = Bar
5957 self.__sortUsingCriterion(rh._order, collisionsOfResvs)
5959 # we want to display every room, with or without reservation
5960 else:
5961 # initialize collision bars
5962 bars = {}
5963 bars = sortBarsByImportance( bars, calendarStartDT, calendarEndDT )
5965 # insert rooms
5966 if not self._rh._onlyMy:
5967 rooms = self._rh._rooms
5968 else:
5969 rooms = []
5971 bars = introduceRooms( rooms, bars, calendarStartDT, calendarEndDT, showEmptyDays = showEmptyDays, showEmptyRooms = showEmptyRooms, user = rh._aw.getUser() )
5973 fossilizedBars = {}
5974 for key in bars:
5975 fossilizedBars[str(key)] = [fossilize(bar, IRoomBarFossil) for bar in bars[key]]
5976 vars["barsFossil"] = fossilizedBars
5977 vars["dayAttrs"] = fossilize({})
5978 vars["bars"] = bars
5979 vars["showEmptyRooms"] = showEmptyRooms
5980 vars["manyRooms"] = not self._rh._rooms or len(self._rh._rooms) > 1
5981 vars["calendarParams"] = {}
5982 if self._title and rh._ofMyRooms:
5983 vars["calendarParams"]["ofMyRooms"] ="on"
5984 elif rh._onlyMy:
5985 vars["calendarParams"]["onlyMy"] = "on"
5986 elif rh._allRooms:
5987 vars["calendarParams"]["roomGUID"] = "allRooms"
5988 else:
5989 for room in rh._roomGUIDs:
5990 vars["calendarParams"]["roomGUID"]= room
5991 if rh._onlyPrebookings:
5992 vars["calendarParams"]["onlyPrebookings"] = "on"
5993 if rh._onlyBookings:
5994 vars["calendarParams"]["onlyBookings"] ="on"
5996 vars["calendarFormUrl"] = urlHandlers.UHRoomBookingBookingList.getURL()
5998 return vars
6001 def __sortUsingCriterion(self, order, uresvs):
6003 if order == "" or order =="room":
6004 # standard sorting order (by room, and then date)
6005 uresvs.sort(lambda r1,r2: cmp(r1.withReservation.room.name,r2.withReservation.room.name))
6006 else:
6007 if order == 'date':
6008 uresvs.sort(lambda r1, r2: cmp(r1.startDT, r2.startDT))
6009 elif order == 'reason':
6010 uresvs.sort(lambda r1, r2: cmp(r1.withReservation.reason.lower(), r2.withReservation.reason.lower()))
6011 elif order == 'for':
6012 uresvs.sort(lambda r1, r2: cmp(r1.withReservation.bookedForName.lower(), r2.withReservation.bookedForName.lower()))
6013 elif order == 'hours':
6014 uresvs.sort(lambda r1, r2: cmp(r1.startDT.time(), r2.startDT.time()))
6017 # 3. Details of...
6019 def barsList2Dictionary( bars ):
6021 Converts:
6022 list of bars => dictionary of bars, key = datetime, value = list of bars
6024 h = {}
6025 for bar in bars:
6026 d = bar.startDT.date()
6027 if h.has_key( d ):
6028 h[d].append( bar )
6029 else:
6030 h[d] = [bar]
6031 return h
6033 def addOverlappingPrebookings( bars ):
6035 Adds bars representing overlapping pre-bookings.
6036 Returns new bars dictionary.
6039 # For each day
6040 for dt in bars.keys():
6041 dayBars = bars[dt]
6043 # For each (prebooked) bar i
6044 for i in xrange( 0, len( dayBars ) ):
6045 bar = dayBars[i]
6046 if bar.type == Bar.PREBOOKED:
6048 # For each (prebooked) bar j
6049 for j in xrange( i+1, len( dayBars ) ):
6050 collCand = dayBars[j]
6051 if collCand.type == Bar.PREBOOKED:
6053 # If there is an overlap, add PRECONCURRENT bar
6054 over = overlap( bar.startDT, bar.endDT, collCand.startDT, collCand.endDT )
6055 if over and bar.forReservation.room == collCand.forReservation.room:
6056 collision = Collision( over, collCand.forReservation )
6057 dayBars.append( Bar( collision, Bar.PRECONCURRENT ) )
6059 bars[dt] = dayBars # With added concurrent prebooking bars
6061 return bars
6063 def sortBarsByImportance( bars, calendarStartDT, calendarEndDT ):
6065 Moves conflict bars to the end of the list,
6066 so they will be drawn last and therefore be visible.
6068 Returns sorted bars.
6070 for dt in bars.keys():
6071 dayBars = bars[dt]
6072 dayBars.sort()
6073 bars[dt] = dayBars
6075 for day in iterdays( calendarStartDT, calendarEndDT ):
6076 if not bars.has_key( day.date() ):
6077 bars[day.date()] = []
6079 return bars
6081 def getRoomBarsList( rooms ):
6082 roomBarsList = []
6083 if rooms is None:
6084 rooms=[]
6085 for room in rooms:
6086 roomBarsList.append( RoomBars( room, [] ) )
6087 roomBarsList.sort()
6088 return roomBarsList
6090 def introduceRooms( rooms, dayBarsDic, calendarStartDT, calendarEndDT, showEmptyDays=True, showEmptyRooms=True, user = None ):
6091 # Input:
6092 # dayBarsDic is a dictionary date => [bar1, bar2, bar3, ...]
6094 # Output:
6095 # newDayBarsDic is a dictionary date => [roomBars1, roomBars2, roomBars3, ...],
6096 # where roomBars is object JSON:{ room: RoomBase, bars: [bar1, bar2, bar3, ...] }
6097 #import copy
6098 #cleanRoomBarsList = getRoomBarsList( rooms )
6099 newDayBarsDic = {}
6100 from MaKaC.common.utils import formatDate
6101 for day in iterdays( calendarStartDT, calendarEndDT ):
6102 dayBars = dayBarsDic[day.date()]
6103 roomBarsDic = {}
6104 for bar in dayBars:
6105 bar.canReject = bar.forReservation.id is not None and bar.forReservation.canReject(user)
6106 if bar.forReservation.repeatability != None:
6107 bar.rejectURL = str(urlHandlers.UHRoomBookingRejectBookingOccurrence.getURL( bar.forReservation, formatDate(bar.startDT.date()) ))
6108 else:
6109 bar.rejectURL = str(urlHandlers.UHRoomBookingRejectBooking.getURL( bar.forReservation ))
6110 room = bar.forReservation.room
6111 if not roomBarsDic.has_key( room ):
6112 roomBarsDic[room] = []
6113 # Bars order should be preserved
6114 roomBarsDic[room].append( bar )
6116 if showEmptyRooms:
6117 dayRoomBarsList = getRoomBarsList( rooms ) #copy.copy( cleanRoomBarsList )
6119 for roomBar in dayRoomBarsList:
6120 roomBar.bars = roomBarsDic.get( roomBar.room, [] )
6121 else:
6122 dayRoomBarsList = []
6123 for room in roomBarsDic.keys():
6124 dayRoomBarsList.append(RoomBars(room,roomBarsDic[room]))
6126 if showEmptyDays or len(dayBars) > 0:
6127 newDayBarsDic[day.date()] = dayRoomBarsList
6129 return newDayBarsDic
6131 def getDayAttrsForRoom(dayDT, room):
6132 attrs = {'tooltip': '', 'className': ''}
6133 roomBlocked = room.getBlockedDay(dayDT)
6134 if roomBlocked:
6135 block = roomBlocked.block
6136 if roomBlocked and block.canOverride(ContextManager.get('currentUser'), explicitOnly=True):
6137 attrs['className'] = "blocked_permitted"
6138 attrs['tooltip'] = _('Blocked by %s:\n%s\n\n<b>You are permitted to override the blocking.</b>') % (block.createdByUser.getFullName(), block.message)
6139 elif roomBlocked and roomBlocked.active is True:
6140 if block.canOverride(ContextManager.get('currentUser'), room):
6141 attrs['className'] = "blocked_override"
6142 attrs['tooltip'] = _('Blocked by %s:\n%s\n\n<b>You own this room or are an administrator and are thus permitted to override the blocking. Please use this privilege with care!</b>') % (block.createdByUser.getFullName(), block.message)
6143 else:
6144 attrs['className'] = "blocked"
6145 attrs['tooltip'] = _('Blocked by %s:\n%s') % (block.createdByUser.getFullName(), block.message)
6146 elif roomBlocked and roomBlocked.active is None:
6147 attrs['className'] = "preblocked"
6148 attrs['tooltip'] = _('Blocking requested by %s:\n%s\n\n<b>If this blocking is approved, any colliding bookings will be rejected!</b>') % (block.createdByUser.getFullName(), block.message)
6149 return attrs
6151 class WRoomBookingRoomStats( WTemplated ):
6153 def __init__( self, rh, standalone = False ):
6154 self._rh = rh
6155 self._standalone = standalone
6157 def getVars( self ):
6158 vars = WTemplated.getVars( self )
6159 vars["room"] = self._rh._room
6160 vars["standalone"] = self._standalone
6161 vars["period"] = self._rh._period
6162 vars["kpiAverageOccupation"] = str( int( round( self._rh._kpiAverageOccupation * 100 ) ) ) + "%"
6163 # Bookings
6164 vars["kbiTotalBookings"] = self._rh._totalBookings
6165 # Next 9 KPIs
6166 vars["stats"] = self._rh._booking_stats
6167 vars["statsURL"] = urlHandlers.UHRoomBookingRoomStats.getURL()
6168 return vars
6171 class WRoomBookingRoomDetails( WTemplated ):
6173 def __init__( self, rh, standalone = False ):
6174 self._rh = rh
6175 self._standalone = standalone
6177 def getVars( self ):
6178 vars = WTemplated.getVars( self )
6179 vars["room"] = self._rh._room
6180 goodFactory = Location.parse( self._rh._room.locationName ).factory
6181 attributes = goodFactory.getCustomAttributesManager().getAttributes( location = self._rh._room.locationName )
6182 vars["attrs"] = {}
6183 for attribute in attributes:
6184 if not attribute.get("hidden",False) or self._rh._getUser().isAdmin():
6185 vars["attrs"][attribute['name']] = self._rh._room.customAtts.get(attribute['name'],"")
6186 if attribute['name'] == 'notification email' :
6187 vars["attrs"][attribute['name']] = vars["attrs"][attribute['name']].replace(',', ', ')
6188 vars["config"] = Config.getInstance()
6189 #vars["roomPhoto"] = urlHandlers.UHSendRoomPhoto.getURL( self._rh._room.photoId, small = False )
6190 vars["standalone"] = self._standalone
6191 vars["actionSucceeded"] = self._rh._afterActionSucceeded
6192 vars["deletionFailed"] = self._rh._afterDeletionFailed
6194 vars["roomStatsUH"] = urlHandlers.UHRoomBookingRoomStats
6196 if self._standalone:
6197 vars["bookingFormUH"] = urlHandlers.UHRoomBookingBookingForm
6198 vars["modifyRoomUH"] = urlHandlers.UHRoomBookingRoomForm
6199 vars["deleteRoomUH"] = urlHandlers.UHRoomBookingDeleteRoom
6200 vars["bookingDetailsUH"] = urlHandlers.UHRoomBookingBookingDetails
6201 else:
6202 vars["bookingDetailsUH"] = urlHandlers.UHConfModifRoomBookingDetails
6203 vars["conference"] = self._rh._conf
6204 vars["bookingFormUH"] = urlHandlers.UHConfModifRoomBookingBookingForm
6205 vars["modifyRoomUH"] = urlHandlers.UHRoomBookingRoomForm
6206 vars["deleteRoomUH"] = urlHandlers.UHRoomBookingDeleteRoom
6208 # Calendar range: 3 months
6209 if self._rh._searchingStartDT and self._rh._searchingEndDT:
6210 sd = self._rh._searchingStartDT
6211 calendarStartDT = datetime( sd.year, sd.month, sd.day, 0, 0, 1 )
6212 ed = self._rh._searchingEndDT
6213 calendarEndDT = datetime( ed.year, ed.month, ed.day, 23, 59 )
6214 else:
6215 now = datetime.now()
6216 calendarStartDT = datetime( now.year, now.month, now.day, 0, 0, 1 )
6217 calendarEndDT = calendarStartDT + timedelta( 3 * 31, 50, 0, 0, 59, 23 )
6219 # Example resv. to ask for other reservations
6220 resvEx = CrossLocationFactory.newReservation( location = self._rh._room.locationName )
6221 resvEx.startDT = calendarStartDT
6222 resvEx.endDT = calendarEndDT
6223 resvEx.repeatability = RepeatabilityEnum.daily
6224 resvEx.room = self._rh._room
6225 resvEx.isConfirmed = None # to include not also confirmed
6227 # Bars: Existing reservations
6228 collisionsOfResvs = resvEx.getCollisions()
6230 bars = []
6231 for c in collisionsOfResvs:
6232 if c.withReservation.isConfirmed:
6233 bars.append( Bar( c, Bar.UNAVAILABLE ) )
6234 else:
6235 bars.append( Bar( c, Bar.PREBOOKED ) )
6237 bars = barsList2Dictionary( bars )
6238 bars = addOverlappingPrebookings( bars )
6239 bars = sortBarsByImportance( bars, calendarStartDT, calendarEndDT )
6241 # Set owner for all
6242 if not self._standalone:
6243 for dt in bars.iterkeys():
6244 for bar in bars[dt]:
6245 bar.forReservation.setOwner( self._rh._conf )
6247 vars["calendarStartDT"] = calendarStartDT
6248 vars["calendarEndDT"] = calendarEndDT
6249 bars = introduceRooms( [self._rh._room], bars, calendarStartDT, calendarEndDT, user = self._rh._aw.getUser() )
6250 fossilizedBars = {}
6251 for key in bars:
6252 fossilizedBars[str(key)] = [fossilize(bar, IRoomBarFossil) for bar in bars[key]]
6253 vars["barsFossil"] = fossilizedBars
6254 vars["dayAttrs"] = fossilize(dict((day.strftime("%Y-%m-%d"), getDayAttrsForRoom(day, self._rh._room)) for day in bars.iterkeys()))
6255 vars["bars"] = bars
6256 vars["iterdays"] = iterdays
6257 vars["day_name"] = day_name
6258 vars["Bar"] = Bar
6259 vars["withConflicts"] = False
6260 vars["currentUser"] = self._rh._aw.getUser()
6262 return vars
6264 class WRoomBookingDetails( WTemplated ):
6266 def __init__(self, rh, conference = None):
6267 self._rh = rh
6268 self._resv = rh._resv
6269 self._conf = conference
6270 self._standalone = (conference is None)
6272 def getVars( self ):
6273 vars=WTemplated.getVars( self )
6274 vars["standalone"] = self._standalone
6275 vars["reservation"] = self._resv
6276 vars["config"] = Config.getInstance()
6277 #vars["smallPhotoUH"] = urlHandlers.UHSendRoomPhoto
6278 #vars["roomPhotoUH"] = urlHandlers.UHSendRoomPhoto
6279 vars["actionSucceeded"] = self._rh._afterActionSucceeded
6280 if self._rh._afterActionSucceeded:
6281 vars["title"] = self._rh._title
6282 vars["description"] = self._rh._description
6284 if self._standalone:
6285 vars["roomDetailsUH"] = urlHandlers.UHRoomBookingRoomDetails
6286 vars["modifyBookingUH"] = urlHandlers.UHRoomBookingBookingForm
6287 vars["cloneURL"] = urlHandlers.UHRoomBookingCloneBooking.getURL(self._resv)
6288 else:
6289 vars["roomDetailsUH"] = urlHandlers.UHConfModifRoomBookingRoomDetails
6290 vars["modifyBookingUH"] = urlHandlers.UHConfModifRoomBookingBookingForm
6291 vars["cloneURL"] = urlHandlers.UHConfModifRoomBookingCloneBooking.getURL(self._resv, self._conf)
6293 vars["bookMessage"] = "Book"
6294 if not self._resv.isConfirmed:
6295 vars["bookMessage"] = "PRE-Book"
6297 return vars
6299 # 4. Booking Form
6301 class WRoomBookingBookingForm( WTemplated ):
6303 def __init__( self, rh, standalone = False ):
6304 self._rh = rh
6305 self._candResv = rh._candResv
6306 self._standalone = standalone
6308 def getVars( self ):
6309 vars = WTemplated.getVars( self )
6311 vars["standalone"] = self._standalone
6312 vars["config"] = Config.getInstance()
6314 if self._standalone:
6315 vars["conf"] = None
6316 vars["saveBookingUH"] = urlHandlers.UHRoomBookingSaveBooking
6317 vars["roomDetailsUH"] = urlHandlers.UHRoomBookingRoomDetails
6318 vars["calendarPreviewUH"] = urlHandlers.UHRoomBookingBookingForm
6319 vars["bookingFormURL"] = urlHandlers.UHRoomBookingBookingForm
6320 else:
6321 vars["conf"] = self._rh._conf
6322 vars["saveBookingUH"] = urlHandlers.UHConfModifRoomBookingSaveBooking
6323 vars["roomDetailsUH"] = urlHandlers.UHConfModifRoomBookingRoomDetails
6324 vars["calendarPreviewUH"] = urlHandlers.UHConfModifRoomBookingBookingForm
6325 vars["bookingFormURL"] = urlHandlers.UHConfModifRoomBookingBookingForm
6327 vars["candResv"] = self._candResv
6328 vars["startDT"] = self._candResv.startDT
6329 vars["endDT"] = self._candResv.endDT
6330 vars["startT"] = '%02d:%02d' % (self._candResv.startDT.hour, self._candResv.startDT.minute )
6331 vars["endT"] = '%02d:%02d' % (self._candResv.endDT.hour, self._candResv.endDT.minute )
6333 vars["showErrors"] = self._rh._showErrors
6334 vars["errors"] = self._rh._errors
6335 vars["thereAreConflicts"] = self._rh._thereAreConflicts
6336 vars["skipConflicting"] = self._rh._skipConflicting
6338 if self._rh._formMode == FormMode.MODIF:
6339 vars["allowPast"] = "true"
6340 else:
6341 vars["allowPast"] = "false"
6342 vars["formMode"] = self._rh._formMode
6343 vars["FormMode"] = FormMode
6345 # [Book] or [PRE-Book] ?
6346 bookingMessage = "Book"
6347 room = self._candResv.room
6348 user = self._rh._getUser()
6349 if room.canPrebook( user ) and not room.canBook( user ):
6350 bookingMessage = "PRE-Book"
6351 vars["bookingMessage"] = bookingMessage
6353 if self._rh._formMode != FormMode.MODIF:
6354 bText = bookingMessage
6355 else:
6356 bText = "Save"
6358 vars["roomBookingRoomCalendar"] = WRoomBookingRoomCalendar( self._rh, self._standalone, buttonText=bText).getHTML( {} )
6360 return vars
6362 class WRoomBookingConfirmBooking( WRoomBookingBookingForm ):
6364 def getVars( self ):
6365 vars = WTemplated.getVars( self )
6367 vars["candResv"] = self._candResv
6369 vars["standalone"] = self._standalone
6370 vars["formMode"] = self._rh._formMode
6371 vars["FormMode"] = FormMode
6372 vars["collisions"] = self._rh._collisions
6374 # If we are here, we are either in booking mode and trying to overwrite PRE-Bookings...
6375 bookingMessage = "Book"
6376 bookingMessageOther = "PRE-Book"
6377 vars["rejectOthers"] = True
6378 room = self._candResv.room
6379 user = self._rh._getUser()
6380 if room.canPrebook( user ) and not room.canBook( user ):
6381 # ...or we are in PRE-booking mode and conflicting with another PRE-Booking
6382 bookingMessage = "PRE-Book"
6383 bookingMessageOther = "PRE-Book"
6384 vars["rejectOthers"] = False
6385 vars["bookingMessage"] = bookingMessage
6386 vars["bookingMessageOther"] = bookingMessageOther
6388 if self._standalone:
6389 vars["conf"] = None
6390 vars["saveBookingUH"] = urlHandlers.UHRoomBookingSaveBooking
6391 vars["roomDetailsUH"] = urlHandlers.UHRoomBookingRoomDetails
6392 else:
6393 vars["conf"] = self._rh._conf
6394 vars["saveBookingUH"] = urlHandlers.UHConfModifRoomBookingSaveBooking
6395 vars["roomDetailsUH"] = urlHandlers.UHConfModifRoomBookingRoomDetails
6396 return vars
6398 class WRoomBookingRoomForm( WTemplated ):
6400 def __init__( self, rh ):
6401 self._rh = rh
6403 def getVars( self ):
6404 vars = WTemplated.getVars( self )
6406 candRoom = self._rh._candRoom
6407 goodFactory = Location.parse( candRoom.locationName ).factory
6409 vars["Location"] = Location
6410 vars["room"] = candRoom
6411 vars["largePhotoPath"] = None
6412 vars["smallPhotoPath"] = None
6413 vars["config"] = Config.getInstance()
6414 vars["possibleEquipment"] = goodFactory.getEquipmentManager().getPossibleEquipment( location = candRoom.locationName )
6416 vars["showErrors"] = self._rh._showErrors
6417 vars["errors"] = self._rh._errors
6419 vars["insert"] = ( candRoom.id == None )
6420 vars["attrs"] = goodFactory.getCustomAttributesManager().getAttributes( location = candRoom.locationName )
6421 resp = candRoom.getResponsible()
6422 if resp:
6423 vars["responsibleName"] = resp.getFullName()
6424 else:
6425 vars["responsibleName"] = ""
6427 nbd = candRoom.getNonBookableDates()
6428 if len(nbd) == 0:
6429 from MaKaC.plugins.RoomBooking.default.room import NonBookableDate
6430 nbd = [NonBookableDate(None, None)]
6431 vars["nonBookableDates"] = nbd
6433 return vars
6436 class WRoomBookingRoomCalendar( WTemplated ):
6438 def __init__( self, rh, standalone = False, buttonText ='' ):
6439 self._rh = rh
6440 self._candResv = rh._candResv
6441 self._standalone = standalone
6442 self._buttonText = buttonText
6444 def getVars( self ):
6445 vars = WTemplated.getVars( self )
6447 candResv = self._candResv
6448 room = candResv.room
6450 if self._standalone:
6451 vars["bookingDetailsUH"] = urlHandlers.UHRoomBookingBookingDetails
6452 else:
6453 vars["bookingDetailsUH"] = urlHandlers.UHConfModifRoomBookingDetails
6455 # Calendar range
6456 now = datetime.now()
6457 if candResv != None: #.startDT != None and candResv.endDT != None:
6458 calendarStartDT = datetime( candResv.startDT.year, candResv.startDT.month, candResv.startDT.day, 0, 0, 1 ) # Potential performance problem
6459 calendarEndDT = datetime( candResv.endDT.year, candResv.endDT.month, candResv.endDT.day, 23, 59 ) # with very long reservation periods
6460 else:
6461 calendarStartDT = datetime( now.year, now.month, now.day, 0, 0, 1 )
6462 calendarEndDT = calendarStartDT + timedelta( 3 * 31, 50, 0, 0, 59, 23 )
6464 # example resv. to ask for other reservations
6465 resvEx = CrossLocationFactory.newReservation( location = room.locationName )
6466 resvEx.startDT = calendarStartDT
6467 resvEx.endDT = calendarEndDT
6468 resvEx.repeatability = RepeatabilityEnum.daily
6469 resvEx.room = room
6470 resvEx.isConfirmed = None # To include both confirmed and not confirmed
6472 # Bars: Existing reservations
6473 collisionsOfResvs = resvEx.getCollisions()
6474 bars = []
6475 for c in collisionsOfResvs:
6476 if c.withReservation.isConfirmed:
6477 bars.append( Bar( c, Bar.UNAVAILABLE ) )
6478 else:
6479 bars.append( Bar( c, Bar.PREBOOKED ) )
6481 # Bars: Candidate reservation
6482 periodsOfCandResv = candResv.splitToPeriods()
6483 for p in periodsOfCandResv:
6484 bars.append( Bar( Collision( (p.startDT, p.endDT), candResv ), Bar.CANDIDATE ) )
6486 # Bars: Conflicts all vs candidate
6487 candResvIsConfirmed = candResv.isConfirmed;
6488 candResv.isConfirmed = None
6489 allCollisions = candResv.getCollisions()
6490 candResv.isConfirmed = candResvIsConfirmed
6491 if candResv.id:
6492 # Exclude candidate vs self pseudo-conflicts (Booking modification)
6493 allCollisions = filter( lambda c: c.withReservation.id != candResv.id, allCollisions )
6494 collisions = [] # only with confirmed resvs
6495 for c in allCollisions:
6496 if c.withReservation.isConfirmed:
6497 bars.append( Bar( c, Bar.CONFLICT ) )
6498 collisions.append( c )
6499 else:
6500 bars.append( Bar( c, Bar.PRECONFLICT ) )
6502 if not candResv.isRejected and not candResv.isCancelled:
6503 vars["thereAreConflicts"] = len( collisions ) > 0
6504 else:
6505 vars["thereAreConflicts"] = False
6506 vars["conflictsNumber"] = len( collisions )
6508 bars = barsList2Dictionary( bars )
6509 bars = addOverlappingPrebookings( bars )
6510 bars = sortBarsByImportance( bars, calendarStartDT, calendarEndDT )
6512 if not self._standalone:
6513 for dt in bars.iterkeys():
6514 for bar in bars[dt]:
6515 bar.forReservation.setOwner( self._rh._conf )
6517 vars["blockConflicts"] = candResv.getBlockingConflictState(self._rh._aw.getUser())
6519 vars["calendarStartDT"] = calendarStartDT
6520 vars["calendarEndDT"] = calendarEndDT
6521 bars = introduceRooms( [room], bars, calendarStartDT, calendarEndDT, user = self._rh._aw.getUser() )
6522 fossilizedBars = {}
6523 for key in bars:
6524 fossilizedBars[str(key)] = [fossilize(bar, IRoomBarFossil) for bar in bars[key]]
6525 vars["barsFossil"] = fossilizedBars
6526 vars["dayAttrs"] = fossilize(dict((day.strftime("%Y-%m-%d"), getDayAttrsForRoom(day, room)) for day in bars.iterkeys()))
6527 vars["bars"] = bars
6528 vars["iterdays"] = iterdays
6529 vars["day_name"] = day_name
6530 vars["Bar"] = Bar
6531 vars["room"] = room
6532 vars["buttonText"] = self._buttonText
6533 vars["currentUser"] = self._rh._aw.getUser()
6534 vars["withConflicts"] = True
6536 return vars
6539 class WRoomBookingStatement( WTemplated ):
6541 def __init__( self, rh ):
6542 self._rh = rh
6544 def getVars( self ):
6545 vars = WTemplated.getVars( self )
6546 vars['title'] = self._rh._title
6547 vars['description'] = self._rh._description
6548 return vars
6550 class WRoomBookingAdmin( WTemplated ):
6552 def __init__( self, rh ):
6553 self._rh = rh
6555 def getVars( self ):
6556 vars = WTemplated.getVars( self )
6557 vars["Location"] = Location
6558 return vars
6561 class WRoomBookingAdminLocation( WTemplated ):
6563 def __init__( self, rh, location ):
6564 self._rh = rh
6565 self._location = location
6567 def getVars( self ):
6568 vars = WTemplated.getVars( self )
6569 vars["location"] = self._location
6570 vars["possibleEquipment"] = self._location.factory.getEquipmentManager().getPossibleEquipment(location = self._location.friendlyName)
6571 vars["AttsManager"] = self._location.factory.getCustomAttributesManager()
6573 # Rooms
6574 rooms = self._location.factory.newRoom().getRooms(location = self._location.friendlyName)
6575 rooms.sort(key = lambda r: r.getFullName())
6577 vars["Rooms"] = rooms
6579 rh = self._rh
6581 vars["withKPI"] = rh._withKPI
6583 if rh._withKPI:
6584 vars["kpiAverageOccupation"] = str( int( round( rh._kpiAverageOccupation * 100 ) ) ) + "%"
6586 vars["kpiTotalRooms"] = rh._kpiTotalRooms
6587 vars["kpiActiveRooms"] = rh._kpiActiveRooms
6588 vars["kpiReservableRooms"] = rh._kpiReservableRooms
6590 vars["kpiReservableCapacity"] = rh._kpiReservableCapacity
6591 vars["kpiReservableSurface"] = rh._kpiReservableSurface
6593 # Bookings
6595 vars["kbiTotalBookings"] = rh._totalBookings
6597 # Next 9 KPIs
6598 vars["stats"] = rh._booking_stats
6600 return vars
6602 class WRoomBookingBlockingsForMyRooms(WTemplated):
6604 def __init__(self, roomBlocks):
6605 self._roomBlocks = roomBlocks
6607 def getVars(self):
6608 vars = WTemplated.getVars(self)
6609 vars['roomBlocks'] = self._roomBlocks
6610 return vars
6612 class WRoomBookingBlockingDetails(WTemplated):
6614 def __init__(self, block):
6615 self._block = block
6617 def getVars(self):
6618 vars = WTemplated.getVars(self)
6619 vars['block'] = self._block
6620 return vars
6622 class WRoomBookingBlockingList(WTemplated):
6624 def __init__(self, blocks):
6625 self._blocks = blocks
6627 def getVars(self):
6628 vars = WTemplated.getVars(self)
6630 self._blocks.sort(key=attrgetter('startDate'), reverse=True)
6631 vars['blocks'] = self._blocks
6632 return vars
6634 class WRoomBookingBlockingForm(WTemplated):
6636 def __init__(self, block, hasErrors):
6637 self._block = block
6638 self._hasErrors = hasErrors
6640 def getVars(self):
6641 vars = WTemplated.getVars(self)
6642 vars['block'] = self._block
6643 vars['hasErrors'] = self._hasErrors
6644 return vars
6646 class WBaseSearchBox(WTemplated):
6648 def __init__(self, template='SearchBox', targetId=0):
6649 # overload the template
6650 WTemplated.__init__(self,template)
6651 self._targetId = targetId
6653 def getVars(self):
6654 vars = WTemplated.getVars( self )
6655 vars["searchAction"] = urlHandlers.UHSearch.getURL();
6656 vars['targetId'] = self._targetId
6657 vars['searchImg'] = imgLogo=Configuration.Config.getInstance().getSystemIconURL( "search" )
6658 vars['categId'] = 0
6659 return vars
6661 class WMiniSearchBox(WBaseSearchBox):
6663 def __init__(self, confId):
6664 WBaseSearchBox.__init__(self, template='MiniSearchBox',targetId = confId)
6666 def getVars(self):
6667 vars = WBaseSearchBox.getVars( self )
6668 return vars
6670 class WCategorySearchBox(WBaseSearchBox):
6672 def __init__(self, categId = 0, optionsClass='arrowExpandIcon'):
6673 WBaseSearchBox.__init__(self, targetId = categId)
6674 self._categId = categId
6675 self._moreOptionsClass = optionsClass
6677 def getVars(self):
6678 vars = WBaseSearchBox.getVars( self )
6679 vars["categId"] = self._categId
6680 vars['moreOptionsClass'] = self._moreOptionsClass
6681 return vars
6683 class WRootSearchBox(WBaseSearchBox):
6685 def __init__(self):
6686 # overload the template
6687 WBaseSearchBox.__init__(self,'RootSearchBox')
6689 def getVars(self):
6690 vars = WBaseSearchBox.getVars( self )
6691 vars["innerBox"] = WBaseSearchBox().getHTML()
6692 return vars
6694 class WUtils:
6695 """A interface for creating easily some HTML elements..."""
6697 def createImg(cls, imgId, imgInfo="", imgText="", **attributes):
6698 """ returns an HTML image with optional text on the right.
6699 Params:
6700 imgId -- ID of the picture (see /code/MaKaC/common/MaCaKConfig.py ->SystemIcons).
6701 ImgInfo -- optional information text about the link.
6702 imgText -- optional text which will be displayed on the right of the pic.
6703 attributes -- [dictionary] attributes for <img> (e.g. border="" name="" ...).
6705 attr = utils.dictionaryToString(attributes)
6706 return """<img src="%s" alt="%s" %s /> %s"""%(Config.getInstance().getSystemIconURL(imgId),imgInfo,attr,imgText)
6707 createImg = classmethod(createImg)
6709 def createImgButton(cls, url, imgId, imgInfo="", imgText="", **attributes):
6710 """ returns an HTML image link with optional text on the right.
6711 Params:
6712 url -- link of target.
6713 imgId -- ID of the picture (see /code/MaKaC/common/MaCaKConfig.py ->SystemIcons).
6714 ImgInfo -- optional information text about the link.
6715 imgText -- optional text which will be displayed on the right of the pic.
6716 attributes -- [dictionary] attributes for <a> (e.g. onclick="" onchange="" ...).
6718 attr = utils.dictionaryToString(attributes)
6719 return """<a href="%s" %s>
6720 <img src="%s" alt="%s" /> %s
6721 </a>"""%(url, attr, Config.getInstance().getSystemIconURL(imgId), imgInfo, imgText)
6722 createImgButton = classmethod(createImgButton)
6724 def createChangingImgButton(cls, url, imgID, imgOverId, imgInfo="", imgText="", **attributes):
6725 """ returns a changing HTML image link
6726 (i.e. the image changes depending on mouseOver/mouseOut)
6727 with optional text on the right.
6729 Params:
6730 url -- link of target.
6731 imgID -- ID of the basic picture (see /code/MaKaC/common/MaCaKConfig.py ->SystemIcons).
6732 imgOverId -- ID of the picture appearing with onMouseOver.
6733 ImgInfo -- optional information text about the link.
6734 imgText -- optional text which will be displayed on the right of the pic.
6735 attributes -- [dictionary] attributes for <a> (e.g. onclick="" onchange="" ...).
6737 attr = utils.dictionaryToString(attributes)
6738 iconUrl = Config.getInstance().getSystemIconURL(imgID)
6739 iconOverUrl = Config.getInstance().getSystemIconURL(imgOverId)
6740 return """<a href="%s" %s>
6741 <img src="%s" alt="%s" onmouseover="javascript:this.src='%s'" onMouseOut="javascript:this.src='%s'"/> %s
6742 </a>"""%(url, attr, iconUrl, imgInfo, iconOverUrl, iconUrl, imgText)
6743 createChangingImgButton = classmethod(createChangingImgButton)
6745 def createTextarea(cls, content="", **attributes):
6746 """ returns an HTML textarea with optional text.
6747 Params:
6748 content -- optional text which will be displayed in the textarea.
6749 attributes -- [dictionary] attributes for <input> (e.g. name="" type="" ...).
6751 #check
6752 if content==None: content=""
6753 #attributes to string...
6754 attr = utils.dictionaryToString(attributes)
6755 #return HTML string
6756 return """<textarea rows="5" cols="15" %s>%s</textarea>"""%(attr,content)
6757 createTextarea = classmethod(createTextarea)
6759 def createInput(cls, text="", **attributes):
6760 """ returns an HTML input with optional text.
6761 Params:
6762 text -- optional text which will be displayed on the right of the input.
6763 attributes -- [dictionary] attributes for <input> (e.g. name="" type="" ...).
6765 #check
6766 if text==None: text=""
6767 #attributes to string...
6768 attr = utils.dictionaryToString(attributes)
6769 #return HTML string
6770 return """<input %s/>%s"""%(attr,text)
6771 createInput = classmethod(createInput)
6773 def createSelect(cls, emptyOption, options, selected="", **attributes):
6774 """ returns an HTML select field.
6775 Params:
6776 emptyOption -- [bool] if True, add a selectionable empty option in the select.
6777 options -- list of the options.
6778 selected -- (optional) the selected option.
6779 attributes -- [dictionary] attributes for <select> (e.g. name="" onchange="" ...).
6781 #attributes to string...
6782 attr = utils.dictionaryToString(attributes)
6783 #with empty option?
6784 if emptyOption==True:
6785 optionsHTML="<option></option>"
6786 else:
6787 optionsHTML=""
6788 #treating options...
6789 for option in options:
6790 if option!=None and option!="":
6791 if str(option)==str(selected):
6792 optionsHTML += """<option selected>%s</option>"""%(option)
6793 else:
6794 optionsHTML += "<option>%s</option>"%(option)
6795 return """<select %s>%s</select>"""%(attr,optionsHTML)
6796 createSelect = classmethod(createSelect)
6798 def appendNewLine(cls, htmlContent):
6799 """ appends a new line <br/> to the given html element.
6800 Params:
6801 htmlContent -- [str] html element
6803 return str(htmlContent) + "<br/>"
6804 appendNewLine = classmethod(appendNewLine)
6806 class WBeautifulHTMLList(WTemplated):
6808 def __init__(self, listObject, classNames, level):
6809 """ classNames: a dictionary such as {'UlClassName' : 'optionList'}. See the getVars for more class names.
6811 WTemplated.__init__(self)
6812 self.__listObject = listObject
6813 self.__classNames = classNames
6814 self.__level = level
6816 def getVars(self):
6817 vars = WTemplated.getVars( self )
6818 vars["ListObject"] = self.__listObject
6819 vars["UlClassName"] = self.__classNames.get("UlClassName", "")
6820 vars["LiClassName"] = self.__classNames.get("LiClassName", "")
6821 vars["DivClassName"] = self.__classNames.get("DivClassName", "")
6822 vars["Level"] = self.__level
6823 return vars
6825 class WBeautifulHTMLDict(WTemplated):
6827 def __init__(self, dictObject, classNames, level):
6828 """ classNames: a dictionary such as {'UlClassName' : 'optionList'}. See the getVars for more class names.
6830 WTemplated.__init__(self)
6831 self.__dictObject = dictObject
6832 self.__classNames = classNames
6833 self.__level = level
6835 def getVars(self):
6836 vars = WTemplated.getVars( self )
6837 vars["DictObject"] = self.__dictObject
6838 vars["UlClassName"] = self.__classNames.get("UlClassName", "")
6839 vars["LiClassName"] = self.__classNames.get("LiClassName", "")
6840 vars["DivClassName"] = self.__classNames.get("DivClassName", "")
6841 vars["KeyClassName"] = self.__classNames.get("KeyClassName", "")
6842 vars["Level"] = self.__level
6843 return vars
6846 class WFilterCriteria(WTemplated):
6848 Draws the options for a filter criteria object
6849 This means rendering the actual table that contains
6850 all the HTML for the several criteria
6853 def __init__(self, options, filterCrit, extraInfo=""):
6854 WTemplated.__init__(self, tpl_name = "FilterCriteria")
6855 self._filterCrit = filterCrit
6856 self._options = options
6857 self._extraInfo = extraInfo
6859 def _drawFieldOptions(self, formName, form):
6860 raise Exception("Method WFilterCriteria._drawFieldOptions must be overwritten")
6862 def getVars(self):
6864 vars = WTemplated.getVars( self )
6866 vars["extra"] = self._extraInfo
6868 vars["content"] = list((name, self._drawFieldOptions(name, form))
6869 for (name, form) in self._options)
6870 return vars
6872 class WDateField(WTemplated):
6874 def __init__(self, name, date, format, isDisabled=False, isMandatory=False):
6875 self._withTime = format.find('%H') >= 0
6876 self._name = name
6877 self._format = format
6878 self._isMandatory = isMandatory
6879 self._date = date
6880 self._isDisabled = isDisabled
6882 def getVars(self):
6883 vars = WTemplated.getVars(self)
6884 vars['name'] = self._name
6885 vars['date'] = self._date
6886 if self._date:
6887 vars['dateDisplay'] = datetime.strftime(self._date, self._format)
6888 else:
6889 vars['dateDisplay'] = ''
6890 vars['isDisabled'] = self._isDisabled
6891 vars['withTime'] = self._withTime
6892 vars['isMandatory'] = self._isMandatory
6893 vars['format'] = self._format
6894 return vars