Пример #1
0
    def run(self, template_name, **kwargs):
        template_dir = os.path.join(Config.getInstance().getTPLDir(), 'latex')
        template = tpl_render(os.path.join(template_dir, template_name), kwargs)

        self._dir = tempfile.mkdtemp(prefix="indico-texgen-", dir=Config.getInstance().getTempDir())
        source_filename = os.path.join(self._dir, template_name + '.tex')
        target_filename = os.path.join(self._dir, template_name + '.pdf')
        log_filename = os.path.join(self._dir, 'output.log')
        log_file = open(log_filename, 'a+')

        with open(source_filename, 'w') as f:
            f.write(template)

        try:
            self.run_latex(source_filename, log_file)
            if self.has_toc:
                self.run_latex(source_filename, log_file)
        finally:
            log_file.close()

            if not os.path.exists(target_filename):
                report_no = self._save_error_report(source_filename, log_filename)
                # something went terribly wrong, no LaTeX file was produced
                raise LaTeXRuntimeException(source_filename, log_filename, report_no, kwargs)

        return target_filename
Пример #2
0
    def _send(msgData):
        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))

        to_addrs = msgData["toList"] | msgData["ccList"] | msgData["bccList"]
        try:
            Logger.get("mail").info(
                "Sending email: To: {} / CC: {} / BCC: {}".format(
                    ", ".join(msgData["toList"]) or "None",
                    ", ".join(msgData["ccList"]) or "None",
                    ", ".join(msgData["bccList"]) or "None",
                )
            )
            server.sendmail(msgData["fromAddr"], to_addrs, msgData["msg"])
        except smtplib.SMTPRecipientsRefused as e:
            raise MaKaCError("Email address is not valid: {}".format(e.recipients))
        finally:
            server.quit()
        Logger.get("mail").info("Mail sent to {}".format(", ".join(to_addrs)))
Пример #3
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 ""}
Пример #4
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, doNotSanitize)

        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
Пример #5
0
    def deleted(self, obj, oldOwner):
        print "****DELETING OBJ=",obj, oldOwner

        objClass = type(oldOwner).__name__
        objClassTitle = oldOwner.getTitle().lower()

        if objClass == 'Poster':
            objType = obj.getFileType().lower()
            objName = obj.getFileName().lower()
            if objName.find('poster') > -1 and objType == 'pdf' and objName.find('list_of_poster') == -1 and objName.find('session') == -1:
                # If POSTER is present, remove it
                tempDir = Config.getInstance().getSharedTempDir()
                postersDir = tempDir+"/posters"
                if os.path.isdir(postersDir):
                    confId = str(oldOwner.owner.getId())
                    thumbPath = postersDir + "/poster_" + confId
                    if os.path.isfile(thumbPath):
                        os.remove(thumbPath)
        else:
            if (objClassTitle.find('photo') > -1 or objClassTitle.find('picture') > -1 or objClassTitle.find('group') > -1):
                objType = obj.getFileType().lower()
                objName = obj.getFileName().lower()
                if (objType == 'jpg'):
                    # If Group Photo is present, remove it
                    tempDir = Config.getInstance().getSharedTempDir()
                    photoDir = tempDir+"/photos"
                    if os.path.isdir(photoDir):
                        confId = str(oldOwner.owner.getId())
                        thumbPath = photoDir + "/photo_" + confId + "_" + objName
                        if os.path.isfile(thumbPath):
                            os.remove(thumbPath)
        return
Пример #6
0
    def _process(self):
        flower_url = Config.getInstance().getFlowerURL()

        notset = object()
        overridden_tasks = Config.getInstance().getScheduledTaskOverride()
        tasks = []
        for entry in celery.conf['CELERYBEAT_SCHEDULE'].values():
            override = overridden_tasks.get(entry['task'], notset)
            custom_schedule = None
            disabled = False
            if override is notset:
                pass
            elif not override:
                disabled = True
            elif isinstance(override, dict):
                custom_schedule = override.get('schedule')
            else:
                custom_schedule = override

            tasks.append({'name': entry['task'],
                          'schedule': entry['schedule'],
                          'custom_schedule': custom_schedule,
                          'disabled': disabled})
        tasks.sort(key=itemgetter('disabled', 'name'))

        return WPCelery.render_template('celery_tasks.html', flower_url=flower_url, tasks=tasks, timedelta=timedelta)
Пример #7
0
    def _processUnexpectedError(self, e):
        """Unexpected errors"""

        if Config.getInstance().getEmbeddedWebserver() or Config.getInstance().getPropagateAllExceptions():
            # Re-raise to get the nice werkzeug exception view
            raise
        return errors.WPUnexpectedError(self).display()
Пример #8
0
    def getVars( self ):
        vars = wcomponents.WTemplated.getVars( self )
        vars["types"] = "<br>".join( self._getTypeFilterItemList() )
        vars["status"] = "<br>".join( self._getStatusFilterItemList() )
        vars["others"] = "<br>".join( self._getOthersFilterItemList() )
        vars["accTypes"] = "<br>".join( self._getAccTypeFilterItemList() )
        f = filters.SimpleFilter(self._filterCrit,self._sortingCrit)
        al = []
        abstractsToPrint = []
        self._checked = ""
        if vars["selectAll"]:
            self._checked = " checked"
        abstractList = f.apply( self._track.getAbstractList() )
        for abstract in abstractList:
            al.append( self._getAbstractHTML( abstract ) )
            abstractsToPrint.append("""<input type="hidden" name="abstracts" value="%s">"""%abstract.getId())
        vars["filteredNumberAbstracts"] = str(len(abstractList))
        vars["totalNumberAbstracts"] = str(len(self._track.getAbstractList()))
        if self._order == "up":
            al.reverse()
        vars["abstracts"] = "".join( al )
        vars["abstractsToPrint"] = "\n".join(abstractsToPrint)

        sortingField = self._sortingCrit.getField()
        vars["currentSorting"] = ""

        for crit in ["type", "status", "number", "date", "rating"]:
            url = self._getURL()

            vars["%sImg" % crit] = ""
            url.addParam("sortBy", crit)

            if sortingField.getId() == crit:
                vars["currentSorting"] = '<input type="hidden" name="sortBy" value="%s">' % crit
                if self._order == "down":
                    vars["%sImg" % crit] = """<img src="%s" alt="">"""%(Config.getInstance().getSystemIconURL("downArrow"))
                    url.addParam("order","up")
                elif self._order == "up":
                    vars["%sImg" % crit] = """<img src="%s" alt="">"""%(Config.getInstance().getSystemIconURL("upArrow"))
                    url.addParam("order","down")
            vars["%sSortingURL" % crit] = str(url)

        url = urlHandlers.UHTrackModifAbstracts.getURL( self._track )
        url.addParam("order", self._order)
        url.addParam("OK", "1")
        url.setSegment( "abstracts" )
        vars["filterPostURL"]=quoteattr(str(url))
        vars["accessAbstract"] = quoteattr(str(urlHandlers.UHTrackAbstractDirectAccess.getURL(self._track)))
        vars["allAbstractsURL"] = str(urlHandlers.UHConfAbstractManagment.getURL(self._conf))
        l = []
        for tpl in self._conf.getAbstractMgr().getNotificationTplList():
            l.append("""<option value="%s">%s</option>"""%(tpl.getId(), tpl.getName()))
        vars["notifTpls"] = "\n".join(l)
        vars["actionURL"]=quoteattr(str(urlHandlers.UHAbstractsTrackManagerAction.getURL(self._track)))
        vars["selectURL"]=quoteattr(str(urlHandlers.UHTrackModifAbstracts.getURL(self._track)))
        vars["filterUsed"] = self._filterUsed
        vars["resetFiltersURL"] = str(urlHandlers.UHTrackModifAbstracts.getURL(self._track))
        vars["pdfIconURL"] = quoteattr(str(Config.getInstance().getSystemIconURL("pdf")))
        vars["canModify"] = self._canModify
        return vars
