Exemple #1
0
def set_best_lang():
    """
    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.
    """

    if not has_request_context():
        return 'en_GB' if current_app.config['TESTING'] else HelperMaKaCInfo.getMaKaCInfoInstance().getLang()
    elif 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'

        with DBMgr.getInstance().global_connection():
            # fall back to server default
            minfo = HelperMaKaCInfo.getMaKaCInfoInstance()
            resolved_lang = minfo.getLang()

    session.lang = resolved_lang
    return resolved_lang
Exemple #2
0
    def _sendReport(self):
        info = HelperMaKaCInfo().getMaKaCInfoInstance()
        cfg = Config.getInstance()

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

        toAddr = info.getSupportEmail()

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

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

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

        # send it
        GenericMailer.send(GenericNotification(maildata))
Exemple #3
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,
            "extraCSS": map(self._fix_path, self.getCSSFiles() + plugin_css),
            "extraJSFiles": map(self._fix_path, self.getJSFiles() + plugin_js),
            "extraJS": self._extraJS,
            "language": session.lang or info.getLang(),
            "social": info.getSocialAppConfig(),
            "assets": self._asset_env
        })
Exemple #4
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 = []
Exemple #5
0
    def _includeJSPackage(self, packageName, module = 'indico'):
        info = HelperMaKaCInfo().getMaKaCInfoInstance()

        if info.isDebugActive():
            return ['js/%s/%s/Loader.js' % (module, packageName)]
        else:
            return ['js/%s/pack/%s.pack.js' % (module, packageName)]
Exemple #6
0
    def _includePresentationFiles(self):
        info = HelperMaKaCInfo().getMaKaCInfoInstance()

        if info.isDebugActive():
            return ['js/presentation/Loader.js']
        else:
            return ['js/presentation/pack/Presentation.pack.js']
