Exemplo n.º 1
0
    def sanitizationCheck(target, params, accessWrapper, doNotSanitize=[]):
        # first make sure all params are utf-8
        Sanitization._encodeUnicode(params)

        # then check the security level of data sent to the server
        # if no user logged in, then no html allowed
        if accessWrapper.getUser():
            level = Config.getInstance().getSanitizationLevel()
        elif target and hasattr(target, "canModify") and target.canModify(accessWrapper):
            # not logged user, but use a modification key
            level = Config.getInstance().getSanitizationLevel()
        else:
            level = 0

        if level not in range(4):
            level = 1

        if level == 0:
            # Escape all HTML tags
            Sanitization._escapeHTML(params)

        elif level in [1, 2]:
            # level 1 or default: raise error if script or style detected
            # level 2: raise error if script but style accepted
            Sanitization._sanitize(params, level, doNotSanitize)

        elif level == 3:
            # Absolutely no checks
            return
Exemplo n.º 2
0
 def getVars(self):
     vars = wcomponents.WTemplated.getVars( self )
     vars["logo"] = ""
     if self._conf.getLogo():
         vars["logo"] = "<img src=\"%s\" alt=\"%s\" border=\"0\">"%(vars["logoURL"], self._conf.getTitle())
     vars["confTitle"] = self._conf.getTitle()
     vars["displayURL"] = urlHandlers.UHConferenceDisplay.getURL(self._conf)
     vars["imgConferenceRoom"] = Config.getInstance().getSystemIconURL( "conferenceRoom" )
     #################################
     # Fermi timezone awareness      #
     #################################
     vars["confDateInterval"] = i18nformat("""_("from") %s _("to") %s""")%(format_date(self._conf.getStartDate(), format='long'), format_date(self._conf.getEndDate(), format='long'))
     if self._conf.getStartDate().strftime("%d%B%Y") == \
             self._conf.getEndDate().strftime("%d%B%Y"):
         vars["confDateInterval"] = format_date(self._conf.getStartDate(), format='long')
     elif self._conf.getStartDate().month == self._conf.getEndDate().month:
         vars["confDateInterval"] = "%s-%s %s"%(self._conf.getStartDate().day, self._conf.getEndDate().day, format_date(self._conf.getStartDate(), format='MMMM yyyy'))
     #################################
     # Fermi timezone awareness(end) #
     #################################
     vars["body"] = self._body
     vars["confLocation"] = ""
     if self._conf.getLocationList():
         vars["confLocation"] =  self._conf.getLocationList()[0].getName()
         vars["supportEmail"] = ""
     if self._conf.getSupportInfo().hasEmail():
         mailto = quoteattr("""mailto:%s?subject=%s"""%(self._conf.getSupportInfo().getEmail(), urllib.quote( self._conf.getTitle() ) ))
         vars["supportEmail"] =  _("""<a href=%s class="confSupportEmail"><img src="%s" border="0" alt="email"> %s</a>""")%(mailto,
                                                     Config.getInstance().getSystemIconURL("mail"),
                                                     self._conf.getSupportInfo().getCaption())
     format = displayMgr.ConfDisplayMgrRegistery().getDisplayMgr(self._conf).getFormat()
     vars["bgColorCode"] = format.getFormatOption("titleBgColor")["code"]
     vars["textColorCode"] = format.getFormatOption("titleTextColor")["code"]
     return vars
Exemplo n.º 3
0
 def _process( self ):
     filename = "%s - contribution.xml"%self._target.getTitle()
     from MaKaC.common.output import outputGenerator, XSLTransformer
     xmlgen = XMLGen()
     xmlgen.initXml()
     outgen = outputGenerator(self.getAW(), xmlgen)
     xmlgen.openTag("event")
     outgen.confToXML(self._target.getConference(),0,1,1,showContribution=self._target.getId(), overrideCache=True)
     xmlgen.closeTag("event")
     basexml = xmlgen.getXml()
     path = Config.getInstance().getStylesheetsDir()
     stylepath = "%s.xsl" % (os.path.join(path,self._xmltype))
     if self._xmltype != "standard" and os.path.exists(stylepath):
         try:
             parser = XSLTransformer(stylepath)
             data = parser.process(basexml)
         except:
             data = "Cannot parse stylesheet: %s" % sys.exc_info()[0]
     else:
         data = basexml
     self._req.headers_out["Content-Length"] = "%s"%len(data)
     cfg = Config.getInstance()
     mimetype = cfg.getFileTypeMimeType( "XML" )
     self._req.content_type = """%s"""%(mimetype)
     self._req.headers_out["Content-Disposition"] = """inline; filename="%s\""""%filename.replace("\r\n"," ")
     return data
Exemplo n.º 4
0
 def _process(self):
     filename = "%s - contribution.xml" % self._target.getTitle()
     from MaKaC.common.output import outputGenerator, XSLTransformer
     xmlgen = XMLGen()
     xmlgen.initXml()
     outgen = outputGenerator(self.getAW(), xmlgen)
     xmlgen.openTag("event")
     outgen.confToXML(self._target.getConference(),
                      0,
                      1,
                      1,
                      showContribution=self._target.getId(),
                      overrideCache=True)
     xmlgen.closeTag("event")
     basexml = xmlgen.getXml()
     path = Config.getInstance().getStylesheetsDir()
     stylepath = "%s.xsl" % (os.path.join(path, self._xmltype))
     if self._xmltype != "standard" and os.path.exists(stylepath):
         try:
             parser = XSLTransformer(stylepath)
             data = parser.process(basexml)
         except:
             data = "Cannot parse stylesheet: %s" % sys.exc_info()[0]
     else:
         data = basexml
     self._req.headers_out["Content-Length"] = "%s" % len(data)
     cfg = Config.getInstance()
     mimetype = cfg.getFileTypeMimeType("XML")
     self._req.content_type = """%s""" % (mimetype)
     self._req.headers_out[
         "Content-Disposition"] = """inline; filename="%s\"""" % cleanHTMLHeaderFilename(
             filename)
     return data
Exemplo n.º 5
0
    def sanitizationCheck(target, params, accessWrapper, doNotSanitize=[]):
        # first make sure all params are utf-8
        Sanitization._encodeUnicode(params)

        # then check the security level of data sent to the server
        # if no user logged in, then no html allowed
        if accessWrapper.getUser():
            level = Config.getInstance().getSanitizationLevel()
        elif target and hasattr(
                target, "canModify") and target.canModify(accessWrapper):
            # not logged user, but use a modification key
            level = Config.getInstance().getSanitizationLevel()
        else:
            level = 0

        if level not in range(4):
            level = 1

        if level == 0:
            #Escape all HTML tags
            Sanitization._escapeHTML(params)

        elif level in [1, 2]:
            #level 1 or default: raise error if script or style detected
            #level 2: raise error if script but style accepted
            Sanitization._sanitize(params, level, doNotSanitize)

        elif level == 3:
            # Absolutely no checks
            return
Exemplo n.º 6
0
 def _getMaterialHTML(self, contrib):
     lm=[]
     paper=contrib.getPaper()
     if paper is not None:
         lm.append("""<a href=%s><img src=%s border="0" alt="paper"><span style="font-style: italic;"><small> %s</small></span></a>"""%(
             quoteattr(str(urlHandlers.UHMaterialDisplay.getURL(paper))),
             quoteattr(str(Config.getInstance().getSystemIconURL( "smallPaper" ))),
             self.htmlText("paper")))
     slides=contrib.getSlides()
     if slides is not None:
         lm.append("""<a href=%s><img src=%s border="0" alt="slides"><span style="font-style: italic;"><small> %s</small></span></a>"""%(
             quoteattr(str(urlHandlers.UHMaterialDisplay.getURL(slides))),
             quoteattr(str(Config.getInstance().getSystemIconURL( "smallSlides" ))),
             self.htmlText("slides")))
     poster=contrib.getPoster()
     if poster is not None:
         lm.append("""<a href=%s><img src=%s border="0" alt="poster"><span style="font-style: italic;"><small> %s</small></span></a>"""%(
             quoteattr(str(urlHandlers.UHMaterialDisplay.getURL(poster))),
             quoteattr(str(Config.getInstance().getSystemIconURL( "smallPoster" ))),
             self.htmlText("poster")))
     slides=contrib.getSlides()
     video=contrib.getVideo()
     if video is not None:
         lm.append("""<a href=%s><img src=%s border="0" alt="video"><span style="font-style: italic;"><small> %s</small></span></a>"""%(
             quoteattr(str(urlHandlers.UHMaterialDisplay.getURL(video))),
             quoteattr(str(Config.getInstance().getSystemIconURL( "smallVideo" ))),
             self.htmlText("video")))
     return ", ".join(lm)