Пример #9
0
Файл: base.py Проект: fph/indico
    def _getHTMLHeader( self ):
        from MaKaC.webinterface.rh.base import RHModificationBaseProtected
        from MaKaC.webinterface.rh.admins import RHAdminBase

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

        plugin_css = values_from_signal(signals.plugin.inject_css.send(self.__class__), as_list=True,
                                        multi_value_types=list)
        plugin_js = values_from_signal(signals.plugin.inject_js.send(self.__class__), as_list=True,
                                       multi_value_types=list)

        return wcomponents.WHTMLHeader().getHTML({
            "area": area,
            "baseurl": self._getBaseURL(),
            "conf": Config.getInstance(),
            "page": self,
            "printCSS": map(self._fix_path, self.getPrintCSSFiles()),
            "extraCSS": map(self._fix_path, self.getCSSFiles() + plugin_css + self.get_extra_css_files()),
            "extraJSFiles": map(self._fix_path, self.getJSFiles() + plugin_js),
            "language": session.lang or Config.getInstance().getDefaultLocale(),
            # XXX: Remove SOCIAL_ENABLED once this is moved out of ZODB
            "social": HelperMaKaCInfo().getMaKaCInfoInstance().getSocialAppConfig() if self.SOCIAL_ENABLED else {},
            "assets": self._asset_env
        })
Пример #10
0
 def _checkCSRF(self):
     token = request.headers.get('X-CSRF-Token', request.form.get('csrf_token'))
     if self.CSRF_ENABLED and request.method != 'GET' and token != session.csrf_token:
         msg = _(u"It looks like there was a problem with your current session. Please use your browser's back "
                 u"button, reload the page and try again.")
         raise BadRequest(msg)
     elif not self.CSRF_ENABLED and current_app.debug and request.method != 'GET':
         # Warn if CSRF is not enabled for a RH in new code
         module = self.__class__.__module__
         if module.startswith('indico.modules.') or module.startswith('indico.core.'):
             msg = (u'{} request sent to {} which has no CSRF checks. Set `CSRF_ENABLED = True` in the class to '
                    u'enable them.').format(request.method, self.__class__.__name__)
             warnings.warn(msg, RuntimeWarning)
     # legacy csrf check (referer-based):
     # 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.')
Пример #11
0
def set_best_lang(check_session=True):
    """
    Get the best language/locale for the current user. This means that first
    the session will be checked, and then in the absence of an explicitly-set
    language, we will try to guess it from the browser settings and only
    after that fall back to the server's default.
    """
    from indico.core.config import Config

    if not has_request_context():
        return 'en_GB' if current_app.config['TESTING'] else Config.getInstance().getDefaultLocale()
    elif 'lang' in g:
        return g.lang
    elif check_session and session.lang is not None:
        return session.lang

    # try to use browser language
    preferred = [x.replace('-', '_') for x in request.accept_languages.values()]
    resolved_lang = negotiate_locale(preferred, list(get_all_locales()), aliases=LOCALE_ALIASES)

    if not resolved_lang:
        if current_app.config['TESTING']:
            return 'en_GB'

        # fall back to server default
        resolved_lang = Config.getInstance().getDefaultLocale()

    # As soon as we looked up a language, cache it during the request.
    # This will be returned when accessing `session.lang` since there's code
    # which reads the language from there and might fail (e.g. by returning
    # lazy strings) if it's not set.
    g.lang = resolved_lang
    return resolved_lang
Пример #12
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
Пример #13
0
def pytest_configure(config):
    # Load all the plugins defined in pytest_plugins
    config.pluginmanager.consider_module(sys.modules[__name__])
    config.indico_temp_dir = py.path.local(tempfile.mkdtemp(prefix="indicotesttmp."))
    plugins = filter(None, [x.strip() for x in re.split(r"[\s,;]+", config.getini("indico_plugins"))])
    # Throw away all indico.conf options early
    Config.getInstance().reset(
        {
            "DBConnectionParams": ("localhost", 0),  # invalid port - just so we never connect to a real ZODB!
            "SmtpServer": ("localhost", 0),  # invalid port - just in case so we NEVER send emails!
            "CacheBackend": "null",
            "Loggers": [],
            "UploadedFilesTempDir": config.indico_temp_dir.strpath,
            "XMLCacheDir": config.indico_temp_dir.strpath,
            "ArchiveDir": config.indico_temp_dir.strpath,
            "StorageBackends": {"default": config.indico_temp_dir},
            "AttachmentStorage": "default",
            "Plugins": plugins,
            "SecretKey": os.urandom(16),
        }
    )
    # Make sure we don't write any log files (or worse: send emails)
    Logger.reset()
    del logging.root.handlers[:]
    logging.root.addHandler(logging.NullHandler())
    # Silence the annoying pycountry logger
    import pycountry.db

    pycountry.db.logger.addHandler(logging.NullHandler())
Пример #14
0
    def _processUnexpectedError(self, e):
        """Unexpected errors"""

        self._responseUtil.redirect = None
        if Config.getInstance().getEmbeddedWebserver() or Config.getInstance().getPropagateAllExceptions():
            raise
        return errors.WPUnexpectedError(self).display()
Пример #15
0
    def __getAvailableTemplates(self):
        tplDir = Config.getInstance().getTPLDir()

        tplRE = re.compile('^([^\.]+)\.([^\.]+)\.tpl$')

        templates = {}

        fnames = os.listdir(tplDir);
        for fname in fnames:
            m = tplRE.match(fname)
            if m:
                templates[m.group(2)] = None

        tplRE = re.compile('^([^\.]+)\.([^\.]+)\.wohl$')

        fnames = os.listdir(os.path.join(tplDir, 'chelp'))
        for fname in fnames:
            m = tplRE.match(fname)
            if m:
                templates[m.group(2)] = None

        cssRE = re.compile('Default.([^\.]+)\.css$')

        fnames = os.listdir(Config.getInstance().getCssDir())
        for fname in fnames:
            m = cssRE.match(fname)
            if m:
                templates[m.group(1)] = None

        return templates.keys()
