Esempio n. 1
0
    def _getHTMLHeader( self ):
        from MaKaC.webinterface.pages.conferences import WPConfSignIn
        from MaKaC.webinterface.pages.signIn import WPSignIn
        from MaKaC.webinterface.pages.registrationForm import WPRegistrationFormSignIn
        from MaKaC.webinterface.rh.base import RHModificationBaseProtected
        from MaKaC.webinterface.rh.admins import RHAdminBase

        baseurl = self._getBaseURL()
        if ((isinstance(self, WPSignIn) or isinstance(self, WPConfSignIn) or isinstance(self, WPRegistrationFormSignIn)) and \
                Config.getInstance().getLoginURL().startswith("https")) or \
                self._rh._req.is_https() and self._rh._tohttps:
            baseurl = baseurl.replace("http://","https://")
            baseurl = urlHandlers.setSSLPort( baseurl )

        area=""
        if isinstance(self._rh, RHModificationBaseProtected):
            area=_(""" - _("Management area")""")
        elif isinstance(self._rh, RHAdminBase):
            area=_(""" - _("Administrator area")""")

        return wcomponents.WHTMLHeader().getHTML({
                            "area": area,
                            "baseurl": baseurl,
                            "conf": Config.getInstance(),
                            "page": self,
                            "extraCSSFiles": self._extraCSSFiles,
                            "extraCSS": self._extraCSS,
                            "extraJSFiles": self.getJSFiles(),
                            "extraJS": self._extraJS,
                            "language": self._getAW().getSession().getLang()
                            })
Esempio n. 2
0
 def convert(filepath, converter, material):
     # Material UID
     materialUID="%s"%material.getLocator()
     # Getting variables
     responseURL = Config.getInstance().getFileConverterResponseURL()
     serverURL = Config.getInstance().getFileConverterServerURL()
     up = urlparse.urlparse(serverURL)
     if up[0] == "":
         #writeLog("Wrong conversion server URL")
         return
     host = up[1]
     selector = up[2]        
     # Checking the file
     localFile = filepath.strip()
     localFile = localFile.replace("\\", "/")
     filename = localFile.split("/")[-1]
     if not os.access(localFile, os.F_OK):
         #writeLog("Local file to upload invalid")
         return False
     fic=open(localFile, "rb")
     segnum=0
     segsize = SEGMENT_SIZE
     filekey = 'segfile'
     i = 0
     
     try :
         h = httplib.HTTP(host)
     except Exception, e:
         #writeLog("Error : Can't connect to host:%s"%host)
         return False
Esempio n. 3
0
    def _checkParams(self, params):

        self._params = params
        self._noQuery = False
        self._page = int(params.get('page', 1))

        isearch = Config.getInstance().getIndicoSearchServer()
        SEAClassName = Config.getInstance().getIndicoSearchClass()

        moduleName = '.'.join(SEAClassName.split('.')[:-1])
        self._SEAClassName = SEAClassName.split('.')[-1]
        self._searchingPrivate = self.getAW().getUser() != None

        # and now for some introspection magic...
        # load the requestClass from wherever it is, and instantiate a classobj
        clazz = getattr(__import__(moduleName, globals(), locals(), ['']),
                        self._SEAClassName)

        # now we can call the constructor
        self._seAdapter = clazz(self._target, self._searchingPrivate)

        if self._searchingPrivate:
            self._sessionHash = "%s_%s" % (self._getSession().getId(),
                                           self.getAW().getUser().getId())
        else:
            self._sessionHash = 'PUBLIC'
Esempio n. 4
0
 def _getBaseURL(self):
     if self._rh._req.is_https() and Config.getInstance().getBaseSecureURL(
     ):
         baseurl = Config.getInstance().getBaseSecureURL()
     else:
         baseurl = Config.getInstance().getBaseURL()
     return baseurl
Esempio n. 5
0
    def _sendErrorEmail(self, e):
        ty, ex, tb = sys.exc_info()
        tracebackList = traceback.format_list(traceback.extract_tb(tb))
        text = _("""
                    Offline website creation for the [event:%s] had caused
                    an error while running the task.

                    - Request from user: %s <%s>

                    - Details of the exception:
                        %s

                    - Traceback:

                        %s

                    --

                    <Indico support> indico-project @ cern.ch
                    """) % (self._conf.getId(), self._toUser.getFullName(),
                            self._toUser.getEmail(), e,
                            "\n".join(tracebackList))
        maildata = {
            "fromAddr": Config.getInstance().getSupportEmail(),
            "toList": [Config.getInstance().getSupportEmail()],
            "subject": _("[Indico] Error in task: Offline website creation"),
            "body": text
        }
        GenericMailer.send(GenericNotification(maildata))
Esempio n. 6
0
    def alertCreation(self, confs):
        conf = confs[0]
        fromAddr = Config.getInstance().getSupportEmail()
        addrs = [ Config.getInstance().getSupportEmail() ]
        eventType = conf.getType()
        if eventType == "conference":
            type = "conference"
        elif eventType == "meeting":
            type = "meeting"
        else:
            type = "lecture"
        chair = ""
        if conf.getChairmanText() != "":
            chair = conf.getChairmanText()
        else:
            for c in conf.getChairList():
                chair += c.getFullName() + "; "
        subject = "New %s in indico (%s)" % (type,conf.getId())
        if conf.getRoom() != None:
            room = conf.getRoom().getName()
        else:
            room = ""
        text = """
_Category_
%s
_Title_
%s
_Speaker/Chair_
%s
_Room_
%s
_Description_
%s
_Creator_
%s (%s)"""%(conf.getOwner().getTitle(), conf.getTitle(), chair, room, conf.getDescription(), conf.getCreator().getFullName(), conf.getCreator().getId())
        if len(confs) == 1:
            text += """
_Date_
%s -> %s
_Access_
%s""" % ( conf.getAdjustedStartDate(), conf.getAdjustedEndDate(), urlHandlers.UHConferenceDisplay.getURL(conf))
        else:
            i = 1
            for c in confs:
                text += """
_Date%s_
%s -> %s
_Access%s_
%s """ % (i,c.getAdjustedStartDate(), c.getAdjustedEndDate(), i,urlHandlers.UHConferenceDisplay.getURL(c))
                i+=1

        msg = ("Content-Type: text/plain; charset=\"utf-8\"\r\nFrom: %s\r\nReturn-Path: %s\r\nTo: %s\r\nCc: \r\nSubject: %s\r\n\r\n"%(fromAddr, fromAddr, addrs, subject))
        msg = msg + text
        maildata = { "fromAddr": fromAddr, "toList": addrs, "subject": subject, "body": text }
        GenericMailer.send(maildata)
        # Category notification
        if conf.getOwner().getNotifyCreationList() != "":
            addrs2 = [ conf.getOwner().getNotifyCreationList() ]
            maildata2 = { "fromAddr": fromAddr, "toList": addrs2, "subject": subject, "body": text }
            GenericMailer.send(maildata2)