Exemplo n.º 7
0
    def _sendReport(self):
        cfg = Config.getInstance()

        # if no e-mail address was specified,
        # add a default one
        if self._userMail:
            fromAddr = self._userMail
        else:
            fromAddr = '*****@*****.**'

        toAddr = Config.getInstance().getSupportEmail()

        Logger.get('errorReport').debug('mailing %s' % toAddr)

        subject = "[Indico@%s] Error report" % cfg.getBaseURL()

        # build the message body
        body = [
            "-" * 20, "Error details\n", self._code, self._message,
            "Inner error: " + str(self._inner),
            str(self._requestInfo), "-" * 20
        ]
        maildata = {
            "fromAddr": fromAddr,
            "toList": [toAddr],
            "subject": subject,
            "body": "\n".join(body)
        }

        # send it
        GenericMailer.send(GenericNotification(maildata))
Exemplo n.º 8
0
    def _prepare(self, check = True):

        # Date checks...
        if check:
            from MaKaC.conference import ConferenceHolder
            if not ConferenceHolder().hasKey(self.conf.getId()):
                self.getLogger().warning("Conference %s no longer exists! "
                                     "Deleting alarm." % self.conf.getId())
                self.conf.removeAlarm(self)
                self.suicide()
            elif self.conf.getStartDate() <= self._getCurrentDateTime():
                self.getLogger().warning("Conference %s already started. "
                                     "Deleting alarm." % self.conf.getId())
                self.conf.removeAlarm(self)
                self.suicide()
                return False

        # Email
        startDateTime = format_datetime(self.conf.getAdjustedStartDate(), format="short")
        self.setUpSubject()
        try:
            locationText = self.conf.getLocation().getName()
            if self.conf.getLocation().getAddress() != "":
                locationText += ", %s" % self.conf.getLocation().getAddress()
            if self.conf.getRoom().getName() != "":
                locationText += " (%s)" % self.conf.getRoom().getName()
        except:
            locationText = ""
        if locationText != "":
            locationText = " %s: %s" % ( _("Location"), locationText)

        if self.getToAllParticipants() :
            if self.conf.getType() == "conference":
                for r in self.conf.getRegistrantsList():
                    self.addToUser(r)
            else:
                for p in self.conf.getParticipation().getParticipantList() :
                    self.addToUser(p)
        from MaKaC.webinterface import urlHandlers
        if Config.getInstance().getShortEventURL() != "":
            url = "%s%s" % (Config.getInstance().getShortEventURL(),self.conf.getId())
        else:
            url = urlHandlers.UHConferenceDisplay.getURL(self.conf)
        self.setText("""Hello,
    Please note that the event "%s" will start on %s (%s).
    %s

    You can access the full event here:
    %s

Best Regards

""" % (self.conf.getTitle(),\
                startDateTime,\
                self.conf.getTimezone(),\
                locationText,\
                url,\
                ))
        self._setMailText()
        return True
Exemplo n.º 9
0
 def _getAnswer(self):
     self._target.getReportNumberHolder().addReportNumber(self._reportNumberSystem, self._reportNumber)
     if self._reportNumberSystem in Config.getInstance().getReportNumberSystems().keys():
         reportNumberId="s%sr%s"%(self._reportNumberSystem, self._reportNumber)
         name = Config.getInstance().getReportNumberSystems()[self._reportNumberSystem]["name"]
         return {"id":reportNumberId, "name":name , "system":self._reportNumberSystem, "number": self._reportNumber}
     else:
         return {}
Exemplo n.º 10
0
    def getVars(self):
        vars = wcomponents.WTemplated.getVars(self)

        sortingField = None
        if self.sortCriteria in self.sortFields:
            sortingField = self.sortCriteria

        for crit in ["speaker", "status", "cont", "reqType"]:
            url = collaborationUrlHandlers.UHCollaborationElectronicAgreement.getURL(
                self._conf)
            vars["%sImg" % crit] = ""
            url.addParam("sortBy", crit)

            if sortingField == crit:
                if self.order == "up":
                    vars["%sImg" % crit] = '<img src="%s" alt="up">' % (
                        Config.getInstance().getSystemIconURL("upArrow"))
                    url.addParam("order", "down")
                elif self.order == "down":
                    vars["%sImg" % crit] = '<img src="%s" alt="down">' % (
                        Config.getInstance().getSystemIconURL("downArrow"))
                    url.addParam("order", "up")

            vars["%sSortingURL" % crit] = str(url)

        vars["conf"] = self._conf
        vars["contributions"] = self.getTableContent()

        self._fromList.append({
            "name": "Indico Mailer",
            "email": Config.getInstance().getNoReplyEmail()
        })
        vars['fromList'] = self._fromList
        manager = self._conf.getCSBookingManager()
        vars['manager'] = manager
        vars['user'] = self._user

        if hasattr(manager, "_speakerWrapperList"):
            vars['signatureCompleted'] = manager.areSignatureCompleted()
        else:
            vars['signatureCompleted'] = None

        vars['STATUS_STRING'] = STATUS_STRING
        vars['canShow'] = manager.isAnyRequestAccepted()
        vars['SpeakerStatusEnum'] = SpeakerStatusEnum
        vars['user'] = self._user
        vars['collaborationUrlHandlers'] = collaborationUrlHandlers
        vars['urlPaperAgreement'] = self.getPaperAgreementURL()
        vars['agreementName'] = CollaborationTools.getOptionValue(
            "RecordingRequest", "AgreementName")
        vars[
            "notifyElectronicAgreementAnswer"] = manager.notifyElectronicAgreementAnswer(
            )
        vars["emailIconURL"] = (str(
            Config.getInstance().getSystemIconURL("mail_grey")))
        return vars
Exemplo n.º 11
0
def send_login_info(user, event=None):
    token_storage = GenericCache('resetpass')
    endpoint = 'event.confLogin-resetPassword' if event else 'user.signIn-resetPassword'

    idList = user.getIdentityList()
    logins = []
    for id in idList:
        if not hasattr(id, 'setPassword'):
            config = Config.getInstance()
            extra_message = config.getAuthenticatorConfigById(id.getAuthenticatorTag()).get("ResetPasswordMessage")
            msg = _("Sorry, you are using an externally managed account (%s) to login into Indico.") % id.getLogin()
            if extra_message:
                msg += "\n" + extra_message
            logins.append({
                'tag': id.getAuthenticatorTag(),
                'login': id.getLogin(),
                'error': msg
            })
        else:
            tag = id.getAuthenticatorTag()
            login = id.getLogin()
            data = {'tag': tag, 'login': login}
            token = str(uuid.uuid4())
            while token_storage.get(token):
                token = str(uuid.uuid4())
            token_storage.set(token, data, 6*3600)
            url = url_for(endpoint, event, token=token, _external=True, _secure=True)
            logins.append({
                'tag': tag,
                'login': login,
                'link': url
            })
    if not logins:
        url = urlHandlers.UHUserDetails.getURL(user)
        text = _("Sorry, we did not find your login.\nPlease, create one here:\n%s") % url
    else:
        text = _("You can use the following links within the next six hours to reset your password.")
        for entry in logins:
            text += "\n\n==================\n"
            if 'link' in entry:
                text += _("Click below to reset your password for the %s login '%s':\n") % (entry['tag'],
                                                                                            entry['login'])
                text += entry['link']
            else:
                text += entry['error']
            text += "\n==================\n"
    maildata = {
        "fromAddr": "Indico Mailer <%s>" % Config.getInstance().getNoReplyEmail(),
        "toList": [user.getEmail()],
        "subject": _("[%s] Login Information") % getSubjectIndicoTitle(),
        "body": text
    }
    GenericMailer.send(GenericNotification(maildata))