Пример #16
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
Пример #17
0
    def _connect(self):
        """Connect to the CacheClient.

        This method must be called before accessing ``self._client``.
        """
        # Maybe we already have a client in this instance
        if self._client is not None:
            return
        # If not, we might have one from another instance
        self._client = ContextManager.get('GenericCacheClient', None)

        if self._client is not None:
            return

        # If not, create a new one
        backend = Config.getInstance().getCacheBackend()
        if backend == 'memcached':
            self._client = MemcachedCacheClient(Config.getInstance().getMemcachedServers())
        elif backend == 'redis':
            self._client = RedisCacheClient(Config.getInstance().getRedisCacheURL())
        elif backend == 'files':
            self._client = FileCacheClient(Config.getInstance().getXMLCacheDir())
        else:
            self._client = NullCacheClient()

        ContextManager.set('GenericCacheClient', self._client)
Пример #18
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)
Пример #19
0
def generate_public_auth_request(apiKey, path, params=None):
    apiMode = api_settings.get('security_mode')
    if params is None:
        params = {}
    if apiKey:
        key = apiKey.token
        secret_key = apiKey.secret
        persistent = apiKey.is_persistent_allowed and api_settings.get('allow_persistent')
    else:
        key = secret_key = None
        persistent = False
    if api_settings.get('require_https'):
        baseURL = Config.getInstance().getBaseSecureURL()
    else:
        baseURL = Config.getInstance().getBaseURL()
    publicRequestsURL = None
    authRequestURL = None
    if apiMode == APIMode.KEY:
        publicRequestsURL = build_indico_request(path, params)
        authRequestURL = build_indico_request(path, params, key) if key else None
    elif apiMode == APIMode.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 == APIMode.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 == APIMode.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 == APIMode.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 ""}
Пример #20
0
    def _send(msgData):
        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))

        to_addrs = msgData['toList'] | msgData['ccList'] | msgData['bccList']
        try:
            Logger.get('mail').info('Sending email: To: {} / CC: {} / BCC: {}'.format(
                ', '.join(msgData['toList']) or 'None',
                ', '.join(msgData['ccList']) or 'None',
                ', '.join(msgData['bccList']) or 'None'))
            server.sendmail(msgData['fromAddr'], to_addrs, msgData['msg'])
        except smtplib.SMTPRecipientsRefused as e:
            raise MaKaCError('Email address is not valid: {}'.format(e.recipients))
        finally:
            server.quit()
        Logger.get('mail').info('Mail sent to {}'.format(', '.join(to_addrs)))
Пример #21
0
    def process(self):
        """
        Processes the request, analyzing the parameters, and feeding them to the
        _getAnswer() method (implemented by derived classes)
        """

        ContextManager.set('currentRH', self)

        self._checkParams()
        self._checkProtection()

        if self.CHECK_HTML:
            try:
                security.Sanitization.sanitizationCheck(self._target, self._params, self._aw, ['requestInfo'])
            except HtmlForbiddenTag as e:
                raise HTMLSecurityError('ERR-X0', 'HTML Security problem. {}'.format(e))

        if self._doProcess:
            if Config.getInstance().getProfile():
                import profile, pstats, random
                proffilename = os.path.join(Config.getInstance().getTempDir(), "service%s.prof" % random.random())
                result = [None]
                profile.runctx("result[0] = self._getAnswer()", globals(), locals(), proffilename)
                answer = result[0]
                rep = Config.getInstance().getTempDir()
                stats = pstats.Stats(proffilename)
                stats.strip_dirs()
                stats.sort_stats('cumulative', 'time', 'calls')
                stats.dump_stats(os.path.join(rep, "IndicoServiceRequestProfile.log"))
                os.remove(proffilename)
            else:
                answer = self._getAnswer()
            self._deleteTempFiles()

            return answer
Пример #22
0
    def getVars( self ):
        from indico.web.http_api.util import generate_public_auth_request

        vars = WHeader.getVars( self )
        vars["categurl"] = self._conf.as_event.category.url

        vars["conf"] = vars["target"] = self._conf

        vars["imgLogo"] = Config.getInstance().getSystemIconURL("miniLogo")
        vars["MaKaCHomeURL"] = self._conf.as_event.category.url

        # Default values to avoid NameError while executing the template
        styles = theme_settings.get_themes_for("conference")

        vars["viewoptions"] = [{'id': theme_id, 'name': data['title']}
                               for theme_id, data in sorted(styles.viewitems(), key=lambda x: x[1]['title'])]
        vars["SelectedStyle"] = ""
        vars["pdfURL"] = ""
        vars["displayURL"] = str(urlHandlers.UHConferenceOtherViews.getURL(self._conf))

        # Setting the buttons that will be displayed in the header menu
        vars["showFilterButton"] = False
        vars["showMoreButton"] = True
        vars["showExportToICal"] = True
        vars["showExportToPDF"] = False
        vars["showDLMaterial"] = True
        vars["showLayout"] = True

        vars["displayNavigationBar"] = layout_settings.get(self._conf, 'show_nav_bar')

        # This is basically the same WICalExportBase, but we need some extra
        # logic in order to have the detailed URLs
        apiMode = api_settings.get('security_mode')

        vars["icsIconURL"] = str(Config.getInstance().getSystemIconURL("ical_grey"))
        vars["apiMode"] = apiMode
        vars["signingEnabled"] = apiMode in {APIMode.SIGNED, APIMode.ONLYKEY_SIGNED, APIMode.ALL_SIGNED}
        vars["persistentAllowed"] = api_settings.get('allow_persistent')
        user = self._aw.getUser()
        apiKey = user.api_key if user else None

        topURLs = generate_public_auth_request(apiKey, '/export/event/%s.ics' % self._conf.getId())
        urls = generate_public_auth_request(apiKey, '/export/event/%s.ics' % self._conf.getId(),
                                            {'detail': 'contributions'})

        vars["requestURLs"] = {
            'publicRequestURL': topURLs["publicRequestURL"],
            'authRequestURL':  topURLs["authRequestURL"],
            'publicRequestDetailedURL': urls["publicRequestURL"],
            'authRequestDetailedURL':  urls["authRequestURL"]
        }

        vars["persistentUserEnabled"] = apiKey.is_persistent_allowed if apiKey else False
        vars["apiActive"] = apiKey is not None
        vars["userLogged"] = user is not None
        tpl = get_template_module('api/_messages.html')
        vars['apiKeyUserAgreement'] = tpl.get_ical_api_key_msg()
        vars['apiPersistentUserAgreement'] = tpl.get_ical_persistent_msg()

        return vars
