source: indico/indico/MaKaC/webinterface/rh/categoryDisplay.py @ cdd2b4

burotelhello-world-walkthroughipv6new-webexprov-dual-interfacev0.97-seriesv0.98-seriesv0.98.2v0.98.3v0.98b1v0.98b2v0.99v1.0v1.1
Last change on this file since cdd2b4 was cdd2b4, checked in by Jose Benito <jose.benito.gonzalez@…>, 3 years ago

[FIX] set support caption as Support

  • Property mode set to 100644
File size: 21.8 KB
Line 
1# -*- coding: utf-8 -*-
2##
3## $Id: categoryDisplay.py,v 1.54 2009/06/16 15:00:14 jose Exp $
4##
5## This file is part of CDS Indico.
6## Copyright (C) 2002, 2003, 2004, 2005, 2006, 2007 CERN.
7##
8## CDS Indico is free software; you can redistribute it and/or
9## modify it under the terms of the GNU General Public License as
10## published by the Free Software Foundation; either version 2 of the
11## License, or (at your option) any later version.
12##
13## CDS Indico is distributed in the hope that it will be useful, but
14## WITHOUT ANY WARRANTY; without even the implied warranty of
15## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
16## General Public License for more details.
17##
18## You should have received a copy of the GNU General Public License
19## along with CDS Indico; if not, write to the Free Software Foundation, Inc.,
20## 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA.
21
22from datetime import timedelta, datetime
23
24#################################
25# Fermi timezone awareness      #
26#################################
27from pytz import timezone
28from MaKaC.common.timezoneUtils import nowutc, DisplayTZ
29#################################
30# Fermi timezone awareness(end) #
31#################################
32import MaKaC.webinterface.rh.base as base
33from base import RoomBookingDBMixin
34import MaKaC.webinterface.locators as locators
35import MaKaC.webinterface.wcalendar as wcalendar
36import MaKaC.webinterface.webFactoryRegistry as webFactoryRegistry
37import MaKaC.webinterface.urlHandlers as urlHandlers
38import MaKaC.webinterface.pages.category as category
39import MaKaC.webinterface.displayMgr as displayMgr
40from MaKaC.errors import MaKaCError,FormValuesError
41import MaKaC.conference as conference
42from MaKaC.conference import ConferenceChair
43from MaKaC.common.general import *
44import MaKaC.statistics as statistics
45from MaKaC.common.Configuration import Config
46import MaKaC.user as user
47from MaKaC.ICALinterface.conference import CategoryToiCal
48from MaKaC.RSSinterface.conference import CategoryToRSS
49import MaKaC.common.info as info
50from MaKaC.i18n import _
51from MaKaC.rb_location import Location, CrossLocationQueries
52from MaKaC.webinterface.user import UserListModificationBase
53from MaKaC.common.utils import validMail, setValidEmailSeparators
54
55class RHCategDisplayBase( base.RHDisplayBaseProtected ):
56
57    def _checkParams( self, params, mustExist = 1 ):
58        l = locators.CategoryWebLocator( params, mustExist )
59        self._target = l.getObject()
60
61        # throw an error if the category was not found
62        if mustExist and self._target == None:
63            raise MaKaCError("The specified category does not exist")
64        if self._target:
65            self._getSession().setVar("currentCategoryId", self._target.getId())
66
67
68class RHCategoryDisplay( RHCategDisplayBase ):
69    _uh = urlHandlers.UHCategoryDisplay
70
71    def _process( self ):
72
73        wfReg = webFactoryRegistry.WebFactoryRegistry()
74        p = category.WPCategoryDisplay( self, self._target, wfReg )
75        return p.display()
76
77
78class RHCategoryMap( RHCategDisplayBase ):
79    _uh = urlHandlers.UHCategoryMap
80
81    def _process( self ):
82        p = category.WPCategoryMap( self, self._target )
83        return p.display()
84
85class RHCategoryStatistics( RHCategDisplayBase ):
86    _uh = urlHandlers.UHCategoryStatistics
87
88    def _process( self ):
89        wfReg = webFactoryRegistry.WebFactoryRegistry()
90        stats = statistics.CategoryStatistics(self._target).getStatistics()
91        p = category.WPCategoryStatistics( self, self._target, wfReg, stats )
92        return p.display()
93
94class RHCategOverviewDisplay( RHCategDisplayBase ):
95
96    def _checkParams( self, params ):
97        id = params.get("selCateg", "")
98        if id != "" and not params.has_key("categId"):
99            params["categId"] = id
100        RHCategDisplayBase._checkParams( self, params )
101        if not self._target:
102            raise MaKaCError( _("wrong category identifier"))
103        tz = DisplayTZ(self._aw).getDisplayTZ()
104        month = int( params.get("month", nowutc().astimezone(timezone(tz)).month) )
105        year = int( params.get("year", nowutc().astimezone(timezone(tz)).year) )
106        day = int( params.get("day", nowutc().astimezone(timezone(tz)).day) )
107        sd = timezone(tz).localize(datetime( year, month, day ))
108        period = params.get("period", "day")
109        if period == "month":
110            self._cal = wcalendar.MonthOverview( self._aw, sd, [self._target] )
111        elif period == "week":
112            self._cal = wcalendar.WeekOverview( self._aw, sd, [self._target] )
113        elif period == "nextweek":
114            self._cal = wcalendar.NextWeekOverview( self._aw, [self._target] )
115        else:
116            self._cal = wcalendar.Overview( self._aw, sd, [self._target] )
117        self._cal.setDetailLevel( params.get("detail", "conference") )
118
119    def _process( self ):
120        p = category.WPCategOverview( self, self._target, self._cal )
121        return p.display()
122
123class RHConferenceCreationBase( RHCategoryDisplay ):
124
125    def _checkProtection( self ):
126        self._checkSessionUser()
127        RHCategoryDisplay._checkProtection( self )
128        if not self._target.isConferenceCreationRestricted():
129            return
130        if not self._target.canCreateConference( self._getUser() ):
131            raise MaKaCError( _("You are not allowed to create conferences inside this category"))
132
133    def _checkParams( self, params, mustExist=1 ):
134        RHCategoryDisplay._checkParams( self, params, mustExist )
135        #if self._target.getSubCategoryList():
136        #    raise MaKaCError( _("Cannot add conferences to a category which already contains some sub-categories"))
137        self._wf = None
138        self._wfReg = webFactoryRegistry.WebFactoryRegistry()
139        et = params.get("event_type", "").strip()
140        if et != "" and et !="default":
141            self._wf = self._wfReg.getFactoryById( et )
142
143
144#-------------------------------------------------------------------------------------
145
146class RHConferenceCreation( RoomBookingDBMixin, RHConferenceCreationBase ):
147    _uh = urlHandlers.UHConferenceCreation
148
149    def getCurrentURL( self ):
150        url = self._uh.getURL(self._target)
151        url.addParam("event_type", self._event_type)
152        return url
153
154    def _checkProtection( self ):
155        try:
156            RHConferenceCreationBase._checkProtection( self )
157        except Exception:
158            self._target = None
159
160    def _checkParams( self, params ):
161        self._params = params
162        self._event_type = params.get("event_type", "").strip()
163        RHConferenceCreationBase._checkParams( self, params, mustExist=0 )
164        self._askForType = (params.get("event_type", "").strip() == "")
165
166    def _getSelectTypePage( self ):
167        p = category.WPConferenceCreationSelectType( self, self._target )
168        return p.display( wfs=self._wfReg.getFactoryList() )
169
170    def _process( self ):
171
172        if self._askForType:
173            return self._getSelectTypePage()
174        else:
175            p = category.WPConferenceCreationMainData( self, self._target )
176            if self._wf != None:
177                p = self._wf.getEventCreationPage( self, self._target )
178            return p.display(**self._params)
179
180#-------------------------------------------------------------------------------------
181
182class RHConferencePerformCreation( RHConferenceCreationBase ):
183    _uh = urlHandlers.UHConferencePerformCreation
184
185    def _checkParams( self, params ):
186        self._params =params
187        RHConferenceCreationBase._checkParams( self, params )
188        self._datecheck = False
189        self._confirm = False
190        self._performedAction = ""
191        if "ok" in params:
192            self._confirm = True
193        return
194
195    def _process( self ):
196        params = self._getRequestParams()
197        if params["title"]=="":
198            params["title"]="No Title"
199        # change number of dates (lecture)
200        if self._confirm == True:
201            if self._params.get("event_type","") != "simple_event":
202                c = self._createEvent( self._params )
203                self.alertCreation([c])
204            # lectures
205            else:
206                lectures = []
207                for i in range (1, int(self._params["nbDates"])+1):
208                    self._params["sDay"] = self._params.get("sDay_%s"%i,"")
209                    self._params["sMonth"] = self._params.get("sMonth_%s"%i,"")
210                    self._params["sYear"] = self._params.get("sYear_%s"%i,"")
211                    self._params["sHour"] = self._params.get("sHour_%s"%i,"")
212                    self._params["sMinute"] = self._params.get("sMinute_%s"%i,"")
213                    self._params["duration"] = int(self._params.get("dur_%s"%i,60))
214                    lectures.append(self._createEvent(self._params))
215                self.alertCreation(lectures)
216                lectures.sort(sortByStartDate)
217                # create links
218                for i in range(0,len(lectures)):
219                    lecture = lectures[i]
220                    if len(lectures) > 1:
221                        lecture.setTitle("%s (%s/%s)" % (lecture.getTitle(),i+1,len(lectures)))
222                    for j in range(0,len(lectures)):
223                        if j != i:
224                            mat = conference.Material()
225                            mat.setTitle("part%s"%(j+1))
226                            url = str(urlHandlers.UHConferenceDisplay.getURL(lectures[j]))
227                            link = conference.Link()
228                            link.setURL(url)
229                            link.setName(url)
230                            mat.addResource(link)
231                            lecture.addMaterial(mat)
232                c = lectures[0]
233            self._redirect(urlHandlers.UHConferenceModification.getURL( c ) )
234        else :
235            url = urlHandlers.UHCategoryDisplay.getURL(self._target)
236            self._redirect(url)
237
238    def _createEvent(self, params):
239        c = self._target.newConference( self._getUser() )
240        UtilsConference.setValues( c, self._params )
241        if self._wf:
242            self._wfReg.registerFactory( c, self._wf )
243        avatars, newUsers = self._getPersons()
244        UtilPersons.addToConf(avatars, newUsers, c, self._params.has_key('grant-manager'))
245        if params.get("sessionSlots",None) is not None :
246            if params["sessionSlots"] == "enabled" :
247                c.enableSessionSlots()
248            else :
249                c.disableSessionSlots()
250        return c
251
252    def _getPersons(self):
253        avatars, newUsers = [], []
254        from MaKaC.services.interface.rpc import json
255        chairpersonDict = json.decode(self._params.get("chairperson"))
256        if chairpersonDict:
257            avatars, newUsers, editedAvatars = UserListModificationBase.retrieveUsers({"userList":chairpersonDict})
258        #raise "avt: %s, newusers: %s, edited: %s"%(map(lambda x:x.getFullName(),avatars), newUsers, editedAvatars)
259        return avatars, newUsers
260
261    def alertCreation(self, confs):
262        conf = confs[0]
263        self._emailsToBeSent = []
264        fromAddr = info.HelperMaKaCInfo.getMaKaCInfoInstance().getSupportEmail()
265        addrs = [ info.HelperMaKaCInfo.getMaKaCInfoInstance().getSupportEmail() ]
266        eventType = conf.getType()
267        if eventType == "conference":
268            type = "conference"
269        elif eventType == "meeting":
270            type = "meeting"
271        else:
272            type = "lecture"
273        chair = ""
274        if conf.getChairmanText() != "":
275            chair = conf.getChairmanText()
276        else:
277            for c in conf.getChairList():
278                chair += c.getFullName() + "; "
279        subject = "New %s in indico (%s)" % (type,conf.getId())
280        if conf.getRoom() != None:
281            room = conf.getRoom().getName()
282        else:
283            room = ""
284        text = """
285_Category_
286%s
287_Title_
288%s
289_Speaker/Chair_
290%s
291_Room_
292%s
293_Description_
294%s
295_Creator_
296%s (%s)"""%(conf.getOwner().getTitle(), conf.getTitle(), chair, room, conf.getDescription(), conf.getCreator().getFullName(), conf.getCreator().getId())
297        if len(confs) == 1:
298            text += """
299_Date_
300%s -> %s
301_Access_
302%s""" % ( conf.getStartDate(), conf.getEndDate(), urlHandlers.UHConferenceDisplay.getURL(conf))
303        else:
304            i = 1
305            for c in confs:
306                text += """
307_Date%s_
308%s -> %s
309_Access%s_
310%s """ % (i,c.getStartDate(), c.getEndDate(), i,urlHandlers.UHConferenceDisplay.getURL(c))
311                i+=1
312
313        msg = ("Content-Type: text/plain; charset=\"utf-8\"\r\nFrom: %s\r\nReturn-Path: %s\r\nTo: %s\r\nCc: \r\nSubject: %s\r\n\r\n"%(fromAddr, fromAddr, addrs, subject))
314        msg = msg + text
315        maildata = { "fromAddr": fromAddr, "toList": addrs, "subject": subject, "body": text }
316        self._emailsToBeSent.append(maildata)
317        # Category notification
318        if conf.getOwner().getNotifyCreationList() != "":
319            addrs2 = [ conf.getOwner().getNotifyCreationList() ]
320            maildata2 = { "fromAddr": fromAddr, "toList": addrs2, "subject": subject, "body": text }
321            self._emailsToBeSent.append(maildata2)
322
323
324class UtilPersons:
325
326    @staticmethod
327    def addToConf( avatars, newUsers, conf, grantManager):
328
329        if newUsers :
330            for newUser in newUsers:
331                person = ConferenceChair()
332                person.setFirstName(newUser.get("firstName",""))
333                person.setFamilyName(newUser.get("familyName",""))
334                person.setEmail(newUser.get("email",""))
335                person.setAffiliation(newUser.get("affiliation",""))
336                person.setAddress(newUser.get("address",""))
337                person.setPhone(newUser.get("telephone",""))
338                person.setTitle(newUser.get("title",""))
339                person.setFax(newUser.get("fax",""))
340                if not UtilPersons._alreadyDefined(person) :
341                    #TODO: add to conf
342                    UtilPersons._add(conf, person, grantManager)
343                else :
344                    #self._errorList.append("%s has been already defined as %s of this conference"%(person.getFullName(),self._typeName))
345                    pass
346
347        if avatars:
348
349            for selected in avatars :
350                if isinstance(selected, user.Avatar) :
351                    person = ConferenceChair()
352                    person.setDataFromAvatar(selected)
353                    if not UtilPersons._alreadyDefined(person):
354                        #TODO: add to conf
355                        UtilPersons._add(conf, person, grantManager)
356                    else :
357                        #self._errorList.append("%s has been already defined as %s of this conference"%(person.getFullName(),self._typeName))
358                        pass
359
360                #elif isinstance(selected, user.Group) :
361                #    for member in selected.getMemberList() :
362                #        person = ConferenceChair()
363                #        person.setDataFromAvatar(member)
364                #        if not self._alreadyDefined(person, definedList) :
365                #            definedList.append([person,params.has_key("submissionControl")])
366                #        else :
367                #            self._errorList.append("%s has been already defined as %s of this conference"%(presenter.getFullName(),self._typeName))
368
369    @staticmethod
370    def _alreadyDefined(person):#, definedList):
371        #if person is None :
372        #    return True
373        #if definedList is None :
374        #    return False
375        #fullName = person.getFullName()
376        #for p in definedList :
377        #    if p[0].getFullName() == fullName :
378        #        return True
379        return False
380
381    @staticmethod
382    def _add(conf, chair, grant):
383        conf.addChair(chair)
384        if grant:
385            conf.grantModification(chair)
386
387class UtilsConference:
388
389    def setValues(c, confData):
390        c.setTitle( confData["title"] )
391        c.setDescription( confData["description"] )
392        c.setOrgText(confData.get("orgText",""))
393        c.setComments(confData.get("comments",""))
394        c.setKeywords( confData["keywords"] )
395        if "shortURLTag" in confData.keys():
396            tag = confData["shortURLTag"].strip()
397            if c.getUrlTag() != tag:
398                from MaKaC.common.url import ShortURLMapper
399                sum = ShortURLMapper()
400                sum.remove(c)
401                c.setUrlTag(tag)
402                if tag:
403                    sum.add(tag, c)
404        c.setContactInfo( confData.get("contactInfo","") )
405        #################################
406        # Fermi timezone awareness      #
407        #################################
408        c.setTimezone(confData["Timezone"])
409        tz = confData["Timezone"]
410        try:
411            sDate = timezone(tz).localize(datetime(int(confData["sYear"]), \
412                                 int(confData["sMonth"]), \
413                                 int(confData["sDay"]), \
414                                 int(confData["sHour"]), \
415                                 int(confData[ "sMinute"])))
416        except ValueError,e:
417            raise FormValuesError("The start date you have entered is not correct: %s"%e, "Event")
418
419        if confData.get("duration","") != "":
420            eDate = sDate + timedelta(minutes=confData["duration"])
421        else:
422            try:
423                eDate = timezone(tz).localize(datetime(   int(confData["eYear"]), \
424                                     int(confData["eMonth"]), \
425                                     int(confData["eDay"]), \
426                                     int(confData["eHour"]), \
427                                     int(confData[ "eMinute"])))
428            except ValueError,e:
429                raise FormValuesError("The end date you have entered is not correct: %s"%e)
430        moveEntries = int(confData.get("move",0))
431        c.setDates( sDate.astimezone(timezone('UTC')), \
432                    eDate.astimezone(timezone('UTC')), moveEntries = moveEntries )
433
434        #################################
435        # Fermi timezone awareness(end) #
436        #################################
437        if confData.get("locationName","").strip() == "":
438            c.setLocation( None )
439        else:
440            l = c.getLocation()
441            if not l:
442                l = conference.CustomLocation()
443                c.setLocation( l )
444            l.setName( confData["locationName"] )
445            l.setAddress( confData.get("locationAddress","") )
446
447        roomName = confData.get( "locationBookedRoom" )  or  confData.get( "roomName" )  or  ""
448        if roomName.strip() == "":
449            c.setRoom( None )
450        else:
451            r = c.getRoom()
452            if not r:
453                r = conference.CustomRoom()
454                c.setRoom( r )
455            r.setName( roomName )
456
457        emailstr = setValidEmailSeparators(confData.get("supportEmail", ""))
458
459        if (emailstr != "") and not validMail(emailstr):
460            raise FormValuesError("One of the emails specified or one of the separators is invalid")
461
462        c.setSupportEmail(emailstr)
463        displayMgr.ConfDisplayMgrRegistery().getDisplayMgr(c).setSupportEmailCaption(confData.get("supportCaption","Support"))
464        displayMgr.ConfDisplayMgrRegistery().getDisplayMgr(c).setDefaultStyle(confData.get("defaultStyle",""))
465        if c.getVisibility() != confData.get("visibility",999):
466            c.setVisibility( confData.get("visibility",999) )
467        curType = c.getType()
468        newType = confData.get("eventType","")
469        if newType != "" and newType != curType:
470            import MaKaC.webinterface.webFactoryRegistry as webFactoryRegistry
471            wr = webFactoryRegistry.WebFactoryRegistry()
472            factory = wr.getFactoryById(newType)
473            wr.registerFactory(c,factory)
474            dispMgr = displayMgr.ConfDisplayMgrRegistery().getDisplayMgr(c)
475            styleMgr = info.HelperMaKaCInfo.getMaKaCInfoInstance().getStyleManager()
476            dispMgr.setDefaultStyle(styleMgr.getDefaultStylesheetForEventType(newType))
477    setValues = staticmethod( setValues )
478
479
480class RHCategoryGetIcon(RHCategDisplayBase):
481
482    def _process(self):
483        icon=self._target.getIcon()
484        self._req.headers_out["Content-Length"]="%s"%icon.getSize()
485        cfg=Config.getInstance()
486        mimetype=cfg.getFileTypeMimeType(icon.getFileType())
487        self._req.content_type="""%s"""%(mimetype)
488        self._req.headers_out["Content-Disposition"]="""inline; filename="%s\""""%icon.getFileName()
489        return self._target.getIcon().readBin()
490
491class RHCategoryOpenService(base.RH):
492
493    def _checkProtection(self):
494        pass
495
496    def _checkParams( self, params ):
497        l = locators.CategoryWebLocator( params )
498        self._target = l.getObject()
499
500    def _process(self):
501        # throw an error if the category was not found
502        if self._target == None:
503            from mod_python import apache
504            self._req.status = apache.HTTP_NOT_FOUND
505            return "Specified category does not exist!"
506
507        return self._processData()
508
509class RHCategoryToiCal(RHCategoryOpenService):
510
511    def _processData( self ):
512        filename = "%s - Event.ics"%self._target.getName().replace("/","")
513        data = ""
514        data += CategoryToiCal(self._target).getBody()
515        self._req.headers_out["Content-Length"] = "%s"%len(data)
516        cfg = Config.getInstance()
517        mimetype = cfg.getFileTypeMimeType( "ICAL" )
518        self._req.content_type = """%s"""%(mimetype)
519        self._req.headers_out["Content-Disposition"] = """inline; filename="%s\""""%filename
520        return data
521
522
523class RHCategoryToRSS(RHCategoryOpenService):
524
525    def _getRSS( self, tz ):
526        return CategoryToRSS(self._target,tz=tz).getBody()
527
528    def _processData( self ):
529        data = ""
530        tz = DisplayTZ(self._aw).getDisplayTZ()
531        data += self._getRSS(tz)
532        cfg = Config.getInstance()
533        mimetype = cfg.getFileTypeMimeType( "RSS" )
534        self._req.content_type = """%s"""%(mimetype)
535        return data
536
537class RHTodayCategoryToRSS(RHCategoryToRSS):
538
539    def _getRSS( self, tz ):
540        return CategoryToRSS(self._target, date=nowutc().astimezone(timezone(tz)), tz=tz).getBody()
541
542
543def sortByStartDate(conf1,conf2):
544    return cmp(conf1.getStartDate(),conf2.getStartDate())
545
Note: See TracBrowser for help on using the repository browser.