Exemple #7
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.
    """
    if not has_request_context():
        return 'en_GB' if current_app.config['TESTING'] else HelperMaKaCInfo.getMaKaCInfoInstance().getLang()
    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'

        with DBMgr.getInstance().global_connection():
            # fall back to server default
            minfo = HelperMaKaCInfo.getMaKaCInfoInstance()
            resolved_lang = minfo.getLang()

    # 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
Exemple #8
0
def set_best_lang():
    """
    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.
    """

    if not has_request_context():
        return 'en_GB' if current_app.config[
            'TESTING'] else HelperMaKaCInfo.getMaKaCInfoInstance().getLang()
    elif 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'

        with DBMgr.getInstance().global_connection():
            # fall back to server default
            minfo = HelperMaKaCInfo.getMaKaCInfoInstance()
            resolved_lang = minfo.getLang()

    session.lang = resolved_lang
    return resolved_lang
Exemple #9
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
        })
Exemple #10
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()
            })
Exemple #11
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":
            HelperMaKaCInfo.getMaKaCInfoInstance().getSupportEmail(),
            "toList":
            [HelperMaKaCInfo.getMaKaCInfoInstance().getSupportEmail()],
            "subject": _("[Indico] Error in task: Offline website creation"),
            "body": text
        }
        GenericMailer.send(GenericNotification(maildata))
Exemple #12
0
 def __init__(self):
     self._newsItems = []
     self._p_changed = 1
     self._newsCounter = Counter()
     self._recentDays = 14 #days to keep a 'New' tag on recent news items
     # fetch all news from the previous location.
     self.addNewsItem(NewsItem( _("Previous news"), HelperMaKaCInfo.getMaKaCInfoInstance().getNews(), "general"))
Exemple #13
0
def _run(args):
    _setup(args)

    formatter = logging.Formatter(
        "%(asctime)s %(name)s - %(levelname)s %(filename)s:%(lineno)s: %(message)s"
    )

    root = logging.getLogger('')
    handler = logging.StreamHandler()
    handler.setFormatter(formatter)
    root.addHandler(handler)

    dbi = DBMgr.getInstance(max_disconnect_poll=40)
    dbi.startRequest()

    info = HelperMaKaCInfo.getMaKaCInfoInstance()
    useRBDB = info.getRoomBookingModuleActive()

    if useRBDB:
        DALManager.connect()

    sm = SchedulerModule.getDBInstance()
    t = sm.getTaskById(args.taskid)

    t.plugLogger(logging.getLogger('console.run/%s' % args.taskid))
    t.run()

    if useRBDB:
        DALManager.commit()
        DALManager.disconnect()
    dbi.endRequest()
 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>".format(info.getTitle(), Config.getInstance().getSupportEmail())
     return supEmail
Exemple #15
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')
Exemple #16
0
 def timezone(self):
     if '_timezone' in self:
         return self['_timezone']
     if '_avatarId' not in self:
         return 'LOCAL'
     with DBMgr.getInstance().global_connection():
         return HelperMaKaCInfo.getMaKaCInfoInstance().getTimezone()
Exemple #17
0
class sendLoginInfo:
    
    def __init__( self, user ):
        self._user = user
    
    def send (self ):
        idList = self._user.getIdentityList()
        logins = []
        for id in idList:
            try:
                pw = id.password
            except AttributeError, e:
                pw = _(" Sorry, you are using your NICE credentials to login into Indico. Please contact the CERN helpdesk in case you do not remember your password ([email protected]).")
            logins.append( [id.getAuthenticatorTag(), id.getLogin(),pw])
        if logins == []:
            text = _("Sorry, we did not find your login.\nPlease, create one here:\n%s")%urlHandlers.UHUserDetails.getURL(self._user)
        else:
            text = _("Please, find your login and password:"******"\n\n==================\n"
                text += _("system:%s\n")%l[0]
                text += _("Login:%s\n")%l[1]
                text += _("Password:%s\n")%l[2]
                text += "==================\n"
        maildata = { "fromAddr": "Indico Mailer<%s>"%HelperMaKaCInfo.getMaKaCInfoInstance().getSupportEmail(), "toList": [self._user.getEmail()], "subject": _("[%s] Login Information")%getSubjectIndicoTitle(), "body": text }
        GenericMailer.send(GenericNotification(maildata))
Exemple #18
0
    def _process_POST(self):
        if User.has_rows():
            return redirect(url_for('misc.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', to_unicode(setup_form.language.data))

        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)
        minfo.setLang(setup_form.language.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('misc.index'))
def _run(args):
    _setup(args)

    formatter = logging.Formatter("%(asctime)s %(name)s - %(levelname)s %(filename)s:%(lineno)s: %(message)s")

    root = logging.getLogger('')
    handler = logging.StreamHandler()
    handler.setFormatter(formatter)
    root.addHandler(handler)

    dbi = DBMgr.getInstance(max_disconnect_poll=40)
    dbi.startRequest()

    info = HelperMaKaCInfo.getMaKaCInfoInstance()
    useRBDB = info.getRoomBookingModuleActive()

    if useRBDB:
        DALManager.connect()

    sm = SchedulerModule.getDBInstance()
    t = sm.getTaskById(args.taskid)

    t.plugLogger(logging.getLogger('console.run/%s' % args.taskid))
    t.run()

    if useRBDB:
        DALManager.commit()
        DALManager.disconnect()
    dbi.endRequest()
Exemple #20
0
 def timezone(self):
     if '_timezone' in self:
         return self['_timezone']
     if '_avatarId' not in self:
         return 'LOCAL'
     with DBMgr.getInstance().global_connection():
         return HelperMaKaCInfo.getMaKaCInfoInstance().getTimezone()
Exemple #21
0
 def _process(self):
     if self._target.isClosed():
         p = conferences.WPConferenceModificationClosed(self, self._target)
     else:
         if (self._target.getId() == "default"):
             p = admins.WPPosterTemplateDesign(self, self._target,
                                               self.__templateId,
                                               self.__new)
         else:
             if self.__new == True and self.__baseTemplate != 'blank':
                 dconf = HelperMaKaCInfo.getMaKaCInfoInstance(
                 ).getDefaultConference()
                 templMan = self._target.getPosterTemplateManager()
                 newId = self.__templateId
                 dconf.getPosterTemplateManager().getTemplateById(
                     self.__baseTemplate).clone(templMan, newId)
                 url = urlHandlers.UHConfModifPosterPrinting().getURL(
                     self._target)
                 self._redirect(url)
                 return
             else:
                 p = conferences.WPConfModifPosterDesign(
                     self, self._target, self.__templateId, self.__new,
                     self.__baseTemplate)
     return p.display()
Exemple #22
0
 def getVars(self):
     vars = wcomponents.WTemplated.getVars(self)
     vars["mode"] = self._mode
     vars["isModeSelect"] = self._mode == Evaluation._SELECT_SUBMITTERS
     vars["submissions"] = self._conf.getEvaluation().getSubmissions()
     vars["utils"] = utils
     vars[
         "actionUrl"] = urlHandlers.UHConfModifEvaluationResultsSubmittersActions.getURL(
             self._conf)
     if self._mode == Evaluation._REMOVE_SUBMITTERS:
         vars["inputCheckboxName"] = "removedSubmitters"
         vars["inputSubmitStyle"] = 'style="color:#ee0000"'
         vars[
             "submitConfirm"] = """onsubmit="javascript:return confirmation();" """
     elif self._mode == Evaluation._SELECT_SUBMITTERS:
         vars["inputCheckboxName"] = "selectedSubmitters"
         vars["inputSubmitStyle"] = ''
         vars["submitConfirm"] = ''
     else:
         if HelperMaKaCInfo.getMaKaCInfoInstance().isDebugActive():
             raise Exception("Evaluation - unknown mode (given: %s)" %
                             self._mode)
         vars["inputCheckboxName"] = "unknownMode"
         vars["inputSubmitStyle"] = ''
         vars["submitConfirm"] = ''
     return vars
Exemple #23
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())
Exemple #24
0
 def _process(self):
     language = HelperMaKaCInfo.getMaKaCInfoInstance().getLang()
     stats = {
         'python_version': python_version(),
         'indico_version': MaKaC.__version__,
         'language': language
     }
     return jsonify(stats)
Exemple #25
0
 def lang(self):
     if '_lang' in self:
         return self['_lang']
     elif self.user:
         return self.user.getLang()
     else:
         with DBMgr.getInstance().global_connection():
             return HelperMaKaCInfo.getMaKaCInfoInstance().getLang()
Exemple #26
0
def getSubjectIndicoTitle():
    minfo=HelperMaKaCInfo.getMaKaCInfoInstance()
    systitle="Indico"
    if minfo.getTitle().strip() != "":
        systitle=minfo.getTitle().strip()
    if minfo.getOrganisation().strip() != "":
        systitle="%s @ %s"%(systitle, minfo.getOrganisation().strip())
    return systitle
Exemple #27
0
def getSubjectIndicoTitle():
    minfo = HelperMaKaCInfo.getMaKaCInfoInstance()
    systitle = "Indico"
    if minfo.getTitle().strip() != "":
        systitle = minfo.getTitle().strip()
    if minfo.getOrganisation().strip() != "":
        systitle = "%s @ %s" % (systitle, minfo.getOrganisation().strip())
    return systitle
Exemple #28
0
 def lang(self):
     if '_lang' in self:
         return self['_lang']
     elif self.user:
         return self.user.getLang()
     else:
         with DBMgr.getInstance().global_connection():
             return HelperMaKaCInfo.getMaKaCInfoInstance().getLang()
Exemple #29
0
    def __init__( self, rh ):
        config = Config.getInstance()
        db_connected = DBMgr.getInstance().isConnected()
        if db_connected:
            debug = HelperMaKaCInfo.getMaKaCInfoInstance().isDebugActive()
        else:
            debug = False

        self._rh = rh
        self._locTZ = ""

        url_path = urlparse(config.getBaseURL()).path

        self._asset_env = Environment(os.path.join(config.getHtdocsDir(), 'static', 'assets'),
                                      '{0}/static/assets/'.format(url_path))
        self._asset_env.config['PYSCSS_STATIC_URL'] = '{0}/static/'.format(url_path)
        self._asset_env.config['PYSCSS_LOAD_PATHS'] = [
            os.path.join(config.getHtdocsDir(), 'sass', 'lib', 'compass'),
            os.path.join(config.getHtdocsDir(), 'sass')
        ]
        self._asset_env.config['PYSCSS_DEBUG_INFO'] = debug and Config.getInstance().getSCSSDebugInfo()

        self._asset_env.append_path(config.getHtdocsDir(), '/')
        self._asset_env.append_path(os.path.join(config.getHtdocsDir(), 'css'), '{0}/css'.format(url_path))
        self._asset_env.append_path(os.path.join(config.getHtdocsDir(), 'js'), '{0}/js'.format(url_path))

        # 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 = []
Exemple #30
0
 def __init__(self):
     info = HelperMaKaCInfo.getMaKaCInfoInstance()
     self._plugin_asset_env = PluginEnvironment('Collaboration', os.path.dirname(__file__), '/Collaboration')
     self._plugin_asset_env.debug = info.isDebugActive()
     self._plugin_asset_env.register('collaboration', Bundle('js/Collaboration.js',
                                                                 'js/bookings.js',
                                                                 filters='rjsmin',
                                                                 output="Collaboration_%(version)s.min.js"))
Exemple #31
0
def _get_remote_ip(req):
    hostIP = str(req.get_remote_ip())

    minfo = HelperMaKaCInfo.getMaKaCInfoInstance()
    if minfo.useProxy():
        # if we're behind a proxy, use X-Forwarded-For
        return req.headers_in.get("X-Forwarded-For", hostIP).split(", ")[-1]
    else:
        return hostIP
Exemple #32
0
 def __init__(self, rh, templateClass):
     WPAdminPlugins.__init__(self, rh, 'livesync', '')
     self._templateClass = templateClass
     info = HelperMaKaCInfo.getMaKaCInfoInstance()
     self._plugin_asset_env = PluginEnvironment('livesync', os.path.dirname(__file__), '/livesync')
     self._plugin_asset_env.debug = info.isDebugActive()
     self._plugin_asset_env.register('livesync', Bundle('js/livesync.js',
                                                        filters='rjsmin',
                                                        output="livesync__%(version)s.min.js"))
Exemple #33
0
    def send( self ):
        minfo = HelperMaKaCInfo.getMaKaCInfoInstance()
        name = self._user.getStraightFullName()
        text = """Dear Administrator,