Пример #23
0
def pytest_configure(config):
    # Load all the plugins defined in pytest_plugins
    config.pluginmanager.consider_module(sys.modules[__name__])
    config.indico_temp_dir = py.path.local(tempfile.mkdtemp(prefix='indicotesttmp.'))
    plugins = filter(None, [x.strip() for x in re.split(r'[\s,;]+', config.getini('indico_plugins'))])
    # Throw away all indico.conf options early
    Config.getInstance().reset({
        'DBConnectionParams': ('localhost', 0),  # invalid port - just so we never connect to a real ZODB!
        'SmtpServer': ('localhost', 0),  # invalid port - just in case so we NEVER send emails!
        'CacheBackend': 'null',
        'Loggers': [],
        'UploadedFilesTempDir': config.indico_temp_dir.strpath,
        'XMLCacheDir': config.indico_temp_dir.strpath,
        'ArchiveDir': config.indico_temp_dir.strpath,
        'StorageBackends': {'default': config.indico_temp_dir},
        'AttachmentStorage': 'default',
        'Plugins': plugins,
        'SecretKey': os.urandom(16)
    })
    # Make sure we don't write any log files (or worse: send emails)
    Logger.reset()
    del logging.root.handlers[:]
    logging.root.addHandler(logging.NullHandler())
    # Silence the annoying pycountry logger
    import pycountry.db
    pycountry.db.logger.addHandler(logging.NullHandler())
Пример #24
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()

        request_info = self._requestInfo or ''
        if isinstance(request_info, (dict, list)):
            request_info = pformat(request_info)

        # build the message body
        body = [
            "-" * 20,
            "Error details\n",
            self._code,
            self._message,
            "Inner error: " + str(self._inner),
            request_info,
            "-" * 20
        ]
        maildata = {"fromAddr": fromAddr, "toList": [toAddr], "subject": subject, "body": "\n".join(body)}
        GenericMailer.send(GenericNotification(maildata))
Пример #25
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)
Пример #26
0
    def _process_POST(self):
        if User.query.has_rows():
            return redirect(url_for_index())
        setup_form = BootstrapForm(request.form)
        if not setup_form.validate():
            flash(_("Some fields are invalid. Please, correct them and submit the form again."), 'error')
            return redirect(url_for('bootstrap.index'))

        # Creating new user
        user = User()
        user.first_name = to_unicode(setup_form.first_name.data)
        user.last_name = to_unicode(setup_form.last_name.data)
        user.affiliation = to_unicode(setup_form.affiliation.data)
        user.email = to_unicode(setup_form.email.data)
        user.is_admin = True

        identity = Identity(provider='indico', identifier=setup_form.username.data, password=setup_form.password.data)
        user.identities.add(identity)

        db.session.add(user)
        db.session.flush()

        user.settings.set('timezone', Config.getInstance().getDefaultTimezone())
        user.settings.set('lang', session.lang or Config.getInstance().getDefaultLocale())

        login_user(user, identity)
        full_name = user.full_name  # needed after the session closes

        transaction.commit()

        # Configuring server's settings
        minfo = HelperMaKaCInfo.getMaKaCInfoInstance()
        minfo.setOrganisation(setup_form.affiliation.data)

        message = get_template_module('bootstrap/flash_messages.html').bootstrap_success(name=full_name)
        flash(Markup(message), 'success')

        # Activate instance tracking
        if setup_form.enable_tracking.data:
            contact_name = setup_form.contact_name.data
            contact_email = setup_form.contact_email.data

            try:
                register_instance(contact_name, contact_email)
            except (HTTPError, ValueError) as err:
                message = get_template_module('bootstrap/flash_messages.html').community_error(err=err)
                category = 'error'
            except Timeout:
                message = get_template_module('bootstrap/flash_messages.html').community_timeout()
                category = 'error'
            except RequestException as exc:
                message = get_template_module('bootstrap/flash_messages.html').community_exception(exc=exc)
                category = 'error'
            else:
                message = get_template_module('bootstrap/flash_messages.html').community_success()
                category = 'success'
            flash(Markup(message), category)

        return redirect(url_for_index())
Пример #27
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 {}
Пример #28
0
def smtp(disallow_emails, smtpserver):
    """Wrapper for the `smtpserver` fixture which updates the Indico config
    and disables the SMTP autofail logic for that smtp server.
    """
    old_smtp_server = Config.getInstance().getSmtpServer()
    Config.getInstance().update(SmtpServer=smtpserver.addr)
    disallow_emails.add(smtpserver.addr)  # whitelist our smtp server
    yield smtpserver
    Config.getInstance().update(SmtpServer=old_smtp_server)
Пример #29
0
    def __init__(self, plugin_name, plugin_dir, url_path):
        config = Config.getInstance()
        url_base_path = urlparse(config.getBaseURL()).path
        output_dir = os.path.join(config.getHtdocsDir(), 'static', 'assets', 'plugins', plugin_name)
        url = '{0}/static/assets/plugins/{1}'.format(url_base_path, url_path)

        super(PluginEnvironment, self).__init__(output_dir, url)
        self.debug = Config.getInstance().getDebug()
        self.append_path(os.path.join(plugin_dir, 'htdocs'), url=os.path.join(url_base_path, url_path))
Пример #30
0
    def create(self, static_site_id):
        config = Config.getInstance()
        self._fileHandler = ZIPFileHandler()

        # create the home page html
        self._create_home()

        # Create main and static folders
        self._mainPath = self._normalize_path(u"OfflineWebsite-{}".format(self._conf.getTitle().decode("utf-8")))
        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()
        return self._save_file(self._fileHandler.getPath(), static_site_id)
Пример #31
0
def redisLinkedTo(dbi, prevVersion):
    """Import linkedTo information into Redis"""
    if not Config.getInstance().getRedisConnectionURL():
        print console.colored("  Redis not configured, skipping", 'yellow')
        return

    with redis_client.pipeline(transaction=False) as pipe:
        for i, avatar in enumerate(AvatarHolder()._getIdx().itervalues()):
            avatar_links.init_links(avatar, client=pipe)
            if i % 1000 == 0:
                pipe.execute()
                dbi.sync()
            print '\r  %d' % i,
            sys.stdout.flush()
        pipe.execute()
    print '\r  Done   '
Пример #32
0
    def getVars(self):
        """Returns a dictionary containing the TPL variables that will
            be passed at the TPL formating time. For this class, it will
            return the configuration user defined variables.
           Classes inheriting from this one will have to take care of adding
            their variables to the ones returned by this method.
        """
        self._rh = g.get('rh')

        cfg = Config.getInstance()
        vars = cfg.getTPLVars()

        for paramName in self.__params:
            vars[paramName] = self.__params[paramName]

        return vars
Пример #33
0
def processRequest(method, params, internal=False):
    # lookup handler
    handler = lookupHandler(method)

    if not internal and Config.getInstance().getCSRFLevel() >= 1:
        if session.csrf_protected and session.csrf_token != request.headers.get(
                'X-CSRF-Token'):
            raise CSRFError()

    # invoke handler
    if hasattr(handler, 'process'):
        result = handler(params).process()
    else:
        result = handler(params)

    return result