Exemplo n.º 12
0
def checkSMTPServer():
    if Config.getInstance().getSmtpUseTLS():
        server.ehlo()
        (code, errormsg) = server.starttls()
        if code != 220:
            from MaKaC.errors import MaKaCError
            raise MaKaCError("Can't start secure connection to SMTP server: %d, %s"%(code, errormsg))
    if Config.getInstance().getSmtpLogin():
        login = Config.getInstance().getSmtpLogin()
        password = Config.getInstance().getSmtpPassword()
        (code, errormsg) = server.login(login, password)
        if code != 235:
            from MaKaC.errors import MaKaCError
            raise MaKaCError("Can't login on SMTP server: %d, %s"%(code, errormsg))
    return True
Exemplo n.º 13
0
    def send(notification):
        server = smtplib.SMTP(Config.getInstance().getSmtpServer())
        if Config.getInstance().getSmtpUseTLS():
            server.ehlo()
            (code, errormsg) = server.starttls()
            if code != 220:
                raise MaKaCError(
                    _("Can't start secure connection to SMTP server: %d, %s") %
                    (code, errormsg))
        if Config.getInstance().getSmtpLogin():
            login = Config.getInstance().getSmtpLogin()
            password = Config.getInstance().getSmtpPassword()
            (code, errormsg) = server.login(login, password)
            if code != 235:
                raise MaKaCError(
                    _("Can't login on SMTP server: %d, %s") % (code, errormsg))
        fromAddr = notification.getFromAddr()
        for to in notification.getToList():
            if len(to) == 0:
                notification.getToList().remove(to)
        for cc in notification.getCCList():
            if len(cc) == 0:
                notification.getCCList().remove(cc)

        to = ", ".join(notification.getToList())
        #        raise to
        cc = ""
        if len(notification.getCCList()) > 0:
            cc = "Cc: %s\r\n" % ", ".join(notification.getCCList())
        try:
            ct = notification.getContentType()
        except:
            ct = "text/plain"
        subject = notification.getSubject()
        body = notification.getBody()
        msg="""Content-Type: %s; charset=\"utf-8\"\r\nFrom: %s\r\nTo: %s\r\n%sSubject: %s\r\n\r\n%s"""%(ct, fromAddr,\
                to,cc,subject,body)
        try:
            Logger.get('mail').debug(
                "Mailing %s  CC: %s" %
                (notification.getToList(), notification.getCCList()))
            server.sendmail(
                fromAddr,
                notification.getToList() + notification.getCCList(), msg)
        except smtplib.SMTPRecipientsRefused, e:
            server.quit()
            raise MaKaCError(
                _("Email address is not valid: ") + str(e.recipients))
Exemplo n.º 14
0
    def getVars(self):
        vars = wcomponents.WTemplated.getVars(self)

        sortingField = None
        if self.sortCriteria in self.sortFields:
            sortingField = self.sortCriteria

        for crit in ["speaker", "status", "cont", "reqType"]:
            url = collaborationUrlHandlers.UHCollaborationElectronicAgreement.getURL(self._conf)
            vars["%sImg" % crit] = ""
            url.addParam("sortBy", crit)

            if sortingField == crit:
                if self.order == "up":
                    vars["%sImg" % crit] = '<img src="%s" alt="up">' % (Config.getInstance().getSystemIconURL("upArrow"))
                    url.addParam("order","down")
                elif self.order == "down":
                    vars["%sImg" % crit] = '<img src="%s" alt="down">' % (Config.getInstance().getSystemIconURL("downArrow"))
                    url.addParam("order","up")

            vars["%sSortingURL" % crit] = str(url)

        vars["conf"] = self._conf
        vars["contributions"] = self.getTableContent()

        self._fromList.append({"name": "Indico Mailer",
                               "email": Config.getInstance().getNoReplyEmail()})
        vars['fromList'] = self._fromList
        manager = Catalog.getIdx("cs_bookingmanager_conference").get(self._conf.getId())
        vars['manager'] = manager
        vars['user'] = self._user

        if hasattr(manager, "_speakerWrapperList"):
            vars['signatureCompleted'] = manager.areSignatureCompleted()
        else:
            vars['signatureCompleted'] = None

        vars['STATUS_STRING'] = STATUS_STRING
        vars['canShow'] = manager.isAnyRequestAccepted()
        vars['SpeakerStatusEnum'] = SpeakerStatusEnum
        vars['user'] = self._user
        vars['collaborationUrlHandlers'] = collaborationUrlHandlers
        vars['urlPaperAgreement'] = self.getPaperAgreementURL()
        vars['agreementName'] = CollaborationTools.getOptionValue("RecordingRequest", "AgreementName")
        vars["notifyElectronicAgreementAnswer"] = manager.notifyElectronicAgreementAnswer()
        vars["emailIconURL"]=(str(Config.getInstance().getSystemIconURL("mail_grey")))
        vars["canModify"] = self._conf.canModify( self._rh.getAW() )
        return vars
Exemplo n.º 15
0
    def _process(self):
        self._disableCaching()
        #Check for automatic login
        auth = AuthenticatorMgr()
        av = auth.autoLogin(self)
        if av:
            url = self._returnURL
            tzUtil = timezoneUtils.SessionTZ(av)
            tz = tzUtil.getSessionTZ()
            self._getSession().setVar("ActiveTimezone", tz)
            self._getSession().setUser(av)
            if Config.getInstance().getBaseSecureURL().startswith('https://'):
                url = str(url).replace('http://', 'https://')
            self._redirect(url, noCache=True)
        if not self._signIn:
            p = signIn.WPSignIn(self)
            return p.display(returnURL=self._returnURL)
        else:
            li = LoginInfo(self._login, self._password)
            av = auth.getAvatar(li)
            if not av:
                p = signIn.WPSignIn(self,
                                    login=self._login,
                                    msg=_("Wrong login or password"))
                return p.display(returnURL=self._returnURL)
            elif not av.isActivated():
                if av.isDisabled():
                    self._redirect(urlHandlers.UHDisabledAccount.getURL(av))
                else:
                    self._redirect(urlHandlers.UHUnactivatedAccount.getURL(av))
                return _(
                    "your account is not activate\nPlease active it and retry")
            else:
                url = self._returnURL
                #raise(str(dir(av)))
                self._getSession().setUser(av)
                tzUtil = timezoneUtils.SessionTZ(av)
                tz = tzUtil.getSessionTZ()
                self._getSession().setVar("ActiveTimezone", tz)

            if self._userId != "":
                if "?" in url:
                    url += "&userId=%s" % self._userId
                else:
                    url += "?userId=%s" % self._userId
            if Config.getInstance().getBaseSecureURL().startswith('https://'):
                url = str(url).replace('http://', 'https://')
            self._redirect(url, noCache=True)
Exemplo n.º 16
0
    def _getTabContent(self, params):
        wc = WContributionDataModification(self._target, self._conf)

        pars = {"postURL": urlHandlers.UHConfPerformAddContribution.getURL(), \
        "calendarIconURL": Config.getInstance().getSystemIconURL( "calendar" ), \
        "calendarSelectURL":  urlHandlers.UHSimpleCalendar.getURL() }
        return wc.getHTML(pars)