Esempio n. 7
0
    def alertCreation(self, confs):
        conf = confs[0]
        fromAddr = Config.getInstance().getSupportEmail()
        addrs = [ Config.getInstance().getSupportEmail() ]
        eventType = conf.getType()
        if eventType == "conference":
            type = "conference"
        elif eventType == "meeting":
            type = "meeting"
        else:
            type = "lecture"
        chair = ""
        if conf.getChairmanText() != "":
            chair = conf.getChairmanText()
        else:
            for c in conf.getChairList():
                chair += c.getFullName() + "; "
        subject = "New %s in indico (%s)" % (type,conf.getId())
        if conf.getRoom() != None:
            room = conf.getRoom().getName()
        else:
            room = ""
        text = """
_Category_
%s
_Title_
%s
_Speaker/Chair_
%s
_Room_
%s
_Description_
%s
_Creator_
%s (%s)"""%(conf.getOwner().getTitle(), conf.getTitle(), chair, room, conf.getDescription(), conf.getCreator().getFullName(), conf.getCreator().getId())
        if len(confs) == 1:
            text += """
_Date_
%s -> %s
_Access_
%s""" % ( conf.getAdjustedStartDate(), conf.getAdjustedEndDate(), urlHandlers.UHConferenceDisplay.getURL(conf))
        else:
            i = 1
            for c in confs:
                text += """
_Date%s_
%s -> %s
_Access%s_
%s """ % (i,c.getAdjustedStartDate(), c.getAdjustedEndDate(), i,urlHandlers.UHConferenceDisplay.getURL(c))
                i+=1

        msg = ("Content-Type: text/plain; charset=\"utf-8\"\r\nFrom: %s\r\nReturn-Path: %s\r\nTo: %s\r\nCc: \r\nSubject: %s\r\n\r\n"%(fromAddr, fromAddr, addrs, subject))
        msg = msg + text
        maildata = { "fromAddr": fromAddr, "toList": addrs, "subject": subject, "body": text }
        GenericMailer.send(maildata)
        # Category notification
        if conf.getOwner().getNotifyCreationList() != "":
            addrs2 = [ conf.getOwner().getNotifyCreationList() ]
            maildata2 = { "fromAddr": fromAddr, "toList": addrs2, "subject": subject, "body": text }
            GenericMailer.send(maildata2)
Esempio n. 8
0
def generate_public_auth_request(apiMode, apiKey, path, params= {}, persistent=False, https = True):
    from indico.web.http_api import API_MODE_KEY, API_MODE_ONLYKEY, API_MODE_SIGNED, API_MODE_ONLYKEY_SIGNED, API_MODE_ALL_SIGNED

    key = apiKey.getKey() if apiKey else None
    secret_key = apiKey.getSignKey() if apiKey else None
    if https:
        baseURL = Config.getInstance().getBaseSecureURL()
    else:
        baseURL = Config.getInstance().getBaseURL()
    publicRequestsURL = None
    authRequestURL = None
    if apiMode == API_MODE_KEY:
        publicRequestsURL = build_indico_request(path, params)
        authRequestURL = build_indico_request(path, params, key) if key else None
    elif apiMode == API_MODE_ONLYKEY:
        authRequestURL = build_indico_request(path, params, key) if key else None
        params["onlypublic"] = "yes"
        publicRequestsURL = build_indico_request(path, params, key) if key else None
    elif apiMode == API_MODE_SIGNED:
        publicRequestsURL = build_indico_request(path, params)
        authRequestURL = build_indico_request(path, params, key, secret_key, persistent)  if key and secret_key else None
    elif apiMode == API_MODE_ONLYKEY_SIGNED:
        publicRequestsURL = build_indico_request(path, params, key)  if key else None
        authRequestURL = build_indico_request(path, params, key, secret_key, persistent)  if key and secret_key else None
    elif apiMode == API_MODE_ALL_SIGNED:
        authRequestURL = build_indico_request(path, params, key, secret_key, persistent)  if key else None
        params["onlypublic"] = "yes"
        publicRequestsURL = build_indico_request(path, params, key, secret_key, persistent)  if key else None
    return {"publicRequestURL": (baseURL + publicRequestsURL) if publicRequestsURL else "", "authRequestURL": (baseURL + authRequestURL) if authRequestURL else ""}
Esempio n. 9
0
    def convert(filepath, converter, material):
        # Material UID
        materialUID = "%s" % material.getLocator()
        # Getting variables
        responseURL = Config.getInstance().getFileConverterResponseURL()
        serverURL = Config.getInstance().getFileConverterServerURL()
        up = urlparse.urlparse(serverURL)
        if up[0] == "":
            #writeLog("Wrong conversion server URL")
            return
        host = up[1]
        selector = up[2]
        # Checking the file
        localFile = filepath.strip()
        localFile = localFile.replace("\\", "/")
        filename = localFile.split("/")[-1]
        if not os.access(localFile, os.F_OK):
            #writeLog("Local file to upload invalid")
            return False
        fic = open(localFile, "rb")
        segnum = 0
        segsize = SEGMENT_SIZE
        filekey = 'segfile'
        i = 0

        try:
            h = httplib.HTTP(host)
        except Exception, e:
            #writeLog("Error : Can't connect to host:%s"%host)
            return False
Esempio n. 10
0
    def _sendErrorEmail(self, e):
        ty, ex, tb = sys.exc_info()
        tracebackList = traceback.format_list(traceback.extract_tb(tb))
        text = (
            _(
                """
                    Offline website creation for the [event:%s] had caused
                    an error while running the task.

                    - Request from user: %s <%s>

                    - Details of the exception:
                        %s

                    - Traceback:

                        %s

                    --

                    <Indico support> indico-project @ cern.ch
                    """
            )
            % (self._conf.getId(), self._toUser.getFullName(), self._toUser.getEmail(), e, "\n".join(tracebackList))
        )
        maildata = {
            "fromAddr": Config.getInstance().getSupportEmail(),
            "toList": [Config.getInstance().getSupportEmail()],
            "subject": _("[Indico] Error in task: Offline website creation"),
            "body": text,
        }
        GenericMailer.send(GenericNotification(maildata))
Esempio n. 11
0
def generate_public_auth_request(apiMode, apiKey, path, params= {}, persistent=False, https = True):
    from indico.web.http_api import API_MODE_KEY, API_MODE_ONLYKEY, API_MODE_SIGNED, API_MODE_ONLYKEY_SIGNED, API_MODE_ALL_SIGNED

    key = apiKey.getKey() if apiKey else None
    secret_key = apiKey.getSignKey() if apiKey else None
    if https:
        baseURL = Config.getInstance().getBaseSecureURL()
    else:
        baseURL = Config.getInstance().getBaseURL()
    publicRequestsURL = None
    authRequestURL = None
    if apiMode == API_MODE_KEY:
        publicRequestsURL = build_indico_request(path, params)
        authRequestURL = build_indico_request(path, params, key) if key else None
    elif apiMode == API_MODE_ONLYKEY:
        authRequestURL = build_indico_request(path, params, key) if key else None
        params["onlypublic"] = "yes"
        publicRequestsURL = build_indico_request(path, params, key) if key else None
    elif apiMode == API_MODE_SIGNED:
        publicRequestsURL = build_indico_request(path, params)
        authRequestURL = build_indico_request(path, params, key, secret_key, persistent)  if key and secret_key else None
    elif apiMode == API_MODE_ONLYKEY_SIGNED:
        publicRequestsURL = build_indico_request(path, params, key)  if key else None
        authRequestURL = build_indico_request(path, params, key, secret_key, persistent)  if key and secret_key else None
    elif apiMode == API_MODE_ALL_SIGNED:
        authRequestURL = build_indico_request(path, params, key, secret_key, persistent)  if key else None
        params["onlypublic"] = "yes"
        publicRequestsURL = build_indico_request(path, params, key, secret_key, persistent)  if key else None
    return {"publicRequestURL": (baseURL + publicRequestsURL) if publicRequestsURL else "", "authRequestURL": (baseURL + authRequestURL) if authRequestURL else ""}