Пример #34
0
 def _setup_assets(self):
     config = Config.getInstance()
     url_base_path = urlparse(config.getBaseURL()).path
     output_dir = os.path.join(config.getHtdocsDir(), 'static', 'assets',
                               'plugins', self.name)
     output_url = '{}/static/assets/plugins/{}'.format(
         url_base_path, self.name)
     static_dir = os.path.join(self.root_path, 'static')
     static_url = '{}/static/plugins/{}'.format(url_base_path, self.name)
     self.assets = Environment(output_dir,
                               output_url,
                               debug=config.getDebug())
     self.assets.append_path(output_dir, output_url)
     self.assets.append_path(static_dir, static_url)
     configure_pyscss(self.assets)
     self.register_assets()
Пример #35
0
    def _generate_zip_file(self, attachments):
        temp_file = NamedTemporaryFile(suffix='indico.tmp', dir=Config.getInstance().getTempDir())
        with ZipFile(temp_file.name, 'w', allowZip64=True) as zip_handler:
            self.used = set()
            for attachment in attachments:
                name = self._prepare_folder_structure(attachment)
                self.used.add(name)
                with attachment.file.storage.get_local_path(attachment.file.storage_file_id) as filepath:
                    zip_handler.write(filepath, name)

        # Delete the temporary file after some time.  Even for a large file we don't
        # need a higher delay since the webserver will keep it open anyway until it's
        # done sending it to the client.
        delete_file.apply_async(args=[temp_file.name], countdown=3600)
        temp_file.delete = False
        return send_file('material-{}.zip'.format(self._conf.id), temp_file.name, 'application/zip', inline=False)
Пример #36
0
def generate_public_auth_request(apiKey, path, params=None):
    apiMode = api_settings.get('security_mode')
    if params is None:
        params = {}
    if apiKey:
        key = apiKey.token
        secret_key = apiKey.secret
        persistent = apiKey.is_persistent_allowed and api_settings.get(
            'allow_persistent')
    else:
        key = secret_key = None
        persistent = False
    baseURL = Config.getInstance().getBaseURL()
    publicRequestsURL = None
    authRequestURL = None
    if apiMode == APIMode.KEY:
        publicRequestsURL = build_indico_request(path, params)
        authRequestURL = build_indico_request(path, params,
                                              key) if key else None
    elif apiMode == APIMode.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 == APIMode.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 == APIMode.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 == APIMode.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 ""
    }
Пример #37
0
def create_user(email, data, identity=None, settings=None, other_emails=None, from_moderation=True):
    """Create a new user.

    This may also convert a pending user to a proper user in case the
    email address matches such a user.

    :param email: The primary email address of the user.
    :param data: The data used to populate the user.
    :param identity: An `Identity` to associate with the user.
    :param settings: A dict containing user settings.
    :param other_emails: A set of email addresses that are also used
                         to check for a pending user. They will also
                         be added as secondary emails to the user.
    :param from_moderation: Whether the user was created through the
                            moderation process or manually by an admin.
    """
    if other_emails is None:
        other_emails = set()
    if settings is None:
        settings = {}
    cfg = Config.getInstance()
    settings.setdefault('timezone', cfg.getDefaultTimezone())
    settings.setdefault('lang', cfg.getDefaultLocale())
    # Get a pending user if there is one
    user = User.find_first(~User.is_deleted, User.is_pending,
                           User.all_emails.contains(db.func.any(list({email} | set(other_emails)))))
    if not user:
        user = User()

    if email in user.secondary_emails:
        # This can happen if there's a pending user who has a secondary email
        # for some weird reason which should now become the primary email...
        user.make_email_primary(email)
    else:
        user.email = email
    user.populate_from_dict(data)
    user.is_pending = False
    user.secondary_emails |= other_emails
    user.favorite_users.add(user)
    if identity is not None:
        user.identities.add(identity)
    db.session.add(user)
    user.settings.set_multi(settings)
    db.session.flush()
    signals.users.registered.send(user, from_moderation=from_moderation, identity=identity)
    db.session.flush()
    return user
Пример #38
0
def url_for(endpoint, *targets, **values):
    """Wrapper for Flask's url_for() function.

    Instead of an endpoint you can also pass an URLHandler - in this case **only** its _endpoint will be used.
    However, there is usually no need to do so. This is just so you can use it in places where sometimes a UH
    might be passed instead.

    The `target` argument allows you to pass some object having a `getLocator` method returning a dict. This
    should be used e.g. when generating an URL for an event since `getLocator()` provides the `{'confId': 123}`
    dict instead of you having to pass `confId=event.getId()` as a kwarg.

    For details on Flask's url_for, please see its documentation.
    Anyway, the important arguments you can put in `values` besides actual arguments are:
    _external: if set to `True`, an absolute URL is generated
    _secure: if True/False, set _scheme to https/http if possible (only with _external)
    _scheme: a string specifying the desired URL scheme (only with _external) - use _secure if possible!
    _anchor: if provided this is added as #anchor to the URL.
    """

    if hasattr(endpoint, '_endpoint'):
        endpoint = endpoint._endpoint

    secure = values.pop('_secure', None)
    if secure is not None:
        from indico.core.config import Config
        if secure and Config.getInstance().getBaseSecureURL():
            values['_scheme'] = 'https'
        elif not secure:
            values['_scheme'] = 'http'

    if targets:
        locator = {}
        for target in targets:
            if target:  # don't fail on None or mako's Undefined
                locator.update(target.getLocator())
        intersection = set(locator.iterkeys()) & set(values.iterkeys())
        if intersection:
            raise ValueError('url_for kwargs collide with locator: %s' %
                             ', '.join(intersection))
        values.update(locator)

    for key, value in values.iteritems():
        # Avoid =True and =False in the URL
        if isinstance(value, bool):
            values[key] = int(value)

    return _url_for(endpoint, **values)
Пример #39
0
 def getVars(self):
     wvars = wcomponents.WTemplated.getVars(self)
     wvars["body_title"] = self._getTitle()
     if not wvars.has_key("redirection"):
         wvars["redirection"] = None
     if self._mode == Evaluation._SUBMIT:
         wvars["status"] = _("submitted")
     elif self._mode == Evaluation._EDIT:
         wvars["status"] = _("modified")
     else:  # should never be here...
         if Config.getInstance().getDebug():
             raise Exception(
                 _("Evaluation - Possible modes are %s, given : %s.") %
                 ([Evaluation._SUBMIT, Evaluation._EDIT], self._mode))
         else:
             wvars["status"] = _("submitted")
     return wvars