Exemplo n.º 17
0
    def _process(self):
        filename = "%s - Abstract.xml" % self._target.getTitle()

        x = XMLGen()
        x.openTag("abstract")
        x.writeTag("Id", self._target.getId())
        x.writeTag("Title", self._target.getTitle())
        afm = self._target.getConference().getAbstractMgr(
        ).getAbstractFieldsMgr()
        for f in afm.getFields():
            id = f.getId()
            if f.isActive() and self._target.getField(id).strip() != "":
                x.writeTag(id.replace(" ", "_"), self._target.getField(id))
        x.writeTag("Conference", self._target.getConference().getTitle())
        l = []
        for au in self._target.getAuthorList():
            if self._target.isPrimaryAuthor(au):
                x.openTag("PrimaryAuthor")
                x.writeTag("FirstName", au.getFirstName())
                x.writeTag("FamilyName", au.getSurName())
                x.writeTag("Email", au.getEmail())
                x.writeTag("Affiliation", au.getAffiliation())
                x.closeTag("PrimaryAuthor")
            else:
                l.append(au)

        for au in l:
            x.openTag("Co-Author")
            x.writeTag("FirstName", au.getFirstName())
            x.writeTag("FamilyName", au.getSurName())
            x.writeTag("Email", au.getEmail())
            x.writeTag("Affiliation", au.getAffiliation())
            x.closeTag("Co-Author")

        for au in self._target.getSpeakerList():
            x.openTag("Speaker")
            x.writeTag("FirstName", au.getFirstName())
            x.writeTag("FamilyName", au.getSurName())
            x.writeTag("Email", au.getEmail())
            x.writeTag("Affiliation", au.getAffiliation())
            x.closeTag("Speaker")

        #To change for the new contribution type system to:
        #x.writeTag("ContributionType", self._target.getContribType().getName())
        x.writeTag("ContributionType", self._target.getContribType())

        for t in self._target.getTrackList():
            x.writeTag("Track", t.getTitle())

        x.closeTag("abstract")

        data = x.getXml()

        self._req.headers_out["Content-Length"] = "%s" % len(data)
        cfg = Config.getInstance()
        mimetype = cfg.getFileTypeMimeType("XML")
        self._req.content_type = """%s""" % (mimetype)
        self._req.headers_out[
            "Content-Disposition"] = """inline; filename="%s\"""" % filename
        return data
Exemplo n.º 18
0
 def _process(self):
     filename = "%s - Contribution.xml" % self._target.getTitle().replace(
         "/", "")
     from MaKaC.common.xmlGen import XMLGen
     from MaKaC.common.output import outputGenerator
     xmlgen = XMLGen()
     xmlgen.initXml()
     outgen = outputGenerator(self.getAW(), xmlgen)
     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"
         ]
     ])
     outgen.contribToXMLMarc21(self._target, xmlgen)
     xmlgen.closeTag("marc:record")
     data = xmlgen.getXml()
     self._req.headers_out["Content-Length"] = "%s" % len(data)
     cfg = Config.getInstance()
     mimetype = cfg.getFileTypeMimeType("XML")
     self._req.content_type = """%s""" % (mimetype)
     self._req.headers_out[
         "Content-Disposition"] = """inline; filename="%s\"""" % cleanHTMLHeaderFilename(
             filename)
     return data
Exemplo n.º 19
0
 def _checkCSRF(self):
     # Check referer for POST requests. We do it here so we can properly use indico's error handling
     if Config.getInstance().getCSRFLevel() < 3 or request.method != 'POST':
         return
     referer = request.referrer
     # allow empty - otherwise we might lock out paranoid users blocking referers
     if not referer:
         return
     # valid http referer
     if referer.startswith(Config.getInstance().getBaseURL()):
         return
     # valid https referer - if https is enabled
     base_secure = Config.getInstance().getBaseSecureURL()
     if base_secure and referer.startswith(base_secure):
         return
     raise BadRefererError('This operation is not allowed from an external referer.')
Exemplo n.º 20
0
    def __mergeTooltip(self, tooltip, snippets, count, doc):

            (ttTarget, ttText, ttType) = tooltip

            xpathRes= doc.xpath(ttTarget)

            ttText =  self.__convertTextToHTML(ttText)

            for elem in xpathRes:

                content =   '{indico:help ref=snip%s}' % count

                filteredText = ttText.replace('\n', '').replace('"', '&quot;')

                if ttType == 'explicit':
                    snippets['snip'+str(count)] ="""<span class="contextHelp" title="%s">
                                                <span style="color: Green; margin-left: 6px; font-size:smaller;"><img style="border: None;display:inline-block;vertical-align: middle" src="%s"/></span>
                                                </span>""" % (filteredText,Config.getInstance().getSystemIconURL( "help" ))

                    elem.append(builder.E.span(content))
                elif ttType == 'hover':
                    elem.set('class', ('contextHelp ' + elem.get('class')).strip())
                    elem.set('title', filteredText)

                else:
                    raise Exception( _('Tooltip type not recognized: ') + str(type))

                count += 1

            return count
Exemplo n.º 21
0
def send_file(req, fdata):
    cfg = Config.getInstance()
    if cfg.getUseXSendFile() and req.headers_in['User-Agent'].find(
            'Android') == -1:
        return ""
    else:
        return fdata.readBin()
Exemplo n.º 22
0
 def _process(self):
     s = MaintenanceMng.getStat(Config.getInstance().getTempDir())
     dbSize = MaintenanceMng.humanReadableSize(
         DBMgr.getInstance().getDBSize(), 'm')
     nWebsession = MaintenanceMng.getWebsessionNum()
     p = adminPages.WPMaintenance(self, s, dbSize, nWebsession)
     return p.display()
Exemplo n.º 23
0
    def _process( self ):

        try:        
            cfg = Config.getInstance()
            dir = os.path.join(cfg.getTPLDir(),"js")
            file = cfg.getTPLFile( self._tplName )

            if file == "":
                file = "%s.tpl"%self._tplName

            self._tplFile = os.path.join(dir, file)        

            htmlPath = os.path.join(cfg.getTempDir(), file+".tmp")

            if os.access(htmlPath, os.R_OK):
                fh = open(htmlPath, "r")
                htmlData = fh.read()
                fh.close()
            else:
                fh = open( self._tplFile, "r")
                text = fh.read()
                fh.close()

                self._dict["__rh__"] = self
                self._dict["user"] = None

                htmlData = TemplateExec().executeTemplate( text, self._dict, self._tplName )
                fh = open(htmlPath, "w")
                fh.write(htmlData)
                fh.close()

        except Exception, e:
            return 'indicoError: %s' % e
Exemplo n.º 24
0
 def _getTabContent(self, params):
     p = WSEContributionCreation(self._conf)
     pars = {"postURL": urlHandlers.UHMConfPerformAddContribution.getURL(), \
     "calendarIconURL": Config.getInstance().getSystemIconURL( "calendar" ), \
     "calendarSelectURL":  urlHandlers.UHSimpleCalendar.getURL(), \
     "targetDay": self._targetDay}
     return p.getHTML(pars)
Exemplo n.º 25
0
    def _sendReport(self):
        info = HelperMaKaCInfo().getMaKaCInfoInstance()
        cfg = Config.getInstance()

        # if no e-mail address was specified,
        # add a default one
        if self._userMail:
            fromAddr = self._userMail
        else:
            fromAddr = "*****@*****.**"

        toAddr = info.getSupportEmail()

        Logger.get("errorReport").debug("mailing %s" % toAddr)

        subject = "[Indico@%s] Error report" % cfg.getBaseURL()

        # build the message body
        body = [
            "-" * 20,
            "Error details\n",
            self._code,
            self._message,
            "Inner error: " + str(self._inner),
            str(self._requestInfo),
            "-" * 20,
        ]
        maildata = {"fromAddr": fromAddr, "toList": [toAddr], "subject": subject, "body": "\n".join(body)}

        # send it
        GenericMailer.send(GenericNotification(maildata))