Esempio n. 12
0
    def getCore(self, rss):
        date = str(
            self._conf.getAdjustedStartDate(
                self._tz).strftime("%a, %d %b %Y %H:%M:%S %Z"))
        title = "%s - %s" % (date, self._conf.getTitle())
        if Config.getInstance().getShortEventURL() != "":
            url = "%s%s" % (Config.getInstance().getShortEventURL(),
                            self._conf.getId())
        else:
            url = urlHandlers.UHConferenceDisplay.getURL(self._conf)
        rss.openTag("item")
        rss.writeTag("title", title)
        rss.writeTag("link", url)

        if not self._protected:
            desc = self._conf.getDescription()
        else:
            desc = ""

        rss.writeTag("description", desc)
        rss.writeTag(
            "pubDate",
            self._conf.getAdjustedModificationDate(
                self._tz).strftime("%a, %d %b %Y %H:%M:%S %Z"))
        rss.writeTag("guid", url)
        rss.closeTag("item")
        return rss
Esempio n. 13
0
 def _process(self):
     try:
         user = self._request_token.getUser()
         access_tokens = Catalog.getIdx('user_oauth_access_token').get(user.getId())
         timestamp = nowutc()
         if access_tokens is not None:
             for access_token in list(access_tokens):
                 if access_token.getConsumer().getName() == self._request_token.getConsumer().getName():
                     access_token.setTimestamp(timestamp)
                     response = {'oauth_token': access_token.getId(),
                                 'oauth_token_secret': access_token.getToken().secret,
                                 'user_id': user.getId(),
                                 'oauth_token_ttl': Config.getInstance().getOAuthAccessTokenTTL(),
                                 'oauth_token_expiration_timestamp': access_token.getTimestamp() +
                                 timedelta(seconds=Config.getInstance().getOAuthAccessTokenTTL())}
                     return urlencode(response)
         access_token_key = OAuthUtils.gen_random_string()
         access_token_secret = OAuthUtils.gen_random_string()
         access_token = Token(access_token_key, oauth.Token(access_token_key, access_token_secret),
                              timestamp, self._request_token.getConsumer(), user)
         AccessTokenHolder().add(access_token)
         response = {'oauth_token': access_token_key,
                     'oauth_token_secret': access_token_secret,
                     'user_id': user.getId(),
                     'oauth_token_ttl': Config.getInstance().getOAuthAccessTokenTTL(),
                     'oauth_token_expiration_timestamp': access_token.getTimestamp() +
                     timedelta(seconds=Config.getInstance().getOAuthAccessTokenTTL())}
         return urlencode(response)
     except oauth.Error, err:
         raise OAuthError(err.message, 401)
Esempio n. 14
0
def cleanCache():
    """ removes an entire cache directory"""
    path = os.path.join(Config().getInstance().getXMLCacheDir(), "categories")
    if os.path.exists(path):
        shutil.rmtree(path)
    path = os.path.join(Config().getInstance().getXMLCacheDir(), "events")
    if os.path.exists(path):
        shutil.rmtree(path)
Esempio n. 15
0
    def _setFakeConfig(self, custom):
        """
        Sets a fake configuration for the current process, using a temporary directory
        """
        config = Config.getInstance()
        test_config = TestConfig.getInstance()

        temp = tempfile.mkdtemp(prefix="indico_")
        self._info('Using %s as temporary dir' % temp)

        os.mkdir(os.path.join(temp, 'log'))
        os.mkdir(os.path.join(temp, 'archive'))

        indicoDist = pkg_resources.get_distribution('indico')
        htdocsDir = indicoDist.get_resource_filename('indico', 'indico/htdocs')
        etcDir = indicoDist.get_resource_filename('indico', 'etc')

        # minimal defaults
        defaults = {
            'BaseURL':
            'http://localhost:8000/indico',
            'BaseSecureURL':
            '',
            'UseXSendFile':
            False,
            'AuthenticatorList': ['Local'],
            'SmtpServer': ('localhost', 58025),
            'SmtpUseTLS':
            'no',
            'DBConnectionParams':
            ('localhost', TestConfig.getInstance().getFakeDBPort()),
            'LogDir':
            os.path.join(temp, 'log'),
            'XMLCacheDir':
            os.path.join(temp, 'cache'),
            'HtdocsDir':
            htdocsDir,
            'ArchiveDir':
            os.path.join(temp, 'archive'),
            'UploadedFilesTempDir':
            os.path.join(temp, 'tmp'),
            'ConfigurationDir':
            etcDir
        }

        defaults.update(custom)

        # set defaults
        config.reset(defaults)

        Config.setInstance(config)
        self._cfg = config

        # re-configure logging and template generator, so that paths are updated
        from MaKaC.common import TemplateExec
        from MaKaC.common.logger import Logger
        TemplateExec.mako = TemplateExec._define_lookup()
        Logger.reset()
Esempio n. 16
0
    def create(self):
        config = Config.getInstance()
        self._fileHandler = ZIPFileHandler()

        # create the home page html
        self._create_home()

        # Create main and static folders
        self._mainPath = "OfflineWebsite-%s" % self._normalize_path(self._conf.getTitle())
        self._fileHandler.addDir(self._mainPath)
        self._staticPath = os.path.join(self._mainPath, "static")
        self._fileHandler.addDir(self._staticPath)
        # Add i18n js
        self._addFolderFromSrc(
            os.path.join(self._staticPath, "js", "indico", "i18n"),
            os.path.join(config.getHtdocsDir(), "js", "indico", "i18n"),
        )
        # Add system icons (not referenced in HTML/CSS)
        for icon in Config.getInstance().getSystemIcons().itervalues():
            self._addFileFromSrc(
                os.path.join(self._staticPath, "images", icon), os.path.join(config.getHtdocsDir(), "images", icon)
            )
        # IE compat files (in conditional comments so BS doesn't see them)
        for path in ie_compatibility.urls():
            self._addFileFromSrc(
                os.path.join(self._staticPath, path.lstrip("/")), os.path.join(config.getHtdocsDir(), path.lstrip("/"))
            )

        # Getting all materials, static files (css, images, js and vars.js.tpl)
        self._getAllMaterial()
        self._html = self._get_static_files(self._html)

        # Specific changes
        self._create_other_pages()

        # Retrieve files that were not available in the file system (e.e. js/css from plugins)
        self._get_failed_paths()
        self._failed_paths = set()

        # Retrieve files referenced in CSS files
        self._get_css_refs()

        # A custom event CSS might reference an uploaded image so we need to check for failed paths again
        self._get_failed_paths()

        # Creating ConferenceDisplay.html file
        conferenceDisplayPath = os.path.join(self._mainPath, urlHandlers.UHConferenceDisplay.getStaticURL())
        self._fileHandler.addNewFile(conferenceDisplayPath, self._html)

        # Creating index.html file
        self._fileHandler.addNewFile(
            "index.html", '<meta http-equiv="Refresh" content="0; url=%s">' % conferenceDisplayPath
        )

        self._fileHandler.close()
        self._outputFile = self._generateZipFile(self._fileHandler.getPath())
        return self._outputFile
Esempio n. 17
0
def getReportNumberItems(obj):
    rns = obj.getReportNumberHolder().listReportNumbers()
    reportCodes = []

    for rn in rns:
        key = rn[0]
        if key in Config.getInstance().getReportNumberSystems().keys():
            number = rn[1]
            reportNumberId="s%sr%s"%(key, number)
            name = Config.getInstance().getReportNumberSystems()[key]["name"]
            reportCodes.append({"id" : reportNumberId, "number": number, "system": key, "name": name})
    return reportCodes
Esempio n. 18
0
def _fix_url_path(path):
    """Sanitizes an URL extracted from the HTML document"""
    if path.startswith("static/"):
        # It's a path that was prefixed with baseurl
        path = path[7:]
    elif path.startswith(Config.getInstance().getBaseURL()):
        path = path[len(Config.getInstance().getBaseURL()) :]
    elif path.startswith(Config.getInstance().getBaseSecureURL()):
        path = path[len(Config.getInstance().getBaseSecureURL()) :]
    path = path.lstrip("/")
    path = _remove_qs(path)
    return path