Пример #40
0
 def getVars(self):
     vars = wcomponents.WTemplated.getVars(self)
     conf = self._question.getEvaluation().getConference()
     #required
     if self._question.isRequired():
         vars["required"] = "* "
     else:
         vars["required"] = ""
     #questionValue, keyword, description, help
     vars["questionValue"] = self._question.getQuestionValue()
     vars["keyword"] = self._question.getKeyword()
     vars["description"] = self._question.getDescription()
     vars["help"] = self._question.getHelp()
     #question input
     vars["input"] = self._question.displayHtml(disabled="disabled")
     #actionUrl for change position + edit question
     url = urlHandlers.UHConfModifEvaluationEditPerformChanges.getURL(conf)
     url.addParam("mode", Question._EDIT)
     vars["actionUrl"] = url
     #change question position select
     posName = "posChange_%s" % (self._question.getPosition())
     nbQuestions = self._question.getEvaluation().getNbOfQuestions()
     questionPos = self._question.getPosition()
     vars["posChange"] = WUtils.createSelect(False,
                                             range(1, nbQuestions + 1),
                                             questionPos,
                                             name=posName,
                                             onchange="this.form.submit()")
     #actual position
     vars["actualPosition"] = self._question.getPosition()
     #modifiy question
     url = urlHandlers.UHConfModifEvaluationEdit.getURL(
         conf, mode=Question._EDIT, questionPos=questionPos)
     vars["editQuestion"] = WUtils.createImgButton(url, "edit", "edit")
     #remove question
     url = urlHandlers.UHConfModifEvaluationEditPerformChanges.getURL(
         conf, mode=Question._REMOVE, questionPos=questionPos)
     vars["removeQuestionUrl"] = url
     vars["removeQuestionInput"] = WUtils.createInput(
         type="image",
         name="remove",
         id="questionRemove%s" % self._question.getPosition(),
         alt="remove",
         src=Config.getInstance().getSystemIconURL("remove"))
     #return
     return vars
Пример #41
0
    def _getParams(self):
        self._offset = get_query_parameter(self._queryParams, ['O', 'offset'], 0, integer=True)
        if self._offset < 0:
            raise HTTPAPIError('Offset must be a positive number', 400)
        self._orderBy = get_query_parameter(self._queryParams, ['o', 'order'])
        self._descending = get_query_parameter(self._queryParams, ['c', 'descending'], 'no') == 'yes'
        self._detail = get_query_parameter(self._queryParams, ['d', 'detail'], self.DEFAULT_DETAIL)
        tzName = get_query_parameter(self._queryParams, ['tz'], None)

        self._serverTZ = Config.getInstance().getDefaultTimezone()

        if tzName is None:
            tzName = self._serverTZ
        try:
            self._tz = pytz.timezone(tzName)
        except pytz.UnknownTimeZoneError, e:
            raise HTTPAPIError("Bad timezone: '%s'" % e.message, 400)
Пример #42
0
def url_rule_to_angular(endpoint):
    """Converts a flask-style rule to angular style"""
    mapping = {
        'reg_form_id': 'confFormId',
        'section_id': 'sectionId',
        'field_id': 'fieldId',
    }
    rules = list(current_app.url_map.iter_rules(endpoint))
    assert len(rules) == 1
    rule = rules[0]
    assert not rule.defaults
    segments = [
        ':' + mapping.get(data, data) if is_dynamic else data
        for is_dynamic, data in rule._trace
    ]
    prefix = url_parse(Config.getInstance().getBaseURL()).path.rstrip('/')
    return prefix + ''.join(segments).split('|', 1)[-1]
Пример #43
0
 def _get_css_refs(self):
     """Adds files referenced in stylesheets and rewrite the URLs inside those stylesheets"""
     config = Config.getInstance()
     for path in self._css_files:
         src_path = os.path.join(config.getHtdocsDir(), path)
         dst_path = os.path.join(self._staticPath, path)
         if dst_path in self._downloaded_files and not os.path.exists(
                 src_path):
             css = self._downloaded_files[dst_path]
         else:
             with open(src_path, 'rb') as f:
                 css = f.read()
         # Extract all paths inside url()
         urls = set(
             m.group('url') for m in RE_CSS_URL.finditer(css)
             if m.group('url')[0] != '#')
         for url in urls:
             orig_url = url
             url = _remove_qs(url)  # get rid of cache busters
             if url[0] == '/':
                 # make it relative and resolve '..' elements
                 url = os.path.normpath(url[1:])
                 # anything else is straightforward: the url is now relative to the htdocs folder
                 ref_src_path = os.path.join(config.getHtdocsDir(), url)
                 ref_dst_path = os.path.join(self._staticPath, url)
                 # the new url is relative to the css location
                 static_url = os.path.relpath(url, os.path.dirname(path))
             else:
                 # make the relative path absolute (note: it's most likely NOT relative to htdocs!)
                 css_abs_path = os.path.join(config.getHtdocsDir(), path)
                 # now we can combine the relative url with that path to get the proper paths of the resource
                 ref_src_path = os.path.normpath(
                     os.path.join(os.path.dirname(css_abs_path), url))
                 ref_dst_path = os.path.normpath(
                     os.path.join(self._staticPath, os.path.dirname(path),
                                  url))
                 static_url = os.path.relpath(ref_src_path,
                                              os.path.dirname(css_abs_path))
             if not os.path.isfile(ref_src_path):
                 htdocs_relative_path = os.path.relpath(
                     ref_src_path, config.getHtdocsDir())
                 self._failed_paths.add(htdocs_relative_path)
             else:
                 self._addFileFromSrc(ref_dst_path, ref_src_path)
             css = css.replace(orig_url, static_url)
         self._fileHandler.addNewFile(dst_path, css)
Пример #44
0
    def __init__(self, task):
        GenericNotification.__init__(self)
        self.setFromAddr("Indico <%s>" % Config.getInstance().getNoReplyEmail())
        self.setToList([task.avatar.getEmail()])
        self.setSubject("""
The offline version of the event "%s" is ready to be downloaded
""" % (task.conference.getTitle()))
        self.setBody("""
Dear %s,

The offline version for the event "%s" was successfully generated and it is ready to be downloaded.

Download link: %s

Best Regards,
--
Indico""" % (task.avatar.getStraightFullName(), task.conference.getTitle(), task.getDownloadLink()))
Пример #45
0
def notify_request_managers(req, template, **context):
    """Notifies request managers about something

    :param req: the :class:`Request`
    :param template: the template for the notification
    :param context: data passed to the template
    """
    event = req.event_new
    from_addr = Config.getInstance().getSupportEmail()
    request_manager_emails = _get_request_manager_emails(req)
    if not request_manager_emails:
        return
    context['event'] = event
    context['req'] = req
    tpl_request_managers = _get_template_module(template, **context)
    return make_email(request_manager_emails, from_address=from_addr,
                      subject=tpl_request_managers.get_subject(), body=tpl_request_managers.get_body())
Пример #46
0
    def get_local_path(self, file_id):
        """Returns a local path for the file.

        While this path MAY point to the permanent location of the
        stored file, it MUST NOT be used for anything but read
        operations and MUST NOT be used after existing this function's
        contextmanager.

        :param file_id: The ID of the file within the storage backend.
        """
        with self.open(file_id) as fd:
            with NamedTemporaryFile(suffix='indico.tmp',
                                    dir=Config.getInstance().
                                    getUploadedFilesTempDir()) as tmpfile:
                copyfileobj(fd, tmpfile, 1024 * 1024)
                tmpfile.flush()
                yield tmpfile.name