Exemplo n.º 26
0
    def archiveTempBackgrounds(self, conf):
        """ Archives all the temporary backgrounds of this template.
        This method archives all of the temporary backgrounds of this template, which are
        stored in the form of filepath strings, in the __tempBackgroundsFilePaths dictionary,
        to a dictionary which stores LocalFile objects. The ids are copied, since there is a
        shared id counter for both dictionaries.
        After the archiving, the __tempBackgroundsFilePaths dictionary is reset to {}
        """

        for backgroundId, (
                filePath,
                bgPosition) in self.__tempBackgroundsFilePaths.iteritems():
            cfg = Config.getInstance()
            tempPath = cfg.getUploadedFilesSharedTempDir()
            filePath = os.path.join(tempPath, filePath)
            fileName = "background" + str(
                backgroundId) + "_t" + self.__id + "_c" + conf.id

            file = conference.LocalFile()
            file.setName(fileName)
            file.setDescription("Background " + str(backgroundId) +
                                " of the template " + self.__id +
                                " of the conference " + conf.id)
            file.setFileName(fileName)
            file.setFilePath(filePath)

            file.setOwner(conf)
            file.setId(fileName)
            file.archive(conf._getRepository())

            self.__backgrounds[backgroundId] = file
            self.__bgPositions[backgroundId] = bgPosition

        self.notifyModification()
        self.__tempBackgroundsFilePaths = {}
Exemplo n.º 27
0
    def _process(self):
        #syslog.syslog("In RHResetTZ id: " + str(sess.id))
        parms = self._getRequestParams()

        tz = None
        if not parms.has_key("activeTimezone") or parms["activeTimezone"] == "My":
            if self._aw.getUser():
                tz = self._aw.getUser().getTimezone()
            else:
                tz = info.HelperMaKaCInfo.getMaKaCInfoInstance().getTimezone()
        else:
            tz = parms["activeTimezone"]

        try:
            if parms["saveToProfile"] == "on":
                user = session.user
                if tz == "LOCAL":
                    user.setDisplayTZMode("Event Timezone")
                else:
                    user.setTimezone(tz)
                    user.setDisplayTZMode("MyTimezone")
        except:
            pass

        session.timezone = tz
        # redirect to the calling URL with the new session tz.
        self._redirect(request.referrer or Config.getInstance().getBaseURL())
Exemplo n.º 28
0
    def __mergeTooltip(self, tooltip, snippets, count, doc):

        (ttTarget, ttText, ttType) = tooltip

        xpathRes = doc.xpath(ttTarget)

        ttText = self.__convertTextToHTML(ttText)

        for elem in xpathRes:

            content = '{indico:help ref=snip%s}' % count

            filteredText = ttText.replace('\n', '').replace('"', '&quot;')

            if ttType == 'explicit':
                snippets['snip' +
                         str(count)] = """<span class="contextHelp" title="%s">
                                                <span style="color: Green; margin-left: 6px; font-size:smaller;"><img style="border: None;display:inline-block;vertical-align: middle" src="%s"/></span>
                                                </span>""" % (
                             filteredText,
                             Config.getInstance().getSystemIconURL("help"))

                elem.append(builder.E.span(content))
            elif ttType == 'hover':
                elem.set('class', ('contextHelp ' + elem.get('class')).strip())
                elem.set('title', filteredText)

            else:
                raise Exception(_('Tooltip type not recognized: ') + str(type))

            count += 1

        return count
Exemplo n.º 29
0
def set_file_headers(req, fname, fpath, last_modified, ftype, data, size):
    cfg = Config.getInstance()

    mimetype = cfg.getFileTypeMimeType(ftype)
    req.content_type = str(mimetype)

    if 'User-Agent' in req.headers_in and \
            req.headers_in['User-Agent'].find('Android') != -1:
        dispos = "attachment"
    else:
        dispos = "inline"

    req.headers_out.update({
        "Content-Length":
        str(size),
        "Last-Modified":
        formatdate(time.mktime(last_modified.timetuple())),
        "Content-Disposition":
        '{0}; filename="{1}"'.format(dispos, fname)
    })

    if cfg.getUseXSendFile() and req.headers_in['User-Agent'].find(
            'Android') == -1:
        # X-Send-File support makes it easier, just let the web server
        # do all the heavy lifting

        # send_x_file only sets headers
        req.send_x_file(fpath)
Exemplo n.º 30
0
    def _process(self):
        manager = self._conf.getCSBookingManager()
        sw = manager.getSpeakerWrapperByUniqueId(self.spkUniqueId)
        if sw:
            self.file = sw.getLocalFile()
            self._req.headers_out["Content-Length"] = "%s"%self.file.getSize()
            self._req.headers_out["Last-Modified"] = "%s"%time.mktime(self.file.getCreationDate().timetuple())
            cfg = Config.getInstance()
            mimetype = cfg.getFileTypeMimeType( self.file.getFileType() )
            print self.file.getFilePath()
            self._req.content_type = """%s"""%(mimetype)
            dispos = "inline"
            try:
                if self._req.headers_in['User-Agent'].find('Android') != -1:
                    dispos = "attachment"
            except KeyError:
                pass
            self._req.headers_out["Content-Disposition"] = '%s; filename="%s"' % (dispos, cleanHTMLHeaderFilename(self.file.getFileName()))

            if cfg.getUseXSendFile():
                # X-Send-File support makes it easier, just let the web server
                # do all the heavy lifting
                return self._req.send_x_file(self.file.getFilePath())
            else:
                return self.file.readBin()
        else:
            raise MaKaCError("The speaker wrapper id does not match any existing speaker.")
Exemplo n.º 31
0
    def _process( self ):
        self._notify('materialDownloaded', self._file)

        if isinstance(self._file, Link):
            self._redirect(self._file.getURL())
        elif self._file.getId() != "minutes":
            #self._req.headers_out["Accept-Ranges"] = "bytes"
            self._req.headers_out["Content-Length"] = "%s"%self._file.getSize()
            self._req.headers_out["Last-Modified"] = "%s"%formatdate(time.mktime(self._file.getCreationDate().timetuple()))
            cfg = Config.getInstance()
            mimetype = cfg.getFileTypeMimeType( self._file.getFileType() )
            self._req.content_type = """%s"""%(mimetype)
            dispos = "inline"

            try:
                if self._req.headers_in['User-Agent'].find('Android') != -1:
                    dispos = "attachment"
            except KeyError:
                pass

            self._req.headers_out["Content-Disposition"] = '%s; filename="%s"' % (dispos, self._file.getFileName())

            if cfg.getUseXSendFile() and self._req.headers_in['User-Agent'].find('Android') == -1:
                # X-Send-File support makes it easier, just let the web server
                # do all the heavy lifting
                return self._req.send_x_file(self._file.getFilePath())
            else:
                return self._file.readBin()
        else:
            p = files.WPMinutesDisplay(self, self._file )
            return p.display()
Exemplo n.º 32
0
    def _process(self):

        if not self._target.isScheduled():
            raise NoReportError(
                _("You cannot export the contribution with id %s because it is not scheduled"
                  ) % self._target.getId())

        filename = "%s-Contribution.ics" % self._target.getTitle()

        hook = ContributionHook({}, 'contribution', {
            'event': self._conf.getId(),
            'idlist': self._contrib.getId(),
            'dformat': 'ics'
        })
        res = hook(self.getAW(), self._req)
        resultFossil = {'results': res[0]}

        serializer = Serializer.create('ics')
        data = serializer(resultFossil)

        self._req.headers_out["Content-Length"] = "%s" % len(data)
        cfg = Config.getInstance()
        mimetype = cfg.getFileTypeMimeType("ICAL")
        self._req.content_type = """%s""" % (mimetype)
        self._req.headers_out[
            "Content-Disposition"] = """inline; filename="%s\"""" % cleanHTMLHeaderFilename(
                filename)
        return data
