source: indico/indico/MaKaC/webinterface/rh/conferenceDisplay.py @ ef8b79d

hello-world-walkthroughipv6v0.98-seriesv0.98.2v0.98.3v0.98b2v0.99v1.0v1.1
Last change on this file since ef8b79d was ef8b79d, checked in by Jose Benito <jose.benito.gonzalez@…>, 21 months ago

[REF] Use a less-crappy way to throw errors

  • unfortunately it's also less user-friendly
  • Property mode set to 100644
File size: 59.5 KB
Line 
1
2# -*- coding: utf-8 -*-
3##
4##
5## This file is part of CDS Indico.
6## Copyright (C) 2002, 2003, 2004, 2005, 2006, 2007 CERN.
7##
8## CDS Indico is free software; you can redistribute it and/or
9## modify it under the terms of the GNU General Public License as
10## published by the Free Software Foundation; either version 2 of the
11## License, or (at your option) any later version.
12##
13## CDS Indico is distributed in the hope that it will be useful, but
14## WITHOUT ANY WARRANTY; without even the implied warranty of
15## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
16## General Public License for more details.
17##
18## You should have received a copy of the GNU General Public License
19## along with CDS Indico; if not, write to the Free Software Foundation, Inc.,
20## 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA.
21from datetime import timedelta,datetime, time
22import os, re, 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, WPError404
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, KeyAccessError, NotFoundError
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        minfo = info.HelperMaKaCInfo.getMaKaCInfoInstance()
215        self._params["msg"] = ""
216        if self._save:
217            save = True
218            #check submited data
219            if not self._params.get("name",""):
220                self._params["msg"] += _("You must enter a name.")+"<br>"
221                save = False
222            if not self._params.get("surName",""):
223                self._params["msg"] += _("You must enter a surname.")+"<br>"
224                save = False
225            if not self._params.get("organisation",""):
226                self._params["msg"] += _("You must enter the name of your organisation.")+"<br>"
227                save = False
228            if not self._params.get("email",""):
229                self._params["msg"] += _("You must enter an email address.")+"<br>"
230                save = False
231            if not self._params.get("login",""):
232                self._params["msg"] += _("You must enter a login.")+"<br>"
233                save = False
234            if not self._params.get("password",""):
235                self._params["msg"] += _("You must define a password.")+"<br>"
236                save = False
237            if self._params.get("password","") != self._params.get("passwordBis",""):
238                self._params["msg"] += _("You must enter the same password twice.")+"<br>"
239                save = False
240            if not ih.isLoginFree(self._params.get("login","")):
241                self._params["msg"] += _("Sorry, the login you requested is already in use. Please choose another one.")+"<br>"
242                save = False
243            if not self._validMail(self._params.get("email","")):
244                self._params["msg"] += _("You must enter a valid email address")
245                save = False
246        if save:
247            #Data are OK, Now check if there is an existing user or create a new one
248            ah = user.AvatarHolder()
249            res =  ah.match({"email": self._params["email"]}, exact=1, forceWithoutExtAuth=True)
250            if res:
251                #we find a user with the same email
252                a = res[0]
253                #check if the user have an identity:
254                if a.getIdentityList():
255                    self._redirect( urlHandlers.UHConfUserExistWithIdentity.getURL( self._conf, a))
256                    return
257                else:
258                    #create the identity to the user and send the comfirmatio email
259                    li = user.LoginInfo( self._params["login"], self._params["password"] )
260                    id = ih.createIdentity( li, a, "Local" )
261                    ih.add( id )
262                    DBMgr.getInstance().commit()
263                    if minfo.getModerateAccountCreation():
264                        mail.sendAccountCreationModeration(a).send()
265                    else:
266                        mail.sendConfirmationRequest(a).send()
267                        if minfo.getNotifyAccountCreation():
268                            mail.sendAccountCreationNotification(a).send()
269            else:
270                a = user.Avatar()
271                _UserUtils.setUserData( a, self._params )
272                ah.add(a)
273                li = user.LoginInfo( self._params["login"], self._params["password"] )
274                id = ih.createIdentity( li, a, "Local" )
275                ih.add( id )
276                DBMgr.getInstance().commit()
277                if minfo.getModerateAccountCreation():
278                    mail.sendAccountCreationModeration(a).send()
279                else:
280                    mail.sendConfirmationRequest(a).send()
281                    if minfo.getNotifyAccountCreation():
282                        mail.sendAccountCreationNotification(a).send()
283            self._redirect( urlHandlers.UHConfUserCreated.getURL( self._conf, a ) )
284        else:
285            p = conferences.WPConfUserCreation( self, self._conf, self._params )
286            return p.display()
287
288    def _validMail(self,email):
289        if re.search("^[a-zA-Z][\w\.-]*[a-zA-Z0-9]@[a-zA-Z0-9][\w\.-]*[a-zA-Z0-9]\.[a-zA-Z][a-zA-Z\.]*[a-zA-Z]$",email):
290            return True
291        return False
292
293class RHConfUserCreated( conferenceBase.RHConferenceBase ):
294
295    def _checkParams( self, params ):
296        conferenceBase.RHConferenceBase._checkParams( self, params )
297        self._av = user.AvatarHolder().getById(params["userId"])
298
299    def _process( self ):
300        p = conferences.WPConfUserCreated( self, self._conf, self._av )
301        return p.display()
302
303
304class RHConfActivate( conferenceBase.RHConferenceBase ):
305
306    def _checkParams( self, params ):
307        conferenceBase.RHConferenceBase._checkParams(self, params )
308        self._userId = params.get( "userId", "" ).strip()
309        self._key = params.get( "key", "" ).strip()
310        self._returnURL = params.get( "returnURL", "").strip()
311
312
313    def _process( self ):
314        av = user.AvatarHolder().getById(self._userId)
315        if av.isActivated():
316            p = conferences.WPConfAccountAlreadyActivated( self, self._conf, av )
317            return p.display()
318            #return "your account is already activated"
319        if av.isDisabled():
320            p = conferences.WPConfAccountDisabled( self, self._conf, av )
321            return p.display()
322            #return "your account is disabled. please, ask to enable it"
323        elif self._key == av.getKey():
324            av.activateAccount()
325            p = conferences.WPConfAccountActivated( self, self._conf, av, self._returnURL )
326            return p.display()
327            #return "Your account is activate now"
328        else:
329            return "Wrong key. Please, ask for a new one"
330
331
332class RHConfUserExistWithIdentity( conferenceBase.RHConferenceBase ):
333
334    def _checkParams( self, params ):
335        conferenceBase.RHConferenceBase._checkParams( self, params )
336        self._av = user.AvatarHolder().getById(params["userId"])
337
338    def _process( self ):
339        p = conferences.WPConfUserExistWithIdentity( self, self._conf, self._av )
340        return p.display()
341
342
343class RHConfSendLogin( conferenceBase.RHConferenceBase ):
344
345    def _checkParams( self, params ):
346        conferenceBase.RHConferenceBase._checkParams( self, params )
347        self._userId = params.get( "userId", "" ).strip()
348        self._email = params.get("email", "").strip()
349
350    def _process( self ):
351        av = None
352        if self._userId != "":
353            av = user.AvatarHolder().getById(self._userId)
354        elif self._email != "":
355            try:
356                av = user.AvatarHolder().match({"email":self._email})[0]
357            except IndexError:
358                pass
359        if av:
360            sm = mail.sendLoginInfo(av)
361            sm.send()
362        self._redirect(urlHandlers.UHConfSignIn.getURL( self._conf ))
363
364
365class RHConferenceBaseDisplay( RHConferenceBase, RHDisplayBaseProtected ):
366
367    def _checkParams( self, params ):
368        RHConferenceBase._checkParams( self, params )
369
370    def _checkProtection( self ):
371
372        from MaKaC.webinterface.rh.collaboration import RCCollaborationAdmin, RCCollaborationPluginAdmin
373        if not RCCollaborationAdmin.hasRights(self, None) and \
374            not RCCollaborationPluginAdmin.hasRights(self, plugins = "any"):
375            RHDisplayBaseProtected._checkProtection( self )
376
377
378class RHConferenceDisplay( RoomBookingDBMixin, RHConferenceBaseDisplay ):
379    _uh = urlHandlers.UHConferenceDisplay
380
381    def _process( self ):
382        params = self._getRequestParams()
383        #set default variables
384        if not self._reqParams.has_key("showDate"):
385            self._reqParams["showDate"] = "all"
386        if not self._reqParams.has_key("showSession"):
387            self._reqParams["showSession"] = "all"
388        if not self._reqParams.has_key("detailLevel"):
389            self._reqParams["detailLevel"] = "contribution"
390        #get default/selected view
391        view = "static"
392        wf = self.getWebFactory()
393        if wf != None:
394            type = self.getWebFactory().getId()
395        else:
396            type = "conference"
397        styleMgr = info.HelperMaKaCInfo.getMaKaCInfoInstance().getStyleManager()
398        if self._reqParams.has_key("view"):
399            view = self._reqParams["view"]
400        else:
401            view = displayMgr.ConfDisplayMgrRegistery().getDisplayMgr(self._target).getDefaultStyle()
402            # if no default view was attributed, then get the configuration default
403            if view == "" or not styleMgr.existsStyle(view):
404                view =styleMgr.getDefaultStyleForEventType( type )
405                displayMgr.ConfDisplayMgrRegistery().getDisplayMgr(self._target).setDefaultStyle( view )
406        isLibxml = True
407        warningText = ""
408        try:
409            import lxml
410        except:
411            isLibxml = False
412
413        # create the html factory
414        if type == "conference":
415            if params.get("ovw", False):
416                p = conferences.WPConferenceDisplay( self, self._target )
417            else:
418                self._page = None
419                intPagesMgr=internalPagesMgr.InternalPagesMgrRegistery().getInternalPagesMgr(self._target)
420                for page in intPagesMgr.getPagesList():
421                    if page.isHome():
422                        self._page = page
423                if not self._page:
424                    p = conferences.WPConferenceDisplay( self, self._target )
425                else:
426                    p = conferences.WPInternalPageDisplay(self,self._target, self._page)
427        elif view in styleMgr.getXSLStyles():
428            if not isLibxml:
429                warningText = "lxml needs to be installed if you want to use a stylesheet-driven display - switching to static display"
430            self._req.content_type = "text/xml"
431            p = conferences.WPXSLConferenceDisplay( self, self._target, view, type, self._reqParams )
432        elif view != "static":
433            p = conferences.WPTPLConferenceDisplay( self, self._target, view, type, self._reqParams )
434        else:
435            if wf != None:
436                p = wf.getConferenceDisplayPage( self, self._target, self._reqParams )
437            else:
438                p = conferences.WPConferenceDisplay( self, self._target )
439        # generate the html
440
441        return warningText + p.display(**params)
442
443
444class RHConferenceOtherViews( RoomBookingDBMixin, RHConferenceBaseDisplay ):
445    """this class is for the conference type objects only
446    it is an alternative to the standard TimeTable view"""
447    _uh = urlHandlers.UHConferenceOtherViews
448
449    def _process( self ):
450        #set default variables
451        if not self._reqParams.has_key("showDate"):
452            self._reqParams["showDate"] = "all"
453        if not self._reqParams.has_key("showSession"):
454            self._reqParams["showSession"] = "all"
455        if not self._reqParams.has_key("detailLevel"):
456            self._reqParams["detailLevel"] = "contribution"
457        #get default/selected view
458        view = "standard"
459        type = "conference"
460        styleMgr = info.HelperMaKaCInfo.getMaKaCInfoInstance().getStyleManager()
461        isLibxml = True
462        try:
463            import lxml
464        except:
465            isLibxml = False
466        if self._reqParams.has_key("view"):
467            view = self._reqParams["view"]
468        else:
469            view = displayMgr.ConfDisplayMgrRegistery().getDisplayMgr(self._target).getDefaultStyle()
470            # if no default view was attributed, then get the configuration default
471            if view == "":
472                view =styleMgr.getDefaultStyleForEventType( type )
473                displayMgr.ConfDisplayMgrRegistery().getDisplayMgr(self._target).setDefaultStyle( view )
474        # create the html factory
475        if view in styleMgr.getXSLStyles() and isLibxml:
476            p = conferences.WPXSLConferenceDisplay( self, self._target, view, type, self._reqParams )
477        elif view != "static":
478            p = conferences.WPTPLConferenceDisplay( self, self._target, view, type, self._reqParams )
479        else:
480            p = conferences.WPMeetingTimeTable( self, self._target,"parallel","meeting",self._reqParams )
481        # generate the html
482        if view == "xml" and self._reqParams.get('fr') == 'no':
483            self._req.content_type = "text/xml"
484        return p.display()
485
486
487class RHConferenceGetLogo(RHConferenceBaseDisplay):
488
489    def _process(self):
490        logo=self._target.getLogo()
491        self._req.headers_out["Content-Length"]="%s"%logo.getSize()
492        cfg=Config.getInstance()
493        mimetype=cfg.getFileTypeMimeType(logo.getFileType())
494        self._req.content_type="""%s"""%(mimetype)
495        self._req.headers_out["Content-Disposition"]="""inline; filename="%s\""""%cleanHTMLHeaderFilename(logo.getFileName())
496        return self._target.getLogo().readBin()
497
498
499class RHConferenceGetCSS(RHConferenceBaseDisplay):
500
501    """
502    CSS which is used just for a conference.
503    """
504
505    def _process(self):
506        sm = displayMgr.ConfDisplayMgrRegistery().getDisplayMgr(self._conf).getStyleManager()
507        css=sm.getLocalCSS()
508        if css:
509            self._req.headers_out["Content-Length"]="%s"%css.getSize()
510            self._req.content_type="text/css"
511            self._req.headers_out["Content-Disposition"]="""inline; filename="%s\""""%css.getFileName()
512            return css.readBin()
513
514        return ""
515
516
517class RHConferenceGetPic(RHConferenceBaseDisplay):
518
519    def _checkParams(self, params):
520        RHConferenceBaseDisplay._checkParams( self, params )
521        self._picId = params.get("picId","")
522
523    def _process(self):
524        im = displayMgr.ConfDisplayMgrRegistery().getDisplayMgr(self._conf).getImagesManager()
525        if im.getPic(self._picId):
526            pic=im.getPic(self._picId).getLocalFile()
527            self._req.headers_out["Content-Length"]="%s"%pic.getSize()
528            cfg=Config.getInstance()
529            mimetype=cfg.getFileTypeMimeType(pic.getFileType())
530            self._req.content_type="""%s"""%(mimetype)
531            self._req.headers_out["Content-Disposition"]="""inline; filename="%s\""""%pic.getFileName()
532            return pic.readBin()
533        else:
534            from indico.web.wsgi import webinterface_handler_config as apache
535            self._req.status = apache.HTTP_NOT_FOUND
536            return WPError404(self, urlHandlers.UHConferenceDisplay.getURL(self._conf)).display()
537
538
539class RHConferenceEmail(RHConferenceBaseDisplay, base.RHProtected):
540    _uh = urlHandlers.UHConferenceEmail
541
542    def _checkProtection(self):
543        base.RHProtected._checkProtection(self)
544
545    def _checkParams( self, params ):
546        RHConferenceBaseDisplay._checkParams( self, params )
547        self._auth = params.has_key("authId")
548        self._chair = params.has_key("chairId")
549        if params.has_key("contribId"):
550            contrib = self._conf.getContributionById(params.get("contribId",""))
551        if self._chair:
552            chairid=params.get("chairId","")
553            chair = self._conf.getChairById(chairid)
554            if chair == None:
555                raise NotFoundError(_("The chair you try to email does not exist."))
556            self._emailto = chair.getEmail()
557        if self._auth:
558            authid=params.get("authId","")
559            if not contrib:
560                raise MaKaCError(_("The author's contribution does not exist anymore."))
561            author = contrib.getAuthorById(authid)
562            if author == None:
563                raise NotFoundError(_("The author you try to email does not exist."))
564            self._emailto = author
565
566    def _process(self):
567        postURL = urlHandlers.UHConferenceSendEmail.getURL(self._emailto)
568        p=conferences.WPEMail(self, self._target)
569        return p.display(emailto=[self._emailto], postURL=postURL)
570
571class RHConferenceSendEmail (RHConferenceBaseDisplay, base.RHProtected):
572    _uh = urlHandlers.UHConferenceSendEmail
573
574    def _checkProtection(self):
575        base.RHProtected._checkProtection(self)
576
577    def _checkParams(self, params):
578        RHConferenceBaseDisplay._checkParams( self, params )
579        if params.has_key("contribId"):
580            contrib = self._conf.getContributionById(params.get("contribId",""))
581        if params.has_key("chairId"):
582            chairid=params.get("chairId","")
583            self._to = self._conf.getChairById(chairid).getEmail()
584        if params.has_key("authId"):
585            authid=params.get("authId","")
586            self._to = contrib.getAuthorById(authid).getEmail()
587        fromId = params.get("from","")
588        self._from = (user.AvatarHolder()).getById(fromId).getEmail()
589        self._cc = self._from
590        self._subject=params.get("subject","")
591        self._body = params.get("body","")
592        self._send = params.has_key("OK")
593
594    def _process(self):
595        if self._send:
596            mail.personMail.send(self._to, self._cc, self._from,self._subject,self._body)
597            p = conferences.WPSentEmail(self, self._target)
598            return p.display()
599        else:
600            self._redirect(urlHandlers.UHConferenceDisplay.getURL(self._conf))
601
602
603
604class RHConferenceProgram( RHConferenceBaseDisplay ):
605    _uh = urlHandlers.UHConferenceProgram
606
607    def _checkParams( self, params ):
608        RHConferenceBaseDisplay._checkParams( self, params )
609        self._xs = self._normaliseListParam( params.get("xs", []) )
610
611
612    def _process( self ):
613        p = conferences.WPConferenceProgram( self, self._target )
614        return p.display( xs = self._xs )
615
616
617class RHConferenceProgramPDF( RHConferenceBaseDisplay ):
618
619    def _process( self ):
620        tz = timezoneUtils.DisplayTZ(self._aw,self._target).getDisplayTZ()
621        filename = "%s - Programme.pdf"%cleanHTMLHeaderFilename(self._target.getTitle())
622        from MaKaC.PDFinterface.conference import ProgrammeToPDF
623        pdf = ProgrammeToPDF(self._target, tz=tz)
624        data = pdf.getPDFBin()
625        #self._req.headers_out["Accept-Ranges"] = "bytes"
626        self._req.headers_out["Content-Length"] = "%s"%len(data)
627        cfg = Config.getInstance()
628        mimetype = cfg.getFileTypeMimeType( "PDF" )
629        #self._req.content_type = """%s; name="%s\""""%(mimetype, filename )
630        self._req.content_type = """%s"""%(mimetype)
631        self._req.headers_out["Content-Disposition"] = """inline; filename="%s\""""%filename.replace("\r\n"," ")
632        return data
633
634class RHConferenceTimeTable( RoomBookingDBMixin, RHConferenceBaseDisplay ):
635    _uh = urlHandlers.UHConferenceTimeTable
636
637    def _process( self ):
638        defStyle = displayMgr.ConfDisplayMgrRegistery().getDisplayMgr(self._target).getDefaultStyle()
639        if defStyle in ["", "static", "parallel"]:
640            p = conferences.WPConferenceTimeTable( self, self._target )
641            return p.display( **self._getRequestParams() )
642        else:
643            url = urlHandlers.UHConferenceOtherViews.getURL( self._conf )
644            url.addParam("view", defStyle)
645            self._redirect(url)
646
647
648class RHTimeTablePDF(RHConferenceTimeTable):
649
650    fontsizes = ['xxx-small', 'xx-small', 'x-small', 'smaller', 'small', 'normal', 'large', 'larger']
651
652    def _checkParams(self,params):
653        RHConferenceTimeTable._checkParams(self,params)
654        self._showSessions=self._normaliseListParam(params.get("showSessions",[]))
655        if "all" in self._showSessions:
656            self._showSessions.remove("all")
657        self._showDays=self._normaliseListParam(params.get("showDays",[]))
658        if "all" in self._showDays:
659            self._showDays.remove("all")
660        self._sortingCrit=None
661        if params.has_key("sortBy") and params["sortBy"].strip()!="":
662            self._sortingCrit=contribFilters.SortingCriteria([params.get( "sortBy", "number").strip()])
663        self._pagesize = params.get('pagesize','A4')
664        self._fontsize = params.get('fontsize','normal')
665        try:
666            self._firstPageNumber = int(params.get('firstPageNumber','1'))
667        except ValueError:
668            self._firstPageNumber = 1
669        self._showSpeakerAffiliation = False
670        if params.has_key("showSpeakerAffiliation"):
671            self._showSpeakerAffiliation = True
672        # Keep track of the used layout for getting back after cancelling
673        # the export.
674        self._view = params.get("view", displayMgr.ConfDisplayMgrRegistery().getDisplayMgr(self._target).getDefaultStyle())
675
676    def _reduceFontSize( self ):
677        index = self.fontsizes.index(self._fontsize)
678        if index > 0:
679            self._fontsize = self.fontsizes[index-1]
680            return True
681        return False
682
683    def _process(self):
684        tz = timezoneUtils.DisplayTZ(self._aw,self._target).getDisplayTZ()
685        params = self._getRequestParams()
686        ttPDFFormat=TimetablePDFFormat(params)
687
688        # Choose action depending on the button pressed
689        if params.has_key("cancel"):
690            # If the export is cancelled, redirect to the display
691            # page
692            url = urlHandlers.UHConferenceDisplay.getURL(self._conf)
693            url.addParam("view", self._view)
694            self._redirect(url)
695        else :
696            retry = True
697            while retry:
698                if params.get("typeTT","normalTT")=="normalTT":
699                    filename = "timetable.pdf"
700                    pdf = TimeTablePlain(self._target,self.getAW(),
701                            showSessions=self._showSessions,showDays=self._showDays,
702                            sortingCrit=self._sortingCrit, ttPDFFormat=ttPDFFormat,
703                            pagesize = self._pagesize, fontsize = self._fontsize,
704                            firstPageNumber = self._firstPageNumber,
705                            showSpeakerAffiliation = self._showSpeakerAffiliation)
706                else:
707                    filename = "SimplifiedTimetable.pdf"
708                    pdf = SimplifiedTimeTablePlain(self._target,self.getAW(),
709                        showSessions=self._showSessions,showDays=self._showDays,
710                        sortingCrit=self._sortingCrit, ttPDFFormat=ttPDFFormat,
711                        pagesize = self._pagesize, fontsize = self._fontsize)
712                try:
713                    data=pdf.getPDFBin()
714                    retry = False
715                except LayoutError, e:
716                    if not self._reduceFontSize():
717                        raise MaKaCError("Error in PDF generation - One of the paragraphs does not fit on a page")
718                except Exception:
719                    raise
720
721    ##        tries = 5
722    ##        while tries:
723    ##            if params.get("typeTT","normalTT")=="normalTT":
724    ##                filename = "timetable.pdf"
725    ##                pdf = TimeTablePlain(self._target,self.getAW(),
726    ##                        showSessions=self._showSessions,showDays=self._showDays,
727    ##                        sortingCrit=self._sortingCrit, ttPDFFormat=ttPDFFormat,
728    ##                        pagesize = self._pagesize, fontsize = self._fontsize, firstPageNumber = self._firstPageNumber, tz=tz)
729    ##            else:
730    ##                filename = "SimplifiedTimetable.pdf"
731    ##                pdf = SimplifiedTimeTablePlain(self._target,self.getAW(),
732    ##                    showSessions=self._showSessions,showDays=self._showDays,
733    ##                    sortingCrit=self._sortingCrit, ttPDFFormat=ttPDFFormat,
734    ##                    pagesize = self._pagesize, fontsize = self._fontsize, tz=tz)
735    ##            try:
736    ##                data=pdf.getPDFBin()
737    ##                tries = 0
738    ##            except LayoutError, e:
739    ##                if self._reduceFontSize():
740    ##                    tries -= 1
741    ##                else:
742    ##                    tries = 0
743    ##                    raise MaKaCError(str(e))
744
745            self._req.headers_out["Content-Length"] = "%s"%len(data)
746            cfg=Config.getInstance()
747            mimetype=cfg.getFileTypeMimeType("PDF")
748            self._req.content_type = """%s"""%(mimetype)
749            self._req.headers_out["Content-Disposition"]="""inline; filename="%s\""""%filename
750            return data
751
752class RHTimeTableCustomizePDF(RHConferenceTimeTable):
753
754    def _checkParams(self,params):
755        RHConferenceTimeTable._checkParams(self,params)
756        self._cancel = params.has_key("cancel")
757        self._view = params.get("view", "standard")
758
759    def _process(self):
760        # TODO: why not construct p this way only if wf == None?
761        p=conferences.WPTimeTableCustomizePDF(self, self._target)
762        wf = self.getWebFactory()
763        if wf != None:
764            p=wf.getTimeTableCustomizePDF(self, self._target, self._view)
765        return p.display(**self._getRequestParams())
766
767
768class _HideWithdrawnFilterField(filters.FilterField):
769    """
770    """
771    _id = "hide_withdrawn"
772
773    def __init__(self,conf,values):
774        pass
775
776    def satisfies(self,contribution):
777        """
778        """
779        return not isinstance(contribution.getCurrentStatus(),conference.ContribStatusWithdrawn)
780
781
782class ContributionsFilterCrit(filters.FilterCriteria):
783    _availableFields = { \
784        contribFilters.TypeFilterField.getId():contribFilters.TypeFilterField, \
785        contribFilters.TrackFilterField.getId():contribFilters.TrackFilterField, \
786        contribFilters.SessionFilterField.getId():contribFilters.SessionFilterField, \
787        _HideWithdrawnFilterField.getId(): _HideWithdrawnFilterField
788                }
789
790
791class RHContributionList( RHConferenceBaseDisplay ):
792    _uh = urlHandlers.UHContributionList
793
794    def _checkParams( self, params ):
795        RHConferenceBaseDisplay._checkParams( self, params )
796        # Sorting
797        self._sortingCrit=contribFilters.SortingCriteria( [params.get( "sortBy", "number").strip()] )
798        self._order = params.get("order","down")
799        # Filtering
800        filterUsed = params.has_key( "OK" ) # this variable is true when the
801                                            # filter has been used
802        filter = {"hide_withdrawn": True}
803        ltypes = []
804        if not filterUsed:
805            for type in self._conf.getContribTypeList():
806                ltypes.append( type.getId() )
807        else:
808            for id in self._normaliseListParam( params.get("selTypes", []) ):
809                ltypes.append(id)
810        filter["type"] = ltypes
811
812        ltracks = []
813        if not filterUsed:
814            for track in self._conf.getTrackList():
815                ltracks.append( track.getId() )
816        filter["track"] = self._normaliseListParam( params.get("selTracks", ltracks) )
817
818        lsessions = []
819        if not filterUsed:
820            for session in self._conf.getSessionList():
821                lsessions.append( session.getId() )
822        filter["session"] = self._normaliseListParam( params.get("selSessions", lsessions) )
823
824        self._filterCrit=ContributionsFilterCrit(self._conf,filter)
825        typeShowNoValue, trackShowNoValue, sessionShowNoValue = True, True, True
826        if filterUsed:
827            if self._conf.getContribTypeList():
828                typeShowNoValue =  params.has_key("typeShowNoValue")
829            if self._conf.getTrackList():
830                trackShowNoValue =  params.has_key("trackShowNoValue")
831            if self._conf.getSessionList():
832                sessionShowNoValue =  params.has_key("sessionShowNoValue")
833        self._filterCrit.getField("type").setShowNoValue( typeShowNoValue )
834        self._filterCrit.getField("track").setShowNoValue( trackShowNoValue )
835        self._filterCrit.getField("session").setShowNoValue( sessionShowNoValue )
836        self._sc=params.get("sc",1)
837        self._nc=params.get("nc",20)
838
839
840    def _process( self ):
841        p = conferences.WPContributionList( self, self._target )
842        return p.display(sortingCrit = self._sortingCrit, filterCrit = self._filterCrit, sc=self._sc, nc=self._nc, order=self._order)
843
844
845class RHAuthorIndex(RHConferenceBaseDisplay):
846    _uh=urlHandlers.UHConfAuthorIndex
847
848    def _checkParams( self, params ):
849        RHConferenceBaseDisplay._checkParams( self, params )
850        self._view=params.get("view","full")
851        self._letter=params.get("letter","a")
852
853    def _process(self):
854        p=conferences.WPAuthorIndex(self,self._target)
855        return p.display(viewMode=self._view,selLetter=self._letter)
856
857class RHSpeakerIndex(RHConferenceBaseDisplay):
858    _uh=urlHandlers.UHConfAuthorIndex
859
860    def _checkParams( self, params ):
861        RHConferenceBaseDisplay._checkParams( self, params )
862        self._view=params.get("view","full")
863        self._letter=params.get("letter","a")
864
865    def _process(self):
866        p=conferences.WPSpeakerIndex(self,self._target)
867        return p.display(viewMode=self._view,selLetter=self._letter)
868
869class RHMyStuff(RHConferenceBaseDisplay,base.RHProtected):
870    _uh=urlHandlers.UHConfMyStuff
871
872    def _checkProtection(self):
873        base.RHProtected._checkProtection(self)
874
875    def _process(self):
876        p=conferences.WPMyStuff(self,self._target)
877        return p.display()
878
879class RHConfMyStuffMySessions(RHConferenceBaseDisplay,base.RHProtected):
880    _uh=urlHandlers.UHConfMyStuffMySessions
881
882    def _checkProtection(self):
883        base.RHProtected._checkProtection(self)
884
885    def _process(self):
886        p=conferences.WPConfMyStuffMySessions(self,self._target)
887        return p.display()
888
889class RHConfMyStuffMyContributions(RHConferenceBaseDisplay,base.RHProtected):
890    _uh=urlHandlers.UHConfMyStuffMyContributions
891
892    def _checkProtection(self):
893        base.RHProtected._checkProtection(self)
894
895    def _process(self):
896        p=conferences.WPConfMyStuffMyContributions(self,self._target)
897        return p.display()
898
899class RHConfMyStuffMyTracks(RHConferenceBaseDisplay,base.RHProtected):
900    _uh=urlHandlers.UHConfMyStuffMyTracks
901
902    def _checkProtection(self):
903        base.RHProtected._checkProtection(self)
904
905    def _process(self):
906        p=conferences.WPConfMyStuffMyTracks(self,self._target)
907        return p.display()
908
909
910class RHContribsActions:
911    """
912    class to select the action to do with the selected abstracts
913    """
914    def __init__(self, req):
915        self._req = req
916
917    def process(self, params):
918        if params.has_key("PDF"):
919            return RHContributionListToPDF(self._req).process(params)
920        return "no action to do"
921
922class RHContributionListToPDF(RHConferenceBaseDisplay):
923
924    def _checkParams( self, params ):
925        RHConferenceBaseDisplay._checkParams( self, params )
926        self._contribIds = self._normaliseListParam( params.get("contributions", []) )
927        self._contribs = []
928        for id in self._contribIds:
929            contrib = self._conf.getContributionById(id)
930            if contrib.canAccess(self.getAW()):
931                self._contribs.append(contrib)
932
933    def _process( self ):
934        tz = timezoneUtils.DisplayTZ(self._aw,self._conf).getDisplayTZ()
935        filename = "Contributions.pdf"
936        if not self._contribs:
937            return "No contributions to print"
938        from MaKaC.PDFinterface.conference import ConfManagerContribsToPDF
939        pdf = ConfManagerContribsToPDF(self._conf, self._contribs, tz=tz)
940        data = pdf.getPDFBin()
941        self._req.set_content_length(len(data))
942        cfg = Config.getInstance()
943        mimetype = cfg.getFileTypeMimeType( "PDF" )
944        self._req.content_type = """%s"""%(mimetype)
945        self._req.headers_out["Content-Disposition"] = """inline; filename="%s\""""%filename
946        return data
947
948
949class RHConferenceMenuClose(RHConferenceBaseDisplay):
950
951    def _checkParams( self, params ):
952        RHConferenceBaseDisplay._checkParams( self, params )
953        self._currentURL = params.get("currentURL","")
954
955    def _process( self ):
956        websession = self._getSession()
957        websession.setVar("menuStatus", "close")
958        self._redirect(self._currentURL)
959
960
961class RHConferenceMenuOpen(RHConferenceBaseDisplay):
962
963    def _checkParams( self, params ):
964        RHConferenceBaseDisplay._checkParams( self, params )
965        self._currentURL = params.get("currentURL","")
966
967    def _process( self ):
968        websession = self._getSession()
969        websession.setVar("menuStatus", "open")
970        self._redirect(self._currentURL)
971
972
973class RHAbstractBook(RHConferenceBaseDisplay):
974    _uh=urlHandlers.UHConfAbstractBook
975
976    def _checkProtection( self ):
977        RHConferenceBaseDisplay._checkProtection(self)
978        if not self._conf.getAbstractMgr().isActive() or not self._conf.hasEnabledSection("cfa"):
979            raise MaKaCError( _("The Call For Abstracts was disabled by the conference managers"))
980
981    def _process( self ):
982        tz = timezoneUtils.DisplayTZ(self._aw,self._target).getDisplayTZ()
983        filename = "%s - Book of abstracts.pdf"%cleanHTMLHeaderFilename(self._target.getTitle())
984        pdf = AbstractBook(self._target,self.getAW(), tz=tz)
985        data = pdf.getPDFBin()
986        self._req.headers_out["Content-Length"] = "%s"%len(data)
987        cfg = Config.getInstance()
988        mimetype = cfg.getFileTypeMimeType( "PDF" )
989        self._req.content_type = """%s"""%(mimetype)
990        self._req.headers_out["Content-Disposition"] = """inline; filename="%s\""""%filename.replace("\r\n"," ")
991        return data
992
993
994class RHConfParticipantsNewPending(RHConferenceDisplay):
995    _uh = urlHandlers.UHConfParticipantsNewPending
996
997    def _process( self ):
998        params = self._getRequestParams()
999
1000        errorList = []
1001        if self._conf.getStartDate() < timezoneUtils.nowutc() :
1002            errorList.append("This event began on %s"%self._conf.getStartDate())
1003            errorList.append("You cannot apply for participation after the event began")
1004
1005        if not self._conf.getParticipation().isAllowedForApplying() :
1006            errorList.append("Participation in this event is restricted to persons invited")
1007            errorList.append("If you insist on taking part in this event, please contact the event manager")
1008
1009        if errorList:
1010            self._reqParams["errorMsg"] = errorList
1011            return RHConferenceDisplay._process(self)
1012
1013        params["formAction"] = str(urlHandlers.UHConfParticipantsAddPending.getURL(self._conf))
1014        user = self._getUser()
1015        if user is not None :
1016            params["titleValue"] = user.getTitle()
1017            params["surNameValue"] = user.getFamilyName()
1018            params["nameValue"] = user.getName()
1019            params["emailValue"] = user.getEmail()
1020            params["addressValue"] = user.getAddress()
1021            params["affiliationValue"] = user.getAffiliation()
1022            params["phoneValue"] = user.getTelephone()
1023            params["faxValue"] = user.getFax()
1024
1025            params["disabledTitle"] = params["disabledSurName"] = True
1026            params["disabledName"] = params["disabledEmail"] = True
1027            params["disabledAddress"] = params["disabledPhone"] = True
1028            params["disabledFax"] = params["disabledAffiliation"] = True
1029
1030
1031        wf=self.getWebFactory()
1032        if wf is not None:
1033            p = wf.getConfModifParticipantsNewPending(self, self._conf)
1034        else :
1035            p = conferences.WPConfModifParticipantsNewPending( self, self._target )
1036        return p.display(**params)
1037
1038
1039class RHConfParticipantsAddPending(RHConferenceDisplay):
1040    _uh = urlHandlers.UHConfParticipantsAddPending
1041
1042    def _process( self ):
1043        params = self._getRequestParams()
1044        errorList = []
1045        infoList = []
1046        if params.has_key("ok") :
1047            user = self._getUser()
1048            pending = Participant(self._conf, user)
1049            if user is None :
1050                pending.setTitle(params.get("title",""))
1051                pending.setFamilyName(params.get("surName",""))
1052                pending.setFirstName(params.get("name",""))
1053                pending.setEmail(params.get("email",""))
1054                pending.setAffiliation(params.get("affiliation",""))
1055                pending.setAddress(params.get("address",""))
1056                pending.setTelephone(params.get("phone",""))
1057                pending.setFax(params.get("fax",""))
1058            participation = self._conf.getParticipation()
1059            if participation.alreadyParticipating(pending) != 0 or participation.alreadyPending(pending) != 0:
1060                errorList.append("There is already a participant with the email address '%s' in this meeting."
1061                                 % pending.getEmail())
1062            else:
1063                if participation.addPendingParticipant(pending):
1064                    if participation.getAutoAccept():
1065                        infoList.append(_("The request for participation has been accepted"))
1066                    else:
1067                        infoList.append("The participant identified by email '%s' has been added to the list of pending participants"
1068                                    % pending.getEmail())
1069                else:
1070                    errorList.append(_("The participant cannot be added."))
1071
1072        if infoList:
1073            self._reqParams["infoMsg"] = infoList
1074        if errorList:
1075            self._reqParams["errorMsg"] = errorList
1076
1077        return RHConferenceDisplay._process(self)
1078
1079
1080class RHConfParticipantsRefusal(RHConferenceBaseDisplay):
1081    _uh = urlHandlers.UHConfParticipantsRefusal
1082
1083    def _checkParams( self, params ):
1084        RHConferenceBaseDisplay._checkParams(self, params )
1085        self._confirm = params.has_key( "confirm" )
1086        self._cancel = params.has_key( "cancel" )
1087
1088    def _process( self ):
1089        params = self._getRequestParams()
1090        participantId = params["participantId"]
1091        if self._cancel:
1092            participant = self._conf.getParticipation().getParticipantById(participantId)
1093            url = urlHandlers.UHConferenceDisplay.getURL( self._conf )
1094            self._redirect( url )
1095        elif self._confirm:
1096            participant = self._conf.getParticipation().getParticipantById(participantId)
1097            participant.setStatusRefused()
1098            url = urlHandlers.UHConferenceDisplay.getURL( self._conf )
1099            self._redirect( url )
1100        else:
1101            return conferences.WPConfModifParticipantsRefuse( self, self._conf ).display(**params)
1102
1103
1104class RHConfParticipantsInvitation(RHConferenceBaseDisplay):
1105    _uh = urlHandlers.UHConfParticipantsInvitation
1106
1107    def _checkParams( self, params ):
1108        RHConferenceBaseDisplay._checkParams(self, params )
1109        self._confirm = params.has_key( "confirm" )
1110        self._cancel = params.has_key( "cancel" )
1111
1112    def _process( self ):
1113        params = self._getRequestParams()
1114        participantId = params["participantId"]
1115        if self._cancel:
1116            participant = self._conf.getParticipation().getParticipantById(participantId)
1117            if participant == None:
1118                raise NoReportError("It seems you have been withdrawn from the list of invited participants")
1119            participant.setStatusRejected()
1120            url = urlHandlers.UHConferenceDisplay.getURL( self._conf )
1121            self._redirect( url )
1122        elif self._confirm:
1123            participant = self._conf.getParticipation().getParticipantById(participantId)
1124            if participant == None:
1125                raise NoReportError("It seems you have been withdrawn from the list of invited participants")
1126            participant.setStatusAccepted()
1127            url = urlHandlers.UHConferenceDisplay.getURL( self._conf )
1128            self._redirect( url )
1129        else:
1130            return conferences.WPConfModifParticipantsInvite( self, self._conf ).display(**params)
1131
1132class RHConferenceToiCal(RHConferenceBaseDisplay):
1133
1134    def _checkParams( self, params ):
1135        RHConferenceBaseDisplay._checkParams( self, params )
1136        self._detailLevel = params.get("detailLevel","top")
1137
1138    def _process( self ):
1139        filename = "%s - Event.ics"%cleanHTMLHeaderFilename(self._target.getTitle())
1140        ical = ConferenceToiCal(self._target.getConference())
1141
1142        if self._detailLevel == "contributions":
1143            data = ical.getDetailedBody()
1144        else:
1145            data = ical.getBody()
1146
1147        self._req.headers_out["Content-Length"] = "%s"%len(data)
1148        cfg = Config.getInstance()
1149        mimetype = cfg.getFileTypeMimeType( "ICAL" )
1150        self._req.content_type = """%s"""%(mimetype)
1151        self._req.headers_out["Content-Disposition"] = """inline; filename="%s\""""%filename.replace("\r\n"," ")
1152        return data
1153
1154class RHConferenceToXML(RoomBookingDBMixin, RHConferenceBaseDisplay):
1155
1156    def _checkParams( self, params ):
1157        RHConferenceBaseDisplay._checkParams( self, params )
1158        self._xmltype = params.get("xmltype","standard")
1159
1160    def _process( self ):
1161        filename = "%s - Event.xml"%cleanHTMLHeaderFilename(self._target.getTitle())
1162        from MaKaC.common.xmlGen import XMLGen
1163        from MaKaC.common.output import outputGenerator
1164        xmlgen = XMLGen()
1165        xmlgen.initXml()
1166        outgen = outputGenerator(self.getAW(), xmlgen)
1167        xmlgen.openTag("event")
1168        outgen.confToXML(self._target.getConference(),0,0,1)
1169        xmlgen.closeTag("event")
1170        data = xmlgen.getXml()
1171        self._req.headers_out["Content-Length"] = "%s"%len(data)
1172        cfg = Config.getInstance()
1173        mimetype = cfg.getFileTypeMimeType( "XML" )
1174        self._req.content_type = """%s"""%(mimetype)
1175        self._req.headers_out["Content-Disposition"] = """inline; filename="%s\""""%filename.replace("\r\n"," ")
1176        return data
1177
1178
1179class RHConferenceToMarcXML(RHConferenceBaseDisplay):
1180
1181    def _process( self ):
1182        filename = "%s - Event.xml"%cleanHTMLHeaderFilename(self._target.getTitle())
1183        from MaKaC.common.xmlGen import XMLGen
1184        from MaKaC.common.output import outputGenerator
1185        xmlgen = XMLGen()
1186        xmlgen.initXml()
1187        outgen = outputGenerator(self.getAW(), xmlgen)
1188        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"]])
1189        outgen.confToXMLMarc21(self._target.getConference())
1190        xmlgen.closeTag("marc:record")
1191        data = xmlgen.getXml()
1192        self._req.headers_out["Content-Length"] = "%s"%len(data)
1193        cfg = Config.getInstance()
1194        mimetype = cfg.getFileTypeMimeType( "XML" )
1195        self._req.content_type = """%s"""%(mimetype)
1196        self._req.headers_out["Content-Disposition"] = """inline; filename="%s\""""%filename.replace("\r\n"," ")
1197        return data
1198
1199class RHWriteMinutes( RHConferenceBaseDisplay ):
1200
1201    def _checkProtection(self):
1202        if not self._target.canModify( self.getAW() ):
1203            if self._target.getModifKey() != "":
1204                raise ModificationError()
1205            if self._getUser() == None:
1206                self._preserveParams()
1207                self._checkSessionUser()
1208            else:
1209                raise ModificationError()
1210
1211    def _preserveParams(self):
1212        preservedParams = self._getRequestParams().copy()
1213        self._websession.setVar("minutesPreservedParams",preservedParams)
1214
1215    def _getPreservedParams(self):
1216        params = self._websession.getVar("minutesPreservedParams")
1217        if params is None :
1218            return {}
1219        return params
1220
1221    def _removePreservedParams(self):
1222        self._websession.setVar("minutesPreservedParams",None)
1223
1224    def _checkParams( self, params ):
1225        RHConferenceBaseDisplay._checkParams( self, params )
1226        preservedParams = self._getPreservedParams()
1227        if preservedParams != {}:
1228            params.update(preservedParams)
1229            self._removePreservedParams()
1230        self._cancel = params.has_key("cancel")
1231        self._save = params.has_key("OK")
1232        self._compile = params.has_key("compile")
1233        self._text = params.get("text", "")#.strip()
1234
1235    def _getCompiledMinutes( self ):
1236        minutes = []
1237        isHTML = False
1238        cList = self._target.getContributionList()
1239        cList.sort(sortContributionByDate)
1240        for c in cList:
1241            if c.getMinutes():
1242                minText = c.getMinutes().getText()
1243                minutes.append([c.getTitle(),minText])
1244                if isStringHTML(minText):
1245                    isHTML = True
1246        if isHTML:
1247            lb = "<br>"
1248        else:
1249            lb = "\n"
1250        text = "%s (%s)%s" % (self._target.getTitle(), self._target.getStartDate().strftime("%d %b %Y"), lb)
1251        part = self._target.getParticipation().getPresentParticipantListText()
1252        if part != "":
1253            text += "Present: %s%s" % (part,lb)
1254        uList = self._target.getChairList()
1255        chairs = ""
1256        for chair in uList:
1257            if chairs != "":
1258                chairs += "; "
1259            chairs += chair.getFullName()
1260        if len(uList) > 0:
1261            text += "Chaired by: %s%s%s" % (chairs, lb, lb)
1262        for min in minutes:
1263            text += "==================%s%s%s==================%s%s%s%s" % (lb,min[0],lb,lb,min[1],lb,lb)
1264        return text
1265
1266    def _process( self ):
1267        wf=self.getWebFactory()
1268        if self._compile:
1269            minutes = self._target.getMinutes()
1270            if not minutes:
1271                minutes = self._target.createMinutes()
1272            text = self._getCompiledMinutes()
1273            minutes.setText( text )
1274        if self._save:
1275            minutes = self._target.getMinutes()
1276            if not minutes:
1277                minutes = self._target.createMinutes()
1278            minutes.setText( self._text )
1279        elif not self._cancel:
1280            if wf is None:
1281                wp = conferences.WPConfDisplayWriteMinutes(self, self._target)
1282            else:
1283                wp = wf.getConferenceDisplayWriteMinutes( self, self._conf)
1284            return wp.display()
1285        self._redirect( urlHandlers.UHConferenceDisplay.getURL( self._target ) )
1286
1287
1288class RHInternalPageDisplay(RHConferenceBaseDisplay):
1289    _uh=urlHandlers.UHInternalPageDisplay
1290
1291    def _checkParams(self,params):
1292        RHConferenceBaseDisplay._checkParams(self,params)
1293        if params.has_key("pageId"):
1294            pageId=params.get("pageId")
1295            intPagesMgr=internalPagesMgr.InternalPagesMgrRegistery().getInternalPagesMgr(self._conf)
1296            self._page=intPagesMgr.getPageById(pageId)
1297            self._target = self._page
1298            if self._page is None:
1299                raise MaKaCError( _("The webpage, you are trying to access, does not exist"))
1300        else:
1301            raise MaKaCError( _("The webpage, you are trying to access, does not exist"))
1302
1303    def _checkProtection(self):
1304        if not self._conf.canView( self.getAW() ):
1305            from MaKaC.conference import Link,LocalFile
1306
1307            if self._conf.getAccessKey() != "":
1308                raise KeyAccessError()
1309            if self._getUser() == None:
1310                self._checkSessionUser()
1311            else:
1312                raise AccessError()
1313
1314    def _process( self ):
1315        p=conferences.WPInternalPageDisplay(self,self._conf, self._page)
1316        return p.display()
1317
1318class RHConferenceLatexPackage(RHConferenceBaseDisplay):
1319
1320    def _process( self ):
1321        #return "nothing"
1322        filename = "%s-BookOfAbstracts.zip"%cleanHTMLHeaderFilename(self._target.getTitle())
1323        zipdata = StringIO.StringIO()
1324        zip = zipfile.ZipFile(zipdata, "w")
1325        for cont in self._target.getContributionList():
1326            f = []
1327            f.append("""\\section*{%s}"""%cont.getTitle())
1328            f.append(" ")
1329            l = []
1330            affil = {}
1331            i = 1
1332            for pa in cont.getPrimaryAuthorList():
1333                if pa.getAffiliation() in affil.keys():
1334                    num = affil[pa.getAffiliation()]
1335                else:
1336                    affil[pa.getAffiliation()] = i
1337                    num = i
1338                    i += 1
1339
1340                l.append("""\\noindent \\underline{%s}$^%d$"""%(pa.getFullName(), num))
1341
1342            for ca in cont.getCoAuthorList():
1343                if ca.getAffiliation() in affil.keys():
1344                    num = affil[ca.getAffiliation()]
1345                else:
1346                    affil[ca.getAffiliation()] = i
1347                    num = i
1348                    i += 1
1349                l.append("""%s$^%d$"""%(ca.getFullName(), num))
1350
1351            f.append(",\n".join(l))
1352            f.append("\n")
1353            l = []
1354            for key in affil.keys():
1355                l.append("""$^%d$%s"""%(affil[key], key))
1356            f.append("\\noindent " + ",\n".join(l))
1357            f.append("\n")
1358            f.append("""\\noindent %s"""%cont.getDescription())
1359            zip.writestr("contribution-%s"%cont.getId(), "\n".join(f))
1360        zip.close()
1361        data = zipdata.getvalue()
1362        zipdata.close()
1363
1364        #self._req.headers_out["Accept-Ranges"] = "bytes"
1365        self._req.headers_out["Content-Length"] = "%s"%len(data)
1366        cfg = Config.getInstance()
1367        mimetype = cfg.getFileTypeMimeType( "ZIP" )
1368        #self._req.content_type = """%s; name="%s\""""%(mimetype, filename )
1369        self._req.content_type = """%s"""%(mimetype)
1370        self._req.headers_out["Content-Disposition"] = """inline; filename="%s\""""%filename.replace("\r\n"," ")
1371        return data
1372
1373
1374class RHFullMaterialPackage(RHConferenceBaseDisplay):
1375    _uh=urlHandlers.UHConferenceDisplayMaterialPackage
1376
1377    def _checkParams( self, params ):
1378        RHConferenceBaseDisplay._checkParams( self, params )
1379        self._errors = params.get("errors","")
1380
1381    def _process( self ):
1382
1383        wf = self.getWebFactory()
1384        if wf!=None : #Event == Meeting/Lecture
1385            p = wf.getDisplayFullMaterialPackage(self,self._target)
1386        else : #Event == Conference
1387            p = conferences.WPDisplayFullMaterialPackage(self,self._target)
1388        return p.display(errors=self._errors)
1389
1390
1391
1392
1393class RHFullMaterialPackagePerform(RHConferenceBaseDisplay):
1394    _uh=urlHandlers.UHConferenceDisplayMaterialPackagePerform
1395
1396    def _checkParams( self, params ):
1397        RHConferenceBaseDisplay._checkParams( self, params )
1398        self._days=self._normaliseListParam(params.get("days",[]))
1399        self._mainResource = (params.get("mainResource","") != "")
1400        self._fromDate = ""
1401        fromDay = params.get("fromDay","")
1402        fromMonth = params.get("fromMonth","")
1403        fromYear = params.get("fromYear","")
1404        if fromDay != "" and fromMonth != "" and fromYear != "" and \
1405           fromDay != "dd" and fromMonth != "mm" and fromYear != "yyyy":
1406            self._fromDate = "%s %s %s"%(fromDay, fromMonth, fromYear)
1407        self._cancel = params.has_key("cancel")
1408        self._materialTypes=self._normaliseListParam(params.get("materialType",[]))
1409        self._sessionList = self._normaliseListParam(params.get("sessionList",[]))
1410
1411    def _process( self ):
1412        if not self._cancel:
1413            if self._materialTypes != []:
1414                p=ConferencePacker(self._conf, self._aw)
1415                path=p.pack(self._materialTypes, self._days, self._mainResource, self._fromDate, ZIPFileHandler(),self._sessionList)
1416                if not p.getItems():
1417                    raise NoReportError(_("The selected package does not contain any items."))
1418                filename = "full-material.zip"
1419                cfg = Config.getInstance()
1420                mimetype = cfg.getFileTypeMimeType( "ZIP" )
1421                self._req.content_type = """%s"""%(mimetype)
1422                self._req.headers_out["Content-Disposition"] = """inline; filename="%s\""""%filename
1423                self._req.sendfile(path)
1424            else:
1425                url = urlHandlers.UHConferenceDisplayMaterialPackage.getURL(self._conf)
1426                url.addParam("errors", _("You have to select at least one material type"))
1427                self._redirect( url )
1428        else:
1429            self._redirect( urlHandlers.UHConferenceDisplay.getURL( self._conf ) )
1430
1431
1432class RHShortURLRedirect(RH):
1433
1434    def _checkParams( self, params ):
1435        self._tag = params.get("tag", "").strip()
1436
1437    def _process(self):
1438        from MaKaC.conference import ConferenceHolder
1439        ch = ConferenceHolder()
1440        from MaKaC.common.url import ShortURLMapper
1441        sum = ShortURLMapper()
1442        if ch.hasKey(self._tag):
1443            conf = ch.getById(self._tag)
1444            self._redirect(urlHandlers.UHConferenceDisplay.getURL(conf))
1445        elif sum.hasKey(self._tag):
1446            conf = sum.getById(self._tag)
1447            self._redirect(urlHandlers.UHConferenceDisplay.getURL(conf))
1448        else:
1449            raise NoReportError(_("The specified event with id or tag \"%s\" does not exist or has been deleted")%self._tag)
1450
Note: See TracBrowser for help on using the repository browser.