source: indico/indico/MaKaC/webinterface/rh/conferenceDisplay.py @ 269f72

burotelhello-world-walkthroughipv6v0.98-seriesv0.98.2v0.98.3v0.98b1v0.98b2v0.99v1.0v1.1
Last change on this file since 269f72 was 269f72, checked in by Pedro Ferreira <jose.pedro.ferreira@…>, 3 years ago

[IMP] mod_WSGI migration

  • Centralized entry point for Indico
  • Remap of mod_apache's rewrite object with mod_wsgi
  • New user-friendly error page
  • Implementation of apache's rewrite with mod_wsgi
  • Python EGG Cache configuration.
  • Property mode set to 100644
File size: 57.4 KB
Line 
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.
11##
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.
16##
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.
20from datetime import timedelta,datetime, time
21import os, sys
22import MaKaC.common.info as info
23import MaKaC.webinterface.rh.base as base
24import MaKaC.webinterface.rh.conferenceBase as conferenceBase
25import MaKaC.webinterface.pages.conferences as conferences
26import MaKaC.webinterface.pages.abstracts as abstracts
27import MaKaC.webinterface.pages.authors as authors
28import MaKaC.webinterface.urlHandlers as urlHandlers
29import MaKaC.webinterface.displayMgr as displayMgr
30import MaKaC.webinterface.internalPagesMgr as internalPagesMgr
31import MaKaC.user as user
32import MaKaC.webinterface.mail as mail
33from MaKaC.webinterface.pages.errors import WPAccessError
34import MaKaC.conference as conference
35from MaKaC.common import Config, DBMgr
36from MaKaC.common.utils import isStringHTML,sortContributionByDate
37from MaKaC.authentication import AuthenticatorMgr
38from MaKaC.webinterface.rh.base import RHDisplayBaseProtected
39from MaKaC.webinterface.rh.base import RoomBookingDBMixin
40from MaKaC.webinterface.rh.conferenceBase import RHConferenceBase, RHSubmitMaterialBase
41import MaKaC.common.filters as filters
42import MaKaC.webinterface.common.contribFilters as contribFilters
43from MaKaC.errors import MaKaCError, ModificationError, NoReportError, AccessError
44from MaKaC.PDFinterface.conference import ConfManagerContribsToPDF,TimeTablePlain,AbstractBook, SimplifiedTimeTablePlain, ProgrammeToPDF, TimetablePDFFormat
45from xml.sax.saxutils import escape
46from MaKaC.participant import Participant
47from MaKaC.ICALinterface.conference import ConferenceToiCal
48from MaKaC.common.contribPacker import ConferencePacker, ZIPFileHandler
49import StringIO, zipfile
50from MaKaC.i18n import _
51
52import MaKaC.common.timezoneUtils as timezoneUtils
53from reportlab.platypus.doctemplate import LayoutError
54from MaKaC.webinterface.rh.base import RH
55from MaKaC.webinterface.common.tools import cleanHTMLHeaderFilename
56
57class RHConfSignIn( conferenceBase.RHConferenceBase ):
58
59    def _checkParams( self, params ):
60        conferenceBase.RHConferenceBase._checkParams( self, params )
61        self._login = params.get( "login", "" ).strip()
62        self._password = params.get( "password", "" ).strip()
63        self._returnURL = params.get( "returnURL", "").strip()
64        if self._returnURL == "":
65            self._returnURL = urlHandlers.UHConferenceDisplay.getURL( self._conf )
66        self._loginURL = params.get( "loginURL", "").strip()
67        self._signIn = params.get("signIn", "").strip()
68
69
70    def _process( self ):
71        self._tohttps = True
72        #Check for automatic login
73        auth = AuthenticatorMgr()
74        av = auth.autoLogin(self)
75        if av:
76            url = self._returnURL
77            self._getSession().setUser( av )
78            self._redirect( url )
79        if not self._signIn:
80            p = conferences.WPConfSignIn( self, self._conf )
81            return p.display( returnURL = self._returnURL )
82        else:
83            li = user.LoginInfo( self._login, self._password )
84            av = auth.getAvatar(li)
85            if not av:
86                p = conferences.WPConfSignIn( self, self._conf, login = self._login, msg = "Wrong login or password" )
87                return p.display( returnURL = self._returnURL )
88            elif not av.isActivated():
89                if av.isDisabled():
90                    self._redirect(urlHandlers.UHConfDisabledAccount.getURL(self._conf, av))
91                else:
92                    self._redirect(urlHandlers.UHConfUnactivatedAccount.getURL( self._conf, av))
93                return "your account is not active\nPlease activate it and retry"
94            else:
95                url = self._returnURL
96                self._getSession().setUser( av )
97                tzUtil = timezoneUtils.SessionTZ(av)
98                tz = tzUtil.getSessionTZ()
99                self._getSession().setVar("ActiveTimezone",tz)
100            self._redirect( url )
101
102# REPLACED BY RHSignOut IN login.py
103#class RHConfSignOut( conferenceBase.RHConferenceBase ):
104#
105#    def _process( self ):
106#        if self._getUser():
107#            self._getSession().setUser( None )
108#            self._setUser( None )
109#        self._redirect( urlHandlers.UHConferenceDisplay.getURL( self._conf ) )
110
111
112
113class RHConferenceAccessKey( conferenceBase.RHConferenceBase ):
114
115    def _checkParams( self, params ):
116        conferenceBase.RHConferenceBase._checkParams(self, params )
117        self._accesskey = params.get( "accessKey", "" ).strip()
118
119    def _process( self ):
120        access_keys = self._getSession().getVar("accessKeys")
121        if access_keys == None:
122            access_keys = {}
123        access_keys[self._conf.getUniqueId()] = self._accesskey
124        self._getSession().setVar("accessKeys",access_keys)
125        url = urlHandlers.UHConferenceDisplay.getURL( self._conf )
126        self._redirect( url )
127
128
129class RHConferenceForceAccessKey( conferenceBase.RHConferenceBase ):
130
131    def _checkParams( self, params ):
132        conferenceBase.RHConferenceBase._checkParams(self, params )
133
134    def _process( self ):
135        wp = WPAccessError( self )
136        return wp.display()
137
138
139class RHConfDisabledAccount( conferenceBase.RHConferenceBase ):
140
141    def _checkParams( self, params ):
142        conferenceBase.RHConferenceBase._checkParams(self, params )
143        self._userId = params.get( "userId", "" ).strip()
144
145    def _process( self ):
146        av = user.AvatarHolder().getById( self._userId )
147        p = conferences.WPConfAccountDisabled( self, self._conf, av )
148        return p.display()
149
150
151class RHConfUnactivatedAccount( conferenceBase.RHConferenceBase ):
152
153    def _checkParams( self, params ):
154        conferenceBase.RHConferenceBase._checkParams(self, params )
155        self._userId = params.get( "userId", "" ).strip()
156
157    def _process( self ):
158        av = user.AvatarHolder().getById(self._userId)
159        p = conferences.WPConfUnactivatedAccount( self, self._conf, av )
160        return p.display()
161
162
163class RHConfSendActivation( conferenceBase.RHConferenceBase ):
164
165    def _checkParams( self, params ):
166        conferenceBase.RHConferenceBase._checkParams(self, params )
167        self._userId = params.get( "userId", "" ).strip()
168
169    def _process( self ):
170        av = user.AvatarHolder().getById(self._userId)
171        sm = mail.sendConfirmationRequest(av)
172        sm.send()
173        self._redirect( urlHandlers.UHConfSignIn.getURL( self._conf ) )
174
175
176class _UserUtils:
177
178    def setUserData( self, a, userData):
179        a.setName( userData["name"] )
180        a.setSurName( userData["surName"] )
181        a.setTitle( userData["title"] )
182        a.setOrganisation( userData["organisation"] )
183        a.setAddress( userData["address"] )
184        a.setEmail( userData["email"] )
185        a.setTelephone( userData["telephone"] )
186        a.setFax( userData["fax"] )
187        ##################################
188        # Fermi timezone awareness       #
189        ##################################
190        a.setTimezone(userData["timezone"])
191        a.setDisplayTZMode(userData["displayTZMode"])
192        ##################################
193        # Fermi timezone awareness(end)  #
194        ##################################
195    setUserData = classmethod( setUserData )
196
197
198class RHConfUserCreation( conferenceBase.RHConferenceBase ):
199    _uh = urlHandlers.UHConfUserCreation
200
201    def _checkProtection( self ):
202        pass
203
204    def _checkParams( self, params ):
205        self._params = params
206        conferenceBase.RHConferenceBase._checkParams( self, params )
207        self._save = params.get("Save", "")
208        self._returnURL = params.get( "returnURL", "").strip()
209
210    def _process( self ):
211        save = False
212        ih = AuthenticatorMgr()
213        self._params["msg"] = ""
214        if self._save:
215            save = True
216            #check submited data
217            if not self._params.get("name",""):
218                self._params["msg"] += "You must enter a name.<br>"
219                save = False
220            if not self._params.get("surName",""):
221                self._params["msg"] += "You must enter a surname.<br>"
222                save = False
223            if not self._params.get("organisation",""):
224                self._params["msg"] += "You must enter the name of your organisation.<br>"
225                save = False
226            if not self._params.get("email",""):
227                self._params["msg"] += "You must enter an email address.<br>"
228                save = False
229            if not self._params.get("login",""):
230                self._params["msg"] += "You must enter a login.<br>"
231                save = False
232            if not self._params.get("password",""):
233                self._params["msg"] += "You must define a password.<br>"
234                save = False
235            if self._params.get("password","") != self._params.get("passwordBis",""):
236                self._params["msg"] += "You must enter the same password two time.<br>"
237                save = False
238            if not ih.isLoginFree(self._params.get("login","")):
239                self._params["msg"] += "Sorry, the login you requested is already in use. Please choose another one.<br>"
240                save = False
241
242        if save:
243            #Data are OK, Now check if there is an existing user or create a new one
244            ah = user.AvatarHolder()
245            res =  ah.match({"email": self._params["email"]}, exact=1, forceWithoutExtAuth=True)
246            if res:
247                #we find a user with the same email
248                a = res[0]
249                #check if the user have an identity:
250                if a.getIdentityList():
251                    self._redirect( urlHandlers.UHConfUserExistWithIdentity.getURL( self._conf, a))
252                    return
253                else:
254                    #create the identity to the user and send the comfirmatio email
255                    li = user.LoginInfo( self._params["login"], self._params["password"] )
256                    id = ih.createIdentity( li, a, "Local" )
257                    ih.add( id )
258                    DBMgr.getInstance().commit()
259                    notif = _AccountActivationNotification( a, self._conf, self._returnURL )
260                    mail.Mailer.send( notif )
261            else:
262                a = user.Avatar()
263                _UserUtils.setUserData( a, self._params )
264                ah.add(a)
265                li = user.LoginInfo( self._params["login"], self._params["password"] )
266                id = ih.createIdentity( li, a, "Local" )
267                ih.add( id )
268                DBMgr.getInstance().commit()
269                notif = _AccountActivationNotification( a, self._conf, self._returnURL )
270                mail.Mailer.send( notif )
271            self._redirect( urlHandlers.UHConfUserCreated.getURL( self._conf, a ) )
272        else:
273            p = conferences.WPConfUserCreation( self, self._conf, self._params )
274            return p.display()
275
276
277class _AccountActivationNotification:
278
279    def __init__( self, dest, conf, returnURL=""):
280        self._destination = dest
281        self._conf = conf
282        self._returnURL=returnURL
283
284    def getSubject( self ):
285        return "User account activation (%s)"%self._conf.getTitle()
286
287    def getDestination( self ):
288        return self._destination
289
290    def getCCList(self):
291        return []
292
293    def getToList(self):
294        return []
295
296    def getMsg( self ):
297        url = urlHandlers.UHConfActiveAccount.getURL( self._conf, self._destination )
298        url.addParam( "key", self._destination.getKey() )
299        if self._returnURL.strip() != "":
300            url.addParam( "returnURL", self._returnURL )
301        return """Welcome to Indico,
302You have created a new account on the Indico conference management system.
303
304In order to activate your new account and being able to be authenticated by the system, please open on your web browser the following URL:
305
306%s
307
308Once you've done it, your account will be fully operational so you can log in and start using the system normally.
309
310Good luck and thank you for using our system.
311                """%( url )
312
313
314class RHConfUserCreated( conferenceBase.RHConferenceBase ):
315
316    def _checkParams( self, params ):
317        conferenceBase.RHConferenceBase._checkParams( self, params )
318        self._av = user.AvatarHolder().getById(params["userId"])
319
320    def _process( self ):
321        p = conferences.WPConfUserCreated( self, self._conf, self._av )
322        return p.display()
323
324
325class RHConfActivate( conferenceBase.RHConferenceBase ):
326
327    def _checkParams( self, params ):
328        conferenceBase.RHConferenceBase._checkParams(self, params )
329        self._userId = params.get( "userId", "" ).strip()
330        self._key = params.get( "key", "" ).strip()
331        self._returnURL = params.get( "returnURL", "").strip()
332
333
334    def _process( self ):
335        av = user.AvatarHolder().getById(self._userId)
336        if av.isActivated():
337            p = conferences.WPConfAccountAlreadyActivated( self, self._conf, av )
338            return p.display()
339            #return "your account is already activated"
340        if av.isDisabled():
341            p = conferences.WPConfAccountDisabled( self, self._conf, av )
342            return p.display()
343            #return "your account is disabled. please, ask to enable it"
344        elif self._key == av.getKey():
345            av.activateAccount()
346            p = conferences.WPConfAccountActivated( self, self._conf, av, self._returnURL )
347            return p.display()
348            #return "Your account is activate now"
349        else:
350            return "Wrong key. Please, ask for a new one"
351
352
353class RHConfUserExistWithIdentity( conferenceBase.RHConferenceBase ):
354
355    def _checkParams( self, params ):
356        conferenceBase.RHConferenceBase._checkParams( self, params )
357        self._av = user.AvatarHolder().getById(params["userId"])
358
359    def _process( self ):
360        p = conferences.WPConfUserExistWithIdentity( self, self._conf, self._av )
361        return p.display()
362
363
364class RHConfSendLogin( conferenceBase.RHConferenceBase ):
365
366    def _checkParams( self, params ):
367        conferenceBase.RHConferenceBase._checkParams( self, params )
368        self._userId = params.get( "userId", "" ).strip()
369        self._email = params.get("email", "").strip()
370
371    def _process( self ):
372        av = None
373        if self._userId != "":
374            av = user.AvatarHolder().getById(self._userId)
375        elif self._email != "":
376            try:
377                av = user.AvatarHolder().match({"email":self._email})[0]
378            except IndexError:
379                pass
380        if av:
381            sm = mail.sendLoginInfo(av)
382            sm.send()
383        self._redirect(urlHandlers.UHConfSignIn.getURL( self._conf ))
384
385
386class RHConferenceBaseDisplay( RHConferenceBase, RHDisplayBaseProtected ):
387
388    def _checkParams( self, params ):
389        RHConferenceBase._checkParams( self, params )
390
391    def _checkProtection( self ):
392        from MaKaC.webinterface.rh.collaboration import RCCollaborationAdmin, RCCollaborationPluginAdmin
393        if not RCCollaborationAdmin.hasRights(self, None) and \
394            not RCCollaborationPluginAdmin.hasRights(self, plugins = "any"):
395            RHDisplayBaseProtected._checkProtection( self )
396
397
398class RHConferenceDisplay( RoomBookingDBMixin, RHConferenceBaseDisplay ):
399    _uh = urlHandlers.UHConferenceDisplay
400
401    def _process( self ):
402        params = self._getRequestParams()
403
404        #set default variables
405        if not self._reqParams.has_key("showDate"):
406            self._reqParams["showDate"] = "all"
407        if not self._reqParams.has_key("showSession"):
408            self._reqParams["showSession"] = "all"
409        if not self._reqParams.has_key("detailLevel"):
410            self._reqParams["detailLevel"] = "contribution"
411        #get default/selected view
412        view = "static"
413        wf = self.getWebFactory()
414        if wf != None:
415            type = self.getWebFactory().getId()
416        else:
417            type = "conference"
418        if self._reqParams.has_key("view"):
419            view = self._reqParams["view"]
420        else:
421            view = displayMgr.ConfDisplayMgrRegistery().getDisplayMgr(self._target).getDefaultStyle()
422            # if no default view was attributed, then get the configuration default
423            if view == "":
424                styleMgr = info.HelperMaKaCInfo.getMaKaCInfoInstance().getStyleManager()
425                view =styleMgr.getDefaultStylesheetForEventType( type )
426                displayMgr.ConfDisplayMgrRegistery().getDisplayMgr(self._target).setDefaultStyle( view )
427        isLibxml = True
428        warningText = ""
429        try:
430            import libxml2
431            import libxslt
432        except:
433            isLibxml = False
434        # create the html factory
435        if type == "conference":
436            if params.get("ovw", False):
437                p = conferences.WPConferenceDisplay( self, self._target )
438            else:
439                self._page = None
440                intPagesMgr=internalPagesMgr.InternalPagesMgrRegistery().getInternalPagesMgr(self._target)
441                for page in intPagesMgr.getPagesList():
442                    if page.isHome():
443                        self._page = page
444                if not self._page:
445                    p = conferences.WPConferenceDisplay( self, self._target )
446                else:
447                    p = conferences.WPInternalPageDisplay(self,self._target, self._page)
448        elif view != "static" and isLibxml:
449            p = conferences.WPXSLConferenceDisplay( self, self._target, view, type, self._reqParams )
450        else:
451            if view != "static":
452                warningText = "libxml2 and libxslt python modules need to be installed if you want to use a stylesheet-driven display - switching to static display"
453            if wf != None:
454                p = wf.getConferenceDisplayPage( self, self._target, self._reqParams )
455            else:
456                p = conferences.WPConferenceDisplay( self, self._target )
457        # generate the html
458
459        return warningText + p.display(**params)
460
461
462class RHConferenceOtherViews( RoomBookingDBMixin, RHConferenceBaseDisplay ):
463    """this class is for the conference type objects only
464    it is an alternative to the standard TimeTable view"""
465    _uh = urlHandlers.UHConferenceOtherViews
466
467    def _process( self ):
468        #set default variables
469        if not self._reqParams.has_key("showDate"):
470            self._reqParams["showDate"] = "all"
471        if not self._reqParams.has_key("showSession"):
472            self._reqParams["showSession"] = "all"
473        if not self._reqParams.has_key("detailLevel"):
474            self._reqParams["detailLevel"] = "contribution"
475        #get default/selected view
476        view = "standard"
477        type = "conference"
478        if self._reqParams.has_key("view"):
479            view = self._reqParams["view"]
480        else:
481            view = displayMgr.ConfDisplayMgrRegistery().getDisplayMgr(self._target).getDefaultStyle()
482            # if no default view was attributed, then get the configuration default
483            if view == "":
484                styleMgr = info.HelperMaKaCInfo.getMaKaCInfoInstance().getStyleManager()
485                view =styleMgr.getDefaultStylesheetForEventType( type )
486                displayMgr.ConfDisplayMgrRegistery().getDisplayMgr(self._target).setDefaultStyle( view )
487        # create the html factory
488        if view != "static":
489            p = conferences.WPXSLConferenceDisplay( self, self._target, view, type, self._reqParams )
490        else:
491            p = conferences.WPMeetingTimeTable( self, self._target,"parallel","meeting",self._reqParams )
492        # generate the html
493        if view == "xml" and self._reqParams.get('fr') == 'no':
494            self._req.content_type = "text/xml"
495        return p.display()
496
497
498class RHConferenceGetLogo(RHConferenceBaseDisplay):
499
500    def _process(self):
501        logo=self._target.getLogo()
502        self._req.headers_out["Content-Length"]="%s"%logo.getSize()
503        cfg=Config.getInstance()
504        mimetype=cfg.getFileTypeMimeType(logo.getFileType())
505        self._req.content_type="""%s"""%(mimetype)
506        self._req.headers_out["Content-Disposition"]="""inline; filename="%s\""""%cleanHTMLHeaderFilename(logo.getFileName())
507        return self._target.getLogo().readBin()
508
509
510class RHConferenceGetCSS(RHConferenceBaseDisplay):
511
512    """
513    CSS which is used just for a conference.
514    """
515
516    def _process(self):
517        sm = displayMgr.ConfDisplayMgrRegistery().getDisplayMgr(self._conf).getStyleManager()
518        css=sm.getLocalCSS()
519        if css:
520            self._req.headers_out["Content-Length"]="%s"%css.getSize()
521            self._req.content_type="text/css"
522            self._req.headers_out["Content-Disposition"]="""inline; filename="%s\""""%css.getFileName()
523            return css.readBin()
524
525        return ""
526
527
528class RHConferenceGetPic(RHConferenceBaseDisplay):
529
530    def _checkParams(self, params):
531        RHConferenceBaseDisplay._checkParams( self, params )
532        self._picId = params.get("picId","")
533
534    def _process(self):
535        im = displayMgr.ConfDisplayMgrRegistery().getDisplayMgr(self._conf).getImagesManager()
536        pic=im.getPic(self._picId).getLocalFile()
537        self._req.headers_out["Content-Length"]="%s"%pic.getSize()
538        cfg=Config.getInstance()
539        mimetype=cfg.getFileTypeMimeType(pic.getFileType())
540        self._req.content_type="""%s"""%(mimetype)
541        self._req.headers_out["Content-Disposition"]="""inline; filename="%s\""""%pic.getFileName()
542        return pic.readBin()
543
544
545class RHConferenceEmail(RHConferenceBaseDisplay, base.RHProtected):
546    _uh = urlHandlers.UHConferenceEmail
547
548    def _checkProtection(self):
549        base.RHProtected._checkProtection(self)
550
551    def _checkParams( self, params ):
552        RHConferenceBaseDisplay._checkParams( self, params )
553        self._auth = params.has_key("authId")
554        self._chair = params.has_key("chairId")
555        if params.has_key("contribId"):
556            contrib = self._conf.getContributionById(params.get("contribId",""))
557        if self._chair:
558            chairid=params.get("chairId","")
559            self._emailto =self._conf.getChairById(chairid).getEmail()
560        if self._auth:
561            authid=params.get("authId","")
562            self._emailto =contrib.getAuthorById(authid).getEmail()
563
564    def _process(self):
565        p=conferences.WPEMail(self, self._target)
566        return p.display(emailto=self._emailto)
567
568class RHConferenceSendEmail (RHConferenceBaseDisplay, base.RHProtected):
569    _uh = urlHandlers.UHConferenceSendEmail
570
571    def _checkProtection(self):
572        base.RHProtected._checkProtection(self)
573
574    def _checkParams(self, params):
575        RHConferenceBaseDisplay._checkParams( self, params )
576        self._to = params.get("to","")
577        self._cc = params.get("cc","")
578        self._from=params.get("from","")
579        self._subject=params.get("subject","")
580        self._body = params.get("body","")
581        self._send = params.has_key("OK")
582
583    def _process(self):
584        if self._send:
585            mail.personMail.send(self._to, self._cc, self._from,self._subject,self._body)
586            p = conferences.WPSentEmail(self, self._target)
587            return p.display()
588        else:
589            self._redirect(urlHandlers.UHConferenceDisplay.getURL(self._conf))
590
591
592
593class RHConferenceProgram( RHConferenceBaseDisplay ):
594    _uh = urlHandlers.UHConferenceProgram
595
596    def _checkParams( self, params ):
597        RHConferenceBaseDisplay._checkParams( self, params )
598        self._xs = self._normaliseListParam( params.get("xs", []) )
599
600
601    def _process( self ):
602        p = conferences.WPConferenceProgram( self, self._target )
603        return p.display( xs = self._xs )
604
605
606class RHConferenceProgramPDF( RHConferenceBaseDisplay ):
607
608    def _process( self ):
609        tz = timezoneUtils.DisplayTZ(self._aw,self._target).getDisplayTZ()
610        filename = "%s - Programme.pdf"%cleanHTMLHeaderFilename(self._target.getTitle())
611        from MaKaC.PDFinterface.conference import ProgrammeToPDF
612        pdf = ProgrammeToPDF(self._target, tz=tz)
613        data = pdf.getPDFBin()
614        #self._req.headers_out["Accept-Ranges"] = "bytes"
615        self._req.headers_out["Content-Length"] = "%s"%len(data)
616        cfg = Config.getInstance()
617        mimetype = cfg.getFileTypeMimeType( "PDF" )
618        #self._req.content_type = """%s; name="%s\""""%(mimetype, filename )
619        self._req.content_type = """%s"""%(mimetype)
620        self._req.headers_out["Content-Disposition"] = """inline; filename="%s\""""%filename
621        return data
622
623class RHConferenceTimeTable( RoomBookingDBMixin, RHConferenceBaseDisplay ):
624    _uh = urlHandlers.UHConferenceTimeTable
625
626    def _process( self ):
627        defStyle = displayMgr.ConfDisplayMgrRegistery().getDisplayMgr(self._target).getDefaultStyle()
628        if defStyle in ["", "static", "parallel"]:
629            p = conferences.WPConferenceTimeTable( self, self._target )
630            return p.display( **self._getRequestParams() )
631        else:
632            url = urlHandlers.UHConferenceOtherViews.getURL( self._conf )
633            url.addParam("view", defStyle)
634            self._redirect(url)
635
636
637class RHTimeTablePDF(RHConferenceTimeTable):
638
639    fontsizes = ['xxx-small', 'xx-small', 'x-small', 'smaller', 'small', 'normal', 'large', 'larger']
640
641    def _checkParams(self,params):
642        RHConferenceTimeTable._checkParams(self,params)
643        self._showSessions=self._normaliseListParam(params.get("showSessions",[]))
644        if "all" in self._showSessions:
645            self._showSessions.remove("all")
646        self._showDays=self._normaliseListParam(params.get("showDays",[]))
647        if "all" in self._showDays:
648            self._showDays.remove("all")
649        self._sortingCrit=None
650        if params.has_key("sortBy") and params["sortBy"].strip()!="":
651            self._sortingCrit=contribFilters.SortingCriteria([params.get( "sortBy", "number").strip()])
652        self._pagesize = params.get('pagesize','A4')
653        self._fontsize = params.get('fontsize','normal')
654        try:
655            self._firstPageNumber = int(params.get('firstPageNumber','1'))
656        except ValueError:
657            self._firstPageNumber = 1
658        self._showSpeakerAffiliation = False
659        if params.has_key("showSpeakerAffiliation"):
660            self._showSpeakerAffiliation = True
661        # Keep track of the used layout for getting back after cancelling
662        # the export.
663        self._view = params.get("view", displayMgr.ConfDisplayMgrRegistery().getDisplayMgr(self._target).getDefaultStyle())
664
665    def _reduceFontSize( self ):
666        index = self.fontsizes.index(self._fontsize)
667        if index > 0:
668            self._fontsize = self.fontsizes[index-1]
669            return True
670        return False
671
672    def _process(self):
673        tz = timezoneUtils.DisplayTZ(self._aw,self._target).getDisplayTZ()
674        params = self._getRequestParams()
675        ttPDFFormat=TimetablePDFFormat(params)
676
677        # Choose action depending on the button pressed
678        if params.has_key("cancel"):
679            # If the export is cancelled, redirect to the display
680            # page
681            url = urlHandlers.UHConferenceDisplay.getURL(self._conf)
682            url.addParam("view", self._view)
683            self._redirect(url)
684        else :
685            retry = True
686            while retry:
687                if params.get("typeTT","normalTT")=="normalTT":
688                    filename = "timetable.pdf"
689                    pdf = TimeTablePlain(self._target,self.getAW(),
690                            showSessions=self._showSessions,showDays=self._showDays,
691                            sortingCrit=self._sortingCrit, ttPDFFormat=ttPDFFormat,
692                            pagesize = self._pagesize, fontsize = self._fontsize,
693                            firstPageNumber = self._firstPageNumber,
694                            showSpeakerAffiliation = self._showSpeakerAffiliation)
695                else:
696                    filename = "SimplifiedTimetable.pdf"
697                    pdf = SimplifiedTimeTablePlain(self._target,self.getAW(),
698                        showSessions=self._showSessions,showDays=self._showDays,
699                        sortingCrit=self._sortingCrit, ttPDFFormat=ttPDFFormat,
700                        pagesize = self._pagesize, fontsize = self._fontsize)
701                try:
702                    data=pdf.getPDFBin()
703                    retry = False
704                except LayoutError, e:
705                    if not self._reduceFontSize():
706                        raise MaKaCError("Error in PDF generation - One of the paragraphs does not fit on a page")
707                except Exception, e:
708                    raise e
709
710    ##        tries = 5
711    ##        while tries:
712    ##            if params.get("typeTT","normalTT")=="normalTT":
713    ##                filename = "timetable.pdf"
714    ##                pdf = TimeTablePlain(self._target,self.getAW(),
715    ##                        showSessions=self._showSessions,showDays=self._showDays,
716    ##                        sortingCrit=self._sortingCrit, ttPDFFormat=ttPDFFormat,
717    ##                        pagesize = self._pagesize, fontsize = self._fontsize, firstPageNumber = self._firstPageNumber, tz=tz)
718    ##            else:
719    ##                filename = "SimplifiedTimetable.pdf"
720    ##                pdf = SimplifiedTimeTablePlain(self._target,self.getAW(),
721    ##                    showSessions=self._showSessions,showDays=self._showDays,
722    ##                    sortingCrit=self._sortingCrit, ttPDFFormat=ttPDFFormat,
723    ##                    pagesize = self._pagesize, fontsize = self._fontsize, tz=tz)
724    ##            try:
725    ##                data=pdf.getPDFBin()
726    ##                tries = 0
727    ##            except LayoutError, e:
728    ##                if self._reduceFontSize():
729    ##                    tries -= 1
730    ##                else:
731    ##                    tries = 0
732    ##                    raise MaKaCError(str(e))
733
734            self._req.headers_out["Content-Length"] = "%s"%len(data)
735            cfg=Config.getInstance()
736            mimetype=cfg.getFileTypeMimeType("PDF")
737            self._req.content_type = """%s"""%(mimetype)
738            self._req.headers_out["Content-Disposition"]="""inline; filename="%s\""""%filename
739            return data
740
741class RHTimeTableCustomizePDF(RHConferenceTimeTable):
742
743    def _checkParams(self,params):
744        RHConferenceTimeTable._checkParams(self,params)
745        self._cancel = params.has_key("cancel")
746        self._view = params.get("view", "standard")
747
748    def _process(self):
749        # TODO: why not construct p this way only if wf == None?
750        p=conferences.WPTimeTableCustomizePDF(self, self._target)
751        wf = self.getWebFactory()
752        if wf != None:
753            p=wf.getTimeTableCustomizePDF(self, self._target, self._view)
754        return p.display(**self._getRequestParams())
755
756
757class _HideWithdrawnFilterField(filters.FilterField):
758    """
759    """
760    _id = "hide_withdrawn"
761
762    def __init__(self,conf,values):
763        pass
764
765    def satisfies(self,contribution):
766        """
767        """
768        return not isinstance(contribution.getCurrentStatus(),conference.ContribStatusWithdrawn)
769
770
771class ContributionsFilterCrit(filters.FilterCriteria):
772    _availableFields = { \
773        contribFilters.TypeFilterField.getId():contribFilters.TypeFilterField, \
774        contribFilters.TrackFilterField.getId():contribFilters.TrackFilterField, \
775        contribFilters.SessionFilterField.getId():contribFilters.SessionFilterField, \
776        _HideWithdrawnFilterField.getId(): _HideWithdrawnFilterField
777                }
778
779
780class RHContributionList( RHConferenceBaseDisplay ):
781    _uh = urlHandlers.UHContributionList
782
783    def _checkParams( self, params ):
784        RHConferenceBaseDisplay._checkParams( self, params )
785        # Sorting
786        self._sortingCrit=contribFilters.SortingCriteria( [params.get( "sortBy", "number").strip()] )
787        self._order = params.get("order","down")
788        # Filtering
789        filterUsed = params.has_key( "OK" ) # this variable is true when the
790                                            # filter has been used
791        filter = {"hide_withdrawn": True}
792        ltypes = []
793        if not filterUsed:
794            for type in self._conf.getContribTypeList():
795                ltypes.append( type.getId() )
796        else:
797            for id in self._normaliseListParam( params.get("selTypes", []) ):
798                ltypes.append(id)
799        filter["type"] = ltypes
800
801        ltracks = []
802        if not filterUsed:
803            for track in self._conf.getTrackList():
804                ltracks.append( track.getId() )
805        filter["track"] = self._normaliseListParam( params.get("selTracks", ltracks) )
806
807        lsessions = []
808        if not filterUsed:
809            for session in self._conf.getSessionList():
810                lsessions.append( session.getId() )
811        filter["session"] = self._normaliseListParam( params.get("selSessions", lsessions) )
812
813        self._filterCrit=ContributionsFilterCrit(self._conf,filter)
814        typeShowNoValue, trackShowNoValue, sessionShowNoValue = True, True, True
815        if filterUsed:
816            if self._conf.getContribTypeList():
817                typeShowNoValue =  params.has_key("typeShowNoValue")
818            if self._conf.getTrackList():
819                trackShowNoValue =  params.has_key("trackShowNoValue")
820            if self._conf.getSessionList():
821                sessionShowNoValue =  params.has_key("sessionShowNoValue")
822        self._filterCrit.getField("type").setShowNoValue( typeShowNoValue )
823        self._filterCrit.getField("track").setShowNoValue( trackShowNoValue )
824        self._filterCrit.getField("session").setShowNoValue( sessionShowNoValue )
825        self._sc=params.get("sc",1)
826        self._nc=params.get("nc",20)
827
828
829    def _process( self ):
830        p = conferences.WPContributionList( self, self._target )
831        return p.display(sortingCrit = self._sortingCrit, filterCrit = self._filterCrit, sc=self._sc, nc=self._nc, order=self._order)
832
833
834class RHAuthorIndex(RHConferenceBaseDisplay):
835    _uh=urlHandlers.UHConfAuthorIndex
836
837    def _checkParams( self, params ):
838        RHConferenceBaseDisplay._checkParams( self, params )
839        self._view=params.get("view","full")
840        self._letter=params.get("letter","a")
841
842    def _process(self):
843        p=conferences.WPAuthorIndex(self,self._target)
844        return p.display(viewMode=self._view,selLetter=self._letter)
845
846class RHSpeakerIndex(RHConferenceBaseDisplay):
847    _uh=urlHandlers.UHConfAuthorIndex
848
849    def _checkParams( self, params ):
850        RHConferenceBaseDisplay._checkParams( self, params )
851        self._view=params.get("view","full")
852        self._letter=params.get("letter","a")
853
854    def _process(self):
855        p=conferences.WPSpeakerIndex(self,self._target)
856        return p.display(viewMode=self._view,selLetter=self._letter)
857
858class RHMyStuff(RHConferenceBaseDisplay,base.RHProtected):
859    _uh=urlHandlers.UHConfMyStuff
860
861    def _checkProtection(self):
862        base.RHProtected._checkProtection(self)
863
864    def _process(self):
865        p=conferences.WPMyStuff(self,self._target)
866        return p.display()
867
868
869class RHContribsActions:
870    """
871    class to select the action to do with the selected abstracts
872    """
873    def __init__(self, req):
874        self._req = req
875
876    def process(self, params):
877        if params.has_key("PDF"):
878            return RHContributionListToPDF(self._req).process(params)
879        return "no action to do"
880
881class RHContributionListToPDF(RHConferenceBaseDisplay):
882
883    def _checkParams( self, params ):
884        RHConferenceBaseDisplay._checkParams( self, params )
885        self._contribIds = self._normaliseListParam( params.get("contributions", []) )
886        self._contribs = []
887        for id in self._contribIds:
888            contrib = self._conf.getContributionById(id)
889            if contrib.canAccess(self.getAW()):
890                self._contribs.append(contrib)
891
892    def _process( self ):
893        tz = timezoneUtils.DisplayTZ(self._aw,self._conf).getDisplayTZ()
894        filename = "Contributions.pdf"
895        if not self._contribs:
896            return "No contributions to print"
897        from MaKaC.PDFinterface.conference import ConfManagerContribsToPDF
898        pdf = ConfManagerContribsToPDF(self._conf, self._contribs, tz=tz)
899        data = pdf.getPDFBin()
900        self._req.set_content_length(len(data))
901        cfg = Config.getInstance()
902        mimetype = cfg.getFileTypeMimeType( "PDF" )
903        self._req.content_type = """%s"""%(mimetype)
904        self._req.headers_out["Content-Disposition"] = """inline; filename="%s\""""%filename
905        return data
906
907
908class RHConferenceMenuClose(RHConferenceBaseDisplay):
909
910    def _checkParams( self, params ):
911        RHConferenceBaseDisplay._checkParams( self, params )
912        self._currentURL = params.get("currentURL","")
913
914    def _process( self ):
915        websession = self._getSession()
916        websession.setVar("menuStatus", "close")
917        self._redirect(self._currentURL)
918
919
920class RHConferenceMenuOpen(RHConferenceBaseDisplay):
921
922    def _checkParams( self, params ):
923        RHConferenceBaseDisplay._checkParams( self, params )
924        self._currentURL = params.get("currentURL","")
925
926    def _process( self ):
927        websession = self._getSession()
928        websession.setVar("menuStatus", "open")
929        self._redirect(self._currentURL)
930
931
932class RHAbstractBook(RHConferenceBaseDisplay):
933    _uh=urlHandlers.UHConfAbstractBook
934
935    def _checkProtection( self ):
936        RHConferenceBaseDisplay._checkProtection(self)
937        if not self._conf.getAbstractMgr().isActive() or not self._conf.hasEnabledSection("cfa"):
938            raise MaKaCError( _("The Call For Abstracts was disabled by the conference managers"))
939
940    def _process( self ):
941        p=conferences.WPAbstractBookCustomise(self,self._target)
942        return p.display()
943
944class RHAbstractBookPerform(RHConferenceBaseDisplay):
945    _uh=urlHandlers.UHConfAbstractBook
946
947    def _checkParams( self, params ):
948        RHConferenceBaseDisplay._checkParams( self, params )
949        self._sortBy = params.get("sortBy","")
950
951    def _process( self ):
952        tz = timezoneUtils.DisplayTZ(self._aw,self._target).getDisplayTZ()
953        filename = "%s - Book of abstracts.pdf"%cleanHTMLHeaderFilename(self._target.getTitle())
954        from MaKaC.PDFinterface.conference import AbstractBook
955        pdf = AbstractBook(self._target,self.getAW(), self._sortBy, tz=tz)
956        data = pdf.getPDFBin()
957        self._req.headers_out["Content-Length"] = "%s"%len(data)
958        cfg = Config.getInstance()
959        mimetype = cfg.getFileTypeMimeType( "PDF" )
960        self._req.content_type = """%s"""%(mimetype)
961        self._req.headers_out["Content-Disposition"] = """inline; filename="%s\""""%filename
962        return data
963
964
965class RHConfParticipantsNewPending(RHConferenceDisplay):
966    _uh = urlHandlers.UHConfParticipantsNewPending
967
968    def _process( self ):
969        params = self._getRequestParams()
970
971        errorList = []
972        if self._conf.getStartDate() < timezoneUtils.nowutc() :
973            errorList.append("This event began on %s"%self._conf.getStartDate())
974            errorList.append("You cannot apply for participation after the event began")
975
976        if not self._conf.getParticipation().isAllowedForApplying() :
977            errorList.append("Participation in this event is restricted to persons invited")
978            errorList.append("If you insist on taking part in this event, please contact the event manager")
979
980        if errorList:
981            self._reqParams["errorMsg"] = errorList
982            return RHConferenceDisplay._process(self)
983
984        params["formAction"] = str(urlHandlers.UHConfParticipantsAddPending.getURL(self._conf))
985        user = self._getUser()
986        if user is not None :
987            params["titleValue"] = user.getTitle()
988            params["surNameValue"] = user.getFamilyName()
989            params["nameValue"] = user.getName()
990            params["emailValue"] = user.getEmail()
991            params["addressValue"] = user.getAddress()
992            params["affiliationValue"] = user.getAffiliation()
993            params["phoneValue"] = user.getTelephone()
994            params["faxValue"] = user.getFax()
995
996            params["disabledTitle"] = params["disabledSurName"] = True
997            params["disabledName"] = params["disabledEmail"] = True
998            params["disabledAddress"] = params["disabledPhone"] = True
999            params["disabledFax"] = params["disabledAffiliation"] = True
1000
1001
1002        wf=self.getWebFactory()
1003        if wf is not None:
1004            p = wf.getConfModifParticipantsNewPending(self, self._conf)
1005        else :
1006            p = conferences.WPConfModifParticipantsNewPending( self, self._target )
1007        return p.display(**params)
1008
1009
1010class RHConfParticipantsAddPending(RHConferenceDisplay):
1011    _uh = urlHandlers.UHConfParticipantsAddPending
1012
1013    def _process( self ):
1014        params = self._getRequestParams()
1015        errorList = []
1016        infoList = []
1017        if params.has_key("ok") :
1018            user = self._getUser()
1019            pending = Participant(self._conf, user)
1020            if user is None :
1021                pending.setTitle(params.get("title",""))
1022                pending.setFamilyName(params.get("surName",""))
1023                pending.setFirstName(params.get("name",""))
1024                pending.setEmail(params.get("email",""))
1025                pending.setAffiliation(params.get("affiliation",""))
1026                pending.setAddress(params.get("address",""))
1027                pending.setTelephone(params.get("phone",""))
1028                pending.setFax(params.get("fax",""))
1029            participation = self._conf.getParticipation()
1030            if participation.alreadyParticipating(pending) != 0:
1031                errorList.append("The participant identified by email '%s' is already in the participants' list"
1032                                 % pending.getEmail())
1033                errorList.append("Please check if you are not already added to the meeting.")
1034            else:
1035                if participation.addPendingParticipant(pending):
1036                    infoList.append("The participant identified by email '%s' has been added to the list of pending participants"
1037                                    % pending.getEmail())
1038                else:
1039                    errorList.append("The participant cannot be added.")
1040
1041        if infoList:
1042            self._reqParams["infoMsg"] = infoList
1043        if errorList:
1044            self._reqParams["errorMsg"] = errorList
1045
1046        return RHConferenceDisplay._process(self)
1047
1048
1049class RHConfParticipantsRefusal(RHConferenceBaseDisplay):
1050    _uh = urlHandlers.UHConfParticipantsRefusal
1051
1052    def _checkParams( self, params ):
1053        RHConferenceBaseDisplay._checkParams(self, params )
1054        self._confirm = params.has_key( "confirm" )
1055        self._cancel = params.has_key( "cancel" )
1056
1057    def _process( self ):
1058        params = self._getRequestParams()
1059        participantId = params["participantId"]
1060        if self._cancel:
1061            participant = self._conf.getParticipation().getParticipantById(participantId)
1062            url = urlHandlers.UHConferenceDisplay.getURL( self._conf )
1063            self._redirect( url )
1064        elif self._confirm:
1065            participant = self._conf.getParticipation().getParticipantById(participantId)
1066            participant.setStatusRefused()
1067            url = urlHandlers.UHConferenceDisplay.getURL( self._conf )
1068            self._redirect( url )
1069        else:
1070            return conferences.WPConfModifParticipantsRefuse( self, self._conf ).display(**params)
1071
1072
1073class RHConfParticipantsInvitation(RHConferenceBaseDisplay):
1074    _uh = urlHandlers.UHConfParticipantsInvitation
1075
1076    def _checkParams( self, params ):
1077        RHConferenceBaseDisplay._checkParams(self, params )
1078        self._confirm = params.has_key( "confirm" )
1079        self._cancel = params.has_key( "cancel" )
1080
1081    def _process( self ):
1082        params = self._getRequestParams()
1083        participantId = params["participantId"]
1084        if self._cancel:
1085            participant = self._conf.getParticipation().getParticipantById(participantId)
1086            if participant == None:
1087                raise NoReportError("It seems you have been withdrawn from the list of invited participants")
1088            participant.setStatusRejected()
1089            url = urlHandlers.UHConferenceDisplay.getURL( self._conf )
1090            self._redirect( url )
1091        elif self._confirm:
1092            participant = self._conf.getParticipation().getParticipantById(participantId)
1093            if participant == None:
1094                raise NoReportError("It seems you have been withdrawn from the list of invited participants")
1095            participant.setStatusAccepted()
1096            url = urlHandlers.UHConferenceDisplay.getURL( self._conf )
1097            self._redirect( url )
1098        else:
1099            return conferences.WPConfModifParticipantsInvite( self, self._conf ).display(**params)
1100
1101class RHConferenceToiCal(RHConferenceBaseDisplay):
1102
1103    def _process( self ):
1104        filename = "%s - Event.ics"%cleanHTMLHeaderFilename(self._target.getTitle())
1105        ical = ConferenceToiCal(self._target.getConference())
1106        data = ical.getBody()
1107        self._req.headers_out["Content-Length"] = "%s"%len(data)
1108        cfg = Config.getInstance()
1109        mimetype = cfg.getFileTypeMimeType( "ICAL" )
1110        self._req.content_type = """%s"""%(mimetype)
1111        self._req.headers_out["Content-Disposition"] = """inline; filename="%s\""""%filename
1112        return data
1113
1114class RHConferenceToXML(RHConferenceBaseDisplay):
1115
1116    def _checkParams( self, params ):
1117        RHConferenceBaseDisplay._checkParams( self, params )
1118        self._xmltype = params.get("xmltype","standard")
1119
1120    def _process( self ):
1121        filename = "%s - Event.xml"%cleanHTMLHeaderFilename(self._target.getTitle())
1122        from MaKaC.common.xmlGen import XMLGen
1123        from MaKaC.common.output import outputGenerator, XSLTransformer
1124        xmlgen = XMLGen()
1125        xmlgen.initXml()
1126        outgen = outputGenerator(self.getAW(), xmlgen)
1127        xmlgen.openTag("event")
1128        outgen.confToXML(self._target.getConference(),0,0,1)
1129        xmlgen.closeTag("event")
1130        basexml = xmlgen.getXml()
1131        path = Config.getInstance().getStylesheetsDir()
1132        stylepath = "%s.xsl" % (os.path.join(path,self._xmltype))
1133        if self._xmltype != "standard" and os.path.exists(stylepath):
1134            try:
1135                parser = XSLTransformer(stylepath)
1136                data = parser.process(basexml)
1137            except:
1138                data = "Cannot parse stylesheet: %s" % sys.exc_info()[0]
1139        else:
1140            data = basexml
1141        self._req.headers_out["Content-Length"] = "%s"%len(data)
1142        cfg = Config.getInstance()
1143        mimetype = cfg.getFileTypeMimeType( "XML" )
1144        self._req.content_type = """%s"""%(mimetype)
1145        self._req.headers_out["Content-Disposition"] = """inline; filename="%s\""""%filename
1146        return data
1147
1148
1149class RHConferenceToMarcXML(RHConferenceBaseDisplay):
1150
1151    def _process( self ):
1152        filename = "%s - Event.xml"%cleanHTMLHeaderFilename(self._target.getTitle())
1153        from MaKaC.common.xmlGen import XMLGen
1154        from MaKaC.common.output import outputGenerator
1155        xmlgen = XMLGen()
1156        xmlgen.initXml()
1157        outgen = outputGenerator(self.getAW(), xmlgen)
1158        xmlgen.openTag("marc:record", [["xmlns:marc","http://www.loc.gov/MARC21/slim"],["xmlns:xsi","http://www.w3.org/2001/XMLSchema-instance"],["xsi:schemaLocation", "http://www.loc.gov/MARC21/slim http://www.loc.gov/standards/marcxml/schema/MARC21slim.xsd"]])
1159        outgen.confToXMLMarc21(self._target.getConference())
1160        xmlgen.closeTag("marc:record")
1161        data = xmlgen.getXml()
1162        self._req.headers_out["Content-Length"] = "%s"%len(data)
1163        cfg = Config.getInstance()
1164        mimetype = cfg.getFileTypeMimeType( "XML" )
1165        self._req.content_type = """%s"""%(mimetype)
1166        self._req.headers_out["Content-Disposition"] = """inline; filename="%s\""""%filename
1167        return data
1168
1169class RHWriteMinutes( RHConferenceBaseDisplay ):
1170
1171    def _checkProtection(self):
1172        if not self._target.canModify( self.getAW() ):
1173            if self._target.getModifKey() != "":
1174                raise ModificationError()
1175            if self._getUser() == None:
1176                self._preserveParams()
1177                self._checkSessionUser()
1178            else:
1179                raise ModificationError()
1180
1181    def _preserveParams(self):
1182        preservedParams = self._getRequestParams().copy()
1183        self._websession.setVar("minutesPreservedParams",preservedParams)
1184
1185    def _getPreservedParams(self):
1186        params = self._websession.getVar("minutesPreservedParams")
1187        if params is None :
1188            return {}
1189        return params
1190
1191    def _removePreservedParams(self):
1192        self._websession.setVar("minutesPreservedParams",None)
1193
1194    def _checkParams( self, params ):
1195        RHConferenceBaseDisplay._checkParams( self, params )
1196        preservedParams = self._getPreservedParams()
1197        if preservedParams != {}:
1198            params.update(preservedParams)
1199            self._removePreservedParams()
1200        self._cancel = params.has_key("cancel")
1201        self._save = params.has_key("OK")
1202        self._compile = params.has_key("compile")
1203        self._text = params.get("text", "")#.strip()
1204
1205    def _getCompiledMinutes( self ):
1206        minutes = []
1207        isHTML = False
1208        cList = self._target.getContributionList()
1209        cList.sort(sortContributionByDate)
1210        for c in cList:
1211            if c.getMinutes():
1212                minText = c.getMinutes().getText()
1213                minutes.append([c.getTitle(),minText])
1214                if isStringHTML(minText):
1215                    isHTML = True
1216        if isHTML:
1217            lb = "<br>"
1218        else:
1219            lb = "\n"
1220        text = "%s (%s)%s" % (self._target.getTitle(), self._target.getStartDate().strftime("%d %b %Y"), lb)
1221        part = self._target.getParticipation().getPresentParticipantListText()
1222        if part != "":
1223            text += "Present: %s%s" % (part,lb)
1224        uList = self._target.getChairList()
1225        chairs = ""
1226        for chair in uList:
1227            if chairs != "":
1228                chairs += "; "
1229            chairs += chair.getFullName()
1230        if len(uList) > 0:
1231            text += "Chaired by: %s%s%s" % (chairs, lb, lb)
1232        for min in minutes:
1233            text += "==================%s%s%s==================%s%s%s%s" % (lb,min[0],lb,lb,min[1],lb,lb)
1234        return text
1235
1236    def _process( self ):
1237        wf=self.getWebFactory()
1238        if self._compile:
1239            minutes = self._target.getMinutes()
1240            if not minutes:
1241                minutes = self._target.createMinutes()
1242            text = self._getCompiledMinutes()
1243            minutes.setText( text )
1244        if self._save:
1245            minutes = self._target.getMinutes()
1246            if not minutes:
1247                minutes = self._target.createMinutes()
1248            minutes.setText( self._text )
1249        elif not self._cancel:
1250            if wf is None:
1251                wp = conferences.WPConfDisplayWriteMinutes(self, self._target)
1252            else:
1253                wp = wf.getConferenceDisplayWriteMinutes( self, self._conf)
1254            return wp.display()
1255        self._redirect( urlHandlers.UHConferenceDisplay.getURL( self._target ) )
1256
1257
1258class RHInternalPageDisplay(RHConferenceBaseDisplay):
1259    _uh=urlHandlers.UHInternalPageDisplay
1260
1261    def _checkParams(self,params):
1262        RHConferenceBaseDisplay._checkParams(self,params)
1263        if params.has_key("pageId"):
1264            pageId=params.get("pageId")
1265            intPagesMgr=internalPagesMgr.InternalPagesMgrRegistery().getInternalPagesMgr(self._conf)
1266            self._page=intPagesMgr.getPageById(pageId)
1267            self._target = self._page
1268            if self._page is None:
1269                raise MaKaCError( _("The webpage, you are trying to access, does not exist"))
1270        else:
1271            raise MaKaCError( _("The webpage, you are trying to access, does not exist"))
1272
1273    def _checkProtection(self):
1274        if not self._conf.canView( self.getAW() ):
1275            from MaKaC.conference import Link,LocalFile
1276
1277            if self._conf.getAccessKey() != "":
1278                raise AccessError()
1279            if self._getUser() == None:
1280                self._checkSessionUser()
1281            else:
1282                raise AccessError()
1283
1284    def _process( self ):
1285        p=conferences.WPInternalPageDisplay(self,self._conf, self._page)
1286        return p.display()
1287
1288class RHConferenceLatexPackage(RHConferenceBaseDisplay):
1289
1290    def _process( self ):
1291        #return "nothing"
1292        filename = "%s-BookOfAbstracts.zip"%cleanHTMLHeaderFilename(self._target.getTitle())
1293        zipdata = StringIO.StringIO()
1294        zip = zipfile.ZipFile(zipdata, "w")
1295        for cont in self._target.getContributionList():
1296            f = []
1297            f.append("""\\section*{%s}"""%cont.getTitle())
1298            f.append(" ")
1299            l = []
1300            affil = {}
1301            i = 1
1302            for pa in cont.getPrimaryAuthorList():
1303                if pa.getAffiliation() in affil.keys():
1304                    num = affil[pa.getAffiliation()]
1305                else:
1306                    affil[pa.getAffiliation()] = i
1307                    num = i
1308                    i += 1
1309
1310                l.append("""\\noindent \\underline{%s}$^%d$"""%(pa.getFullName(), num))
1311
1312            for ca in cont.getCoAuthorList():
1313                if ca.getAffiliation() in affil.keys():
1314                    num = affil[ca.getAffiliation()]
1315                else:
1316                    affil[ca.getAffiliation()] = i
1317                    num = i
1318                    i += 1
1319                l.append("""%s$^%d$"""%(ca.getFullName(), num))
1320
1321            f.append(",\n".join(l))
1322            f.append("\n")
1323            l = []
1324            for key in affil.keys():
1325                l.append("""$^%d$%s"""%(affil[key], key))
1326            f.append("\\noindent " + ",\n".join(l))
1327            f.append("\n")
1328            f.append("""\\noindent %s"""%cont.getDescription())
1329            zip.writestr("contribution-%s"%cont.getId(), "\n".join(f))
1330        zip.close()
1331        data = zipdata.getvalue()
1332        zipdata.close()
1333
1334        #self._req.headers_out["Accept-Ranges"] = "bytes"
1335        self._req.headers_out["Content-Length"] = "%s"%len(data)
1336        cfg = Config.getInstance()
1337        mimetype = cfg.getFileTypeMimeType( "ZIP" )
1338        #self._req.content_type = """%s; name="%s\""""%(mimetype, filename )
1339        self._req.content_type = """%s"""%(mimetype)
1340        self._req.headers_out["Content-Disposition"] = """inline; filename="%s\""""%filename
1341        return data
1342
1343
1344class RHFullMaterialPackage(RHConferenceBaseDisplay):
1345    _uh=urlHandlers.UHConferenceDisplayMaterialPackage
1346
1347    def _checkParams( self, params ):
1348        RHConferenceBaseDisplay._checkParams( self, params )
1349        self._errors = params.get("errors","")
1350
1351    def _process( self ):
1352
1353        wf = self.getWebFactory()
1354        if wf!=None : #Event == Meeting/Lecture
1355            p = wf.getDisplayFullMaterialPackage(self,self._target)
1356        else : #Event == Conference
1357            p = conferences.WPDisplayFullMaterialPackage(self,self._target)
1358        return p.display(errors=self._errors)
1359
1360
1361
1362
1363class RHFullMaterialPackagePerform(RHConferenceBaseDisplay):
1364    _uh=urlHandlers.UHConferenceDisplayMaterialPackagePerform
1365
1366    def _checkParams( self, params ):
1367        RHConferenceBaseDisplay._checkParams( self, params )
1368        self._days=self._normaliseListParam(params.get("days",[]))
1369        self._mainResource = (params.get("mainResource","") != "")
1370        self._fromDate = ""
1371        fromDay = params.get("fromDay","")
1372        fromMonth = params.get("fromMonth","")
1373        fromYear = params.get("fromYear","")
1374        if fromDay != "" and fromMonth != "" and fromYear != "" and \
1375           fromDay != "dd" and fromMonth != "mm" and fromYear != "yyyy":
1376            self._fromDate = "%s %s %s"%(fromDay, fromMonth, fromYear)
1377        self._cancel = params.has_key("cancel")
1378        self._materialTypes=self._normaliseListParam(params.get("materialType",[]))
1379        self._sessionList = self._normaliseListParam(params.get("sessionList",[]))
1380
1381    def _process( self ):
1382        if not self._cancel:
1383            if self._materialTypes != []:
1384                p=ConferencePacker(self._conf, self._aw)
1385                path=p.pack(self._materialTypes, self._days, self._mainResource, self._fromDate, ZIPFileHandler(),self._sessionList)
1386                filename = "full-material.zip"
1387                cfg = Config.getInstance()
1388                mimetype = cfg.getFileTypeMimeType( "ZIP" )
1389                self._req.content_type = """%s"""%(mimetype)
1390                self._req.headers_out["Content-Disposition"] = """inline; filename="%s\""""%filename
1391                self._req.sendfile(path)
1392            else:
1393                url = urlHandlers.UHConferenceDisplayMaterialPackage.getURL(self._conf)
1394                url.addParam("errors", "You have to select at least one material type")
1395                self._redirect( url )
1396        else:
1397            self._redirect( urlHandlers.UHConferenceDisplay.getURL( self._conf ) )
1398
1399
1400class RHShortURLRedirect(RH):
1401
1402    def _checkParams( self, params ):
1403        self._tag = params.get("tag", "").strip()
1404
1405    def _process(self):
1406        from MaKaC.conference import ConferenceHolder
1407        ch = ConferenceHolder()
1408        from MaKaC.common.url import ShortURLMapper
1409        sum = ShortURLMapper()
1410        if ch.hasKey(self._tag):
1411            conf = ch.getById(self._tag)
1412            self._redirect(urlHandlers.UHConferenceDisplay.getURL(conf))
1413        elif sum.hasKey(self._tag):
1414            conf = sum.getById(self._tag)
1415            self._redirect(urlHandlers.UHConferenceDisplay.getURL(conf))
1416        else:
1417            raise MaKaCError("Bad event tag or Id : \"%s\""%self._tag)
1418
Note: See TracBrowser for help on using the repository browser.