Exemplo n.º 33
0
 def check(self):
     errors = []
     if self.title.strip() == "":
         errors.append(_("Abstract title cannot be empty"))
     for f in self._afm.getFields():
         id = f.getId()
         caption = f.getCaption()
         ml = f.getMaxLength()
         limitation = f.getLimitation()
         if f.isMandatory() and self._otherFields.get(id, "") == "":
             errors.append(_("The field '%s' is mandatory") % caption)
         if ml != 0:
             if limitation == "words" and textUtils.wordsCounter(self._otherFields.get(id, "")) > ml:
                 errors.append(_("The field '%s' cannot be more than %s words") % (caption, ml))
             elif limitation == "chars" and len(self._otherFields.get(id, "")) > ml:
                 errors.append(_("The field '%s' cannot be more than %s characters") % (caption, ml))
     if not self.origin == "management":
         if not self._prAuthorsListParam:
             errors.append(_("No primary author has been specified. You must define at least one primary author"))
         if (
             not self._checkSpeaker()
             and self._absMgr.showSelectAsSpeaker()
             and self._absMgr.isSelectSpeakerMandatory()
         ):
             errors.append(_("At least one presenter must be specified"))
     if not self.tracks and self._absMgr.areTracksMandatory():
         # check if there are tracks, otherwise the user cannot select at least one
         if len(self._absMgr.getConference().getTrackList()) != 0:
             errors.append(_("At least one track must be seleted"))
     if self._hasExceededTotalSize():
         errors.append(
             _("The maximum size allowed for the attachments (%sMB) has been exceeded.")
             % Config.getInstance().getMaxUploadFilesTotalSize()
         )
     return errors
Exemplo n.º 34
0
    def __mergeTooltip(self, tooltip, snippets, count, xpathCtxt):
                    
            (ttTarget, ttText, ttType) = tooltip

            xpathRes = xpathCtxt.xpathEval(ttTarget) 
        
            ttText =  self.__convertTextToHTML(ttText)
        
            for elem in xpathRes:               
            
                content =   '{indico:help ref=snip%s}' % count

                filteredText = ttText.replace('\n','').replace('"','&quot;');

                if ttType == 'explicit':
                    snippets['snip'+str(count)] ="""<span onmouseover="domTT_activate(this, event, 'content', '%s', 'type', 'greasy', 'caption', false , 'delay', 100, 'maxWidth', 320, 'styleClass', 'tip' );">
                                                <span style="color: Green; margin-left: 6px; font-size:smaller;"><img style="border: None;display:inline-block;vertical-align: middle" src="%s"/></span>
                                                </span>""" % (filteredText,Config.getInstance().getSystemIconURL( "help" ))
                
                    elem.newChild(None,'span',content)
                elif ttType == 'hover':
                    snippets['snip'+str(count)] ="""domTT_activate(this, event, 'content', '%s', 'type', 'greasy', 'caption', false ,'trail', false, 'delay', 100, 'maxWidth', 320, 'styleClass', 'tip' );""" \
                                                % filteredText
                                                
                    elem.newProp('onmouseover', content)                    
                    
                else:
                    raise Exception( _('Tooltip type not recognized: ') + str(type))
                
                count += 1
                
            return count
Exemplo n.º 35
0
    def invokeMethod(self, method, params, req):

        MAX_RETRIES = 10

        # clear the context
        ContextManager.destroy()

        DBMgr.getInstance().startRequest()

        # room booking database
        _startRequestSpecific2RH()

        # notify components that the request has started
        self._notify('requestStarted', req)

        forcedConflicts = Config.getInstance().getForceConflicts()
        retry = MAX_RETRIES
        try:
            while retry > 0:
                if retry < MAX_RETRIES:
                    # notify components that the request is being retried
                    self._notify('requestRetry', req, MAX_RETRIES - retry)

                try:
                    # delete all queued emails
                    GenericMailer.flushQueue(False)

                    DBMgr.getInstance().sync()

                    try:
                        result = processRequest(method, copy.deepcopy(params), req)
                    except MaKaC.errors.NoReportError, e:
                        raise NoReportError(e.getMsg())
                    rh = ContextManager.get('currentRH')

                    # notify components that the request has ended
                    self._notify('requestFinished', req)
                    # Raise a conflict error if enabled. This allows detecting conflict-related issues easily.
                    if retry > (MAX_RETRIES - forcedConflicts):
                        raise ConflictError
                    _endRequestSpecific2RH( True )
                    DBMgr.getInstance().endRequest(True)
                    GenericMailer.flushQueue(True) # send emails
                    if rh._redisPipeline:
                        try:
                            rh._redisPipeline.execute()
                        except RedisError:
                            Logger.get('redis').exception('Could not execute pipeline')
                    break
                except ConflictError:
                    _abortSpecific2RH()
                    DBMgr.getInstance().abort()
                    retry -= 1
                    continue
                except ClientDisconnected:
                    _abortSpecific2RH()
                    DBMgr.getInstance().abort()
                    retry -= 1
                    time.sleep(MAX_RETRIES - retry)
                    continue
Exemplo n.º 36
0
    def __init__(self, host='localhost', port=8000, enable_ipv6=False):
        """
        Run an Indico WSGI ref server instance
        Very simple dispatching app
        """

        config = Config.getInstance()

        baseURL = config.getBaseURL()
        path = urlparse.urlparse(baseURL)[2].rstrip('/')

        def fake_app(environ, start_response):
            rpath = environ['PATH_INFO']
            m = re.match(r'^%s(.*)$' % path, rpath)
            if m:
                environ['PATH_INFO'] = m.group(1)
                environ['SCRIPT_NAME'] = path
                for msg in application(environ, start_response):
                    yield msg
            else:
                start_response("404 NOT FOUND", [])
                yield 'Not found'

        # if there is an IPv6 address, use it
        if enable_ipv6 and (socket.AF_INET6 in resolve_host(host, per_family=True)):
            server = ThreadedWSGIServerIPV6
        else:
            server = ThreadedWSGIServer

        self.httpd = make_server(host, port, fake_app,
                                 server_class=server,
                                 handler_class=WSGIRequestHandler)
        self.addr = self.httpd.socket.getsockname()[:2]
Exemplo n.º 37
0
    def _getIcalExportParams(self, user, url, params={}):
        minfo = info.HelperMaKaCInfo.getMaKaCInfoInstance()
        apiMode = minfo.getAPIMode()
        apiKey = user.getAPIKey() if user else None

        urls = generate_public_auth_request(
            apiMode,
            apiKey,
            url,
            params,
            minfo.isAPIPersistentAllowed() and (apiKey.isPersistentAllowed() if apiKey else False),
            minfo.isAPIHTTPSRequired(),
        )

        return {
            "currentUser": user,
            "icsIconURL": str(Config.getInstance().getSystemIconURL("ical_grey")),
            "apiMode": apiMode,
            "signingEnabled": apiMode in (API_MODE_SIGNED, API_MODE_ONLYKEY_SIGNED, API_MODE_ALL_SIGNED),
            "persistentAllowed": minfo.isAPIPersistentAllowed(),
            "requestURLs": urls,
            "persistentUserEnabled": apiKey.isPersistentAllowed() if apiKey else False,
            "apiActive": apiKey != None,
            "userLogged": user != None,
            "apiKeyUserAgreement": minfo.getAPIKeyUserAgreement(),
            "apiPersistentUserAgreement": minfo.getAPIPersistentUserAgreement(),
        }
Exemplo n.º 38
0
 def _process(self):
     if not self._cancel:
         if not self._confirmed:
             p = RHMaintenanceTmpCleanup(self)
             return p.display()
         MaintenanceMng.cleanupTmp(Config.getInstance().getTempDir())
     self._redirect(urlHandlers.UHMaintenance.getURL())
Exemplo n.º 39
0
    def setTemplate(self, name, description, format, fd, id, extension = ".template"):
        """ Stores a template.
            There can be 1 template for any format.
        """

        cfg = Config.getInstance()
        tempPath = cfg.getUploadedFilesTempDir()
        tempFileName = tempfile.mkstemp( suffix="MaKaC.tmp", dir = tempPath )[1]
        f = open( tempFileName, "wb" )
        f.write( fd.read() )
        f.close()

        #id = self.getNewTemplateId()

        fileName = "Contribution_template_" + id + "_c" + self._conference.id + extension

        file = conference.LocalFile()
        file.setName( fileName )
        file.setDescription( "Paper reviewing template with id " + id + "with format: " + format + " of the conference " + self._conference.id )
        file.setFileName( fileName )

        file.setFilePath( tempFileName )
        file.setOwner( self._conference )
        file.setId( fileName )
        file.archive( self._conference._getRepository() )

        self._templates[id] = Template(id, self._conference, name, description, format, file)
        self.notifyModification()