Esempio n. 19
0
 def getVars( self ):
     
     vars = wcomponents.WTemplated.getVars( self )
     vars["title"] = self._file.getName()
     vars["description"] = self._file.getDescription()
     vars["type"] = self._file.getFileType()
     vars["typeDesc"] = Config.getInstance().getFileTypeDescription( self._file.getFileType() )
     vars["downloadImg"] = Config.getInstance().getSystemIconURL("download")
     vars["fileName"] = self._file.getFileName()
     vars["fileSize"] = strfFileSize( self._file.getSize() )
     
     return vars
Esempio n. 20
0
 def getByLoginOrUPN(self, id):
     params = urllib.urlencode({'UserName': "******"%id})
     #headers = {"Content-type": "application/x-www-form-urlencoded", "Accept": "text/plain"}
     cred = base64.encodestring("%s:%s"%(Config.getInstance().getNiceLogin(), Config.getInstance().getNicePassword()))[:-1]
     headers = {}
     headers["Content-type"] = "application/x-www-form-urlencoded"
     headers["Accept"] = "text/plain"
     headers["Authorization"] = "Basic %s"%cred
     conn = httplib.HTTPSConnection("winservices-soap.web.cern.ch")
     try:
         conn.request("POST", "/winservices-soap/generic/Authentication.asmx/GetUserInfoFromLogin", params, headers)
     except Exception, e:
         raise MaKaCError( _("Sorry, due to a temporary unavailability of the NICE service, we are unable to authenticate you. Please try later or use your local Indico account if you have one."))
Esempio n. 21
0
    def getVars(self):

        vars = wcomponents.WTemplated.getVars(self)
        vars["title"] = self._file.getName()
        vars["description"] = self._file.getDescription()
        vars["type"] = self._file.getFileType()
        vars["typeDesc"] = Config.getInstance().getFileTypeDescription(
            self._file.getFileType())
        vars["downloadImg"] = Config.getInstance().getSystemIconURL("download")
        vars["fileName"] = self._file.getFileName()
        vars["fileSize"] = strfFileSize(self._file.getSize())

        return vars
Esempio n. 22
0
 def _getMaterialHTML(self):
     lm = []
     paper = self._subContrib.getPaper()
     if paper is not None:
         lm.append(
             """<a href=%s><img src=%s border="0" alt="paper"> %s</a>""" %
             (quoteattr(str(urlHandlers.UHMaterialDisplay.getURL(paper))),
              quoteattr(str(materialFactories.PaperFactory().getIconURL())),
              self.htmlText(materialFactories.PaperFactory().getTitle())))
     slides = self._subContrib.getSlides()
     if slides is not None:
         lm.append(
             """<a href=%s><img src=%s border="0" alt="slide"> %s</a>""" %
             (quoteattr(str(urlHandlers.UHMaterialDisplay.getURL(slides))),
              quoteattr(str(
                  materialFactories.SlidesFactory().getIconURL())),
              self.htmlText(materialFactories.SlidesFactory().getTitle())))
     poster = self._subContrib.getPoster()
     if poster is not None:
         lm.append(
             """<a href=%s><img src=%s border="0" alt="poster"> %s</a>""" %
             (quoteattr(str(urlHandlers.UHMaterialDisplay.getURL(poster))),
              quoteattr(str(
                  materialFactories.PosterFactory().getIconURL())),
              self.htmlText(materialFactories.PosterFactory().getTitle())))
     video = self._subContrib.getVideo()
     if video is not None:
         lm.append(
             """<a href=%s><img src=%s border="0" alt="video"> %s</a>""" %
             (quoteattr(str(urlHandlers.UHMaterialDisplay.getURL(video))),
              quoteattr(str(materialFactories.VideoFactory().getIconURL())),
              self.htmlText(materialFactories.VideoFactory().getTitle())))
     iconURL = quoteattr(
         str(Config.getInstance().getSystemIconURL("material")))
     minutes = self._subContrib.getMinutes()
     if minutes is not None:
         lm.append(
             """<a href=%s><img src=%s border="0" alt="minutes"> %s</a>""" %
             (quoteattr(str(urlHandlers.UHMaterialDisplay.getURL(minutes))),
              quoteattr(str(
                  materialFactories.MinutesFactory().getIconURL())),
              self.htmlText(materialFactories.MinutesFactory().getTitle())))
     iconURL = quoteattr(
         str(Config.getInstance().getSystemIconURL("material")))
     for material in self._subContrib.getMaterialList():
         url = urlHandlers.UHMaterialDisplay.getURL(material)
         lm.append("""<a href=%s><img src=%s border="0" alt=""> %s</a>""" %
                   (quoteattr(str(url)), iconURL,
                    self.htmlText(material.getTitle())))
     return self._getHTMLRow("Material", "<br>".join(lm))
Esempio n. 23
0
    def check(self, userName, Password):
        #Use the nue nice interface to retrieve the user data
##        try:
            params = urllib.urlencode({'Username': userName, 'Password': Password})
            #headers = {"Content-type": "application/x-www-form-urlencoded", "Accept": "text/plain"}
            cred = base64.encodestring("%s:%s"%(Config.getInstance().getNiceLogin(), Config.getInstance().getNicePassword()))[:-1]
            headers = {}
            headers["Content-type"] = "application/x-www-form-urlencoded"
            headers["Accept"] = "text/plain"
            headers["Authorization"] = "Basic %s"%cred
            conn = httplib.HTTPSConnection("winservices-soap.web.cern.ch")
            try:
                conn.request("POST", "/winservices-soap/generic/Authentication.asmx/GetUserInfo", params, headers)
            except Exception, e:
                raise MaKaCError( _("Sorry, due to a temporary unavailability of the NICE service, we are unable to authenticate you. Please try later or use your local Indico account if you have one."))
Esempio n. 24
0
    def OAuthCheckAccessResource(cls, req, query_string):
        from indico.modules.oauth.db import  ConsumerHolder, AccessTokenHolder, OAuthServer

        oauth_request = oauth.Request.from_request(req.get_method(),req.construct_url(req.get_uri()), headers=req.headers_in, query_string=urlencode(query_string))
        Logger.get('oauth.resource').info(oauth_request)
        try:
            now = time.time()
            consumer_key = oauth_request.get_parameter('oauth_consumer_key')
            if not ConsumerHolder().hasKey(consumer_key):
                raise OAuthError('Invalid Consumer Key' , apache.HTTP_UNAUTHORIZED)
            consumer = ConsumerHolder().getById(consumer_key)
            token = oauth_request.get_parameter('oauth_token')
            if not token or not AccessTokenHolder().hasKey(token):
                raise OAuthError('Invalid Token', apache.HTTP_UNAUTHORIZED)
            access_token = AccessTokenHolder().getById(token)
            oauth_consumer = oauth.Consumer(consumer.getId(), consumer.getSecret())
            OAuthServer.getInstance().verify_request(oauth_request, oauth_consumer, access_token.getToken())
            if access_token.getConsumer().getId() != oauth_consumer.key:
                raise OAuthError('Invalid Consumer Key' , apache.HTTP_UNAUTHORIZED)
            elif (now - access_token.getTimestamp()) > Config.getInstance().getOAuthAccessTokenTTL():
                raise OAuthError('Expired Token', apache.HTTP_UNAUTHORIZED)
            return access_token
        except oauth.Error, e:
            if e.message.startswith("Invalid Signature"):
                raise OAuthError("Invalid Signature", apache.HTTP_UNAUTHORIZED)
            else:
                raise OAuthError(e.message, apache.HTTP_BAD_REQUEST)