%s has created a new account in Indico.
<%s>
""" % (name,urlHandlers.UHUserDetails.getURL( self._user ))
        maildata = { "fromAddr": "Indico Mailer<%s>" % minfo.getSupportEmail(), "toList": minfo.getAdminEmails(), "subject": _("[Indico] New account creation"), "body": text }
        GenericMailer.send(GenericNotification(maildata))
Exemple #34
0
 def __init__(self, rh, templateClass):
     WPAdminPlugins.__init__(self, rh, 'livesync', '')
     self._templateClass = templateClass
     info = HelperMaKaCInfo.getMaKaCInfoInstance()
     self._plugin_asset_env = PluginEnvironment('livesync', os.path.dirname(__file__), '/livesync')
     self._plugin_asset_env.debug = info.isDebugActive()
     self._plugin_asset_env.register('livesync', Bundle('js/livesync.js',
                                                        filters='rjsmin',
                                                        output="livesync__%(version)s.min.js"))
Exemple #35
0
def _get_remote_ip(req):
    hostIP = str(req.get_remote_ip())

    minfo = HelperMaKaCInfo.getMaKaCInfoInstance()
    if minfo.useProxy():
        # if we're behind a proxy, use X-Forwarded-For
        return req.headers_in.get("X-Forwarded-For", hostIP).split(", ")[-1]
    else:
        return hostIP
Exemple #36
0
    def _process_GET(self):
        defaults = FormDefaults(**settings.get_all())
        form = CephalopodForm(request.form, obj=defaults)

        affiliation = HelperMaKaCInfo.getMaKaCInfoInstance().getOrganisation()
        enabled = settings.get('joined')
        instance_url = Config.getInstance().getBaseURL()
        language = HelperMaKaCInfo.getMaKaCInfoInstance().getLang()
        tracker_url = urljoin(Config.getInstance().getTrackerURL(), 'api/instance/{}'.format(settings.get('uuid')))
        return WPCephalopod.render_template('cephalopod.html',
                                            affiliation=affiliation,
                                            enabled=enabled,
                                            form=form,
                                            indico_version=MaKaC.__version__,
                                            instance_url=instance_url,
                                            language=language,
                                            python_version=python_version(),
                                            tracker_url=tracker_url)
Exemple #37
0
def validateSignature(ak, minfo, signature, timestamp, path, query):
    ttl = HelperMaKaCInfo.getMaKaCInfoInstance().getAPISignatureTTL()
    if not timestamp and not (ak.isPersistentAllowed() and minfo.isAPIPersistentAllowed()):
        raise HTTPAPIError('Signature invalid (no timestamp)', apache.HTTP_FORBIDDEN)
    elif timestamp and abs(timestamp - int(time.time())) > ttl:
        raise HTTPAPIError('Signature invalid (bad timestamp)', apache.HTTP_FORBIDDEN)
    digest = hmac.new(ak.getSignKey(), normalizeQuery(path, query), hashlib.sha1).hexdigest()
    if signature != digest:
        raise HTTPAPIError('Signature invalid', apache.HTTP_FORBIDDEN)
Exemple #38
0
    def send( notification ):
        info = HelperMaKaCInfo.getMaKaCInfoInstance()
        fromAddr = "%s <%s>"%(info.getTitle(), info.getSupportEmail())
        toAddr = str(notification.getDestination().getEmail())
        text = """%s