Exemplo n.º 40
0
    def __init__(self, host='localhost', port=8000):
        """
        Run an Indico WSGI ref server instance
        Very simple dispatching app
        """

        config = Config.getInstance()

        baseURL = config.getBaseURL()
        path = urlparse.urlparse(baseURL)[2].rstrip('/')

        def fake_app(environ, start_response):
            rpath = environ['PATH_INFO']
            m = re.match(r'^%s(.*)$' % path, rpath)
            if m:
                environ['PATH_INFO'] = m.group(1)
                environ['SCRIPT_NAME'] = path
                for msg in application(environ, start_response):
                    yield msg
            else:
                start_response("404 NOT FOUND", [])
                yield 'Not found'

        self.httpd = make_server(host, port, fake_app,
                                 server_class=ThreadedWSGIServer,
                                 handler_class=WSGIRequestHandler)
        self.addr = self.httpd.socket.getsockname()
Exemplo n.º 41
0
 def getVars(self):
     vars=wcomponents.WTemplated.getVars(self)
     authorObj = self._contrib.getAuthorById(self._authorId)
     if authorObj is None:
         raise MaKaCError( _("Not found the author: %s")%self._authorId)
     authorList=self._conf.getAuthorIndex().getByAuthorObj(authorObj)
     author = None
     if authorList is not None:
         author=authorList[0]
     else:
         raise MaKaCError( _("Not found the author: %s")%self._authorId)
     contribList = []
     for auth in authorList:
         contrib=auth.getContribution()
         if contrib is not None:
             url=urlHandlers.UHContributionDisplay.getURL(contrib)
             material = self._getMaterialHTML(contrib)
             if material.strip()!="":
                 material = "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;( %s )"%material
                 contribList.append("""<p style="text-indent: -3em;margin-left:3em"><a href=%s">%s-%s</a>%s</p>"""%(quoteattr(str(url)),self.htmlText(contrib.getId()),self.htmlText(contrib.getTitle()), material ))
     vars["contributions"] = "".join(contribList)
     vars["fullName"] = author.getFullName()
     vars["mailURL"]=urlHandlers.UHConferenceEmail.getURL(author)
     vars["mailIcon"]=Config.getInstance().getSystemIconURL("mail_big")
     vars["address"] = author.getAddress()
     vars["telephone"] = author.getPhone()
     vars["fax"] = author.getFax()
     vars["organisation"] = author.getAffiliation()
     return vars
Exemplo n.º 42
0
def render_error(message, description, standalone=False):
    if standalone:
        logo_url = Config.getInstance().getSystemIconURL("logoIndico")
        return render_template('standalone_error.html', error_message=message, error_description=description,
                               logo_url=logo_url)
    else:
        return WPErrorWSGI(message, description).getHTML()
Exemplo n.º 43
0
 def _process( self ):
     if not self._cancel:
         if not self._confirmed:
             p=RHMaintenanceTmpCleanup(self)
             return p.display()
         MaintenanceMng.cleanupTmp(Config.getInstance().getTempDir())
     self._redirect(urlHandlers.UHMaintenance.getURL())
Exemplo n.º 44
0
    def archiveTempBackgrounds(self, conf):
        """ Archives all the temporary backgrounds of this template.
        This method archives all of the temporary backgrounds of this template, which are
        stored in the form of filepath strings, in the __tempBackgroundsFilePaths dictionary,
        to a dictionary which stores LocalFile objects. The ids are copied, since there is a
        shared id counter for both dictionaries.
        After the archiving, the __tempBackgroundsFilePaths dictionary is reset to {}
        """

        for backgroundId, (filePath, bgPosition) in self.__tempBackgroundsFilePaths.iteritems():
            cfg = Config.getInstance()
            tempPath = cfg.getUploadedFilesSharedTempDir()
            filePath = os.path.join(tempPath, filePath)
            fileName = "background" + str(backgroundId) + "_t" + self.__id + "_c" + conf.id

            file = conference.LocalFile()
            file.setName( fileName )
            file.setDescription( "Background " + str(backgroundId) + " of the template " + self.__id + " of the conference " + conf.id )
            file.setFileName( fileName )
            file.setFilePath( filePath )

            file.setOwner( conf )
            file.setId( fileName )
            file.archive( conf._getRepository() )

            self.__backgrounds[backgroundId] = file
            self.__bgPositions[backgroundId] = bgPosition

        self.notifyModification()
        self.__tempBackgroundsFilePaths = {}
Exemplo n.º 45
0
    def setTemplate(self, name, description, format, fd, id, extension = ".template"):
        """ Stores a template.
            There can be 1 template for any format.
        """

        cfg = Config.getInstance()
        tempPath = cfg.getUploadedFilesTempDir()
        tempFileName = tempfile.mkstemp( suffix="MaKaC.tmp", dir = tempPath )[1]
        f = open( tempFileName, "wb" )
        f.write( fd.read() )
        f.close()

        #id = self.getNewTemplateId()

        fileName = "Contribution_template_" + id + "_c" + self._conference.id + extension

        file = conference.LocalFile()
        file.setName( fileName )
        file.setDescription( "Paper reviewing template with id " + id + "with format: " + format + " of the conference " + self._conference.id )
        file.setFileName( fileName )

        file.setFilePath( tempFileName )
        file.setOwner( self._conference )
        file.setId( fileName )
        file.archive( self._conference._getRepository() )

        self._templates[id] = Template(id, self._conference, name, description, format, file)
        self.notifyModification()
Exemplo n.º 46
0
    def getVars(self):
        vars = wcomponents.WTemplated.getVars( self )
        vars["logo"] = ""
        if self._conf.getLogo():
            vars["logo"] = "<img src=\"%s\" alt=\"%s\" border=\"0\">"%(vars["logoURL"], self._conf.getTitle())
        vars["confTitle"] = self._conf.getTitle()
        vars["displayURL"] = urlHandlers.UHConferenceDisplay.getURL(self._conf)
        vars["imgConferenceRoom"] = Config.getInstance().getSystemIconURL( "conferenceRoom" ) 
        tzUtil = timezoneUtils.DisplayTZ(self._aw,self._conf)
        tz = tzUtil.getDisplayTZ()
        adjusted_sDate = self._conf.getStartDate().astimezone(timezone(tz))
        adjusted_eDate = self._conf.getEndDate().astimezone(timezone(tz))

        vars["confDateInterval"] = "from %s to %s (%s)"%(adjusted_sDate.strftime("%d %B %Y"), adjusted_eDate.strftime("%d %B %Y"), tz)

        if self._conf.getStartDate().strftime("%d%B%Y") == \
                self._conf.getEndDate().strftime("%d%B%Y"):
            vars["confDateInterval"] = adjusted_sDate.strftime("%d %B %Y") + " (" + tz + ")"
        elif self._conf.getStartDate().month == self._conf.getEndDate().month:
            vars["confDateInterval"] = "%s-%s %s %s"%(adjusted_sDate.day, adjusted_eDate.day, adjusted_sDate.strftime("%B %Y"), tz)
        vars["body"] = self._body     
        vars["confLocation"] = ""
        if self._conf.getLocationList():
            vars["confLocation"] =  self._conf.getLocationList()[0].getName()
            vars["supportEmail"] = ""
        if self._conf.hasSupportEmail():
            mailto = quoteattr("""mailto:%s?subject=%s"""%(self._conf.getSupportEmail(), urllib.quote( self._conf.getTitle() ) ))
            vars["supportEmail"] =  _("""<a href=%s class="confSupportEmail"><img src="%s" border="0" alt="email">  _("support")</a>""")%(mailto, Config.getInstance().getSystemIconURL("mail") )
        format = displayMgr.ConfDisplayMgrRegistery().getDisplayMgr(self._conf).getFormat()
        vars["bgColorCode"] = format.getFormatOption("titleBgColor")["code"]
        vars["textColorCode"] = format.getFormatOption("titleTextColor")["code"]
        return vars                      