Пример #47
0
class PosterFactory(MaterialFactory):

    _id = "poster"
    _title = "Poster"
    _iconURL = Config.getInstance().getSystemIconURL("poster")
    _materialKlasses = [conference.Poster]
    _needsCreationPage = False

    def get(owner):
        """returns the material"""
        return owner.getPoster()

    get = staticmethod(get)

    def remove(owner):
        """performs the deletion of the poster from the owner"""
        owner.removePoster()

    remove = staticmethod(remove)

    def canAdd(target):
        #only one poster can be added to a contribution
        return target.getPoster() == None

    canAdd = staticmethod(canAdd)

    def canDelete(target):
        #only a poster which is already set in a contribution can be deleted
        return target.getPoster() != None

    canDelete = staticmethod(canDelete)

    def getModificationURL(cls, mat):
        """returns the URL for accessing to the modification view of the
            material"""
        return urlHandlers.UHMaterialModification.getURL(mat)

    getModificationURL = classmethod(getModificationURL)

    def create(cls, target):
        m = conference.Poster()
        m.setTitle(cls.getTitle())
        target.setPoster(m)
        return m

    create = classmethod(create)
Пример #48
0
    def get_context(self):
        if self._context is None:
            self._context = context = {}

            for attr in ('date', 'time', 'datetime', 'timedelta'):
                _add_to_context(context,
                                getattr(datetime, attr),
                                doc='stdlib datetime.{}'.format(attr),
                                color='yellow')

            _add_to_context(context, Conference)
            _add_to_context(context, ConferenceHolder)
            _add_to_context(context, CategoryManager)
            _add_to_context(context, AvatarHolder)
            _add_to_context(context, GroupHolder)
            _add_to_context(context, PluginsHolder)
            _add_to_context(context, Catalog)
            _add_to_context(context, IndexesHolder)
            _add_to_context(context, IndicoConfigWrapper(Config.getInstance()),
                            'config')
            _add_to_context(context,
                            LocalProxy(HelperMaKaCInfo.getMaKaCInfoInstance),
                            'minfo')
            _add_to_context(context, current_app, 'app')

            for name, cls in sorted(db.Model._decl_class_registry.iteritems(),
                                    key=itemgetter(0)):
                if hasattr(cls, '__table__'):
                    _add_to_context(context, cls, color='cyan')

            _add_to_context(context,
                            DBMgr.getInstance(),
                            'dbi',
                            doc='zodb db interface',
                            color='cyan!')
            _add_to_context(context,
                            db,
                            'db',
                            doc='sqlalchemy db interface',
                            color='cyan!')
            _add_to_context(context,
                            transaction,
                            doc='transaction module',
                            color='cyan!')

        return self._context
Пример #49
0
def i18n_locale(locale_name):
    """
    Retrieve a locale in a Jed-compatible format
    """
    config = Config.getInstance()
    root_path = os.path.join(current_app.root_path, 'translations')
    plugin_key = ','.join(sorted(plugin_engine.get_active_plugins()))
    plugin_hash = binascii.crc32(plugin_key) & 0xffffffff
    cache_file = os.path.join(
        config.getXMLCacheDir(),
        'assets_i18n_{}_{}.js'.format(locale_name, plugin_hash))

    if not os.path.exists(cache_file):
        i18n_data = locale_data(root_path, locale_name, 'indico')
        if not i18n_data:
            # Dummy data, not having the indico domain would cause lots of failures
            i18n_data = {
                'indico': {
                    '': {
                        'domain': 'indico',
                        'lang': locale_name
                    }
                }
            }

        for pid, plugin in plugin_engine.get_active_plugins().iteritems():
            data = {}
            if plugin.translation_path:
                data = locale_data(plugin.translation_path, locale_name, pid)
            if not data:
                # Dummy entry so we can still load the domain
                data = {pid: {'': {'domain': pid, 'lang': locale_name}}}
            i18n_data.update(data)

        if not i18n_data:
            raise NotFound(
                "Translation for language '{}' not found".format(locale_name))

        with open(cache_file, 'wb') as f:
            f.write("window.TRANSLATIONS = {};".format(json.dumps(i18n_data)))

    return send_file('{}.js'.format(locale_name),
                     cache_file,
                     mimetype='application/x-javascript',
                     no_cache=False,
                     conditional=True)
Пример #50
0
    def _process(self):
        authManager = AuthenticatorMgr()
        if (authManager.isSSOLoginActive() and len(authManager.getList()) == 1
                and not Config.getInstance().getDisplayLoginPage()):
            self._redirect(
                urlHandlers.UHSignInSSO.getURL(
                    authId=authManager.getDefaultAuthenticator().getId()))
            return

        av = authManager.getAvatarByLogin(self._login).values()[0]
        self._responseUtil.content_type = 'application/json'
        if not av:
            return '{"success":false,"message":"User not found"}'
        elif not av.isActivated():
            return '{"success":false,"message":"User not activated"}'
        else:
            return '{"success":true}'
Пример #51
0
 def getMapURL(self, roomName):
     groupdict = self.applyRegularExpressions(roomName)
     if groupdict:
         return self.getBaseMapURL().format(**groupdict)
     if Config.getInstance().getIsRoomBookingActive():
         from indico.modules.rb.models.rooms import Room
         room = Room.find_first(name=roomName)
         if room:
             if all(field in self.getBaseMapURL()
                    for field in ['{building}', '{floor}', '{roomNr}']):
                 return self.getBaseMapURL().format(
                     **{
                         'building': str(room.building),
                         'floor': room.floor,
                         'roomNr': room.number
                     })
     return ""
Пример #52
0
def inject_unicode_debug(s, level=1):
    """
    Wrap a string in invisible unicode characters to trigger a unicode
    error when erroneously mixing unicode and bytestrings.  If unicode
    debug mode is not enabled, this function returns its argument
    without touching it.

    :param s: a unicode string
    :param level: the minimum level of the DebugUnicode mode needed
                  to inject the spaces.  the more likely it is to
                  break things the higher it should be.
    """
    from indico.core.config import Config
    if Config.getInstance().getDebugUnicode() < level:
        return s
    else:
        return u'\N{ZERO WIDTH SPACE}' + s + u'\N{ZERO WIDTH SPACE}'
Пример #53
0
    def __init__(self,
                 rh,
                 _protected_object=None,
                 _current_category=None,
                 **kwargs):
        config = Config.getInstance()
        self._rh = rh
        self._kwargs = kwargs
        self._locTZ = ""

        self._dir = config.getTPLDir()
        self._asset_env = assets.core_env
        self._protected_object = _protected_object
        self._current_category = _current_category

        #store page specific CSS and JS
        self._extraCSS = []