-- 
Indico project <http://cern.ch/indico>
                """%(notification.getMsg())
        maildata = { "fromAddr": fromAddr, "toList": [toAddr], "subject": "[Indico] %s"%notification.getSubject(), "body": text }
        GenericMailer.send(GenericNotification(maildata))
Exemple #39
0
 def __init__(self, booking):
     GenericNotification.__init__(self)
     self._booking = booking
     self._bp = booking._bookingParams
     self._conference = booking.getConference()
     
     self._modifLink = str(booking.getModificationURL())
     
     self.setFromAddr("Indico Mailer<%s>"%HelperMaKaCInfo.getMaKaCInfoInstance().getSupportEmail())
     self.setContentType("text/html")
Exemple #40
0
 def __init__(self):
     self._newsItems = []
     self._p_changed = 1
     self._newsCounter = Counter()
     self._recentDays = 14  #days to keep a 'New' tag on recent news items
     # fetch all news from the previous location.
     self.addNewsItem(
         NewsItem(_("Previous news"),
                  HelperMaKaCInfo.getMaKaCInfoInstance().getNews(),
                  "general"))
Exemple #41
0
def ip_based_acl(dbi, withRBDB, prevVersion):
    """
    Moving from OAI Private Harvesting to a more general IP-based ACL.
    """
    from MaKaC.common.info import IPBasedACLMgr
    minfo = HelperMaKaCInfo.getMaKaCInfoInstance()
    ip_set = set(minfo._oaiPrivateHarvesterList)
    ip_acl_mgr = minfo._ip_based_acl_mgr = IPBasedACLMgr()
    ip_acl_mgr._full_access_acl = ip_set
    dbi.commit()
Exemple #42
0
    def _process_GET(self):
        defaults = FormDefaults(**settings.get_all())
        form = CephalopodForm(request.form, obj=defaults)

        affiliation = HelperMaKaCInfo.getMaKaCInfoInstance().getOrganisation()
        enabled = settings.get('joined')
        instance_url = Config.getInstance().getBaseURL()
        language = HelperMaKaCInfo.getMaKaCInfoInstance().getLang()
        tracker_url = urljoin(Config.getInstance().getTrackerURL(),
                              'api/instance/{}'.format(settings.get('uuid')))
        return WPCephalopod.render_template('cephalopod.html',
                                            affiliation=affiliation,
                                            enabled=enabled,
                                            form=form,
                                            indico_version=MaKaC.__version__,
                                            instance_url=instance_url,
                                            language=language,
                                            python_version=python_version(),
                                            tracker_url=tracker_url)
Exemple #43
0
def ip_based_acl(dbi, withRBDB, prevVersion):
    """
    Moving from OAI Private Harvesting to a more general IP-based ACL.
    """
    from MaKaC.common.info import IPBasedACLMgr
    minfo = HelperMaKaCInfo.getMaKaCInfoInstance()
    ip_set = set(minfo._oaiPrivateHarvesterList)
    ip_acl_mgr = minfo._ip_based_acl_mgr = IPBasedACLMgr()
    ip_acl_mgr._full_access_acl = ip_set
    dbi.commit()
Exemple #44
0
def sync_instance(contact, email):
    contact = contact or settings.get('contact_name')
    email = email or settings.get('contact_email')
    # registration needed if the instance does not have a uuid
    if not settings.get('uuid'):
        logger.warn(
            'unable to synchronise: missing uuid, registering the server instead'
        )
        register_instance(contact, email)
        return

    organisation = HelperMaKaCInfo.getMaKaCInfoInstance().getOrganisation()
    payload = {
        'enabled': True,
        'url': Config.getInstance().getBaseURL(),
        'contact': contact,
        'email': email,
        'organisation': organisation
    }
    url = urljoin(_url, settings.get('uuid'))
    response = requests.patch(url,
                              data=dumps(payload),
                              headers=_headers,
                              timeout=TIMEOUT)
    try:
        response.raise_for_status()
    except HTTPError as err:
        if err.response.status_code == 404:
            logger.warn(
                'unable to synchronise: the server was not registered, registering the server now'
            )
            register_instance(contact, email)
        else:
            logger.error(
                'failed to synchronise the server with the community hub, got: %s',
                err.message)
            raise
    except Timeout:
        logger.error(
            'failed to synchronise: timeout while contacting the community hub'
        )
        raise
    except RequestException as err:
        logger.error(
            'unexpected exception while synchronizing the server with the Community Hub: %s',
            err.message)
        raise
    else:
        settings.set_multi({
            'joined': True,
            'contact_name': payload['contact'],
            'contact_email': payload['email']
        })
        logger.info(
            'successfully synchronized the server with the community hub')
Exemple #45
0
def makoMigration(dbi, withRBDB, prevVersion):
    """
    Installing new TPLs for meeting/lecture styles
    """
    info = HelperMaKaCInfo().getMaKaCInfoInstance()
    sm = info.getStyleManager()
    try:
        del sm._stylesheets
    except:
        pass
    for lid in ['meeting', 'simple_event', 'conference']:
        l = sm._eventStylesheets[lid]
        if 'it' in l:
            l.remove('it')
        if 'administrative3' in l:
            l.remove('administrative3')
        sm._eventStylesheets[lid] = l
    styles = sm.getStyles()
    styles['xml'] = ('xml','XML.xsl',None)
    sm.setStyles(styles)
Exemple #46
0
def buildAW(ak, req, onlyPublic=False):
    aw = AccessWrapper()
    if ak and not onlyPublic:
        # If we have an authenticated request, require HTTPS
        minfo = HelperMaKaCInfo.getMaKaCInfoInstance()
        # Dirty hack: Google calendar converts HTTP API requests from https to http
        # Therefore, not working with Indico setup (requiring https for HTTP API authenticated)
        if not req.is_https() and minfo.isAPIHTTPSRequired() and req.get_user_agent().find("Googlebot") == -1:
            raise HTTPAPIError('HTTPS is required', apache.HTTP_FORBIDDEN)
        aw.setUser(ak.getUser())
    return aw
Exemple #47
0
def buildAW(ak, onlyPublic=False):
    aw = AccessWrapper()
    if ak and not onlyPublic:
        # If we have an authenticated request, require HTTPS
        minfo = HelperMaKaCInfo.getMaKaCInfoInstance()
        # Dirty hack: Google calendar converts HTTP API requests from https to http
        # Therefore, not working with Indico setup (requiring https for HTTP API authenticated)
        if not request.is_secure and minfo.isAPIHTTPSRequired() and request.user_agent.browser != 'google':
            raise HTTPAPIError('HTTPS is required', 403)
        aw.setUser(ak.getUser())
    return aw
Exemple #48
0
 def includeTimetableCSSFiles(cls, obj, params={}):
     """
     Includes additional Css files.
     """
     info = HelperMaKaCInfo.getMaKaCInfoInstance()
     asset_env = PluginEnvironment('importer', os.path.dirname(__file__), 'importer')
     asset_env.debug = info.isDebugActive()
     asset_env.register('importer_css', Bundle('css/importer.css',
                                               filters='cssmin',
                                               output="importer__%(version)s.min.css"))
     params['paths'].extend(asset_env['importer_css'].urls())
    def __init__(self, user, judgement, contribution):
        GenericNotification.__init__(self)
        self.setFromAddr(
            "Indico Mailer<%s>" %
            HelperMaKaCInfo.getMaKaCInfoInstance().getSupportEmail())
        self.setToList([user.getEmail()])

        if isinstance(judgement, EditorJudgement):
            self.setSubject(
                """[Indico] The layout of your contribution "%s" (id: %s) has been reviewed"""
                % (contribution.getTitle(), str(contribution.getId())))
            self.setBody("""Dear Indico user,
        
        The layout of your contribution "%s" (id: %s) has been reviewed.
        The judgement was: %s
        
        The comments of the editor were:
        "%s"
        
        Thank you for using our system.
        """ % (contribution.getTitle(), str(contribution.getId()),
               judgement.getJudgement(), judgement.getComments()))

        elif isinstance(judgement, ReviewerJudgement):
            self.setSubject(
                """[Indico] The content of your contribution "%s" (id: %s) has been reviewed"""
                % (contribution.getTitle(), str(contribution.getId())))
            self.setBody("""Dear Indico user,
        
        The content of your contribution "%s" (id: %s) has been reviewed.
        The judgement was: %s
        
        The comments of the reviewer were:
        "%s"
        
        Thank you for using our system.
        """ % (contribution.getTitle(), str(contribution.getId()),
               judgement.getJudgement(), judgement.getComments()))

        elif isinstance(judgement, RefereeJudgement):
            self.setSubject(
                """[Indico] Your contribution "%s" (id: %s) has been completely reviewed by the referee"""
                % (contribution.getTitle(), str(contribution.getId())))
            self.setBody("""Dear Indico user,
        
        Your contribution "%s" (id: %s) has been completely reviewed by the assigned referee.
        The judgement was: %s
        
        The comments of the referee were:
        "%s"
        
        Thank you for using our system.
        """ % (contribution.getTitle(), str(contribution.getId()),
               judgement.getJudgement(), judgement.getComments()))
Exemple #50
0
    def send( self ):
        minfo=HelperMaKaCInfo.getMaKaCInfoInstance()
        text =  _("""Welcome to Indico,