Esempio n. 25
0
 def getFromAddr(self):
     # TODO: There will be on "from address" from a conference, but what if there are more different conferences
     supEmail = self._psList[0].getConference().getSupportInfo().getEmail(returnNoReply=True)
     if self._forceIndicoFromAddress or supEmail.strip()=="":
         info = HelperMaKaCInfo.getMaKaCInfoInstance()
         return "%s <%s>"%(info.getTitle(), Config.getInstance().getSupportEmail())
     return supEmail
Esempio n. 26
0
def getCat(Cat, fid, icon):#checks if Category exists, creates if need be, then returns the Category to add Conference to
    if fid != '0': #If level is below root
        cursor = agenda.cursor()
        cursor.execute("select * from LEVEL where uid = \'" + fid + "\'")#gets parent LEVEL
        cp = cursor.fetchone()#gets parent info
        #cp[0]-uid, cp[1]-fid, cp[2]-level, cp[3]-title, cp[4]-cd, cp[5]-md, cp[6]-abstract, cp[7]-icon
        #cp[8]-stitle, cp[9]-visibility, cp[10]-modifyPassword, cp[11]-accessPassword, cp[12]-categorder
        if cp[1] == "delet":
            return None
        newCat = conference.Category()#creates Category with parents properties
        newCat.setName(cp[3])
        newCat.setDescription(cp[6])
        newCat.setOrder(cp[12])
        newCat.setVisibility(cp[9])
        newCat.setId(cp[0])
        catParent = getCat(newCat, cp[1], cp[7])#goes to fetch the parent category
    else:#If at root level get the root category
        catParent = conference.CategoryManager().getRoot()
    catlist = catParent.getSubCategoryList()#get list of subcategories already in category
    for tup in catlist:#checks if the category already exists and returns it
        if tup.name == Cat.name and tup.id == Cat.id:
            return tup
    #if category doesn't exist - create it
    catParent.newSubCategory(Cat)
    if icon != "":
        iconpath = Config.getInstance().getCategoryIconPath(Cat.getId())
        os.system("scp tbaron@%s:%s/%s.gif /tmp/%s.gif" % (file_host,hosticonpath,Cat.getId(),Cat.getId()))
        os.system("convert /tmp/%s.gif %s" % (Cat.getId(),iconpath))
    #get_transaction().commit()
    return Cat
Esempio n. 27
0
    def requestConfirmation(owner, block, roomBlockings):
        """
        Notifies (e-mails) room owner about blockings he has to approve.
        Expects only blockings for rooms owned by the specified owner
        """

        emails = []
        # ---- Email creator and contact ----

        to = owner.getEmail()

        subject = "Confirm room blockings"
        wc = WTemplated('RoomBookingEmail_2ResponsibleConfirmBlocking')
        text = wc.getHTML({
            'owner': owner,
            'block': block,
            'roomBlockings': roomBlockings
        })
        fromAddr = Config.getInstance().getNoReplyEmail()
        mailData = {
            "fromAddr": fromAddr,
            "toList": [to],
            "subject": subject,
            "body": text
        }
        emails.append(mailData)
        return emails
Esempio n. 28
0
    def _getAnswer(self):
        spkWrapper = None
        manager = Catalog.getIdx("cs_bookingmanager_conference").get(self._conf.getId())
        for sw in manager.getSpeakerWrapperList():
            if sw.getUniqueIdHash() == self.authKey:
                spkWrapper = sw

        if spkWrapper:
            spkWrapper.setStatus(SpeakerStatusEnum.SIGNED, request.remote_addr)
            spkWrapper.triggerNotification()
            if manager.notifyElectronicAgreementAnswer():
                subject = """[Indico] Electronic Agreement Accepted: '%s'""" % (self._conf.getTitle())
                content = _(self.MESSAGE_ACCEPT).format(
                    speaker=spkWrapper.getObject().getDirectFullName(),
                    title=self._conf.getTitle(),
                    url=self._conf.getURL(),
                )
                emailToList = [self._conf.getCreator().getEmail()]
                for event_manager in self._conf.getManagerList():
                    emailToList.append(event_manager.getEmail())
                notification = ElectronicAgreementOrganiserNotification(
                    emailToList, Config.getInstance().getNoReplyEmail(), content, subject
                )

                GenericMailer.sendAndLog(notification, self._conf, MODULE_NAME)
Esempio n. 29
0
    def _getAnswer(self):
        spkWrapper = None
        manager = self._conf.getCSBookingManager()
        for sw in manager.getSpeakerWrapperList():
            if sw.getUniqueIdHash() == self.authKey:
                spkWrapper = sw

        if spkWrapper:
            spkWrapper.setStatus(SpeakerStatusEnum.REFUSED)
            spkWrapper.setRejectReason(self.reason)
            spkWrapper.triggerNotification()
            if manager.notifyElectronicAgreementAnswer():
                subject = """[Indico] Electronic Agreement Rejected: '%s'""" % (self._conf.getTitle())
                content = _(self.MESSAGE_REJECT).format(
                    speaker=spkWrapper.getObject().getDirectFullName(),
                    title=self._conf.getTitle(),
                    reason=self.reason,
                    url=self._conf.getURL())
                emailToList = [self._conf.getCreator().getEmail()]
                for event_manager in self._conf.getManagerList():
                    emailToList.append(event_manager.getEmail())
                notification = ElectronicAgreementOrganiserNotification(emailToList, Config.getInstance().getNoReplyEmail(), content, subject)

                GenericMailer.sendAndLog(notification, self._conf,
                                         MODULE_NAME)
Esempio n. 30
0
    def _getItem( self, categ, level=0 ):
        if not categ.canView( self._aw ):
            return ""
        html = ""
        number=self._number.newCount()
        for i in range(level):
            html = "%s&nbsp;&nbsp;&nbsp;"%html
        cfg = Config.getInstance()
        checked = ""

        if categ in self._selCategs:
            checked = "checked"
        title = """<input type="checkbox" name="selCateg" id="%s" onClick="alerta(%s);" value="%s" %s> %s"""%\
                    (number,number,categ.getId(), checked, categ.getName() )
        if categ in self._expandedCategs:
            temp = copy( self._expandedCategs )
            temp.remove( categ )
            html = """%s<a href="%s"><img src="%s" border="0" alt="fold"></a> %s"""%\
                (   html, \
                    self._expandURLGen( temp ), \
                    cfg.getSystemIconURL("itemExploded"), \
                    title )
            for subcat in categ.getSubCategoryList():
                html = "%s<br>%s"%(html, self._getItem(subcat, level+1) )
        else:
            html = """%s<a href="%s"><img src="%s" border="0" alt="unfold"></a> %s"""%\
                (   html, \
                    self._expandURLGen( self._expandedCategs+[categ] ), \
                    cfg.getSystemIconURL("itemCollapsed"), \
                    title )
        return html
Esempio n. 31
0
    def _getAnswer(self):
        spkWrapper = None
        manager = self._conf.getCSBookingManager()
        for sw in manager.getSpeakerWrapperList():
            if sw.getUniqueIdHash() == self.authKey:
                spkWrapper = sw

        if spkWrapper:
            spkWrapper.setStatus(SpeakerStatusEnum.SIGNED,
                                 self._req.get_remote_ip())
            spkWrapper.triggerNotification()
            if manager.notifyElectronicAgreementAnswer():
                subject = """[Indico] Electronic Agreement Accepted: '%s'""" % (
                    self._conf.getTitle())
                content = _(self.MESSAGE_ACCEPT).format(
                    speaker=spkWrapper.getObject().getDirectFullName(),
                    title=self._conf.getTitle(),
                    url=self._conf.getURL())
                emailToList = [self._conf.getCreator().getEmail()]
                for event_manager in self._conf.getManagerList():
                    emailToList.append(event_manager.getEmail())
                notification = ElectronicAgreementOrganiserNotification(
                    emailToList,
                    Config.getInstance().getNoReplyEmail(), content, subject)

                GenericMailer.sendAndLog(notification, self._conf, MODULE_NAME)
