source: indico/indico/MaKaC/webinterface/rh/conferenceDisplay.py @ 3df18a

burotelhello-world-walkthroughipv6v0.98-seriesv0.98.2v0.98.3v0.98b1v0.98b2v0.99v1.0v1.1
Last change on this file since 3df18a was 0951a8, checked in by Jose Benito <jose.benito.gonzalez@…>, 3 years ago

[FIX] Do not pass infoMsg/errorMsg in url

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