Пример #54
0
 def _sendReport(self):
     cfg = Config.getInstance()
     fromAddr = self._userMail
     toAddr = cfg.getSupportEmail()
     subject = "[Indico@%s] Error report" % cfg.getBaseURL()
     body = [
         "-" * 20, "User Comments\n",
         "%s\n\n" % self._comments, "-" * 20, "Error details\n", self._msg,
         "-" * 20
     ]
     maildata = {
         "fromAddr": fromAddr,
         "toList": [toAddr],
         "subject": subject,
         "body": "\n".join(body)
     }
     GenericMailer.send(GenericNotification(maildata), skipQueue=True)
Пример #55
0
    def _process_retry_do(self, profile):
        profile_name, res = '', ''
        try:
            # old code gets parameters from call
            # new code utilizes of flask.request
            if len(inspect.getargspec(self._checkParams).args) < 2:
                cp_result = self._checkParams()
            else:
                cp_result = self._checkParams(self._reqParams)

            if isinstance(cp_result, (current_app.response_class, Response)):
                return '', cp_result

            func = getattr(self, '_checkParams_' + request.method, None)
            if func:
                cp_result = func()
                if isinstance(cp_result,
                              (current_app.response_class, Response)):
                    return '', cp_result

        except NoResultFound:  # sqlalchemy .one() not finding anything
            raise NotFoundError(_('The specified item could not be found.'),
                                title=_('Item not found'))

        self._checkProtection()
        func = getattr(self, '_checkProtection_' + request.method, None)
        if func:
            func()

        security.Sanitization.sanitizationCheck(self._target, self._reqParams,
                                                self._aw,
                                                self._doNotSanitizeFields)

        if self._doProcess:
            if profile:
                profile_name = os.path.join(
                    Config.getInstance().getTempDir(),
                    'stone{}.prof'.format(random.random()))
                result = [None]
                profiler.runctx('result[0] = self._process()', globals(),
                                locals(), profile_name)
                res = result[0]
            else:
                res = self._process()
        return profile_name, res
Пример #56
0
    def __init__(self, booking):
        VidyoOwnerNotificationBase.__init__(self)
        self._booking = booking
        self._owner = booking.getOwnerObject()

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

        event = booking.getConference()

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

        self.setSubject(
            """[Indico] You are the owner of a Vidyo public room attached to the event: %s"""
            % event.getTitle())

        self.setBody("""Dear %s%s,<br />
<br />
A new Vidyo room was created in <a href="%s">Indico</a> for the event <a href="%s">%s</a>.<br />
You have been chosen as Owner of this Vidyo public room.<br />
<br />
This means you can manage the room through the Vidyo Desktop application and you will be able to:<br />
 - Invite other users to the room,<br />
 - Lock or unlock the room,<br />
 - Fix a maximum number of attendees,<br />
 - Expel people out of the room,<br />
 - and other similar actions.<br />
<br />
You will not be able, however, to remove or modify the room from Indico, unless you also have management rights for the event.<br />
<br />
<a href="%s">Click here</a> to join the Vidyo room.<br />
<br />
Name of the room: %s<br />
Extension: %s<br />
PIN: %s<br />
Description: %s<br />
<br />
Thank you for using our system.<br />
""" % (self._getOwnerTitleText(), self._owner.getStraightFullName(),
        MailTools.getServerName(),
        urlHandlers.UHConferenceDisplay.getURL(event), event.getTitle(),
        booking.getURL(), booking.getBookingParamByName("roomName"),
        str(booking.getExtension()), self._getPinText(),
        booking.getBookingParamByName("roomDescription")))
Пример #57
0
    def _getHTMLHeader(self):
        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()

        plugin_css = values_from_signal(signals.plugin.inject_css.send(
            self.__class__),
                                        as_list=True,
                                        multi_value_types=list)
        plugin_js = values_from_signal(signals.plugin.inject_js.send(
            self.__class__),
                                       as_list=True,
                                       multi_value_types=list)

        return wcomponents.WHTMLHeader().getHTML({
            "area":
            area,
            "baseurl":
            self._getBaseURL(),
            "conf":
            Config.getInstance(),
            "page":
            self,
            "printCSS":
            map(self._fix_path, self.getPrintCSSFiles()),
            "extraCSS":
            map(self._fix_path,
                self.getCSSFiles() + plugin_css + self.get_extra_css_files()),
            "extraJSFiles":
            map(self._fix_path,
                self.getJSFiles() + plugin_js),
            "language":
            session.lang or info.getLang(),
            "social":
            info.getSocialAppConfig(),
            "assets":
            self._asset_env
        })
Пример #58
0
def register_instance(contact, email):
    organisation = HelperMaKaCInfo.getMaKaCInfoInstance().getOrganisation()
    payload = {
        'url': Config.getInstance().getBaseURL(),
        'contact': contact,
        'email': email,
        'organisation': organisation
    }
    response = requests.post(_url,
                             data=dumps(payload),
                             headers=_headers,
                             timeout=TIMEOUT)
    try:
        response.raise_for_status()
    except HTTPError as err:
        logger.error(
            'failed to register the server to the community hub, got: %s',
            err.message)
        settings.set('joined', False)
        raise
    except Timeout:
        logger.error(
            'failed to register: timeout while contacting the community hub')
        settings.set('joined', False)
        raise
    except RequestException as err:
        logger.error(
            'unexpected exception while registering the server with the Community Hub: %s',
            err.message)
        raise

    json_response = response.json()
    if 'uuid' not in json_response:
        logger.error('invalid json reply from the community hub: uuid missing')
        settings.set('joined', False)
        raise ValueError(
            'invalid json reply from the community hub: uuid missing')

    settings.set_multi({
        'joined': True,
        'uuid': json_response['uuid'],
        'contact_name': payload['contact'],
        'contact_email': payload['email']
    })
    logger.info('successfully registered the server to the community hub')
Пример #59
0
    def _process(self):
        mode = request.form['tz_mode']
        tz = request.form.get('tz')
        update_user = request.form.get('update_user') == '1'

        if mode == 'local':
            session.timezone = 'LOCAL'
        elif mode == 'user' and session.user:
            session.timezone = session.user.settings.get('timezone', Config.getInstance().getDefaultTimezone())
        elif mode == 'custom' and tz in common_timezones_set:
            session.timezone = tz

        if update_user:
            session.user.settings.set('force_timezone', mode != 'local')
            if tz:
                session.user.settings.set('timezone', tz)

        return '', 204
Пример #60
0
    def __init__(self, hostname=None, port=None, max_disconnect_poll=30):
        # Please leave this import here, db.py is imported during installation process
        from indico.core.config import Config
        cfg = Config.getInstance()

        if not hostname:
            hostname = cfg.getDBConnectionParams()[0]
        if not port:
            port = cfg.getDBConnectionParams()[1]

        self._storage = ClientStorage((hostname, port),
                                      username=cfg.getDBUserName(),
                                      password=cfg.getDBPassword(),
                                      realm=cfg.getDBRealm(),
                                      max_disconnect_poll=max_disconnect_poll)
        self._db = MigratedDB(self._storage)
        self._conn = threading.local()
        self._conn.conn = None