Esempio n. 32
0
 def _process(self):
     from MaKaC.common.Configuration import Config
     from MaKaC.externUsers import ExtUserHolder
     from urllib import urlencode
     euh = ExtUserHolder()
     ah = user.AvatarHolder()
     newIdentityList = []
     for id in self._identityList:
         newId = id
         for authId in Config.getInstance().getAuthenticatorList():
             if id[:len(authId)] == authId:
                 dict = euh.getById(authId).getById(id.split(':')[1])
                 av = user.Avatar(dict)
                 newId = ah.add(av)
                 identity = dict["identity"](dict["login"], av)
                 try:
                     dict["authenticator"].add(identity)
                 except:
                     pass
                 av.activateAccount()
         newIdentityList.append("selectedPrincipals=%s" % newId)
     if self._addURL.find("?") != -1:
         targetURL = self._addURL + "&" + urlencode(
             self._params) + "&" + "&".join(newIdentityList)
     else:
         targetURL = self._addURL + "?" + urlencode(
             self._params) + "&" + "&".join(newIdentityList)
     self._redirect(targetURL)
Esempio n. 33
0
 def getFromAddr(self):
     # TODO: There will be on "from address" from a conference, but what if there are more different conferences
     supEmail = self._psList[0].getConference().getSupportInfo().getEmail(returnNoReply=True)
     if self._forceIndicoFromAddress or supEmail.strip()=="":
         info = HelperMaKaCInfo.getMaKaCInfoInstance()
         return "%s <%s>"%(info.getTitle(), Config.getInstance().getSupportEmail())
     return supEmail
Esempio n. 34
0
    def __init__(self, booking):
        VidyoOwnerNotificationBase.__init__(self)
        self._owner = booking.getOwnerObject()

        self.setFromAddr("Indico Mailer <%s>" % Config.getInstance().getSupportEmail())
        self.setContentType("text/html")

        owner = booking.getOwnerObject()
        event = booking.getConference()

        self.setToList([owner.getEmail()])

        self.setSubject("""[Indico] The Vidyo public room %s has been deleted""" % booking.getBookingParamByName("roomName") )

        self.setBody("""Dear %s%s,<br />
<br />
Please note that the Vidyo room named "%s" associated with the Indico event <a href="%s">%s</a>, of which you were the owner, has been deleted by a manager of this event.<br />
<br />
Thank you for using Vidyo and Indico<br />
"""%
                     (self._getOwnerTitleText(),
                      owner.getStraightFullName(),
                      booking.getBookingParamByName("roomName"),
                      urlHandlers.UHConferenceDisplay.getURL(event),
                      event.getTitle()))
Esempio n. 35
0
    def _getItem( self, categ, level=0 ):
        if not categ.canView( self._aw ):
            return ""
        html = ""
        number=self._number.newCount()
        for i in range(level):
            html = "%s&nbsp;&nbsp;&nbsp;"%html
        cfg = Config.getInstance()
        checked = ""

        if categ in self._selCategs:
            checked = "checked"
        title = """<input type="checkbox" name="selCateg" id="%s" onClick="alerta(%s);" value="%s" %s> %s"""%\
                    (number,number,categ.getId(), checked, categ.getName() )
        if categ in self._expandedCategs:
            temp = copy( self._expandedCategs )
            temp.remove( categ )
            html = """%s<a href="%s"><img src="%s" border="0" alt="fold"></a> %s"""%\
                (   html, \
                    self._expandURLGen( temp ), \
                    cfg.getSystemIconURL("itemExploded"), \
                    title )
            for subcat in categ.getSubCategoryList():
                html = "%s<br>%s"%(html, self._getItem(subcat, level+1) )
        else:
            html = """%s<a href="%s"><img src="%s" border="0" alt="unfold"></a> %s"""%\
                (   html, \
                    self._expandURLGen( self._expandedCategs+[categ] ), \
                    cfg.getSystemIconURL("itemCollapsed"), \
                    title )
        return html
Esempio n. 36
0
def createCSV(resvs, req):

    results=[['URL',
             'id',
             'start date',
             'end date',
             'name',
             'site',
             'building',
             'floor',
             'roomNr',
             'IP',
             'H323 IP',
             'uses VC equipment'
             ]]

    for collision in resvs:
        resv = collision.withReservation
        if resv.usesAVC:
            usesAVC = 1
        else:
            usesAVC = 0
        results.append([str(UHRoomBookingBookingDetails.getURL(resv)),
                         str(resv.id),
                         collision.startDT.strftime("%Y-%m-%d %H:%M:%S"),
                         collision.endDT.strftime("%Y-%m-%d %H:%M:%S"),
                         resv.room.name or "",
                         resv.room.site,
                         str(resv.room.building),
                         resv.room.floor,
                         str(resv.room.roomNr),
                         resv.room.customAtts.get('IP') or "",
                         resv.room.customAtts.get('H323 IP') or "",
                         usesAVC
                         ])



    #################### create temp file ###################
    cfg = Config.getInstance()
    tempPath = cfg.getUploadedFilesTempDir()
    tempFileName = tempfile.mkstemp( prefix="Bookings", suffix=".csv", dir = tempPath )[1]

    #################### write the results in the temp file ###################
    fd=open(tempFileName, 'w')
    writer = csv.writer(fd, delimiter=',', quotechar='"', quoting=csv.QUOTE_MINIMAL)
    for i in results:
        writer.writerow(i)
    fd.close()

    #################### return the CSV file ###################
    req.headers_out["Content-Length"] = "%s"%int(os.stat(tempFileName)[stat.ST_SIZE])
    mimetype = cfg.getFileTypeMimeType( cfg.getFileType("CSV") )
    req.content_type = """%s"""%(mimetype)
    req.headers_out["Content-Disposition"] = """inline; filename="%s\""""%cleanHTMLHeaderFilename(os.path.basename(tempFileName))

    fr = open(tempFileName, "rb")
    data = fr.read()
    fr.close()
    return data
Esempio n. 37
0
    def __init__( self, rh ):
        config = Config.getInstance()
        db_connected = DBMgr.getInstance().isConnected()

        self._rh = rh
        self._locTZ = ""

        self._asset_env = Environment(config.getHtdocsDir(), '')

        if db_connected:
            debug = HelperMaKaCInfo.getMaKaCInfoInstance().isDebugActive()
        else:
            debug = False

        # This is done in order to avoid the problem sending the error report because the DB is not connected.
        if db_connected:
            info = HelperMaKaCInfo.getMaKaCInfoInstance()
            self._asset_env.debug = info.isDebugActive()

        self._dir = config.getTPLDir()
        self._asset_env.debug = debug

        if db_connected:
            css_file = config.getCssStylesheetName()
        else:
            css_file = 'Default.css'

        # register existing assets
        assets.register_all_js(self._asset_env)
        assets.register_all_css(self._asset_env, css_file)

        #store page specific CSS and JS
        self._extraCSS = []
        self._extraJS = []