Exemplo n.º 47
0
 def _getTabContent( self, params ):
     p = WSEContributionCreation( self._conf )
     pars = {"postURL": urlHandlers.UHMConfPerformAddContribution.getURL(), \
     "calendarIconURL": Config.getInstance().getSystemIconURL( "calendar" ), \
     "calendarSelectURL":  urlHandlers.UHSimpleCalendar.getURL(), \
     "targetDay": self._targetDay}
     return p.getHTML(pars)
Exemplo n.º 48
0
    def _process(self):

        try:
            cfg = Config.getInstance()
            dir = os.path.join(cfg.getTPLDir(), "js")
            file = cfg.getTPLFile(self._tplName)

            if file == "":
                file = "%s.tpl" % self._tplName

            self._tplFile = os.path.join(dir, file)

            htmlPath = os.path.join(cfg.getTempDir(), file + ".tmp")

            if os.access(htmlPath, os.R_OK):
                fh = open(htmlPath, "r")
                htmlData = fh.read()
                fh.close()
            else:
                fh = open(self._tplFile, "r")
                text = fh.read()
                fh.close()

                self._dict["__rh__"] = self
                self._dict["user"] = None

                htmlData = TemplateExec().executeTemplate(
                    text, self._dict, self._tplName)
                fh = open(htmlPath, "w")
                fh.write(htmlData)
                fh.close()

        except Exception, e:
            return 'indicoError: %s' % e
Exemplo n.º 49
0
 def _process(self):
     # No need to do any processing here. The language change is processed in RH base
     # Remove lang param from referer
     referer = request.referrer or Config.getInstance().getBaseURL()
     referer = re.sub(r'(?<=[&?])lang=[^&]*&?', '', referer)
     referer = re.sub(r'[?&]$', '', referer)
     self._redirect(referer)
Exemplo n.º 50
0
    def _getTabContent( self, params ):
        wc = WContributionDataModification(self._target, self._conf)

        pars = {"postURL": urlHandlers.UHConfPerformAddContribution.getURL(), \
        "calendarIconURL": Config.getInstance().getSystemIconURL( "calendar" ), \
        "calendarSelectURL":  urlHandlers.UHSimpleCalendar.getURL() }
        return wc.getHTML( pars )
Exemplo n.º 51
0
    def getVars(self):
        vars = wcomponents.WTemplated.getVars(self)
        vars["logo"] = ""
        if self._conf.getLogo():
            vars["logo"] = "<img src=\"%s\" alt=\"%s\" border=\"0\">" % (
                vars["logoURL"], self._conf.getTitle())
        vars["confTitle"] = self._conf.getTitle()
        vars["displayURL"] = urlHandlers.UHConferenceDisplay.getURL(self._conf)
        vars["imgConferenceRoom"] = Config.getInstance().getSystemIconURL(
            "conferenceRoom")
        tzUtil = timezoneUtils.DisplayTZ(self._aw, self._conf)
        tz = tzUtil.getDisplayTZ()
        adjusted_sDate = self._conf.getStartDate().astimezone(timezone(tz))
        adjusted_eDate = self._conf.getEndDate().astimezone(timezone(tz))

        vars["confDateInterval"] = i18nformat(
            """_("from") %s _("to") %s (%s)""") % (format_date(
                adjusted_sDate,
                format='long'), format_date(adjusted_eDate, format='long'), tz)

        if self._conf.getStartDate().strftime("%d%B%Y") == \
                self._conf.getEndDate().strftime("%d%B%Y"):
            vars["confDateInterval"] = format_date(
                adjusted_sDate, format='long') + " (" + tz + ")"
        elif self._conf.getStartDate().month == self._conf.getEndDate().month:
            vars["confDateInterval"] = "%s-%s %s %s" % (
                adjusted_sDate.day, adjusted_eDate.day,
                format_date(adjusted_sDate, format='MMMM yyyy'), tz)
        vars["body"] = self._body
        vars["confLocation"] = ""
        if self._conf.getLocationList():
            vars["confLocation"] = self._conf.getLocationList()[0].getName()
            vars["supportEmail"] = ""
        if self._conf.hasSupportEmail():
            mailto = quoteattr("""mailto:%s?subject=%s""" %
                               (self._conf.getSupportEmail(),
                                urllib.quote(self._conf.getTitle())))
            vars["supportEmail"] = i18nformat(
                """<a href=%s class="confSupportEmail"><img src="%s" border="0" alt="email">  _("support")</a>"""
            ) % (mailto, Config.getInstance().getSystemIconURL("mail"))
        format = displayMgr.ConfDisplayMgrRegistery().getDisplayMgr(
            self._conf).getFormat()
        vars["bgColorCode"] = format.getFormatOption("titleBgColor")["code"]
        vars["textColorCode"] = format.getFormatOption(
            "titleTextColor")["code"]
        return vars
Exemplo n.º 52
0
 def getVars(self):
     vars = wcomponents.WTemplated.getVars(self)
     urlGen = vars.get("modAuthorURLGen", None)
     l = []
     for author in self._list:
         authCaption = author.getFullName()
         if author.getAffiliation() != "":
             authCaption = "%s (%s)" % (authCaption,
                                        author.getAffiliation())
         if urlGen:
             authCaption = """<a href=%s>%s</a>""" % (
                 urlGen(author), self.htmlText(authCaption))
         href = "\"\""
         if author.getEmail() != "":
             mailtoSubject = """[%s] _("Contribution") %s: %s""" % (
                 self._conf.getTitle(), self._contrib.getId(),
                 self._contrib.getTitle())
             mailtoURL = "mailto:%s?subject=%s" % (
                 author.getEmail(), urllib.quote(mailtoSubject))
             href = quoteattr(mailtoURL)
         emailHtml = """ <a href=%s><img src="%s" style="border:0px" alt="email"></a> """ % (
             href, Config.getInstance().getSystemIconURL("smallEmail"))
         upURLGen = vars.get("upAuthorURLGen", None)
         up = ""
         if upURLGen is not None:
             up = """<a href=%s><img src=%s border="0" alt="up"></a>""" % (
                 quoteattr(str(upURLGen(author))),
                 quoteattr(
                     str(Config.getInstance().getSystemIconURL("upArrow"))))
         downURLGen = vars.get("downAuthorURLGen", None)
         down = ""
         if downURLGen is not None:
             down = """<a href=%s><img src=%s border="0" alt="down"></a>""" % (
                 quoteattr(str(downURLGen(author))),
                 quoteattr(
                     str(Config.getInstance().getSystemIconURL(
                         "downArrow"))))
         l.append(
             """<input type="checkbox" name="selAuthor" value=%s>%s%s%s %s"""
             %
             (quoteattr(author.getId()), up, down, emailHtml, authCaption))
     vars["authors"] = "<br>".join(l)
     vars["remAuthorsURL"] = vars.get("remAuthorsURL", "")
     vars["addAuthorsURL"] = vars.get("addAuthorsURL", "")
     vars["searchAuthorURL"] = vars.get("searchAuthorURL", "")
     return vars
Exemplo n.º 53
0
 def _getLoginURL( self ):
     url = self.getCurrentURL()
     if url == "":
         url = urlHandlers.UHWelcome.getURL()
     urlLogin = str(urlHandlers.UHConfRegistrationFormSignIn.getURL( self._conf, url ))
     if Config.getInstance().getLoginURL().startswith("https"):
         urlLogin = urlLogin.replace("http://", "https://")
     return urlLogin
Exemplo n.º 54
0
 def _getAnswer(self):
     cfg = Config.getInstance()
     url = cfg.getFileTypeIconURL(self._fileType)
     
     if url == "":
         return None
     else:
         return url
Exemplo n.º 55
0
    def _execute(self, fdata):
        cfg = Config.getInstance()

        self._mime = cfg.getFileTypeMimeType(fdata['ftype'])

        if cfg.getUseXSendFile():
            return ""
        else:
            return fdata['data']