Your registration has been accepted by the site administrator.

You can now login using the following username: %s

Thank you for using Indico.
                """)%(self._user.getIdentityList()[0].getLogin())
        maildata = { "fromAddr": "Indico Mailer<%s>"%minfo.getSupportEmail(), "toList": [self._user.getEmail()], "subject": _("[%s] Registration accepted")%getSubjectIndicoTitle(), "body": text }
        GenericMailer.send(GenericNotification(maildata))
Exemple #51
0
def makoMigration(dbi, withRBDB, prevVersion):
    """
    Installing new TPLs for meeting/lecture styles
    """
    info = HelperMaKaCInfo().getMaKaCInfoInstance()
    sm = info.getStyleManager()
    try:
        del sm._stylesheets
    except:
        pass
    for lid in ['meeting', 'simple_event', 'conference']:
        l = sm._eventStylesheets[lid]
        if 'it' in l:
            l.remove('it')
        if 'administrative3' in l:
            l.remove('administrative3')
        sm._eventStylesheets[lid] = l
    styles = sm.getStyles()
    styles['xml'] = ('xml','XML.xsl',None)
    sm.setStyles(styles)
Exemple #52
0
 def getVars(self):
     minfo = HelperMaKaCInfo.getMaKaCInfoInstance()
     apiMode = minfo.getAPIMode()
     vars = WTemplated.getVars(self)
     vars['avatar'] = self._avatar
     vars['apiKey'] = self._avatar.getAPIKey()
     vars['isAdmin'] = self._rh._getUser().isAdmin()
     vars['signingEnabled'] = apiMode in (API_MODE_SIGNED, API_MODE_ONLYKEY_SIGNED, API_MODE_ALL_SIGNED)
     vars['persistentAllowed'] = minfo.isAPIPersistentAllowed()
     vars['apiPersistentEnableAgreement'] = minfo.getAPIPersistentEnableAgreement()
     vars['apiPersistentDisableAgreement'] = minfo.getAPIPersistentDisableAgreement()
     return vars
Exemple #53
0
    def __init__(self, booking):
        GenericNotification.__init__(self)
        self._booking = booking
        self._bp = booking._bookingParams
        self._conference = booking.getConference()

        self._modifLink = str(booking.getModificationURL())

        self.setFromAddr(
            "Indico Mailer<%s>" %
            HelperMaKaCInfo.getMaKaCInfoInstance().getSupportEmail())
        self.setContentType("text/html")
Exemple #54
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()
        })
Exemple #55
0
 def getVars(self):
     minfo = HelperMaKaCInfo.getMaKaCInfoInstance()
     vars = WTemplated.getVars(self)
     vars['apiMode'] = minfo.getAPIMode()
     vars['httpsRequired'] = minfo.isAPIHTTPSRequired()
     vars['persistentAllowed'] = minfo.isAPIPersistentAllowed()
     vars['apiCacheTTL'] = minfo.getAPICacheTTL()
     vars['apiSignatureTTL'] = minfo.getAPISignatureTTL()
     vars['apiPersistentEnableAgreement'] = minfo.getAPIPersistentEnableAgreement()
     vars['apiPersistentDisableAgreement'] = minfo.getAPIPersistentDisableAgreement()
     vars['apiKeyUserAgreement'] = minfo.getAPIKeyUserAgreement()
     vars['apiPersistentUserAgreement'] = minfo.getAPIPersistentUserAgreement()
     return vars