Esempio n. 38
0
    def _getHTMLHeader( self ):
        from MaKaC.webinterface.pages.conferences import WPConfSignIn
        from MaKaC.webinterface.pages.signIn import WPSignIn
        from MaKaC.webinterface.pages.registrationForm import WPRegistrationFormSignIn
        from MaKaC.webinterface.rh.base import RHModificationBaseProtected
        from MaKaC.webinterface.rh.admins import RHAdminBase

        area=""
        if isinstance(self._rh, RHModificationBaseProtected):
            area=i18nformat(""" - _("Management area")""")
        elif isinstance(self._rh, RHAdminBase):
            area=i18nformat(""" - _("Administrator area")""")

        info = HelperMaKaCInfo().getMaKaCInfoInstance()
        websession = self._getAW().getSession()
        if websession:
            language = websession.getLang()
        else:
            language = info.getLang()

        return wcomponents.WHTMLHeader().getHTML({
            "area": area,
            "baseurl": self._getBaseURL(),
            "conf": Config.getInstance(),
            "page": self,
            "extraCSS": self.getCSSFiles(),
            "extraJSFiles": self.getJSFiles(),
            "extraJS": self._extraJS,
            "language": language,
            "social": info.getSocialAppConfig()
            })
Esempio n. 39
0
 def _process( self ):
     from MaKaC.common.Configuration import Config
     from MaKaC.externUsers import ExtUserHolder
     from urllib import urlencode
     euh = ExtUserHolder()
     ah = user.AvatarHolder()
     newIdentityList = []
     for id in self._identityList:
         newId = id
         for authId in Config.getInstance().getAuthenticatorList():
             if id[:len(authId)] == authId:
                 dict = euh.getById(authId).getById(id.split(':')[1])
                 av = user.Avatar(dict)
                 newId = ah.add(av)
                 identity = dict["identity"](dict["login"], av)
                 try:
                     dict["authenticator"].add(identity)
                 except:
                     pass
                 av.activateAccount()
         newIdentityList.append("selectedPrincipals=%s"%newId)
     if self._addURL.find("?") != -1:
         targetURL = self._addURL + "&" + urlencode(self._params) + "&" + "&".join(newIdentityList)
     else:
         targetURL = self._addURL + "?" + urlencode(self._params) + "&" + "&".join(newIdentityList)
     self._redirect( targetURL )
Esempio n. 40
0
    def __init__(self, plugin_name, plugin_dir, url_path):
        config = Config.getInstance()
        output_dir = os.path.join(config.getHtdocsDir(), 'build', plugin_name)

        super(PluginEnvironment, self).__init__(output_dir, url_path)

        self.append_path(os.path.join(plugin_dir, 'htdocs'), url=url_path)
Esempio n. 41
0
 def getVars(self):
     vars = wcomponents.WTemplated.getVars(self)
     urlGen = vars.get("modSpeakerURLGen", 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]  _("Sub-Contribution") %s: %s""") % (
                 self._conf.getTitle(), self._subContrib.getId(),
                 self._subContrib.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"))
         l.append(
             """<input type="checkbox" name="selAuthor" value=%s>%s %s""" %
             (quoteattr(author.getId()), emailHtml, authCaption))
     vars["authors"] = "<br>".join(l)
     return vars
Esempio n. 42
0
def _define_lookup():
    return IndicoTemplateLookup(directories=[TEMPLATE_DIR],
                                module_directory=os.path.join(Config.getInstance().getTempDir(), "mako_modules"),
                                disable_unicode=True,
                                filesystem_checks=True,
                                imports=FILTER_IMPORTS,
                                cache_enabled=not ContextManager.get('offlineMode'))
Esempio n. 43
0
    def _getAnswer(self):
        spkWrapper = None
        manager = self._conf.getCSBookingManager()
        for sw in manager.getSpeakerWrapperList():
            if sw.getUniqueIdHash() == self.authKey:
                spkWrapper = sw

        if spkWrapper:
            spkWrapper.setStatus(SpeakerStatusEnum.REFUSED)
            spkWrapper.setRejectReason(self.reason)
            spkWrapper.triggerNotification()
            if manager.notifyElectronicAgreementAnswer():
                subject = """[Indico] Electronic Agreement Rejected: '%s'""" % (
                    self._conf.getTitle())
                content = _(self.MESSAGE_REJECT).format(
                    speaker=spkWrapper.getObject().getDirectFullName(),
                    title=self._conf.getTitle(),
                    reason=self.reason,
                    url=self._conf.getURL())
                emailToList = [self._conf.getCreator().getEmail()]
                for event_manager in self._conf.getManagerList():
                    emailToList.append(event_manager.getEmail())
                notification = ElectronicAgreementOrganiserNotification(
                    emailToList,
                    Config.getInstance().getNoReplyEmail(), content, subject)

                GenericMailer.sendAndLog(
                    notification, self._conf,
                    "MaKaC/plugins/Collaboration/RecordingRequest/collaboration.py",
                    None)
Esempio n. 44
0
    def __init__(self, plugin_name, plugin_dir, url_path):
        config = Config.getInstance()
        output_dir = os.path.join(config.getHtdocsDir(), 'build', plugin_name)

        super(PluginEnvironment, self).__init__(output_dir, url_path)

        self.append_path(os.path.join(plugin_dir, 'htdocs'), url=url_path)
Esempio n. 45
0
    def OAuthCheckAccessResource(cls):
        from indico.modules.oauth.db import ConsumerHolder, AccessTokenHolder, OAuthServer

        oauth_request = oauth.Request.from_request(request.method, request.base_url, request.headers,
                                                   parameters=create_flat_args())
        Logger.get('oauth.resource').info(oauth_request)
        try:
            now = nowutc()
            consumer_key = oauth_request.get_parameter('oauth_consumer_key')
            if not ConsumerHolder().hasKey(consumer_key):
                raise OAuthError('Invalid Consumer Key', apache.HTTP_UNAUTHORIZED)
            consumer = ConsumerHolder().getById(consumer_key)
            token = oauth_request.get_parameter('oauth_token')
            if not token or not AccessTokenHolder().hasKey(token):
                raise OAuthError('Invalid Token', 401)
            access_token = AccessTokenHolder().getById(token)
            oauth_consumer = oauth.Consumer(consumer.getId(), consumer.getSecret())
            OAuthServer.getInstance().verify_request(oauth_request, oauth_consumer, access_token.getToken())
            if access_token.getConsumer().getId() != oauth_consumer.key:
                raise OAuthError('Invalid Consumer Key', apache.HTTP_UNAUTHORIZED)
            elif (now - access_token.getTimestamp()) > timedelta(seconds=Config.getInstance().getOAuthAccessTokenTTL()):
                raise OAuthError('Expired Token', apache.HTTP_UNAUTHORIZED)
            return access_token
        except oauth.Error, e:
            if e.message.startswith("Invalid Signature"):
                raise OAuthError("Invalid Signature", 401)
            else:
                raise OAuthError(e.message, 400)
Esempio n. 46
0
    def initialize(cls):
        # Lists of filters for each handler
        filters = {
            'indico': [logging.Filter('indico')],
            'other': [ExtraIndicoFilter()],
            'smtp': [logging.Filter('indico')]
        }

        config = Config.getInstance()

        logConfFilepath = os.path.join(config.getConfigurationDir(),
                                       "logging.conf")

        smtpServer = config.getSmtpServer()
        serverName = config.getWorkerName()
        if not serverName:
            serverName = config.getHostNameURL()

        # Default arguments for the handlers, taken mostly for the configuration
        defaultArgs = {
            'indico': ("FileHandler",
                       "('%s', 'a')" % cls._log_path('indico.log'), 'DEBUG'),
            'other': ("FileHandler",
                      "('%s', 'a')" % cls._log_path('other.log'), 'DEBUG'),
            'smtp':
            ("handlers.SMTPHandler",
             "(%s, 'logger@%s', ['%s'], 'Unexpected Exception occurred at %s')"
             % (smtpServer, serverName, config.getSupportEmail(), serverName),
             "ERROR")
        }

        cls.handlers = LoggerUtils.configFromFile(logConfFilepath, defaultArgs,
                                                  filters)
Esempio n. 47
0
    def __init__(self, booking):
        VidyoOwnerNotificationBase.__init__(self)
        self._owner = booking.getOwnerObject()

        self.setFromAddr("Indico Mailer <%s>" %
                         Config.getInstance().getSupportEmail())
        self.setContentType("text/html")

        owner = booking.getOwnerObject()
        event = booking.getConference()

        self.setToList([owner.getEmail()])

        self.setSubject(
            """[Indico] The Vidyo public room %s has been deleted""" %
            booking.getBookingParamByName("roomName"))

        self.setBody("""Dear %s%s,<br />
<br />
Please note that the Vidyo room named "%s" associated with the Indico event <a href="%s">%s</a>, of which you were the owner, has been deleted by a manager of this event.<br />
<br />
Thank you for using Vidyo and Indico<br />
""" % (self._getOwnerTitleText(), owner.getStraightFullName(),
        booking.getBookingParamByName("roomName"),
        urlHandlers.UHConferenceDisplay.getURL(event), event.getTitle()))
Esempio n. 48
0
    def blockingRequestProcessed(roomBlocking):
        """
        Notifies (e-mails) blocking creator about approval/rejection of his
        blocking request for a room
        """

        emails = []
        # ---- Email creator and contact ----

        to = roomBlocking.block.createdByUser.getEmail()

        if roomBlocking.active == True:
            verb = 'ACCEPTED'
        else:
            verb = 'REJECTED'
        subject = "Room blocking %s" % verb
        wc = WTemplated('RoomBookingEmail_2BlockingCreatorRequestProcessed')
        text = wc.getHTML({
            'block': roomBlocking.block,
            'roomBlocking': roomBlocking,
            'verb': verb
        })
        fromAddr = Config.getInstance().getSupportEmail()
        mailData = {
            "fromAddr": fromAddr,
            "toList": [to],
            "subject": subject,
            "body": text
        }
        emails.append(mailData)
        return emails
Esempio n. 49
0
    def getBody(self):
        res = sets.Set()
        im = indexes.IndexesHolder()
        catIdx = im.getIndex('category')
        calIdx = im.getIndex('calendar')
        if self._date == None:
            c1 = calIdx.getObjectsEndingAfter(nowutc().astimezone(
                timezone(self._tz)))
        else:
            date = self._date
            c1 = calIdx.getObjectsInDay(date)
        confIds = sets.Set(catIdx.getItems(self._categ.getId()))
        confIds.intersection_update(c1)
        res.union_update(confIds)
        res = list(res)
        res.sort(sortByStartDate)
        rss = xmlGen.XMLGen()
        rss.openTag('rss version="2.0"')
        rss.openTag("channel")
        rss.writeTag(
            "title",
            "Indico RSS Feed for category %s" % self._categ.getTitle())

        rss.writeTag("link", Config.getInstance().getBaseURL())

        rss.writeTag(
            "description",
            "Forthcoming meetings in category %s" % self._categ.getTitle())
        rss.writeTag("language", "en")
        rss.writeTag(
            "pubDate",
            nowutc().astimezone(timezone(
                self._tz)).strftime("%a, %d %b %Y %H:%M:%S %Z"))
        rss.writeTag("category", "")
        rss.writeTag("generator",
                     "CDS Indico %s" % Config.getInstance().getVersion())
        rss.writeTag(
            "webMaster",
            info.HelperMaKaCInfo.getMaKaCInfoInstance().getSupportEmail())
        rss.writeTag("ttl", "1440")
        for confId in res:
            ch = ConferenceHolder()
            conf = ch.getById(confId)
            rss = ConferenceToRSS(conf, tz=self._tz).getCore(rss)
        rss.closeTag("channel")
        rss.closeTag("rss")
        return rss.getXml()
Esempio n. 50
0
    def _setFakeConfig(self, custom):
        """
        Sets a fake configuration for the current process, using a temporary directory
        """
        config = Config.getInstance()
        test_config = TestConfig.getInstance()

        temp = tempfile.mkdtemp(prefix="indico_")
        self._info('Using %s as temporary dir' % temp)

        os.mkdir(os.path.join(temp, 'log'))
        os.mkdir(os.path.join(temp, 'archive'))

        indicoDist = pkg_resources.get_distribution('indico')
        htdocsDir = indicoDist.get_resource_filename('indico', 'indico/htdocs')
        etcDir = indicoDist.get_resource_filename('indico', 'etc')

        # minimal defaults
        defaults = {
            'BaseURL': 'http://localhost:8000/indico',
            'BaseSecureURL': '',
            'UseXSendFile': False,
            'AuthenticatorList': ['Local'],
            'SmtpServer': ('localhost', 58025),
            'SmtpUseTLS': 'no',
            'DBConnectionParams': ('localhost', TestConfig.getInstance().getFakeDBPort()),
            'LogDir': os.path.join(temp, 'log'),
            'XMLCacheDir': os.path.join(temp, 'cache'),
            'HtdocsDir': htdocsDir,
            'ArchiveDir': os.path.join(temp, 'archive'),
            'UploadedFilesTempDir': os.path.join(temp, 'tmp'),
            'ConfigurationDir': etcDir
            }

        defaults.update(custom)

        # set defaults
        config.reset(defaults)

        Config.setInstance(config)
        self._cfg = config

        # re-configure logging and template generator, so that paths are updated
        from MaKaC.common import TemplateExec
        from MaKaC.common.logger import Logger
        TemplateExec.mako = TemplateExec._define_lookup()
        Logger.reset()
Esempio n. 51
0
 def _defineToolBar(self):
     edit = wcomponents.WTBItem(
         _("manage this contribution"),
         icon=Config.getInstance().getSystemIconURL("modify"),
         actionURL=urlHandlers.UHSubContributionModification.getURL(
             self._subContrib),
         enabled=self._target.canModify(self._getAW()))
     self._toolBar.addItem(edit)
Esempio n. 52
0
def inlineContextHelp(helpContent):
    """
    Allows you to put [?], the context help marker.
    Help content passed as argument helpContent.
    """
    includeTpl('InlineContextHelp',
               helpContent=helpContent,
               imgSrc=Config.getInstance().getSystemIconURL("help"))
Esempio n. 53
0
 def getVars(self):
     vars = wcomponents.WTemplated.getVars(self)
     vars["indicobaseurl"] = Config.getInstance().getBaseURL()
     url = vars["url"] = self._file.getURL()
     vars["download"] = ""
     if url.find("http://") != -1:
         vars["download"] = """<a href="%s">Download File</a>""" % url
     return vars
Esempio n. 54
0
def contextHelp(helpId):
    """
    Allows you to put [?], the context help marker.
    Help content is defined in <div id="helpId"></div>.
    """
    includeTpl('ContextHelp',
               helpId=helpId,
               imgSrc=Config.getInstance().getSystemIconURL("help"))
Esempio n. 55
0
    def getVars(self):
        vars = wcomponents.WTemplated.getVars( self )
        vars["duration"] =(datetime(1900,1,1)+self._subContrib.getDuration()).strftime("%H:%M")
        vars["SubContrib"] = self._subContrib
        vars["accessWrapper"] = self._aw
        vars["reportNumberSystems"] = Config.getInstance().getReportNumberSystems()

        return vars
Esempio n. 56
0
 def __init__(self):
     (fh,name)=tempfile.mkstemp(prefix="Indico",dir=Config.getInstance().getTempDir())
     os.fdopen(fh).close()
     try:
         self._file=zipfile.ZipFile(name,"w", zipfile.ZIP_DEFLATED, allowZip64=True)
     except:
         self._file=zipfile.ZipFile(name,"w", allowZip64=True)
     self._name=name